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
orgs.rs
use clap::{App, Arg, ArgMatches, SubCommand}; use config; use git_hub::{GitHubResponse, orgs}; use serde_json; use serde_json::Error; pub fn SUBCOMMAND<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("orgs") .about("List, Get, Edit your GitHub Organizations") .version(version!()) .author("penland365 <[email protected]>") .subcommand(SubCommand::with_name("list") .about("Lists GitHub Organizations for the credentialed user.") .arg(Arg::with_name("user") .short("u") .long("user") .help("Searches for public organizations for this user") .value_name("octocat") .takes_value(true)) .arg(Arg::with_name("format") .short("f") .long("format") .help("Sets the output format.") .value_name("json") .takes_value(true))) } pub fn handle(matches: &ArgMatches) -> () { match matches.subcommand() { ("list", Some(list_matches)) => list::handle(list_matches), ("", None) => println!("No subcommand was used for orgs"), (_, _) => unreachable!() } } mod list { use clap::ArgMatches; use config::load_config; use evidence::json_ops; use git_hub::{GitHubResponse, orgs}; use hyper::status::StatusCode; use git_hub::orgs::OrgSummary; #[cfg(windows)] pub const NL: &'static str = "\r\n"; #[cfg(not(windows))] pub const NL: &'static str = "\n"; pub fn handle(matches: &ArgMatches) -> () { let response = match matches.value_of("user") { None => orgs::get_authed_user_orgs(&load_config()), Some(user) => orgs::get_user_public_orgs(user, &load_config()), }; let is_json = match matches.value_of("format") { None => false, Some(format) => format == "json" }; let output = &build_output(&response, is_json); println!("{}", output.trim()); } fn build_output(response: &GitHubResponse, is_json: bool) -> String { match response.status { StatusCode::Forbidden => FORBIDDEN.to_owned(), StatusCode::Unauthorized => UNAUTHORIZED.to_owned(), StatusCode::Ok => match response.body { None => build_200_ok_no_string_body_output(), Some(ref body) => format_output(body.to_owned(), is_json), }, x => format!("Unexpected Http Response Code {}", x) } } fn build_200_ok_no_string_body_output() -> String { format!("An unknown error occurred. GitHub responded with {}, but no string body was found.", StatusCode::Ok) } fn format_output(body: String, is_json: bool) -> String { let orgs: Vec<OrgSummary> = json_ops::from_str_or_die(&body, DESERIALIZE_ORG_SUMMARY); if is_json { json_ops::to_pretty_json_or_die(&orgs, SERIALIZE_ORG_SUMMARY) } else { let mut output = String::with_capacity(100); let header = format!("{0: <10} {1: <10} {2: <45} {3: <30}", "login", "id", "url", "description"); output.push_str(&header); output.push_str(NL); for org in orgs { let line = format!("{0: <10} {1: <10} {2: <45} {3: <30}", org.login, org.id, org.url, org.description); output.push_str(&line); output.push_str(NL); } output } } const DESERIALIZE_ORG_SUMMARY: &'static str = "Error deserializing GitHub Organization Summary JSON."; const SERIALIZE_ORG_SUMMARY: &'static str = "Error serializing GitHub Organization Summary JSON."; const UNAUTHORIZED: &'static str = "401 Unauthorized. Bad Credentials. See https://developer.github.com/v3"; const FORBIDDEN: &'static str = "403 Forbidden. Does your OAuth token have suffecient scope? A minimum of `user` or `read:org` is required. See https://developer.github.com/v3/orgs/"; #[cfg(test)] mod tests { use git_hub::GitHubResponse; use hyper::header::Headers; use hyper::status::StatusCode; use super::{build_output, FORBIDDEN, UNAUTHORIZED}; #[test] fn test_build_output_forbidden() -> ()
#[test] fn test_build_output_unauthorized() -> () { let response = GitHubResponse { status: StatusCode::Unauthorized, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), UNAUTHORIZED); } #[test] fn test_build_output_unknown() -> () { let response = GitHubResponse { status: StatusCode::ImATeapot, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), "Unexpected Http Response Code 418 I'm a teapot"); } #[test] fn test_build_200_ok_no_string_body_output() -> () { assert_eq!(super::build_200_ok_no_string_body_output(), "An unknown error occurred. GitHub responded with 200 OK, but no string body was found."); } #[test] fn test_build_output_no_string_body() -> () { let response = GitHubResponse { status: StatusCode::Ok, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), "An unknown error occurred. GitHub responded with 200 OK, but no string body was found."); } } } // get finagle // patch finagle // list
{ let response = GitHubResponse { status: StatusCode::Forbidden, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), FORBIDDEN); }
identifier_body
main.rs
use binaryninja::architecture::Architecture; use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt}; fn
() { println!("Loading plugins..."); // This loads all the core architecture, platform, etc plugins binaryninja::headless::init(); println!("Loading binary..."); let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`"); println!("Filename: `{}`", bv.metadata().filename()); println!("File size: `{:#x}`", bv.len()); println!("Function count: {}", bv.functions().len()); for func in &bv.functions() { println!(" `{}`:", func.symbol().full_name()); for basic_block in &func.basic_blocks() { // TODO : This is intended to be refactored to be more nice to work with soon(TM) for addr in basic_block.as_ref() { print!(" {} ", addr); match func.arch().instruction_text( bv.read_buffer(addr, func.arch().max_instr_len()) .unwrap() .get_data(), addr, ) { Some((_, tokens)) => { tokens .iter() .for_each(|token| print!("{}", token.text().to_str().unwrap())); println!("") } _ => (), } } } } // Important! You need to call shutdown or your script will hang forever binaryninja::headless::shutdown(); }
main
identifier_name
main.rs
use binaryninja::architecture::Architecture; use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt}; fn main() { println!("Loading plugins..."); // This loads all the core architecture, platform, etc plugins binaryninja::headless::init(); println!("Loading binary..."); let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`"); println!("Filename: `{}`", bv.metadata().filename()); println!("File size: `{:#x}`", bv.len()); println!("Function count: {}", bv.functions().len()); for func in &bv.functions() { println!(" `{}`:", func.symbol().full_name()); for basic_block in &func.basic_blocks() { // TODO : This is intended to be refactored to be more nice to work with soon(TM) for addr in basic_block.as_ref() { print!(" {} ", addr); match func.arch().instruction_text( bv.read_buffer(addr, func.arch().max_instr_len()) .unwrap() .get_data(), addr, ) { Some((_, tokens)) => { tokens .iter() .for_each(|token| print!("{}", token.text().to_str().unwrap())); println!("") } _ => (), } } }
}
} // Important! You need to call shutdown or your script will hang forever binaryninja::headless::shutdown();
random_line_split
main.rs
use binaryninja::architecture::Architecture; use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt}; fn main()
.get_data(), addr, ) { Some((_, tokens)) => { tokens .iter() .for_each(|token| print!("{}", token.text().to_str().unwrap())); println!("") } _ => (), } } } } // Important! You need to call shutdown or your script will hang forever binaryninja::headless::shutdown(); }
{ println!("Loading plugins..."); // This loads all the core architecture, platform, etc plugins binaryninja::headless::init(); println!("Loading binary..."); let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`"); println!("Filename: `{}`", bv.metadata().filename()); println!("File size: `{:#x}`", bv.len()); println!("Function count: {}", bv.functions().len()); for func in &bv.functions() { println!(" `{}`:", func.symbol().full_name()); for basic_block in &func.basic_blocks() { // TODO : This is intended to be refactored to be more nice to work with soon(TM) for addr in basic_block.as_ref() { print!(" {} ", addr); match func.arch().instruction_text( bv.read_buffer(addr, func.arch().max_instr_len()) .unwrap()
identifier_body
crh.rs
//! Port configuration register high use rt; /// Reset value pub const DEFAULT: Register = Register(0x4444_4444); /// Register #[derive(Clone, Copy)] #[repr(C)] pub struct Register(u32); impl Register { /// Sets `pin` configuration pub fn cnf(&mut self, pin: u32, state: u32) -> &mut Self
/// Sets `pin` mode pub fn mode(&mut self, pin: u32, state: u32) -> &mut Self { match (state, pin) { (0b00...0b11, 8...15) => { const MASK: u32 = 0b11; let offset = 4 * (pin - 8); self.0 &=!(MASK << offset); self.0 |= state << offset; } _ => rt::abort(), } self } }
{ match (state, pin) { (0b00...0b11, 8...15) => { const MASK: u32 = 0b11; let offset = 4 * (pin - 8) + 2; self.0 &= !(MASK << offset); self.0 |= state << offset; } _ => rt::abort(), } self }
identifier_body
crh.rs
//! Port configuration register high use rt; /// Reset value pub const DEFAULT: Register = Register(0x4444_4444); /// Register #[derive(Clone, Copy)] #[repr(C)] pub struct Register(u32); impl Register { /// Sets `pin` configuration pub fn cnf(&mut self, pin: u32, state: u32) -> &mut Self { match (state, pin) { (0b00...0b11, 8...15) => { const MASK: u32 = 0b11; let offset = 4 * (pin - 8) + 2; self.0 &=!(MASK << offset); self.0 |= state << offset; } _ => rt::abort(), } self }
/// Sets `pin` mode pub fn mode(&mut self, pin: u32, state: u32) -> &mut Self { match (state, pin) { (0b00...0b11, 8...15) => { const MASK: u32 = 0b11; let offset = 4 * (pin - 8); self.0 &=!(MASK << offset); self.0 |= state << offset; } _ => rt::abort(), } self } }
random_line_split
crh.rs
//! Port configuration register high use rt; /// Reset value pub const DEFAULT: Register = Register(0x4444_4444); /// Register #[derive(Clone, Copy)] #[repr(C)] pub struct
(u32); impl Register { /// Sets `pin` configuration pub fn cnf(&mut self, pin: u32, state: u32) -> &mut Self { match (state, pin) { (0b00...0b11, 8...15) => { const MASK: u32 = 0b11; let offset = 4 * (pin - 8) + 2; self.0 &=!(MASK << offset); self.0 |= state << offset; } _ => rt::abort(), } self } /// Sets `pin` mode pub fn mode(&mut self, pin: u32, state: u32) -> &mut Self { match (state, pin) { (0b00...0b11, 8...15) => { const MASK: u32 = 0b11; let offset = 4 * (pin - 8); self.0 &=!(MASK << offset); self.0 |= state << offset; } _ => rt::abort(), } self } }
Register
identifier_name
rpc.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 https://mozilla.org/MPL/2.0/. */
use app_units::Au; use euclid::default::Rect; use script_traits::UntrustedNodeAddress; use servo_arc::Arc; use style::properties::ComputedValues; use webrender_api::ExternalScrollId; /// Synchronous messages that script can send to layout. /// /// In general, you should use messages to talk to Layout. Use the RPC interface /// if and only if the work is /// /// 1) read-only with respect to LayoutThreadData, /// 2) small, /// 3) and really needs to be fast. pub trait LayoutRPC { /// Requests the dimensions of the content box, as in the `getBoundingClientRect()` call. fn content_box(&self) -> ContentBoxResponse; /// Requests the dimensions of all the content boxes, as in the `getClientRects()` call. fn content_boxes(&self) -> ContentBoxesResponse; /// Requests the geometry of this node. Used by APIs such as `clientTop`. fn node_geometry(&self) -> NodeGeometryResponse; /// Requests the scroll geometry of this node. Used by APIs such as `scrollTop`. fn node_scroll_area(&self) -> NodeGeometryResponse; /// Requests the scroll id of this node. Used by APIs such as `scrollTop` fn node_scroll_id(&self) -> NodeScrollIdResponse; /// Query layout for the resolved value of a given CSS property fn resolved_style(&self) -> ResolvedStyleResponse; fn offset_parent(&self) -> OffsetParentResponse; /// Requests the styles for an element. Contains a `None` value if the element is in a `display: /// none` subtree. fn style(&self) -> StyleResponse; fn text_index(&self) -> TextIndexResponse; /// Requests the list of nodes from the given point. fn nodes_from_point_response(&self) -> Vec<UntrustedNodeAddress>; /// Query layout to get the inner text for a given element. fn element_inner_text(&self) -> String; } pub struct ContentBoxResponse(pub Option<Rect<Au>>); pub struct ContentBoxesResponse(pub Vec<Rect<Au>>); pub struct NodeGeometryResponse { pub client_rect: Rect<i32>, } pub struct NodeScrollIdResponse(pub ExternalScrollId); pub struct ResolvedStyleResponse(pub String); #[derive(Clone)] pub struct OffsetParentResponse { pub node_address: Option<UntrustedNodeAddress>, pub rect: Rect<Au>, } impl OffsetParentResponse { pub fn empty() -> OffsetParentResponse { OffsetParentResponse { node_address: None, rect: Rect::zero(), } } } #[derive(Clone)] pub struct StyleResponse(pub Option<Arc<ComputedValues>>); #[derive(Clone)] pub struct TextIndexResponse(pub Option<usize>);
random_line_split
rpc.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 https://mozilla.org/MPL/2.0/. */ use app_units::Au; use euclid::default::Rect; use script_traits::UntrustedNodeAddress; use servo_arc::Arc; use style::properties::ComputedValues; use webrender_api::ExternalScrollId; /// Synchronous messages that script can send to layout. /// /// In general, you should use messages to talk to Layout. Use the RPC interface /// if and only if the work is /// /// 1) read-only with respect to LayoutThreadData, /// 2) small, /// 3) and really needs to be fast. pub trait LayoutRPC { /// Requests the dimensions of the content box, as in the `getBoundingClientRect()` call. fn content_box(&self) -> ContentBoxResponse; /// Requests the dimensions of all the content boxes, as in the `getClientRects()` call. fn content_boxes(&self) -> ContentBoxesResponse; /// Requests the geometry of this node. Used by APIs such as `clientTop`. fn node_geometry(&self) -> NodeGeometryResponse; /// Requests the scroll geometry of this node. Used by APIs such as `scrollTop`. fn node_scroll_area(&self) -> NodeGeometryResponse; /// Requests the scroll id of this node. Used by APIs such as `scrollTop` fn node_scroll_id(&self) -> NodeScrollIdResponse; /// Query layout for the resolved value of a given CSS property fn resolved_style(&self) -> ResolvedStyleResponse; fn offset_parent(&self) -> OffsetParentResponse; /// Requests the styles for an element. Contains a `None` value if the element is in a `display: /// none` subtree. fn style(&self) -> StyleResponse; fn text_index(&self) -> TextIndexResponse; /// Requests the list of nodes from the given point. fn nodes_from_point_response(&self) -> Vec<UntrustedNodeAddress>; /// Query layout to get the inner text for a given element. fn element_inner_text(&self) -> String; } pub struct ContentBoxResponse(pub Option<Rect<Au>>); pub struct ContentBoxesResponse(pub Vec<Rect<Au>>); pub struct NodeGeometryResponse { pub client_rect: Rect<i32>, } pub struct NodeScrollIdResponse(pub ExternalScrollId); pub struct ResolvedStyleResponse(pub String); #[derive(Clone)] pub struct
{ pub node_address: Option<UntrustedNodeAddress>, pub rect: Rect<Au>, } impl OffsetParentResponse { pub fn empty() -> OffsetParentResponse { OffsetParentResponse { node_address: None, rect: Rect::zero(), } } } #[derive(Clone)] pub struct StyleResponse(pub Option<Arc<ComputedValues>>); #[derive(Clone)] pub struct TextIndexResponse(pub Option<usize>);
OffsetParentResponse
identifier_name
console.rs
use crate::cache; use calx::split_line; use euclid::default::{Point2D, Rect}; use std::io; use std::io::prelude::*; use std::mem; use std::str; use std::sync::Arc; use vitral::{color, Align, Canvas, FontData, Rgba}; struct Message { expire_time_s: f64, text: String, } impl Message { fn new(text: String, time_start_s: f64) -> Message { const TIME_TO_READ_CHAR_S: f64 = 0.1; let expire_time_s = time_start_s + text.len() as f64 * TIME_TO_READ_CHAR_S; Message { expire_time_s, text, } } } /// Output text container. pub struct Console { font: Arc<FontData>, lines: Vec<Message>, input_buffer: String, output_buffer: String, done_reading_s: f64, } impl Default for Console { fn default() -> Self { Console { font: cache::font(), lines: Vec::new(), input_buffer: String::new(), output_buffer: String::new(), done_reading_s: 0.0, } } } impl Console { /// Draw the console as a regular message display. pub fn draw_small(&mut self, canvas: &mut Canvas, screen_area: &Rect<i32>) { let t = calx::precise_time_s(); let mut lines = Vec::new(); // The log can be very long, and we're always most interested in the latest ones, so // do a backwards iteration with an early exist once we hit a sufficiently old item. for msg in self.lines.iter().rev().take_while(|m| m.expire_time_s > t) { // The split_line iterator can't be reversed, need to do a bit of caching here. lines.extend( split_line( &msg.text, |c| self.font.char_width(c).unwrap_or(0), screen_area.size.width, ) .map(|x| x.to_string()), ); } // Draw the lines let mut pos = screen_area.origin; for line in lines.iter().rev() { pos = canvas.draw_text(&*self.font, pos, Align::Left, color::WHITE.alpha(0.4), line); } } /// Draw the console as a big drop-down with a command prompt. pub fn draw_large(&mut self, canvas: &mut Canvas, screen_area: &Rect<i32>) { // TODO: Store color in draw context. let color = Rgba::from([0.6, 0.6, 0.6]); let background = Rgba::from([0.0, 0.0, 0.6, 0.8]); canvas.fill_rect(screen_area, background); let h = self.font.height; let mut lines_left = (screen_area.size.height + h - 1) / h; let mut y = screen_area.max_y() - h; // TODO: Handle enter with text input. // TODO: Command history. // TODO /* canvas .bound(0, y as u32, screen_area.size.width as u32, h as u32) .text_input(color, &mut self.input_buffer); */ y -= h; lines_left -= 1; for msg in self.lines.iter().rev() { // XXX: Duplicated from draw_small. let fragments = split_line( &msg.text,
.collect::<Vec<String>>(); for line in fragments.iter().rev() { canvas.draw_text(&*self.font, Point2D::new(0, y), Align::Left, color, line); y -= h; lines_left -= 1; } if lines_left <= 0 { break; } } } fn end_message(&mut self) { let mut message_text = String::new(); mem::swap(&mut message_text, &mut self.output_buffer); let now = calx::precise_time_s(); if now > self.done_reading_s { self.done_reading_s = now; } let message = Message::new(message_text, now); self.done_reading_s = message.expire_time_s; self.lines.push(message); } pub fn get_input(&mut self) -> String { let mut ret = String::new(); mem::swap(&mut ret, &mut self.input_buffer); ret } } impl Write for Console { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let s = str::from_utf8(buf).expect("Wrote non-UTF-8 to Console"); let mut lines = s.split('\n'); if let Some(line) = lines.next() { self.output_buffer.push_str(line); } for line in lines { self.end_message(); self.output_buffer.push_str(line); } Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
|c| self.font.char_width(c).unwrap_or(0), screen_area.size.width, ) .map(|x| x.to_string())
random_line_split
console.rs
use crate::cache; use calx::split_line; use euclid::default::{Point2D, Rect}; use std::io; use std::io::prelude::*; use std::mem; use std::str; use std::sync::Arc; use vitral::{color, Align, Canvas, FontData, Rgba}; struct Message { expire_time_s: f64, text: String, } impl Message { fn new(text: String, time_start_s: f64) -> Message { const TIME_TO_READ_CHAR_S: f64 = 0.1; let expire_time_s = time_start_s + text.len() as f64 * TIME_TO_READ_CHAR_S; Message { expire_time_s, text, } } } /// Output text container. pub struct Console { font: Arc<FontData>, lines: Vec<Message>, input_buffer: String, output_buffer: String, done_reading_s: f64, } impl Default for Console { fn default() -> Self { Console { font: cache::font(), lines: Vec::new(), input_buffer: String::new(), output_buffer: String::new(), done_reading_s: 0.0, } } } impl Console { /// Draw the console as a regular message display. pub fn draw_small(&mut self, canvas: &mut Canvas, screen_area: &Rect<i32>) { let t = calx::precise_time_s(); let mut lines = Vec::new(); // The log can be very long, and we're always most interested in the latest ones, so // do a backwards iteration with an early exist once we hit a sufficiently old item. for msg in self.lines.iter().rev().take_while(|m| m.expire_time_s > t) { // The split_line iterator can't be reversed, need to do a bit of caching here. lines.extend( split_line( &msg.text, |c| self.font.char_width(c).unwrap_or(0), screen_area.size.width, ) .map(|x| x.to_string()), ); } // Draw the lines let mut pos = screen_area.origin; for line in lines.iter().rev() { pos = canvas.draw_text(&*self.font, pos, Align::Left, color::WHITE.alpha(0.4), line); } } /// Draw the console as a big drop-down with a command prompt. pub fn draw_large(&mut self, canvas: &mut Canvas, screen_area: &Rect<i32>) { // TODO: Store color in draw context. let color = Rgba::from([0.6, 0.6, 0.6]); let background = Rgba::from([0.0, 0.0, 0.6, 0.8]); canvas.fill_rect(screen_area, background); let h = self.font.height; let mut lines_left = (screen_area.size.height + h - 1) / h; let mut y = screen_area.max_y() - h; // TODO: Handle enter with text input. // TODO: Command history. // TODO /* canvas .bound(0, y as u32, screen_area.size.width as u32, h as u32) .text_input(color, &mut self.input_buffer); */ y -= h; lines_left -= 1; for msg in self.lines.iter().rev() { // XXX: Duplicated from draw_small. let fragments = split_line( &msg.text, |c| self.font.char_width(c).unwrap_or(0), screen_area.size.width, ) .map(|x| x.to_string()) .collect::<Vec<String>>(); for line in fragments.iter().rev() { canvas.draw_text(&*self.font, Point2D::new(0, y), Align::Left, color, line); y -= h; lines_left -= 1; } if lines_left <= 0 { break; } } } fn end_message(&mut self) { let mut message_text = String::new(); mem::swap(&mut message_text, &mut self.output_buffer); let now = calx::precise_time_s(); if now > self.done_reading_s
let message = Message::new(message_text, now); self.done_reading_s = message.expire_time_s; self.lines.push(message); } pub fn get_input(&mut self) -> String { let mut ret = String::new(); mem::swap(&mut ret, &mut self.input_buffer); ret } } impl Write for Console { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let s = str::from_utf8(buf).expect("Wrote non-UTF-8 to Console"); let mut lines = s.split('\n'); if let Some(line) = lines.next() { self.output_buffer.push_str(line); } for line in lines { self.end_message(); self.output_buffer.push_str(line); } Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
{ self.done_reading_s = now; }
conditional_block
console.rs
use crate::cache; use calx::split_line; use euclid::default::{Point2D, Rect}; use std::io; use std::io::prelude::*; use std::mem; use std::str; use std::sync::Arc; use vitral::{color, Align, Canvas, FontData, Rgba}; struct Message { expire_time_s: f64, text: String, } impl Message { fn new(text: String, time_start_s: f64) -> Message { const TIME_TO_READ_CHAR_S: f64 = 0.1; let expire_time_s = time_start_s + text.len() as f64 * TIME_TO_READ_CHAR_S; Message { expire_time_s, text, } } } /// Output text container. pub struct Console { font: Arc<FontData>, lines: Vec<Message>, input_buffer: String, output_buffer: String, done_reading_s: f64, } impl Default for Console { fn default() -> Self { Console { font: cache::font(), lines: Vec::new(), input_buffer: String::new(), output_buffer: String::new(), done_reading_s: 0.0, } } } impl Console { /// Draw the console as a regular message display. pub fn draw_small(&mut self, canvas: &mut Canvas, screen_area: &Rect<i32>) { let t = calx::precise_time_s(); let mut lines = Vec::new(); // The log can be very long, and we're always most interested in the latest ones, so // do a backwards iteration with an early exist once we hit a sufficiently old item. for msg in self.lines.iter().rev().take_while(|m| m.expire_time_s > t) { // The split_line iterator can't be reversed, need to do a bit of caching here. lines.extend( split_line( &msg.text, |c| self.font.char_width(c).unwrap_or(0), screen_area.size.width, ) .map(|x| x.to_string()), ); } // Draw the lines let mut pos = screen_area.origin; for line in lines.iter().rev() { pos = canvas.draw_text(&*self.font, pos, Align::Left, color::WHITE.alpha(0.4), line); } } /// Draw the console as a big drop-down with a command prompt. pub fn draw_large(&mut self, canvas: &mut Canvas, screen_area: &Rect<i32>) { // TODO: Store color in draw context. let color = Rgba::from([0.6, 0.6, 0.6]); let background = Rgba::from([0.0, 0.0, 0.6, 0.8]); canvas.fill_rect(screen_area, background); let h = self.font.height; let mut lines_left = (screen_area.size.height + h - 1) / h; let mut y = screen_area.max_y() - h; // TODO: Handle enter with text input. // TODO: Command history. // TODO /* canvas .bound(0, y as u32, screen_area.size.width as u32, h as u32) .text_input(color, &mut self.input_buffer); */ y -= h; lines_left -= 1; for msg in self.lines.iter().rev() { // XXX: Duplicated from draw_small. let fragments = split_line( &msg.text, |c| self.font.char_width(c).unwrap_or(0), screen_area.size.width, ) .map(|x| x.to_string()) .collect::<Vec<String>>(); for line in fragments.iter().rev() { canvas.draw_text(&*self.font, Point2D::new(0, y), Align::Left, color, line); y -= h; lines_left -= 1; } if lines_left <= 0 { break; } } } fn
(&mut self) { let mut message_text = String::new(); mem::swap(&mut message_text, &mut self.output_buffer); let now = calx::precise_time_s(); if now > self.done_reading_s { self.done_reading_s = now; } let message = Message::new(message_text, now); self.done_reading_s = message.expire_time_s; self.lines.push(message); } pub fn get_input(&mut self) -> String { let mut ret = String::new(); mem::swap(&mut ret, &mut self.input_buffer); ret } } impl Write for Console { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let s = str::from_utf8(buf).expect("Wrote non-UTF-8 to Console"); let mut lines = s.split('\n'); if let Some(line) = lines.next() { self.output_buffer.push_str(line); } for line in lines { self.end_message(); self.output_buffer.push_str(line); } Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
end_message
identifier_name
console.rs
use crate::cache; use calx::split_line; use euclid::default::{Point2D, Rect}; use std::io; use std::io::prelude::*; use std::mem; use std::str; use std::sync::Arc; use vitral::{color, Align, Canvas, FontData, Rgba}; struct Message { expire_time_s: f64, text: String, } impl Message { fn new(text: String, time_start_s: f64) -> Message { const TIME_TO_READ_CHAR_S: f64 = 0.1; let expire_time_s = time_start_s + text.len() as f64 * TIME_TO_READ_CHAR_S; Message { expire_time_s, text, } } } /// Output text container. pub struct Console { font: Arc<FontData>, lines: Vec<Message>, input_buffer: String, output_buffer: String, done_reading_s: f64, } impl Default for Console { fn default() -> Self { Console { font: cache::font(), lines: Vec::new(), input_buffer: String::new(), output_buffer: String::new(), done_reading_s: 0.0, } } } impl Console { /// Draw the console as a regular message display. pub fn draw_small(&mut self, canvas: &mut Canvas, screen_area: &Rect<i32>) { let t = calx::precise_time_s(); let mut lines = Vec::new(); // The log can be very long, and we're always most interested in the latest ones, so // do a backwards iteration with an early exist once we hit a sufficiently old item. for msg in self.lines.iter().rev().take_while(|m| m.expire_time_s > t) { // The split_line iterator can't be reversed, need to do a bit of caching here. lines.extend( split_line( &msg.text, |c| self.font.char_width(c).unwrap_or(0), screen_area.size.width, ) .map(|x| x.to_string()), ); } // Draw the lines let mut pos = screen_area.origin; for line in lines.iter().rev() { pos = canvas.draw_text(&*self.font, pos, Align::Left, color::WHITE.alpha(0.4), line); } } /// Draw the console as a big drop-down with a command prompt. pub fn draw_large(&mut self, canvas: &mut Canvas, screen_area: &Rect<i32>) { // TODO: Store color in draw context. let color = Rgba::from([0.6, 0.6, 0.6]); let background = Rgba::from([0.0, 0.0, 0.6, 0.8]); canvas.fill_rect(screen_area, background); let h = self.font.height; let mut lines_left = (screen_area.size.height + h - 1) / h; let mut y = screen_area.max_y() - h; // TODO: Handle enter with text input. // TODO: Command history. // TODO /* canvas .bound(0, y as u32, screen_area.size.width as u32, h as u32) .text_input(color, &mut self.input_buffer); */ y -= h; lines_left -= 1; for msg in self.lines.iter().rev() { // XXX: Duplicated from draw_small. let fragments = split_line( &msg.text, |c| self.font.char_width(c).unwrap_or(0), screen_area.size.width, ) .map(|x| x.to_string()) .collect::<Vec<String>>(); for line in fragments.iter().rev() { canvas.draw_text(&*self.font, Point2D::new(0, y), Align::Left, color, line); y -= h; lines_left -= 1; } if lines_left <= 0 { break; } } } fn end_message(&mut self) { let mut message_text = String::new(); mem::swap(&mut message_text, &mut self.output_buffer); let now = calx::precise_time_s(); if now > self.done_reading_s { self.done_reading_s = now; } let message = Message::new(message_text, now); self.done_reading_s = message.expire_time_s; self.lines.push(message); } pub fn get_input(&mut self) -> String { let mut ret = String::new(); mem::swap(&mut ret, &mut self.input_buffer); ret } } impl Write for Console { fn write(&mut self, buf: &[u8]) -> io::Result<usize>
fn flush(&mut self) -> io::Result<()> { Ok(()) } }
{ let s = str::from_utf8(buf).expect("Wrote non-UTF-8 to Console"); let mut lines = s.split('\n'); if let Some(line) = lines.next() { self.output_buffer.push_str(line); } for line in lines { self.end_message(); self.output_buffer.push_str(line); } Ok(buf.len()) }
identifier_body
main.rs
// Copyright (c) 2013 John Grosen // Licensed under the terms described in the LICENSE file in the root of this repository #[allow(ctypes)]; #[no_std]; #[no_core]; use vga; use term; use util; #[no_mangle] pub fn memset()
fn wait() { do util::range(0, 1<<28) |_| { unsafe { asm!("nop"); } } } #[no_mangle] pub fn kernel_main() { let mut term = &vga::VgaTerm::new(vga::White, vga::LightRed, true) as &term::Terminal; term.put_string("1\n2\n3\n4\n5\n"); term.put_string("6\n7\n8\n9\n10\n"); term.put_string("11\n12\n13\n14\n15\n"); term.put_string("16\n17\n18\n19\n20\n"); term.put_string("21\n22\n23\n24\n25\n"); term.put_string("26\n27\n28\n29\n30\n"); wait(); let mut foo = &vga::VgaTerm::new(vga::Black, vga::White, false) as &term::Terminal; foo.put_string("hi there\n"); term.put_string("gasp"); wait(); term.set_displaying(false); term.put_string("\n:O :O"); foo.set_displaying(true); wait(); foo.set_displaying(false); term.put_string("\n;D"); term.set_displaying(true); loop {} }
{}
identifier_body
main.rs
// Copyright (c) 2013 John Grosen // Licensed under the terms described in the LICENSE file in the root of this repository #[allow(ctypes)]; #[no_std]; #[no_core]; use vga; use term; use util; #[no_mangle] pub fn
() {} fn wait() { do util::range(0, 1<<28) |_| { unsafe { asm!("nop"); } } } #[no_mangle] pub fn kernel_main() { let mut term = &vga::VgaTerm::new(vga::White, vga::LightRed, true) as &term::Terminal; term.put_string("1\n2\n3\n4\n5\n"); term.put_string("6\n7\n8\n9\n10\n"); term.put_string("11\n12\n13\n14\n15\n"); term.put_string("16\n17\n18\n19\n20\n"); term.put_string("21\n22\n23\n24\n25\n"); term.put_string("26\n27\n28\n29\n30\n"); wait(); let mut foo = &vga::VgaTerm::new(vga::Black, vga::White, false) as &term::Terminal; foo.put_string("hi there\n"); term.put_string("gasp"); wait(); term.set_displaying(false); term.put_string("\n:O :O"); foo.set_displaying(true); wait(); foo.set_displaying(false); term.put_string("\n;D"); term.set_displaying(true); loop {} }
memset
identifier_name
main.rs
// Copyright (c) 2013 John Grosen // Licensed under the terms described in the LICENSE file in the root of this repository #[allow(ctypes)]; #[no_std]; #[no_core]; use vga; use term; use util; #[no_mangle] pub fn memset() {} fn wait() { do util::range(0, 1<<28) |_| { unsafe { asm!("nop"); } } } #[no_mangle] pub fn kernel_main() { let mut term = &vga::VgaTerm::new(vga::White, vga::LightRed, true) as &term::Terminal; term.put_string("1\n2\n3\n4\n5\n"); term.put_string("6\n7\n8\n9\n10\n"); term.put_string("11\n12\n13\n14\n15\n"); term.put_string("16\n17\n18\n19\n20\n"); term.put_string("21\n22\n23\n24\n25\n"); term.put_string("26\n27\n28\n29\n30\n"); wait(); let mut foo = &vga::VgaTerm::new(vga::Black, vga::White, false) as &term::Terminal;
term.put_string("\n:O :O"); foo.set_displaying(true); wait(); foo.set_displaying(false); term.put_string("\n;D"); term.set_displaying(true); loop {} }
foo.put_string("hi there\n"); term.put_string("gasp"); wait(); term.set_displaying(false);
random_line_split
echo.rs
//! An "hello world" echo server with tokio-core //! //! This server will create a TCP listener, accept connections in a loop, and //! simply write back everything that's read off of each TCP connection. Each //! TCP connection is processed concurrently with all other TCP connections, and //! each connection will have its own buffer that it's reading in/out of. //! //! To see this server in action, you can run this in one terminal: //! //! cargo run --example echo //! //! and in another terminal you can run: //! //! cargo run --example connect 127.0.0.1:8080 //! //! Each line you type in to the `connect` terminal should be echo'd back to //! you! If you open up multiple terminals running the `connect` example you //! should be able to see them all make progress simultaneously. extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate kcp; use std::env; use std::net::SocketAddr; use futures::Future; use futures::stream::Stream;
fn main() { // Allow passing an address to listen on as the first argument of this // program, but otherwise we'll just set up our TCP listener on // 127.0.0.1:8080 for connections. let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); let addr = addr.parse::<SocketAddr>().unwrap(); // First up we'll create the event loop that's going to drive this server. // This is done by creating an instance of the `Core` type, tokio-core's // event loop. Most functions in tokio-core return an `io::Result`, and // `Core::new` is no exception. For this example, though, we're mostly just // ignoring errors, so we unwrap the return value. // // After the event loop is created we acquire a handle to it through the // `handle` method. With this handle we'll then later be able to create I/O // objects and spawn futures. let mut core = Core::new().unwrap(); let handle = core.handle(); // Next up we create a TCP listener which will listen for incoming // connections. This TCP listener is bound to the address we determined // above and must be associated with an event loop, so we pass in a handle // to our event loop. After the socket's created we inform that we're ready // to go and start accepting connections. let socket = KcpListener::bind(&addr, &handle).unwrap(); println!("Listening on: {}", addr); // Here we convert the `TcpListener` to a stream of incoming connections // with the `incoming` method. We then define how to process each element in // the stream with the `for_each` method. // // This combinator, defined on the `Stream` trait, will allow us to define a // computation to happen for all items on the stream (in this case TCP // connections made to the server). The return value of the `for_each` // method is itself a future representing processing the entire stream of // connections, and ends up being our server. let done = socket.incoming().for_each(move |(socket, addr)| { // Once we're inside this closure this represents an accepted client // from our server. The `socket` is the client connection and `addr` is // the remote address of the client (similar to how the standard library // operates). // // We just want to copy all data read from the socket back onto the // socket itself (e.g. "echo"). We can use the standard `io::copy` // combinator in the `tokio-core` crate to do precisely this! // // The `copy` function takes two arguments, where to read from and where // to write to. We only have one argument, though, with `socket`. // Luckily there's a method, `Io::split`, which will split an Read/Write // stream into its two halves. This operation allows us to work with // each stream independently, such as pass them as two arguments to the // `copy` function. // // The `copy` function then returns a future, and this future will be // resolved when the copying operation is complete, resolving to the // amount of data that was copied. let (reader, writer) = socket.split(); let amt = copy(reader, writer); // After our copy operation is complete we just print out some helpful // information. let msg = amt.then(move |result| { match result { Ok((amt, _, _)) => println!("wrote {} bytes to {}", amt, addr), Err(e) => println!("error on {}: {}", addr, e), } Ok(()) }); // And this is where much of the magic of this server happens. We // crucially want all clients to make progress concurrently, rather than // blocking one on completion of another. To achieve this we use the // `spawn` function on `Handle` to essentially execute some work in the // background. // // This function will transfer ownership of the future (`msg` in this // case) to the event loop that `handle` points to. The event loop will // then drive the future to completion. // // Essentially here we're spawning a new task to run concurrently, which // will allow all of our clients to be processed concurrently. handle.spawn(msg); Ok(()) }); // And finally now that we've define what our server is, we run it! We // didn't actually do much I/O up to this point and this `Core::run` method // is responsible for driving the entire server to completion. // // The `run` method will return the result of the future that it's running, // but in our case the `done` future won't ever finish because a TCP // listener is never done accepting clients. That basically just means that // we're going to be running the server until it's killed (e.g. ctrl-c). core.run(done).unwrap(); }
use tokio_io::AsyncRead; use tokio_io::io::copy; use tokio_core::reactor::Core; use kcp::KcpListener;
random_line_split
echo.rs
//! An "hello world" echo server with tokio-core //! //! This server will create a TCP listener, accept connections in a loop, and //! simply write back everything that's read off of each TCP connection. Each //! TCP connection is processed concurrently with all other TCP connections, and //! each connection will have its own buffer that it's reading in/out of. //! //! To see this server in action, you can run this in one terminal: //! //! cargo run --example echo //! //! and in another terminal you can run: //! //! cargo run --example connect 127.0.0.1:8080 //! //! Each line you type in to the `connect` terminal should be echo'd back to //! you! If you open up multiple terminals running the `connect` example you //! should be able to see them all make progress simultaneously. extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate kcp; use std::env; use std::net::SocketAddr; use futures::Future; use futures::stream::Stream; use tokio_io::AsyncRead; use tokio_io::io::copy; use tokio_core::reactor::Core; use kcp::KcpListener; fn
() { // Allow passing an address to listen on as the first argument of this // program, but otherwise we'll just set up our TCP listener on // 127.0.0.1:8080 for connections. let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); let addr = addr.parse::<SocketAddr>().unwrap(); // First up we'll create the event loop that's going to drive this server. // This is done by creating an instance of the `Core` type, tokio-core's // event loop. Most functions in tokio-core return an `io::Result`, and // `Core::new` is no exception. For this example, though, we're mostly just // ignoring errors, so we unwrap the return value. // // After the event loop is created we acquire a handle to it through the // `handle` method. With this handle we'll then later be able to create I/O // objects and spawn futures. let mut core = Core::new().unwrap(); let handle = core.handle(); // Next up we create a TCP listener which will listen for incoming // connections. This TCP listener is bound to the address we determined // above and must be associated with an event loop, so we pass in a handle // to our event loop. After the socket's created we inform that we're ready // to go and start accepting connections. let socket = KcpListener::bind(&addr, &handle).unwrap(); println!("Listening on: {}", addr); // Here we convert the `TcpListener` to a stream of incoming connections // with the `incoming` method. We then define how to process each element in // the stream with the `for_each` method. // // This combinator, defined on the `Stream` trait, will allow us to define a // computation to happen for all items on the stream (in this case TCP // connections made to the server). The return value of the `for_each` // method is itself a future representing processing the entire stream of // connections, and ends up being our server. let done = socket.incoming().for_each(move |(socket, addr)| { // Once we're inside this closure this represents an accepted client // from our server. The `socket` is the client connection and `addr` is // the remote address of the client (similar to how the standard library // operates). // // We just want to copy all data read from the socket back onto the // socket itself (e.g. "echo"). We can use the standard `io::copy` // combinator in the `tokio-core` crate to do precisely this! // // The `copy` function takes two arguments, where to read from and where // to write to. We only have one argument, though, with `socket`. // Luckily there's a method, `Io::split`, which will split an Read/Write // stream into its two halves. This operation allows us to work with // each stream independently, such as pass them as two arguments to the // `copy` function. // // The `copy` function then returns a future, and this future will be // resolved when the copying operation is complete, resolving to the // amount of data that was copied. let (reader, writer) = socket.split(); let amt = copy(reader, writer); // After our copy operation is complete we just print out some helpful // information. let msg = amt.then(move |result| { match result { Ok((amt, _, _)) => println!("wrote {} bytes to {}", amt, addr), Err(e) => println!("error on {}: {}", addr, e), } Ok(()) }); // And this is where much of the magic of this server happens. We // crucially want all clients to make progress concurrently, rather than // blocking one on completion of another. To achieve this we use the // `spawn` function on `Handle` to essentially execute some work in the // background. // // This function will transfer ownership of the future (`msg` in this // case) to the event loop that `handle` points to. The event loop will // then drive the future to completion. // // Essentially here we're spawning a new task to run concurrently, which // will allow all of our clients to be processed concurrently. handle.spawn(msg); Ok(()) }); // And finally now that we've define what our server is, we run it! We // didn't actually do much I/O up to this point and this `Core::run` method // is responsible for driving the entire server to completion. // // The `run` method will return the result of the future that it's running, // but in our case the `done` future won't ever finish because a TCP // listener is never done accepting clients. That basically just means that // we're going to be running the server until it's killed (e.g. ctrl-c). core.run(done).unwrap(); }
main
identifier_name
echo.rs
//! An "hello world" echo server with tokio-core //! //! This server will create a TCP listener, accept connections in a loop, and //! simply write back everything that's read off of each TCP connection. Each //! TCP connection is processed concurrently with all other TCP connections, and //! each connection will have its own buffer that it's reading in/out of. //! //! To see this server in action, you can run this in one terminal: //! //! cargo run --example echo //! //! and in another terminal you can run: //! //! cargo run --example connect 127.0.0.1:8080 //! //! Each line you type in to the `connect` terminal should be echo'd back to //! you! If you open up multiple terminals running the `connect` example you //! should be able to see them all make progress simultaneously. extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate kcp; use std::env; use std::net::SocketAddr; use futures::Future; use futures::stream::Stream; use tokio_io::AsyncRead; use tokio_io::io::copy; use tokio_core::reactor::Core; use kcp::KcpListener; fn main()
// connections. This TCP listener is bound to the address we determined // above and must be associated with an event loop, so we pass in a handle // to our event loop. After the socket's created we inform that we're ready // to go and start accepting connections. let socket = KcpListener::bind(&addr, &handle).unwrap(); println!("Listening on: {}", addr); // Here we convert the `TcpListener` to a stream of incoming connections // with the `incoming` method. We then define how to process each element in // the stream with the `for_each` method. // // This combinator, defined on the `Stream` trait, will allow us to define a // computation to happen for all items on the stream (in this case TCP // connections made to the server). The return value of the `for_each` // method is itself a future representing processing the entire stream of // connections, and ends up being our server. let done = socket.incoming().for_each(move |(socket, addr)| { // Once we're inside this closure this represents an accepted client // from our server. The `socket` is the client connection and `addr` is // the remote address of the client (similar to how the standard library // operates). // // We just want to copy all data read from the socket back onto the // socket itself (e.g. "echo"). We can use the standard `io::copy` // combinator in the `tokio-core` crate to do precisely this! // // The `copy` function takes two arguments, where to read from and where // to write to. We only have one argument, though, with `socket`. // Luckily there's a method, `Io::split`, which will split an Read/Write // stream into its two halves. This operation allows us to work with // each stream independently, such as pass them as two arguments to the // `copy` function. // // The `copy` function then returns a future, and this future will be // resolved when the copying operation is complete, resolving to the // amount of data that was copied. let (reader, writer) = socket.split(); let amt = copy(reader, writer); // After our copy operation is complete we just print out some helpful // information. let msg = amt.then(move |result| { match result { Ok((amt, _, _)) => println!("wrote {} bytes to {}", amt, addr), Err(e) => println!("error on {}: {}", addr, e), } Ok(()) }); // And this is where much of the magic of this server happens. We // crucially want all clients to make progress concurrently, rather than // blocking one on completion of another. To achieve this we use the // `spawn` function on `Handle` to essentially execute some work in the // background. // // This function will transfer ownership of the future (`msg` in this // case) to the event loop that `handle` points to. The event loop will // then drive the future to completion. // // Essentially here we're spawning a new task to run concurrently, which // will allow all of our clients to be processed concurrently. handle.spawn(msg); Ok(()) }); // And finally now that we've define what our server is, we run it! We // didn't actually do much I/O up to this point and this `Core::run` method // is responsible for driving the entire server to completion. // // The `run` method will return the result of the future that it's running, // but in our case the `done` future won't ever finish because a TCP // listener is never done accepting clients. That basically just means that // we're going to be running the server until it's killed (e.g. ctrl-c). core.run(done).unwrap(); }
{ // Allow passing an address to listen on as the first argument of this // program, but otherwise we'll just set up our TCP listener on // 127.0.0.1:8080 for connections. let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); let addr = addr.parse::<SocketAddr>().unwrap(); // First up we'll create the event loop that's going to drive this server. // This is done by creating an instance of the `Core` type, tokio-core's // event loop. Most functions in tokio-core return an `io::Result`, and // `Core::new` is no exception. For this example, though, we're mostly just // ignoring errors, so we unwrap the return value. // // After the event loop is created we acquire a handle to it through the // `handle` method. With this handle we'll then later be able to create I/O // objects and spawn futures. let mut core = Core::new().unwrap(); let handle = core.handle(); // Next up we create a TCP listener which will listen for incoming
identifier_body
context.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/. */ //! Data needed by the layout task. #![deny(unsafe_code)] use canvas_traits::CanvasMsg; use css::matching::{ApplicableDeclarationsCache, StyleSharingCandidateCache}; use euclid::{Rect, Size2D}; use fnv::FnvHasher; use gfx::display_list::OpaqueNode; use gfx::font_cache_task::FontCacheTask; use gfx::font_context::FontContext; use ipc_channel::ipc::{self, IpcSender}; use msg::compositor_msg::LayerId; use msg::constellation_msg::ConstellationChan; use net_traits::image::base::Image; use net_traits::image_cache_task::{ImageCacheChan, ImageCacheTask, ImageResponse, ImageState}; use net_traits::image_cache_task::{UsePlaceholder}; use script::layout_interface::{Animation, LayoutChan, ReflowGoal}; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::collections::hash_state::DefaultState; use std::rc::Rc; use std::sync::Arc; use std::sync::mpsc::{channel, Sender}; use style::selector_matching::Stylist; use url::Url; use util::geometry::Au; use util::mem::HeapSizeOf; use util::opts; struct LocalLayoutContext { font_context: RefCell<FontContext>, applicable_declarations_cache: RefCell<ApplicableDeclarationsCache>, style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache>, } impl HeapSizeOf for LocalLayoutContext { // FIXME(njn): measure other fields eventually. fn heap_size_of_children(&self) -> usize { self.font_context.heap_size_of_children() } } thread_local!(static LOCAL_CONTEXT_KEY: RefCell<Option<Rc<LocalLayoutContext>>> = RefCell::new(None)); pub fn heap_size_of_local_context() -> usize { LOCAL_CONTEXT_KEY.with(|r| { r.borrow().clone().map_or(0, |context| context.heap_size_of_children()) }) } fn create_or_get_local_context(shared_layout_context: &SharedLayoutContext) -> Rc<LocalLayoutContext> { LOCAL_CONTEXT_KEY.with(|r| { let mut r = r.borrow_mut(); if let Some(context) = r.clone() { if shared_layout_context.screen_size_changed { context.applicable_declarations_cache.borrow_mut().evict_all(); } context } else { let context = Rc::new(LocalLayoutContext { font_context: RefCell::new(FontContext::new(shared_layout_context.font_cache_task.clone())), applicable_declarations_cache: RefCell::new(ApplicableDeclarationsCache::new()), style_sharing_candidate_cache: RefCell::new(StyleSharingCandidateCache::new()), }); *r = Some(context.clone()); context } }) } /// Layout information shared among all workers. This must be thread-safe. pub struct SharedLayoutContext { /// The shared image cache task. pub image_cache_task: ImageCacheTask, /// A channel for the image cache to send responses to. pub image_cache_sender: ImageCacheChan, /// The current screen size. pub screen_size: Size2D<Au>, /// Screen sized changed? pub screen_size_changed: bool, /// A channel up to the constellation. pub constellation_chan: ConstellationChan, /// A channel up to the layout task. pub layout_chan: LayoutChan, /// Interface to the font cache task. pub font_cache_task: FontCacheTask, /// The CSS selector stylist. /// /// FIXME(#2604): Make this no longer an unsafe pointer once we have fast `RWArc`s. pub stylist: *const Stylist, /// The root node at which we're starting the layout. pub reflow_root: Option<OpaqueNode>, /// The URL. pub url: Url, /// Starts at zero, and increased by one every time a layout completes. /// This can be used to easily check for invalid stale data. pub generation: u32, /// A channel on which new animations that have been triggered by style recalculation can be /// sent. pub new_animations_sender: Sender<Animation>, /// A channel to send canvas renderers to paint task, in order to correctly paint the layers pub canvas_layers_sender: Sender<(LayerId, IpcSender<CanvasMsg>)>, /// The visible rects for each layer, as reported to us by the compositor. pub visible_rects: Arc<HashMap<LayerId, Rect<Au>, DefaultState<FnvHasher>>>, /// The animations that are currently running. pub running_animations: Arc<HashMap<OpaqueNode, Vec<Animation>>>, /// Why is this reflow occurring pub goal: ReflowGoal, } // FIXME(#6569) This implementations is unsound: // XXX UNSOUND!!! for image_cache_task // XXX UNSOUND!!! for image_cache_sender // XXX UNSOUND!!! for constellation_chan // XXX UNSOUND!!! for layout_chan // XXX UNSOUND!!! for font_cache_task // XXX UNSOUND!!! for stylist // XXX UNSOUND!!! for new_animations_sender // XXX UNSOUND!!! for canvas_layers_sender #[allow(unsafe_code)] unsafe impl Sync for SharedLayoutContext {} pub struct LayoutContext<'a> { pub shared: &'a SharedLayoutContext, cached_local_layout_context: Rc<LocalLayoutContext>, } impl<'a> LayoutContext<'a> { pub fn new(shared_layout_context: &'a SharedLayoutContext) -> LayoutContext<'a> { let local_context = create_or_get_local_context(shared_layout_context); LayoutContext { shared: shared_layout_context, cached_local_layout_context: local_context, } } #[inline(always)] pub fn font_context(&self) -> RefMut<FontContext> { self.cached_local_layout_context.font_context.borrow_mut() } #[inline(always)] pub fn applicable_declarations_cache(&self) -> RefMut<ApplicableDeclarationsCache>
#[inline(always)] pub fn style_sharing_candidate_cache(&self) -> RefMut<StyleSharingCandidateCache> { self.cached_local_layout_context.style_sharing_candidate_cache.borrow_mut() } pub fn get_or_request_image(&self, url: Url, use_placeholder: UsePlaceholder) -> Option<Arc<Image>> { // See if the image is already available let result = self.shared.image_cache_task.find_image(url.clone(), use_placeholder); match result { Ok(image) => Some(image), Err(state) => { // If we are emitting an output file, then we need to block on // image load or we risk emitting an output file missing the image. let is_sync = opts::get().output_file.is_some() || opts::get().exit_after_load; match (state, is_sync) { // Image failed to load, so just return nothing (ImageState::LoadError, _) => None, // Not loaded, test mode - load the image synchronously (_, true) => { let (sync_tx, sync_rx) = ipc::channel().unwrap(); self.shared.image_cache_task.request_image(url, ImageCacheChan(sync_tx), None); match sync_rx.recv().unwrap().image_response { ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => Some(image), ImageResponse::None => None, } } // Not yet requested, async mode - request image from the cache (ImageState::NotRequested, false) => { self.shared.image_cache_task .request_image(url, self.shared.image_cache_sender.clone(), None); None } // Image has been requested, is still pending. Return no image // for this paint loop. When the image loads it will trigger // a reflow and/or repaint. (ImageState::Pending, false) => None, } } } } }
{ self.cached_local_layout_context.applicable_declarations_cache.borrow_mut() }
identifier_body
context.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/. */ //! Data needed by the layout task. #![deny(unsafe_code)] use canvas_traits::CanvasMsg; use css::matching::{ApplicableDeclarationsCache, StyleSharingCandidateCache}; use euclid::{Rect, Size2D}; use fnv::FnvHasher; use gfx::display_list::OpaqueNode; use gfx::font_cache_task::FontCacheTask; use gfx::font_context::FontContext; use ipc_channel::ipc::{self, IpcSender}; use msg::compositor_msg::LayerId; use msg::constellation_msg::ConstellationChan; use net_traits::image::base::Image; use net_traits::image_cache_task::{ImageCacheChan, ImageCacheTask, ImageResponse, ImageState}; use net_traits::image_cache_task::{UsePlaceholder};
use script::layout_interface::{Animation, LayoutChan, ReflowGoal}; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::collections::hash_state::DefaultState; use std::rc::Rc; use std::sync::Arc; use std::sync::mpsc::{channel, Sender}; use style::selector_matching::Stylist; use url::Url; use util::geometry::Au; use util::mem::HeapSizeOf; use util::opts; struct LocalLayoutContext { font_context: RefCell<FontContext>, applicable_declarations_cache: RefCell<ApplicableDeclarationsCache>, style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache>, } impl HeapSizeOf for LocalLayoutContext { // FIXME(njn): measure other fields eventually. fn heap_size_of_children(&self) -> usize { self.font_context.heap_size_of_children() } } thread_local!(static LOCAL_CONTEXT_KEY: RefCell<Option<Rc<LocalLayoutContext>>> = RefCell::new(None)); pub fn heap_size_of_local_context() -> usize { LOCAL_CONTEXT_KEY.with(|r| { r.borrow().clone().map_or(0, |context| context.heap_size_of_children()) }) } fn create_or_get_local_context(shared_layout_context: &SharedLayoutContext) -> Rc<LocalLayoutContext> { LOCAL_CONTEXT_KEY.with(|r| { let mut r = r.borrow_mut(); if let Some(context) = r.clone() { if shared_layout_context.screen_size_changed { context.applicable_declarations_cache.borrow_mut().evict_all(); } context } else { let context = Rc::new(LocalLayoutContext { font_context: RefCell::new(FontContext::new(shared_layout_context.font_cache_task.clone())), applicable_declarations_cache: RefCell::new(ApplicableDeclarationsCache::new()), style_sharing_candidate_cache: RefCell::new(StyleSharingCandidateCache::new()), }); *r = Some(context.clone()); context } }) } /// Layout information shared among all workers. This must be thread-safe. pub struct SharedLayoutContext { /// The shared image cache task. pub image_cache_task: ImageCacheTask, /// A channel for the image cache to send responses to. pub image_cache_sender: ImageCacheChan, /// The current screen size. pub screen_size: Size2D<Au>, /// Screen sized changed? pub screen_size_changed: bool, /// A channel up to the constellation. pub constellation_chan: ConstellationChan, /// A channel up to the layout task. pub layout_chan: LayoutChan, /// Interface to the font cache task. pub font_cache_task: FontCacheTask, /// The CSS selector stylist. /// /// FIXME(#2604): Make this no longer an unsafe pointer once we have fast `RWArc`s. pub stylist: *const Stylist, /// The root node at which we're starting the layout. pub reflow_root: Option<OpaqueNode>, /// The URL. pub url: Url, /// Starts at zero, and increased by one every time a layout completes. /// This can be used to easily check for invalid stale data. pub generation: u32, /// A channel on which new animations that have been triggered by style recalculation can be /// sent. pub new_animations_sender: Sender<Animation>, /// A channel to send canvas renderers to paint task, in order to correctly paint the layers pub canvas_layers_sender: Sender<(LayerId, IpcSender<CanvasMsg>)>, /// The visible rects for each layer, as reported to us by the compositor. pub visible_rects: Arc<HashMap<LayerId, Rect<Au>, DefaultState<FnvHasher>>>, /// The animations that are currently running. pub running_animations: Arc<HashMap<OpaqueNode, Vec<Animation>>>, /// Why is this reflow occurring pub goal: ReflowGoal, } // FIXME(#6569) This implementations is unsound: // XXX UNSOUND!!! for image_cache_task // XXX UNSOUND!!! for image_cache_sender // XXX UNSOUND!!! for constellation_chan // XXX UNSOUND!!! for layout_chan // XXX UNSOUND!!! for font_cache_task // XXX UNSOUND!!! for stylist // XXX UNSOUND!!! for new_animations_sender // XXX UNSOUND!!! for canvas_layers_sender #[allow(unsafe_code)] unsafe impl Sync for SharedLayoutContext {} pub struct LayoutContext<'a> { pub shared: &'a SharedLayoutContext, cached_local_layout_context: Rc<LocalLayoutContext>, } impl<'a> LayoutContext<'a> { pub fn new(shared_layout_context: &'a SharedLayoutContext) -> LayoutContext<'a> { let local_context = create_or_get_local_context(shared_layout_context); LayoutContext { shared: shared_layout_context, cached_local_layout_context: local_context, } } #[inline(always)] pub fn font_context(&self) -> RefMut<FontContext> { self.cached_local_layout_context.font_context.borrow_mut() } #[inline(always)] pub fn applicable_declarations_cache(&self) -> RefMut<ApplicableDeclarationsCache> { self.cached_local_layout_context.applicable_declarations_cache.borrow_mut() } #[inline(always)] pub fn style_sharing_candidate_cache(&self) -> RefMut<StyleSharingCandidateCache> { self.cached_local_layout_context.style_sharing_candidate_cache.borrow_mut() } pub fn get_or_request_image(&self, url: Url, use_placeholder: UsePlaceholder) -> Option<Arc<Image>> { // See if the image is already available let result = self.shared.image_cache_task.find_image(url.clone(), use_placeholder); match result { Ok(image) => Some(image), Err(state) => { // If we are emitting an output file, then we need to block on // image load or we risk emitting an output file missing the image. let is_sync = opts::get().output_file.is_some() || opts::get().exit_after_load; match (state, is_sync) { // Image failed to load, so just return nothing (ImageState::LoadError, _) => None, // Not loaded, test mode - load the image synchronously (_, true) => { let (sync_tx, sync_rx) = ipc::channel().unwrap(); self.shared.image_cache_task.request_image(url, ImageCacheChan(sync_tx), None); match sync_rx.recv().unwrap().image_response { ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => Some(image), ImageResponse::None => None, } } // Not yet requested, async mode - request image from the cache (ImageState::NotRequested, false) => { self.shared.image_cache_task .request_image(url, self.shared.image_cache_sender.clone(), None); None } // Image has been requested, is still pending. Return no image // for this paint loop. When the image loads it will trigger // a reflow and/or repaint. (ImageState::Pending, false) => None, } } } } }
random_line_split
context.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/. */ //! Data needed by the layout task. #![deny(unsafe_code)] use canvas_traits::CanvasMsg; use css::matching::{ApplicableDeclarationsCache, StyleSharingCandidateCache}; use euclid::{Rect, Size2D}; use fnv::FnvHasher; use gfx::display_list::OpaqueNode; use gfx::font_cache_task::FontCacheTask; use gfx::font_context::FontContext; use ipc_channel::ipc::{self, IpcSender}; use msg::compositor_msg::LayerId; use msg::constellation_msg::ConstellationChan; use net_traits::image::base::Image; use net_traits::image_cache_task::{ImageCacheChan, ImageCacheTask, ImageResponse, ImageState}; use net_traits::image_cache_task::{UsePlaceholder}; use script::layout_interface::{Animation, LayoutChan, ReflowGoal}; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::collections::hash_state::DefaultState; use std::rc::Rc; use std::sync::Arc; use std::sync::mpsc::{channel, Sender}; use style::selector_matching::Stylist; use url::Url; use util::geometry::Au; use util::mem::HeapSizeOf; use util::opts; struct LocalLayoutContext { font_context: RefCell<FontContext>, applicable_declarations_cache: RefCell<ApplicableDeclarationsCache>, style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache>, } impl HeapSizeOf for LocalLayoutContext { // FIXME(njn): measure other fields eventually. fn heap_size_of_children(&self) -> usize { self.font_context.heap_size_of_children() } } thread_local!(static LOCAL_CONTEXT_KEY: RefCell<Option<Rc<LocalLayoutContext>>> = RefCell::new(None)); pub fn heap_size_of_local_context() -> usize { LOCAL_CONTEXT_KEY.with(|r| { r.borrow().clone().map_or(0, |context| context.heap_size_of_children()) }) } fn create_or_get_local_context(shared_layout_context: &SharedLayoutContext) -> Rc<LocalLayoutContext> { LOCAL_CONTEXT_KEY.with(|r| { let mut r = r.borrow_mut(); if let Some(context) = r.clone() { if shared_layout_context.screen_size_changed { context.applicable_declarations_cache.borrow_mut().evict_all(); } context } else { let context = Rc::new(LocalLayoutContext { font_context: RefCell::new(FontContext::new(shared_layout_context.font_cache_task.clone())), applicable_declarations_cache: RefCell::new(ApplicableDeclarationsCache::new()), style_sharing_candidate_cache: RefCell::new(StyleSharingCandidateCache::new()), }); *r = Some(context.clone()); context } }) } /// Layout information shared among all workers. This must be thread-safe. pub struct SharedLayoutContext { /// The shared image cache task. pub image_cache_task: ImageCacheTask, /// A channel for the image cache to send responses to. pub image_cache_sender: ImageCacheChan, /// The current screen size. pub screen_size: Size2D<Au>, /// Screen sized changed? pub screen_size_changed: bool, /// A channel up to the constellation. pub constellation_chan: ConstellationChan, /// A channel up to the layout task. pub layout_chan: LayoutChan, /// Interface to the font cache task. pub font_cache_task: FontCacheTask, /// The CSS selector stylist. /// /// FIXME(#2604): Make this no longer an unsafe pointer once we have fast `RWArc`s. pub stylist: *const Stylist, /// The root node at which we're starting the layout. pub reflow_root: Option<OpaqueNode>, /// The URL. pub url: Url, /// Starts at zero, and increased by one every time a layout completes. /// This can be used to easily check for invalid stale data. pub generation: u32, /// A channel on which new animations that have been triggered by style recalculation can be /// sent. pub new_animations_sender: Sender<Animation>, /// A channel to send canvas renderers to paint task, in order to correctly paint the layers pub canvas_layers_sender: Sender<(LayerId, IpcSender<CanvasMsg>)>, /// The visible rects for each layer, as reported to us by the compositor. pub visible_rects: Arc<HashMap<LayerId, Rect<Au>, DefaultState<FnvHasher>>>, /// The animations that are currently running. pub running_animations: Arc<HashMap<OpaqueNode, Vec<Animation>>>, /// Why is this reflow occurring pub goal: ReflowGoal, } // FIXME(#6569) This implementations is unsound: // XXX UNSOUND!!! for image_cache_task // XXX UNSOUND!!! for image_cache_sender // XXX UNSOUND!!! for constellation_chan // XXX UNSOUND!!! for layout_chan // XXX UNSOUND!!! for font_cache_task // XXX UNSOUND!!! for stylist // XXX UNSOUND!!! for new_animations_sender // XXX UNSOUND!!! for canvas_layers_sender #[allow(unsafe_code)] unsafe impl Sync for SharedLayoutContext {} pub struct LayoutContext<'a> { pub shared: &'a SharedLayoutContext, cached_local_layout_context: Rc<LocalLayoutContext>, } impl<'a> LayoutContext<'a> { pub fn new(shared_layout_context: &'a SharedLayoutContext) -> LayoutContext<'a> { let local_context = create_or_get_local_context(shared_layout_context); LayoutContext { shared: shared_layout_context, cached_local_layout_context: local_context, } } #[inline(always)] pub fn
(&self) -> RefMut<FontContext> { self.cached_local_layout_context.font_context.borrow_mut() } #[inline(always)] pub fn applicable_declarations_cache(&self) -> RefMut<ApplicableDeclarationsCache> { self.cached_local_layout_context.applicable_declarations_cache.borrow_mut() } #[inline(always)] pub fn style_sharing_candidate_cache(&self) -> RefMut<StyleSharingCandidateCache> { self.cached_local_layout_context.style_sharing_candidate_cache.borrow_mut() } pub fn get_or_request_image(&self, url: Url, use_placeholder: UsePlaceholder) -> Option<Arc<Image>> { // See if the image is already available let result = self.shared.image_cache_task.find_image(url.clone(), use_placeholder); match result { Ok(image) => Some(image), Err(state) => { // If we are emitting an output file, then we need to block on // image load or we risk emitting an output file missing the image. let is_sync = opts::get().output_file.is_some() || opts::get().exit_after_load; match (state, is_sync) { // Image failed to load, so just return nothing (ImageState::LoadError, _) => None, // Not loaded, test mode - load the image synchronously (_, true) => { let (sync_tx, sync_rx) = ipc::channel().unwrap(); self.shared.image_cache_task.request_image(url, ImageCacheChan(sync_tx), None); match sync_rx.recv().unwrap().image_response { ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => Some(image), ImageResponse::None => None, } } // Not yet requested, async mode - request image from the cache (ImageState::NotRequested, false) => { self.shared.image_cache_task .request_image(url, self.shared.image_cache_sender.clone(), None); None } // Image has been requested, is still pending. Return no image // for this paint loop. When the image loads it will trigger // a reflow and/or repaint. (ImageState::Pending, false) => None, } } } } }
font_context
identifier_name
check_unused.rs
// // Unused import checking // // Although this is mostly a lint pass, it lives in here because it depends on // resolve data structures and because it finalises the privacy information for // `use` items. // // Unused trait imports can't be checked until the method resolution. We save // candidates here, and do the actual check in librustc_typeck/check_unused.rs. // // Checking for unused imports is split into three steps: // // - `UnusedImportCheckVisitor` walks the AST to find all the unused imports // inside of `UseTree`s, recording their `NodeId`s and grouping them by // the parent `use` item // // - `calc_unused_spans` then walks over all the `use` items marked in the // previous step to collect the spans associated with the `NodeId`s and to // calculate the spans that can be removed by rustfix; This is done in a // separate step to be able to collapse the adjacent spans that rustfix // will remove // // - `check_crate` finally emits the diagnostics based on the data generated // in the last step use crate::imports::ImportKind; use crate::Resolver; use rustc_ast as ast; use rustc_ast::node_id::NodeMap; use rustc_ast::visit::{self, Visitor}; use rustc_ast_lowering::ResolverAstLowering; use rustc_data_structures::fx::FxHashSet; use rustc_errors::pluralize; use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS}; use rustc_session::lint::BuiltinLintDiagnostics; use rustc_span::{MultiSpan, Span, DUMMY_SP}; struct UnusedImport<'a> { use_tree: &'a ast::UseTree, use_tree_id: ast::NodeId, item_span: Span, unused: FxHashSet<ast::NodeId>, } impl<'a> UnusedImport<'a> { fn add(&mut self, id: ast::NodeId) { self.unused.insert(id); } } struct UnusedImportCheckVisitor<'a, 'b> { r: &'a mut Resolver<'b>, /// All the (so far) unused imports, grouped path list unused_imports: NodeMap<UnusedImport<'a>>, base_use_tree: Option<&'a ast::UseTree>, base_id: ast::NodeId, item_span: Span, } impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> { // We have information about whether `use` (import) items are actually // used now. If an import is not used at all, we signal a lint error. fn check_import(&mut self, id: ast::NodeId) { let used = self.r.used_imports.contains(&id); let def_id = self.r.local_def_id(id); if!used { if self.r.maybe_unused_trait_imports.contains(&def_id) { // Check later. return; } self.unused_import(self.base_id).add(id); } else { // This trait import is definitely used, in a way other than // method resolution. self.r.maybe_unused_trait_imports.remove(&def_id); if let Some(i) = self.unused_imports.get_mut(&self.base_id) { i.unused.remove(&id); } } } fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> { let use_tree_id = self.base_id; let use_tree = self.base_use_tree.unwrap(); let item_span = self.item_span; self.unused_imports.entry(id).or_insert_with(|| UnusedImport { use_tree, use_tree_id, item_span, unused: FxHashSet::default(), }) } } impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> { fn visit_item(&mut self, item: &'a ast::Item) { self.item_span = item.span_with_attributes(); // Ignore is_public import statements because there's no way to be sure // whether they're used or not. Also ignore imports with a dummy span // because this means that they were generated in some fashion by the // compiler and we don't need to consider them. if let ast::ItemKind::Use(..) = item.kind { if item.vis.kind.is_pub() || item.span.is_dummy() { return; } } visit::walk_item(self, item); } fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool)
} enum UnusedSpanResult { Used, FlatUnused(Span, Span), NestedFullUnused(Vec<Span>, Span), NestedPartialUnused(Vec<Span>, Vec<Span>), } fn calc_unused_spans( unused_import: &UnusedImport<'_>, use_tree: &ast::UseTree, use_tree_id: ast::NodeId, ) -> UnusedSpanResult { // The full span is the whole item's span if this current tree is not nested inside another // This tells rustfix to remove the whole item if all the imports are unused let full_span = if unused_import.use_tree.span == use_tree.span { unused_import.item_span } else { use_tree.span }; match use_tree.kind { ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => { if unused_import.unused.contains(&use_tree_id) { UnusedSpanResult::FlatUnused(use_tree.span, full_span) } else { UnusedSpanResult::Used } } ast::UseTreeKind::Nested(ref nested) => { if nested.is_empty() { return UnusedSpanResult::FlatUnused(use_tree.span, full_span); } let mut unused_spans = Vec::new(); let mut to_remove = Vec::new(); let mut all_nested_unused = true; let mut previous_unused = false; for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() { let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) { UnusedSpanResult::Used => { all_nested_unused = false; None } UnusedSpanResult::FlatUnused(span, remove) => { unused_spans.push(span); Some(remove) } UnusedSpanResult::NestedFullUnused(mut spans, remove) => { unused_spans.append(&mut spans); Some(remove) } UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => { all_nested_unused = false; unused_spans.append(&mut spans); to_remove.append(&mut to_remove_extra); None } }; if let Some(remove) = remove { let remove_span = if nested.len() == 1 { remove } else if pos == nested.len() - 1 ||!all_nested_unused { // Delete everything from the end of the last import, to delete the // previous comma nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span) } else { // Delete everything until the next import, to delete the trailing commas use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo()) }; // Try to collapse adjacent spans into a single one. This prevents all cases of // overlapping removals, which are not supported by rustfix if previous_unused &&!to_remove.is_empty() { let previous = to_remove.pop().unwrap(); to_remove.push(previous.to(remove_span)); } else { to_remove.push(remove_span); } } previous_unused = remove.is_some(); } if unused_spans.is_empty() { UnusedSpanResult::Used } else if all_nested_unused { UnusedSpanResult::NestedFullUnused(unused_spans, full_span) } else { UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove) } } } } impl Resolver<'_> { crate fn check_unused(&mut self, krate: &ast::Crate) { for import in self.potentially_unused_imports.iter() { match import.kind { _ if import.used.get() || import.vis.get().is_public() || import.span.is_dummy() => { if let ImportKind::MacroUse = import.kind { if!import.span.is_dummy() { self.lint_buffer.buffer_lint( MACRO_USE_EXTERN_CRATE, import.id, import.span, "deprecated `#[macro_use]` attribute used to \ import macros should be replaced at use sites \ with a `use` item to import the macro \ instead", ); } } } ImportKind::ExternCrate {.. } => { let def_id = self.local_def_id(import.id); self.maybe_unused_extern_crates.push((def_id, import.span)); } ImportKind::MacroUse => { let msg = "unused `#[macro_use]` import"; self.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg); } _ => {} } } let mut visitor = UnusedImportCheckVisitor { r: self, unused_imports: Default::default(), base_use_tree: None, base_id: ast::DUMMY_NODE_ID, item_span: DUMMY_SP, }; visit::walk_crate(&mut visitor, krate); for unused in visitor.unused_imports.values() { let mut fixes = Vec::new(); let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) { UnusedSpanResult::Used => continue, UnusedSpanResult::FlatUnused(span, remove) => { fixes.push((remove, String::new())); vec![span] } UnusedSpanResult::NestedFullUnused(spans, remove) => { fixes.push((remove, String::new())); spans } UnusedSpanResult::NestedPartialUnused(spans, remove) => { for fix in &remove { fixes.push((*fix, String::new())); } spans } }; let len = spans.len(); spans.sort(); let ms = MultiSpan::from_spans(spans.clone()); let mut span_snippets = spans .iter() .filter_map(|s| match visitor.r.session.source_map().span_to_snippet(*s) { Ok(s) => Some(format!("`{}`", s)), _ => None, }) .collect::<Vec<String>>(); span_snippets.sort(); let msg = format!( "unused import{}{}", pluralize!(len), if!span_snippets.is_empty() { format!(": {}", span_snippets.join(", ")) } else { String::new() } ); let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span { "remove the whole `use` item" } else if spans.len() > 1 { "remove the unused imports" } else { "remove the unused import" }; visitor.r.lint_buffer.buffer_lint_with_diagnostic( UNUSED_IMPORTS, unused.use_tree_id, ms, &msg, BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes), ); } } }
{ // Use the base UseTree's NodeId as the item id // This allows the grouping of all the lints in the same item if !nested { self.base_id = id; self.base_use_tree = Some(use_tree); } if let ast::UseTreeKind::Nested(ref items) = use_tree.kind { if items.is_empty() { self.unused_import(self.base_id).add(id); } } else { self.check_import(id); } visit::walk_use_tree(self, use_tree, id); }
identifier_body
check_unused.rs
// // Unused import checking // // Although this is mostly a lint pass, it lives in here because it depends on // resolve data structures and because it finalises the privacy information for // `use` items. // // Unused trait imports can't be checked until the method resolution. We save // candidates here, and do the actual check in librustc_typeck/check_unused.rs. // // Checking for unused imports is split into three steps: // // - `UnusedImportCheckVisitor` walks the AST to find all the unused imports // inside of `UseTree`s, recording their `NodeId`s and grouping them by // the parent `use` item // // - `calc_unused_spans` then walks over all the `use` items marked in the // previous step to collect the spans associated with the `NodeId`s and to // calculate the spans that can be removed by rustfix; This is done in a // separate step to be able to collapse the adjacent spans that rustfix // will remove // // - `check_crate` finally emits the diagnostics based on the data generated // in the last step use crate::imports::ImportKind; use crate::Resolver; use rustc_ast as ast; use rustc_ast::node_id::NodeMap; use rustc_ast::visit::{self, Visitor}; use rustc_ast_lowering::ResolverAstLowering; use rustc_data_structures::fx::FxHashSet; use rustc_errors::pluralize; use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS}; use rustc_session::lint::BuiltinLintDiagnostics; use rustc_span::{MultiSpan, Span, DUMMY_SP}; struct UnusedImport<'a> { use_tree: &'a ast::UseTree, use_tree_id: ast::NodeId, item_span: Span, unused: FxHashSet<ast::NodeId>, } impl<'a> UnusedImport<'a> { fn add(&mut self, id: ast::NodeId) { self.unused.insert(id); } } struct UnusedImportCheckVisitor<'a, 'b> { r: &'a mut Resolver<'b>, /// All the (so far) unused imports, grouped path list unused_imports: NodeMap<UnusedImport<'a>>, base_use_tree: Option<&'a ast::UseTree>, base_id: ast::NodeId, item_span: Span, } impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> { // We have information about whether `use` (import) items are actually // used now. If an import is not used at all, we signal a lint error. fn check_import(&mut self, id: ast::NodeId) { let used = self.r.used_imports.contains(&id); let def_id = self.r.local_def_id(id); if!used { if self.r.maybe_unused_trait_imports.contains(&def_id) { // Check later. return; } self.unused_import(self.base_id).add(id); } else { // This trait import is definitely used, in a way other than // method resolution. self.r.maybe_unused_trait_imports.remove(&def_id); if let Some(i) = self.unused_imports.get_mut(&self.base_id) { i.unused.remove(&id); } } } fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> { let use_tree_id = self.base_id; let use_tree = self.base_use_tree.unwrap(); let item_span = self.item_span; self.unused_imports.entry(id).or_insert_with(|| UnusedImport { use_tree, use_tree_id, item_span, unused: FxHashSet::default(), }) } } impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> { fn visit_item(&mut self, item: &'a ast::Item) { self.item_span = item.span_with_attributes(); // Ignore is_public import statements because there's no way to be sure // whether they're used or not. Also ignore imports with a dummy span // because this means that they were generated in some fashion by the // compiler and we don't need to consider them. if let ast::ItemKind::Use(..) = item.kind { if item.vis.kind.is_pub() || item.span.is_dummy() { return; } } visit::walk_item(self, item); } fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) { // Use the base UseTree's NodeId as the item id // This allows the grouping of all the lints in the same item if!nested
if let ast::UseTreeKind::Nested(ref items) = use_tree.kind { if items.is_empty() { self.unused_import(self.base_id).add(id); } } else { self.check_import(id); } visit::walk_use_tree(self, use_tree, id); } } enum UnusedSpanResult { Used, FlatUnused(Span, Span), NestedFullUnused(Vec<Span>, Span), NestedPartialUnused(Vec<Span>, Vec<Span>), } fn calc_unused_spans( unused_import: &UnusedImport<'_>, use_tree: &ast::UseTree, use_tree_id: ast::NodeId, ) -> UnusedSpanResult { // The full span is the whole item's span if this current tree is not nested inside another // This tells rustfix to remove the whole item if all the imports are unused let full_span = if unused_import.use_tree.span == use_tree.span { unused_import.item_span } else { use_tree.span }; match use_tree.kind { ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => { if unused_import.unused.contains(&use_tree_id) { UnusedSpanResult::FlatUnused(use_tree.span, full_span) } else { UnusedSpanResult::Used } } ast::UseTreeKind::Nested(ref nested) => { if nested.is_empty() { return UnusedSpanResult::FlatUnused(use_tree.span, full_span); } let mut unused_spans = Vec::new(); let mut to_remove = Vec::new(); let mut all_nested_unused = true; let mut previous_unused = false; for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() { let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) { UnusedSpanResult::Used => { all_nested_unused = false; None } UnusedSpanResult::FlatUnused(span, remove) => { unused_spans.push(span); Some(remove) } UnusedSpanResult::NestedFullUnused(mut spans, remove) => { unused_spans.append(&mut spans); Some(remove) } UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => { all_nested_unused = false; unused_spans.append(&mut spans); to_remove.append(&mut to_remove_extra); None } }; if let Some(remove) = remove { let remove_span = if nested.len() == 1 { remove } else if pos == nested.len() - 1 ||!all_nested_unused { // Delete everything from the end of the last import, to delete the // previous comma nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span) } else { // Delete everything until the next import, to delete the trailing commas use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo()) }; // Try to collapse adjacent spans into a single one. This prevents all cases of // overlapping removals, which are not supported by rustfix if previous_unused &&!to_remove.is_empty() { let previous = to_remove.pop().unwrap(); to_remove.push(previous.to(remove_span)); } else { to_remove.push(remove_span); } } previous_unused = remove.is_some(); } if unused_spans.is_empty() { UnusedSpanResult::Used } else if all_nested_unused { UnusedSpanResult::NestedFullUnused(unused_spans, full_span) } else { UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove) } } } } impl Resolver<'_> { crate fn check_unused(&mut self, krate: &ast::Crate) { for import in self.potentially_unused_imports.iter() { match import.kind { _ if import.used.get() || import.vis.get().is_public() || import.span.is_dummy() => { if let ImportKind::MacroUse = import.kind { if!import.span.is_dummy() { self.lint_buffer.buffer_lint( MACRO_USE_EXTERN_CRATE, import.id, import.span, "deprecated `#[macro_use]` attribute used to \ import macros should be replaced at use sites \ with a `use` item to import the macro \ instead", ); } } } ImportKind::ExternCrate {.. } => { let def_id = self.local_def_id(import.id); self.maybe_unused_extern_crates.push((def_id, import.span)); } ImportKind::MacroUse => { let msg = "unused `#[macro_use]` import"; self.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg); } _ => {} } } let mut visitor = UnusedImportCheckVisitor { r: self, unused_imports: Default::default(), base_use_tree: None, base_id: ast::DUMMY_NODE_ID, item_span: DUMMY_SP, }; visit::walk_crate(&mut visitor, krate); for unused in visitor.unused_imports.values() { let mut fixes = Vec::new(); let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) { UnusedSpanResult::Used => continue, UnusedSpanResult::FlatUnused(span, remove) => { fixes.push((remove, String::new())); vec![span] } UnusedSpanResult::NestedFullUnused(spans, remove) => { fixes.push((remove, String::new())); spans } UnusedSpanResult::NestedPartialUnused(spans, remove) => { for fix in &remove { fixes.push((*fix, String::new())); } spans } }; let len = spans.len(); spans.sort(); let ms = MultiSpan::from_spans(spans.clone()); let mut span_snippets = spans .iter() .filter_map(|s| match visitor.r.session.source_map().span_to_snippet(*s) { Ok(s) => Some(format!("`{}`", s)), _ => None, }) .collect::<Vec<String>>(); span_snippets.sort(); let msg = format!( "unused import{}{}", pluralize!(len), if!span_snippets.is_empty() { format!(": {}", span_snippets.join(", ")) } else { String::new() } ); let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span { "remove the whole `use` item" } else if spans.len() > 1 { "remove the unused imports" } else { "remove the unused import" }; visitor.r.lint_buffer.buffer_lint_with_diagnostic( UNUSED_IMPORTS, unused.use_tree_id, ms, &msg, BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes), ); } } }
{ self.base_id = id; self.base_use_tree = Some(use_tree); }
conditional_block
check_unused.rs
// // Unused import checking // // Although this is mostly a lint pass, it lives in here because it depends on // resolve data structures and because it finalises the privacy information for // `use` items. // // Unused trait imports can't be checked until the method resolution. We save // candidates here, and do the actual check in librustc_typeck/check_unused.rs. // // Checking for unused imports is split into three steps: // // - `UnusedImportCheckVisitor` walks the AST to find all the unused imports // inside of `UseTree`s, recording their `NodeId`s and grouping them by // the parent `use` item // // - `calc_unused_spans` then walks over all the `use` items marked in the // previous step to collect the spans associated with the `NodeId`s and to // calculate the spans that can be removed by rustfix; This is done in a // separate step to be able to collapse the adjacent spans that rustfix // will remove // // - `check_crate` finally emits the diagnostics based on the data generated // in the last step use crate::imports::ImportKind; use crate::Resolver; use rustc_ast as ast; use rustc_ast::node_id::NodeMap; use rustc_ast::visit::{self, Visitor}; use rustc_ast_lowering::ResolverAstLowering; use rustc_data_structures::fx::FxHashSet; use rustc_errors::pluralize; use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS}; use rustc_session::lint::BuiltinLintDiagnostics; use rustc_span::{MultiSpan, Span, DUMMY_SP}; struct UnusedImport<'a> { use_tree: &'a ast::UseTree, use_tree_id: ast::NodeId, item_span: Span, unused: FxHashSet<ast::NodeId>, } impl<'a> UnusedImport<'a> { fn add(&mut self, id: ast::NodeId) { self.unused.insert(id); } } struct UnusedImportCheckVisitor<'a, 'b> { r: &'a mut Resolver<'b>, /// All the (so far) unused imports, grouped path list unused_imports: NodeMap<UnusedImport<'a>>, base_use_tree: Option<&'a ast::UseTree>, base_id: ast::NodeId, item_span: Span, } impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> { // We have information about whether `use` (import) items are actually // used now. If an import is not used at all, we signal a lint error. fn check_import(&mut self, id: ast::NodeId) { let used = self.r.used_imports.contains(&id); let def_id = self.r.local_def_id(id); if!used { if self.r.maybe_unused_trait_imports.contains(&def_id) { // Check later. return; } self.unused_import(self.base_id).add(id); } else { // This trait import is definitely used, in a way other than // method resolution. self.r.maybe_unused_trait_imports.remove(&def_id); if let Some(i) = self.unused_imports.get_mut(&self.base_id) { i.unused.remove(&id); } } } fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> { let use_tree_id = self.base_id; let use_tree = self.base_use_tree.unwrap(); let item_span = self.item_span; self.unused_imports.entry(id).or_insert_with(|| UnusedImport { use_tree, use_tree_id, item_span, unused: FxHashSet::default(), }) } } impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> { fn visit_item(&mut self, item: &'a ast::Item) { self.item_span = item.span_with_attributes(); // Ignore is_public import statements because there's no way to be sure // whether they're used or not. Also ignore imports with a dummy span // because this means that they were generated in some fashion by the // compiler and we don't need to consider them. if let ast::ItemKind::Use(..) = item.kind { if item.vis.kind.is_pub() || item.span.is_dummy() { return; } } visit::walk_item(self, item); } fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) { // Use the base UseTree's NodeId as the item id // This allows the grouping of all the lints in the same item if!nested { self.base_id = id; self.base_use_tree = Some(use_tree); } if let ast::UseTreeKind::Nested(ref items) = use_tree.kind { if items.is_empty() { self.unused_import(self.base_id).add(id); } } else { self.check_import(id); } visit::walk_use_tree(self, use_tree, id); } } enum UnusedSpanResult { Used, FlatUnused(Span, Span), NestedFullUnused(Vec<Span>, Span), NestedPartialUnused(Vec<Span>, Vec<Span>), } fn calc_unused_spans( unused_import: &UnusedImport<'_>, use_tree: &ast::UseTree, use_tree_id: ast::NodeId, ) -> UnusedSpanResult { // The full span is the whole item's span if this current tree is not nested inside another // This tells rustfix to remove the whole item if all the imports are unused let full_span = if unused_import.use_tree.span == use_tree.span { unused_import.item_span } else { use_tree.span }; match use_tree.kind { ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => { if unused_import.unused.contains(&use_tree_id) { UnusedSpanResult::FlatUnused(use_tree.span, full_span) } else { UnusedSpanResult::Used } } ast::UseTreeKind::Nested(ref nested) => { if nested.is_empty() { return UnusedSpanResult::FlatUnused(use_tree.span, full_span); } let mut unused_spans = Vec::new(); let mut to_remove = Vec::new(); let mut all_nested_unused = true; let mut previous_unused = false; for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() { let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) { UnusedSpanResult::Used => { all_nested_unused = false; None } UnusedSpanResult::FlatUnused(span, remove) => { unused_spans.push(span); Some(remove) } UnusedSpanResult::NestedFullUnused(mut spans, remove) => { unused_spans.append(&mut spans); Some(remove) } UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => { all_nested_unused = false; unused_spans.append(&mut spans); to_remove.append(&mut to_remove_extra); None } }; if let Some(remove) = remove { let remove_span = if nested.len() == 1 { remove } else if pos == nested.len() - 1 ||!all_nested_unused { // Delete everything from the end of the last import, to delete the // previous comma nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span) } else { // Delete everything until the next import, to delete the trailing commas use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo()) }; // Try to collapse adjacent spans into a single one. This prevents all cases of // overlapping removals, which are not supported by rustfix if previous_unused &&!to_remove.is_empty() { let previous = to_remove.pop().unwrap(); to_remove.push(previous.to(remove_span)); } else { to_remove.push(remove_span); } } previous_unused = remove.is_some(); } if unused_spans.is_empty() { UnusedSpanResult::Used } else if all_nested_unused { UnusedSpanResult::NestedFullUnused(unused_spans, full_span) } else { UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove) } } } } impl Resolver<'_> { crate fn
(&mut self, krate: &ast::Crate) { for import in self.potentially_unused_imports.iter() { match import.kind { _ if import.used.get() || import.vis.get().is_public() || import.span.is_dummy() => { if let ImportKind::MacroUse = import.kind { if!import.span.is_dummy() { self.lint_buffer.buffer_lint( MACRO_USE_EXTERN_CRATE, import.id, import.span, "deprecated `#[macro_use]` attribute used to \ import macros should be replaced at use sites \ with a `use` item to import the macro \ instead", ); } } } ImportKind::ExternCrate {.. } => { let def_id = self.local_def_id(import.id); self.maybe_unused_extern_crates.push((def_id, import.span)); } ImportKind::MacroUse => { let msg = "unused `#[macro_use]` import"; self.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg); } _ => {} } } let mut visitor = UnusedImportCheckVisitor { r: self, unused_imports: Default::default(), base_use_tree: None, base_id: ast::DUMMY_NODE_ID, item_span: DUMMY_SP, }; visit::walk_crate(&mut visitor, krate); for unused in visitor.unused_imports.values() { let mut fixes = Vec::new(); let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) { UnusedSpanResult::Used => continue, UnusedSpanResult::FlatUnused(span, remove) => { fixes.push((remove, String::new())); vec![span] } UnusedSpanResult::NestedFullUnused(spans, remove) => { fixes.push((remove, String::new())); spans } UnusedSpanResult::NestedPartialUnused(spans, remove) => { for fix in &remove { fixes.push((*fix, String::new())); } spans } }; let len = spans.len(); spans.sort(); let ms = MultiSpan::from_spans(spans.clone()); let mut span_snippets = spans .iter() .filter_map(|s| match visitor.r.session.source_map().span_to_snippet(*s) { Ok(s) => Some(format!("`{}`", s)), _ => None, }) .collect::<Vec<String>>(); span_snippets.sort(); let msg = format!( "unused import{}{}", pluralize!(len), if!span_snippets.is_empty() { format!(": {}", span_snippets.join(", ")) } else { String::new() } ); let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span { "remove the whole `use` item" } else if spans.len() > 1 { "remove the unused imports" } else { "remove the unused import" }; visitor.r.lint_buffer.buffer_lint_with_diagnostic( UNUSED_IMPORTS, unused.use_tree_id, ms, &msg, BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes), ); } } }
check_unused
identifier_name
check_unused.rs
// // Unused import checking // // Although this is mostly a lint pass, it lives in here because it depends on // resolve data structures and because it finalises the privacy information for // `use` items. // // Unused trait imports can't be checked until the method resolution. We save // candidates here, and do the actual check in librustc_typeck/check_unused.rs. // // Checking for unused imports is split into three steps: // // - `UnusedImportCheckVisitor` walks the AST to find all the unused imports // inside of `UseTree`s, recording their `NodeId`s and grouping them by // the parent `use` item // // - `calc_unused_spans` then walks over all the `use` items marked in the // previous step to collect the spans associated with the `NodeId`s and to // calculate the spans that can be removed by rustfix; This is done in a // separate step to be able to collapse the adjacent spans that rustfix // will remove // // - `check_crate` finally emits the diagnostics based on the data generated // in the last step use crate::imports::ImportKind; use crate::Resolver; use rustc_ast as ast; use rustc_ast::node_id::NodeMap; use rustc_ast::visit::{self, Visitor}; use rustc_ast_lowering::ResolverAstLowering; use rustc_data_structures::fx::FxHashSet; use rustc_errors::pluralize; use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS}; use rustc_session::lint::BuiltinLintDiagnostics; use rustc_span::{MultiSpan, Span, DUMMY_SP}; struct UnusedImport<'a> { use_tree: &'a ast::UseTree, use_tree_id: ast::NodeId, item_span: Span, unused: FxHashSet<ast::NodeId>, } impl<'a> UnusedImport<'a> { fn add(&mut self, id: ast::NodeId) { self.unused.insert(id); } } struct UnusedImportCheckVisitor<'a, 'b> { r: &'a mut Resolver<'b>, /// All the (so far) unused imports, grouped path list unused_imports: NodeMap<UnusedImport<'a>>, base_use_tree: Option<&'a ast::UseTree>, base_id: ast::NodeId, item_span: Span, } impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> { // We have information about whether `use` (import) items are actually // used now. If an import is not used at all, we signal a lint error. fn check_import(&mut self, id: ast::NodeId) { let used = self.r.used_imports.contains(&id); let def_id = self.r.local_def_id(id); if!used { if self.r.maybe_unused_trait_imports.contains(&def_id) { // Check later. return; } self.unused_import(self.base_id).add(id); } else { // This trait import is definitely used, in a way other than // method resolution. self.r.maybe_unused_trait_imports.remove(&def_id); if let Some(i) = self.unused_imports.get_mut(&self.base_id) { i.unused.remove(&id); } } } fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> { let use_tree_id = self.base_id; let use_tree = self.base_use_tree.unwrap(); let item_span = self.item_span; self.unused_imports.entry(id).or_insert_with(|| UnusedImport { use_tree, use_tree_id, item_span, unused: FxHashSet::default(), }) } } impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> { fn visit_item(&mut self, item: &'a ast::Item) { self.item_span = item.span_with_attributes(); // Ignore is_public import statements because there's no way to be sure // whether they're used or not. Also ignore imports with a dummy span // because this means that they were generated in some fashion by the
} } visit::walk_item(self, item); } fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) { // Use the base UseTree's NodeId as the item id // This allows the grouping of all the lints in the same item if!nested { self.base_id = id; self.base_use_tree = Some(use_tree); } if let ast::UseTreeKind::Nested(ref items) = use_tree.kind { if items.is_empty() { self.unused_import(self.base_id).add(id); } } else { self.check_import(id); } visit::walk_use_tree(self, use_tree, id); } } enum UnusedSpanResult { Used, FlatUnused(Span, Span), NestedFullUnused(Vec<Span>, Span), NestedPartialUnused(Vec<Span>, Vec<Span>), } fn calc_unused_spans( unused_import: &UnusedImport<'_>, use_tree: &ast::UseTree, use_tree_id: ast::NodeId, ) -> UnusedSpanResult { // The full span is the whole item's span if this current tree is not nested inside another // This tells rustfix to remove the whole item if all the imports are unused let full_span = if unused_import.use_tree.span == use_tree.span { unused_import.item_span } else { use_tree.span }; match use_tree.kind { ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => { if unused_import.unused.contains(&use_tree_id) { UnusedSpanResult::FlatUnused(use_tree.span, full_span) } else { UnusedSpanResult::Used } } ast::UseTreeKind::Nested(ref nested) => { if nested.is_empty() { return UnusedSpanResult::FlatUnused(use_tree.span, full_span); } let mut unused_spans = Vec::new(); let mut to_remove = Vec::new(); let mut all_nested_unused = true; let mut previous_unused = false; for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() { let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) { UnusedSpanResult::Used => { all_nested_unused = false; None } UnusedSpanResult::FlatUnused(span, remove) => { unused_spans.push(span); Some(remove) } UnusedSpanResult::NestedFullUnused(mut spans, remove) => { unused_spans.append(&mut spans); Some(remove) } UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => { all_nested_unused = false; unused_spans.append(&mut spans); to_remove.append(&mut to_remove_extra); None } }; if let Some(remove) = remove { let remove_span = if nested.len() == 1 { remove } else if pos == nested.len() - 1 ||!all_nested_unused { // Delete everything from the end of the last import, to delete the // previous comma nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span) } else { // Delete everything until the next import, to delete the trailing commas use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo()) }; // Try to collapse adjacent spans into a single one. This prevents all cases of // overlapping removals, which are not supported by rustfix if previous_unused &&!to_remove.is_empty() { let previous = to_remove.pop().unwrap(); to_remove.push(previous.to(remove_span)); } else { to_remove.push(remove_span); } } previous_unused = remove.is_some(); } if unused_spans.is_empty() { UnusedSpanResult::Used } else if all_nested_unused { UnusedSpanResult::NestedFullUnused(unused_spans, full_span) } else { UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove) } } } } impl Resolver<'_> { crate fn check_unused(&mut self, krate: &ast::Crate) { for import in self.potentially_unused_imports.iter() { match import.kind { _ if import.used.get() || import.vis.get().is_public() || import.span.is_dummy() => { if let ImportKind::MacroUse = import.kind { if!import.span.is_dummy() { self.lint_buffer.buffer_lint( MACRO_USE_EXTERN_CRATE, import.id, import.span, "deprecated `#[macro_use]` attribute used to \ import macros should be replaced at use sites \ with a `use` item to import the macro \ instead", ); } } } ImportKind::ExternCrate {.. } => { let def_id = self.local_def_id(import.id); self.maybe_unused_extern_crates.push((def_id, import.span)); } ImportKind::MacroUse => { let msg = "unused `#[macro_use]` import"; self.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg); } _ => {} } } let mut visitor = UnusedImportCheckVisitor { r: self, unused_imports: Default::default(), base_use_tree: None, base_id: ast::DUMMY_NODE_ID, item_span: DUMMY_SP, }; visit::walk_crate(&mut visitor, krate); for unused in visitor.unused_imports.values() { let mut fixes = Vec::new(); let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) { UnusedSpanResult::Used => continue, UnusedSpanResult::FlatUnused(span, remove) => { fixes.push((remove, String::new())); vec![span] } UnusedSpanResult::NestedFullUnused(spans, remove) => { fixes.push((remove, String::new())); spans } UnusedSpanResult::NestedPartialUnused(spans, remove) => { for fix in &remove { fixes.push((*fix, String::new())); } spans } }; let len = spans.len(); spans.sort(); let ms = MultiSpan::from_spans(spans.clone()); let mut span_snippets = spans .iter() .filter_map(|s| match visitor.r.session.source_map().span_to_snippet(*s) { Ok(s) => Some(format!("`{}`", s)), _ => None, }) .collect::<Vec<String>>(); span_snippets.sort(); let msg = format!( "unused import{}{}", pluralize!(len), if!span_snippets.is_empty() { format!(": {}", span_snippets.join(", ")) } else { String::new() } ); let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span { "remove the whole `use` item" } else if spans.len() > 1 { "remove the unused imports" } else { "remove the unused import" }; visitor.r.lint_buffer.buffer_lint_with_diagnostic( UNUSED_IMPORTS, unused.use_tree_id, ms, &msg, BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes), ); } } }
// compiler and we don't need to consider them. if let ast::ItemKind::Use(..) = item.kind { if item.vis.kind.is_pub() || item.span.is_dummy() { return;
random_line_split
build.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. #[cfg(not(feature = "serde_macros"))] mod inner { extern crate syntex; extern crate serde_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let src = Path::new("src/v1/types/mod.rs.in"); let dst = Path::new(&out_dir).join("mod.rs"); let mut registry = syntex::Registry::new(); serde_codegen::register(&mut registry); registry.expand("", &src, &dst).unwrap(); } } #[cfg(feature = "serde_macros")] mod inner { pub fn main()
} fn main() { inner::main(); }
{}
identifier_body
build.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. #[cfg(not(feature = "serde_macros"))] mod inner { extern crate syntex; extern crate serde_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let src = Path::new("src/v1/types/mod.rs.in"); let dst = Path::new(&out_dir).join("mod.rs"); let mut registry = syntex::Registry::new(); serde_codegen::register(&mut registry); registry.expand("", &src, &dst).unwrap(); } } #[cfg(feature = "serde_macros")] mod inner { pub fn
() {} } fn main() { inner::main(); }
main
identifier_name
build.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity.
// the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. #[cfg(not(feature = "serde_macros"))] mod inner { extern crate syntex; extern crate serde_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let src = Path::new("src/v1/types/mod.rs.in"); let dst = Path::new(&out_dir).join("mod.rs"); let mut registry = syntex::Registry::new(); serde_codegen::register(&mut registry); registry.expand("", &src, &dst).unwrap(); } } #[cfg(feature = "serde_macros")] mod inner { pub fn main() {} } fn main() { inner::main(); }
// Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by
random_line_split
transposition_table.rs
use lru_cache::LruCache; use std::hash::Hash; #[derive(Clone)] pub struct TranspositionTable<B, M> where B: Eq + Hash { cache: LruCache<B, (M, u32)>, } impl<B, M> TranspositionTable<B, M> where B: Eq + Hash, M: Clone { pub fn new(capacity: usize) -> TranspositionTable<B, M> { TranspositionTable { cache: LruCache::new(capacity), } } pub fn get(&mut self, board: &B, depth: u32) -> Option<M> { if let Some(precomputed_move) = self.cache.get_mut(board) { if precomputed_move.1 >= depth
} None } pub fn insert(&mut self, board: B, mv: M, depth: u32) { self.cache.insert(board, (mv, depth)); } }
{ return Some(precomputed_move.0.clone()); }
conditional_block
transposition_table.rs
use lru_cache::LruCache; use std::hash::Hash; #[derive(Clone)]
pub struct TranspositionTable<B, M> where B: Eq + Hash { cache: LruCache<B, (M, u32)>, } impl<B, M> TranspositionTable<B, M> where B: Eq + Hash, M: Clone { pub fn new(capacity: usize) -> TranspositionTable<B, M> { TranspositionTable { cache: LruCache::new(capacity), } } pub fn get(&mut self, board: &B, depth: u32) -> Option<M> { if let Some(precomputed_move) = self.cache.get_mut(board) { if precomputed_move.1 >= depth { return Some(precomputed_move.0.clone()); } } None } pub fn insert(&mut self, board: B, mv: M, depth: u32) { self.cache.insert(board, (mv, depth)); } }
random_line_split
transposition_table.rs
use lru_cache::LruCache; use std::hash::Hash; #[derive(Clone)] pub struct TranspositionTable<B, M> where B: Eq + Hash { cache: LruCache<B, (M, u32)>, } impl<B, M> TranspositionTable<B, M> where B: Eq + Hash, M: Clone { pub fn new(capacity: usize) -> TranspositionTable<B, M> { TranspositionTable { cache: LruCache::new(capacity), } } pub fn get(&mut self, board: &B, depth: u32) -> Option<M> { if let Some(precomputed_move) = self.cache.get_mut(board) { if precomputed_move.1 >= depth { return Some(precomputed_move.0.clone()); } } None } pub fn
(&mut self, board: B, mv: M, depth: u32) { self.cache.insert(board, (mv, depth)); } }
insert
identifier_name
transposition_table.rs
use lru_cache::LruCache; use std::hash::Hash; #[derive(Clone)] pub struct TranspositionTable<B, M> where B: Eq + Hash { cache: LruCache<B, (M, u32)>, } impl<B, M> TranspositionTable<B, M> where B: Eq + Hash, M: Clone { pub fn new(capacity: usize) -> TranspositionTable<B, M> { TranspositionTable { cache: LruCache::new(capacity), } } pub fn get(&mut self, board: &B, depth: u32) -> Option<M> { if let Some(precomputed_move) = self.cache.get_mut(board) { if precomputed_move.1 >= depth { return Some(precomputed_move.0.clone()); } } None } pub fn insert(&mut self, board: B, mv: M, depth: u32)
}
{ self.cache.insert(board, (mv, depth)); }
identifier_body
result.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2016 Panopticon authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ //! Result type used throughout the library. //! //! The error type is simply a string. use goblin; use std::borrow::Cow; use std::convert::From; use std::error; use std::fmt; use std::io; use std::result; use std::sync::PoisonError; use serde_cbor; /// Panopticon error type #[derive(Debug)] pub struct Error(pub Cow<'static, str>); /// Panopticon result type pub type Result<T> = result::Result<T, Error>; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl error::Error for Error { fn description<'a>(&'a self) -> &'a str { match &self.0 { &Cow::Borrowed(s) => s, &Cow::Owned(ref s) => s, } } } impl From<String> for Error { fn from(s: String) -> Error { Error(Cow::Owned(s)) } } impl From<&'static str> for Error { fn from(s: &'static str) -> Error { Error(Cow::Borrowed(s)) } } impl From<Cow<'static, str>> for Error { fn from(s: Cow<'static, str>) -> Error { Error(s) } } impl<T> From<PoisonError<T>> for Error { fn from(_: PoisonError<T>) -> Error { Error(Cow::Borrowed("Lock poisoned")) } } impl From<io::Error> for Error { fn from(e: io::Error) -> Error { Error(Cow::Owned(format!("I/O error: {:?}", e))) } } impl From<goblin::error::Error> for Error { fn from(e: goblin::error::Error) -> Error { Error(Cow::Owned(format!("Goblin error: {}", e))) } } impl From<serde_cbor::Error> for Error { fn from(e: serde_cbor::Error) -> Error
}
{ Error(Cow::Owned(format!("Serde error: {}", e))) }
identifier_body
result.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2016 Panopticon authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ //! Result type used throughout the library. //! //! The error type is simply a string. use goblin; use std::borrow::Cow; use std::convert::From; use std::error; use std::fmt; use std::io; use std::result; use std::sync::PoisonError; use serde_cbor; /// Panopticon error type #[derive(Debug)] pub struct Error(pub Cow<'static, str>); /// Panopticon result type pub type Result<T> = result::Result<T, Error>; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl error::Error for Error { fn description<'a>(&'a self) -> &'a str { match &self.0 { &Cow::Borrowed(s) => s, &Cow::Owned(ref s) => s, } } } impl From<String> for Error { fn
(s: String) -> Error { Error(Cow::Owned(s)) } } impl From<&'static str> for Error { fn from(s: &'static str) -> Error { Error(Cow::Borrowed(s)) } } impl From<Cow<'static, str>> for Error { fn from(s: Cow<'static, str>) -> Error { Error(s) } } impl<T> From<PoisonError<T>> for Error { fn from(_: PoisonError<T>) -> Error { Error(Cow::Borrowed("Lock poisoned")) } } impl From<io::Error> for Error { fn from(e: io::Error) -> Error { Error(Cow::Owned(format!("I/O error: {:?}", e))) } } impl From<goblin::error::Error> for Error { fn from(e: goblin::error::Error) -> Error { Error(Cow::Owned(format!("Goblin error: {}", e))) } } impl From<serde_cbor::Error> for Error { fn from(e: serde_cbor::Error) -> Error { Error(Cow::Owned(format!("Serde error: {}", e))) } }
from
identifier_name
result.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2016 Panopticon authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ //! Result type used throughout the library. //! //! The error type is simply a string. use goblin; use std::borrow::Cow; use std::convert::From; use std::error; use std::fmt; use std::io; use std::result; use std::sync::PoisonError; use serde_cbor; /// Panopticon error type #[derive(Debug)] pub struct Error(pub Cow<'static, str>); /// Panopticon result type pub type Result<T> = result::Result<T, Error>; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl error::Error for Error { fn description<'a>(&'a self) -> &'a str { match &self.0 { &Cow::Borrowed(s) => s, &Cow::Owned(ref s) => s, } } } impl From<String> for Error { fn from(s: String) -> Error { Error(Cow::Owned(s)) } } impl From<&'static str> for Error { fn from(s: &'static str) -> Error { Error(Cow::Borrowed(s)) } } impl From<Cow<'static, str>> for Error { fn from(s: Cow<'static, str>) -> Error { Error(s) } } impl<T> From<PoisonError<T>> for Error { fn from(_: PoisonError<T>) -> Error { Error(Cow::Borrowed("Lock poisoned")) } }
Error(Cow::Owned(format!("I/O error: {:?}", e))) } } impl From<goblin::error::Error> for Error { fn from(e: goblin::error::Error) -> Error { Error(Cow::Owned(format!("Goblin error: {}", e))) } } impl From<serde_cbor::Error> for Error { fn from(e: serde_cbor::Error) -> Error { Error(Cow::Owned(format!("Serde error: {}", e))) } }
impl From<io::Error> for Error { fn from(e: io::Error) -> Error {
random_line_split
lib.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/. */ /// A random number generator which shares one instance of an `OsRng`. /// /// A problem with `OsRng`, which is inherited by `StdRng` and so /// `ThreadRng`, is that it reads from `/dev/random`, and so consumes /// a file descriptor. For multi-threaded applications like Servo, /// it is easy to exhaust the supply of file descriptors this way. /// /// This crate fixes that, by only using one `OsRng`, which is just /// used to seed and re-seed an `ServoRng`. #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; pub use rand::{Rand, Rng, SeedableRng}; #[cfg(target_pointer_width = "64")] use rand::isaac::Isaac64Rng as IsaacWordRng; #[cfg(target_pointer_width = "32")] use rand::isaac::IsaacRng as IsaacWordRng; use rand::os::OsRng; use rand::reseeding::{ReseedingRng, Reseeder}; use std::cell::RefCell; use std::mem; use std::rc::Rc; use std::sync::Mutex; use std::u64; // Slightly annoying having to cast between sizes. #[cfg(target_pointer_width = "64")] fn as_isaac_seed(seed: &[usize]) -> &[u64] { unsafe { mem::transmute(seed) } } #[cfg(target_pointer_width = "32")] fn as_isaac_seed(seed: &[usize]) -> &[u32] { unsafe { mem::transmute(seed) } } // The shared RNG which may hold on to a file descriptor lazy_static! { static ref OS_RNG: Mutex<OsRng> = match OsRng::new() { Ok(r) => Mutex::new(r), Err(e) => panic!("Failed to seed OsRng: {}", e), }; } // Generate 32K of data between reseedings const RESEED_THRESHOLD: u64 = 32_768;
pub struct ServoRng { rng: ReseedingRng<IsaacWordRng, ServoReseeder>, } impl Rng for ServoRng { #[inline] fn next_u32(&mut self) -> u32 { self.rng.next_u32() } #[inline] fn next_u64(&mut self) -> u64 { self.rng.next_u64() } } impl<'a> SeedableRng<&'a [usize]> for ServoRng { /// Create a manually-reseeding instane of `ServoRng`. /// /// Note that this RNG does not reseed itself, so care is needed to reseed the RNG /// is required to be cryptographically sound. fn from_seed(seed: &[usize]) -> ServoRng { debug!("Creating new manually-reseeded ServoRng."); let isaac_rng = IsaacWordRng::from_seed(as_isaac_seed(seed)); let reseeding_rng = ReseedingRng::new(isaac_rng, u64::MAX, ServoReseeder); ServoRng { rng: reseeding_rng } } /// Reseed the RNG. fn reseed(&mut self, seed: &'a [usize]) { debug!("Manually reseeding ServoRng."); self.rng.reseed((ServoReseeder, as_isaac_seed(seed))) } } impl ServoRng { /// Create an auto-reseeding instance of `ServoRng`. /// /// This uses the shared `OsRng`, so avoids consuming /// a file descriptor. pub fn new() -> ServoRng { debug!("Creating new ServoRng."); let mut os_rng = OS_RNG.lock().expect("Poisoned lock."); let isaac_rng = IsaacWordRng::rand(&mut *os_rng); let reseeding_rng = ReseedingRng::new(isaac_rng, RESEED_THRESHOLD, ServoReseeder); ServoRng { rng: reseeding_rng } } } // The reseeder for the in-memory RNG. struct ServoReseeder; impl Reseeder<IsaacWordRng> for ServoReseeder { fn reseed(&mut self, rng: &mut IsaacWordRng) { debug!("Reseeding ServoRng."); let mut os_rng = OS_RNG.lock().expect("Poisoned lock."); *rng = IsaacWordRng::rand(&mut *os_rng); } } impl Default for ServoReseeder { fn default() -> ServoReseeder { ServoReseeder } } // A thread-local RNG, designed as a drop-in replacement for rand::ThreadRng. #[derive(Clone)] pub struct ServoThreadRng { rng: Rc<RefCell<ServoRng>>, } // A thread-local RNG, designed as a drop-in replacement for rand::thread_rng. pub fn thread_rng() -> ServoThreadRng { SERVO_THREAD_RNG.with(|t| t.clone()) } thread_local! { static SERVO_THREAD_RNG: ServoThreadRng = ServoThreadRng { rng: Rc::new(RefCell::new(ServoRng::new())) }; } impl Rng for ServoThreadRng { fn next_u32(&mut self) -> u32 { self.rng.borrow_mut().next_u32() } fn next_u64(&mut self) -> u64 { self.rng.borrow_mut().next_u64() } #[inline] fn fill_bytes(&mut self, bytes: &mut [u8]) { self.rng.borrow_mut().fill_bytes(bytes) } } // Generates a random value using the thread-local random number generator. // A drop-in replacement for rand::random. #[inline] pub fn random<T: Rand>() -> T { thread_rng().gen() }
// An in-memory RNG that only uses the shared file descriptor for seeding and reseeding.
random_line_split
lib.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/. */ /// A random number generator which shares one instance of an `OsRng`. /// /// A problem with `OsRng`, which is inherited by `StdRng` and so /// `ThreadRng`, is that it reads from `/dev/random`, and so consumes /// a file descriptor. For multi-threaded applications like Servo, /// it is easy to exhaust the supply of file descriptors this way. /// /// This crate fixes that, by only using one `OsRng`, which is just /// used to seed and re-seed an `ServoRng`. #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; pub use rand::{Rand, Rng, SeedableRng}; #[cfg(target_pointer_width = "64")] use rand::isaac::Isaac64Rng as IsaacWordRng; #[cfg(target_pointer_width = "32")] use rand::isaac::IsaacRng as IsaacWordRng; use rand::os::OsRng; use rand::reseeding::{ReseedingRng, Reseeder}; use std::cell::RefCell; use std::mem; use std::rc::Rc; use std::sync::Mutex; use std::u64; // Slightly annoying having to cast between sizes. #[cfg(target_pointer_width = "64")] fn as_isaac_seed(seed: &[usize]) -> &[u64] { unsafe { mem::transmute(seed) } } #[cfg(target_pointer_width = "32")] fn as_isaac_seed(seed: &[usize]) -> &[u32] { unsafe { mem::transmute(seed) } } // The shared RNG which may hold on to a file descriptor lazy_static! { static ref OS_RNG: Mutex<OsRng> = match OsRng::new() { Ok(r) => Mutex::new(r), Err(e) => panic!("Failed to seed OsRng: {}", e), }; } // Generate 32K of data between reseedings const RESEED_THRESHOLD: u64 = 32_768; // An in-memory RNG that only uses the shared file descriptor for seeding and reseeding. pub struct ServoRng { rng: ReseedingRng<IsaacWordRng, ServoReseeder>, } impl Rng for ServoRng { #[inline] fn next_u32(&mut self) -> u32 { self.rng.next_u32() } #[inline] fn next_u64(&mut self) -> u64 { self.rng.next_u64() } } impl<'a> SeedableRng<&'a [usize]> for ServoRng { /// Create a manually-reseeding instane of `ServoRng`. /// /// Note that this RNG does not reseed itself, so care is needed to reseed the RNG /// is required to be cryptographically sound. fn from_seed(seed: &[usize]) -> ServoRng
/// Reseed the RNG. fn reseed(&mut self, seed: &'a [usize]) { debug!("Manually reseeding ServoRng."); self.rng.reseed((ServoReseeder, as_isaac_seed(seed))) } } impl ServoRng { /// Create an auto-reseeding instance of `ServoRng`. /// /// This uses the shared `OsRng`, so avoids consuming /// a file descriptor. pub fn new() -> ServoRng { debug!("Creating new ServoRng."); let mut os_rng = OS_RNG.lock().expect("Poisoned lock."); let isaac_rng = IsaacWordRng::rand(&mut *os_rng); let reseeding_rng = ReseedingRng::new(isaac_rng, RESEED_THRESHOLD, ServoReseeder); ServoRng { rng: reseeding_rng } } } // The reseeder for the in-memory RNG. struct ServoReseeder; impl Reseeder<IsaacWordRng> for ServoReseeder { fn reseed(&mut self, rng: &mut IsaacWordRng) { debug!("Reseeding ServoRng."); let mut os_rng = OS_RNG.lock().expect("Poisoned lock."); *rng = IsaacWordRng::rand(&mut *os_rng); } } impl Default for ServoReseeder { fn default() -> ServoReseeder { ServoReseeder } } // A thread-local RNG, designed as a drop-in replacement for rand::ThreadRng. #[derive(Clone)] pub struct ServoThreadRng { rng: Rc<RefCell<ServoRng>>, } // A thread-local RNG, designed as a drop-in replacement for rand::thread_rng. pub fn thread_rng() -> ServoThreadRng { SERVO_THREAD_RNG.with(|t| t.clone()) } thread_local! { static SERVO_THREAD_RNG: ServoThreadRng = ServoThreadRng { rng: Rc::new(RefCell::new(ServoRng::new())) }; } impl Rng for ServoThreadRng { fn next_u32(&mut self) -> u32 { self.rng.borrow_mut().next_u32() } fn next_u64(&mut self) -> u64 { self.rng.borrow_mut().next_u64() } #[inline] fn fill_bytes(&mut self, bytes: &mut [u8]) { self.rng.borrow_mut().fill_bytes(bytes) } } // Generates a random value using the thread-local random number generator. // A drop-in replacement for rand::random. #[inline] pub fn random<T: Rand>() -> T { thread_rng().gen() }
{ debug!("Creating new manually-reseeded ServoRng."); let isaac_rng = IsaacWordRng::from_seed(as_isaac_seed(seed)); let reseeding_rng = ReseedingRng::new(isaac_rng, u64::MAX, ServoReseeder); ServoRng { rng: reseeding_rng } }
identifier_body
lib.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/. */ /// A random number generator which shares one instance of an `OsRng`. /// /// A problem with `OsRng`, which is inherited by `StdRng` and so /// `ThreadRng`, is that it reads from `/dev/random`, and so consumes /// a file descriptor. For multi-threaded applications like Servo, /// it is easy to exhaust the supply of file descriptors this way. /// /// This crate fixes that, by only using one `OsRng`, which is just /// used to seed and re-seed an `ServoRng`. #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; pub use rand::{Rand, Rng, SeedableRng}; #[cfg(target_pointer_width = "64")] use rand::isaac::Isaac64Rng as IsaacWordRng; #[cfg(target_pointer_width = "32")] use rand::isaac::IsaacRng as IsaacWordRng; use rand::os::OsRng; use rand::reseeding::{ReseedingRng, Reseeder}; use std::cell::RefCell; use std::mem; use std::rc::Rc; use std::sync::Mutex; use std::u64; // Slightly annoying having to cast between sizes. #[cfg(target_pointer_width = "64")] fn as_isaac_seed(seed: &[usize]) -> &[u64] { unsafe { mem::transmute(seed) } } #[cfg(target_pointer_width = "32")] fn as_isaac_seed(seed: &[usize]) -> &[u32] { unsafe { mem::transmute(seed) } } // The shared RNG which may hold on to a file descriptor lazy_static! { static ref OS_RNG: Mutex<OsRng> = match OsRng::new() { Ok(r) => Mutex::new(r), Err(e) => panic!("Failed to seed OsRng: {}", e), }; } // Generate 32K of data between reseedings const RESEED_THRESHOLD: u64 = 32_768; // An in-memory RNG that only uses the shared file descriptor for seeding and reseeding. pub struct ServoRng { rng: ReseedingRng<IsaacWordRng, ServoReseeder>, } impl Rng for ServoRng { #[inline] fn next_u32(&mut self) -> u32 { self.rng.next_u32() } #[inline] fn
(&mut self) -> u64 { self.rng.next_u64() } } impl<'a> SeedableRng<&'a [usize]> for ServoRng { /// Create a manually-reseeding instane of `ServoRng`. /// /// Note that this RNG does not reseed itself, so care is needed to reseed the RNG /// is required to be cryptographically sound. fn from_seed(seed: &[usize]) -> ServoRng { debug!("Creating new manually-reseeded ServoRng."); let isaac_rng = IsaacWordRng::from_seed(as_isaac_seed(seed)); let reseeding_rng = ReseedingRng::new(isaac_rng, u64::MAX, ServoReseeder); ServoRng { rng: reseeding_rng } } /// Reseed the RNG. fn reseed(&mut self, seed: &'a [usize]) { debug!("Manually reseeding ServoRng."); self.rng.reseed((ServoReseeder, as_isaac_seed(seed))) } } impl ServoRng { /// Create an auto-reseeding instance of `ServoRng`. /// /// This uses the shared `OsRng`, so avoids consuming /// a file descriptor. pub fn new() -> ServoRng { debug!("Creating new ServoRng."); let mut os_rng = OS_RNG.lock().expect("Poisoned lock."); let isaac_rng = IsaacWordRng::rand(&mut *os_rng); let reseeding_rng = ReseedingRng::new(isaac_rng, RESEED_THRESHOLD, ServoReseeder); ServoRng { rng: reseeding_rng } } } // The reseeder for the in-memory RNG. struct ServoReseeder; impl Reseeder<IsaacWordRng> for ServoReseeder { fn reseed(&mut self, rng: &mut IsaacWordRng) { debug!("Reseeding ServoRng."); let mut os_rng = OS_RNG.lock().expect("Poisoned lock."); *rng = IsaacWordRng::rand(&mut *os_rng); } } impl Default for ServoReseeder { fn default() -> ServoReseeder { ServoReseeder } } // A thread-local RNG, designed as a drop-in replacement for rand::ThreadRng. #[derive(Clone)] pub struct ServoThreadRng { rng: Rc<RefCell<ServoRng>>, } // A thread-local RNG, designed as a drop-in replacement for rand::thread_rng. pub fn thread_rng() -> ServoThreadRng { SERVO_THREAD_RNG.with(|t| t.clone()) } thread_local! { static SERVO_THREAD_RNG: ServoThreadRng = ServoThreadRng { rng: Rc::new(RefCell::new(ServoRng::new())) }; } impl Rng for ServoThreadRng { fn next_u32(&mut self) -> u32 { self.rng.borrow_mut().next_u32() } fn next_u64(&mut self) -> u64 { self.rng.borrow_mut().next_u64() } #[inline] fn fill_bytes(&mut self, bytes: &mut [u8]) { self.rng.borrow_mut().fill_bytes(bytes) } } // Generates a random value using the thread-local random number generator. // A drop-in replacement for rand::random. #[inline] pub fn random<T: Rand>() -> T { thread_rng().gen() }
next_u64
identifier_name
rusti.rs
compiling things let binary = repl.binary.to_managed(); let options = @session::options { crate_type: session::unknown_crate, binary: binary, addl_lib_search_paths: @mut repl.lib_search_paths.map(|p| Path(*p)), jit: true, .. copy *session::basic_options() }; // Because we assume that everything is encodable (and assert so), add some // extra helpful information if the error crops up. Otherwise people are // bound to be very confused when they find out code is running that they // never typed in... let sess = driver::build_session(options, |cm, msg, lvl| { diagnostic::emit(cm, msg, lvl); if msg.contains("failed to find an implementation of trait") && msg.contains("extra::serialize::Encodable") { diagnostic::emit(cm, "Currrently rusti serializes bound locals between \ different lines of input. This means that all \ values of local variables need to be encodable, \ and this type isn't encodable", diagnostic::note); } }); let intr = token::get_ident_interner(); // // Stage 1: parse the input and filter it into the program (as necessary) // debug!("parsing: %s", input); let crate = parse_input(sess, binary, input); let mut to_run = ~[]; // statements to run (emitted back into code) let new_locals = @mut ~[]; // new locals being defined let mut result = None; // resultant expression (to print via pp) do find_main(crate, sess) |blk| { // Fish out all the view items, be sure to record 'extern mod' items // differently beause they must appear before all 'use' statements for blk.node.view_items.iter().advance |vi| { let s = do with_pp(intr) |pp, _| { pprust::print_view_item(pp, vi); }; match vi.node { ast::view_item_extern_mod(*) => { repl.program.record_extern(s); } ast::view_item_use(*) => { repl.program.record_view_item(s); } } } // Iterate through all of the block's statements, inserting them into // the correct portions of the program for blk.node.stmts.iter().advance |stmt| { let s = do with_pp(intr) |pp, _| { pprust::print_stmt(pp, *stmt); }; match stmt.node { ast::stmt_decl(d, _) => { match d.node { ast::decl_item(it) => { let name = sess.str_of(it.ident); match it.node { // Structs are treated specially because to make // them at all usable they need to be decorated // with #[deriving(Encoable, Decodable)] ast::item_struct(*) => { repl.program.record_struct(name, s); } // Item declarations are hoisted out of main() _ => { repl.program.record_item(name, s); } } } // Local declarations must be specially dealt with, // record all local declarations for use later on ast::decl_local(l) => { let mutbl = l.node.is_mutbl; do each_binding(l) |path, _| { let s = do with_pp(intr) |pp, _| { pprust::print_path(pp, path, false); }; new_locals.push((s, mutbl)); } to_run.push(s); } } } // run statements with expressions (they have effects) ast::stmt_mac(*) | ast::stmt_semi(*) | ast::stmt_expr(*) => { to_run.push(s); } } } result = do blk.node.expr.map_consume |e| { do with_pp(intr) |pp, _| { pprust::print_expr(pp, e); } }; } // return fast for empty inputs if to_run.len() == 0 && result.is_none() { return repl; } // // Stage 2: run everything up to typeck to learn the types of the new // variables introduced into the program // info!("Learning about the new types in the program"); repl.program.set_cache(); // before register_new_vars (which changes them) let input = to_run.connect("\n"); let test = repl.program.test_code(input, &result, *new_locals); debug!("testing with ^^^^^^ %?", (||{ println(test) })()); let dinput = driver::str_input(test.to_managed()); let cfg = driver::build_configuration(sess, binary, &dinput); let outputs = driver::build_output_filenames(&dinput, &None, &None, [], sess); let (crate, tcx) = driver::compile_upto(sess, copy cfg, &dinput, driver::cu_typeck, Some(outputs)); // Once we're typechecked, record the types of all local variables defined // in this input do find_main(crate.expect("crate after cu_typeck"), sess) |blk| { repl.program.register_new_vars(blk, tcx.expect("tcx after cu_typeck")); } // // Stage 3: Actually run the code in the JIT // info!("actually running code"); let code = repl.program.code(input, &result); debug!("actually running ^^^^^^ %?", (||{ println(code) })()); let input = driver::str_input(code.to_managed()); let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames(&input, &None, &None, [], sess); let sess = driver::build_session(options, diagnostic::emit); driver::compile_upto(sess, cfg, &input, driver::cu_everything, Some(outputs)); // // Stage 4: Inform the program that computation is done so it can update all // local variable bindings. // info!("cleaning up after code"); repl.program.consume_cache(); return repl; fn parse_input(sess: session::Session, binary: @str, input: &str) -> @ast::crate { let code = fmt!("fn main() {\n %s \n}", input); let input = driver::str_input(code.to_managed()); let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames(&input, &None, &None, [], sess); let (crate, _) = driver::compile_upto(sess, cfg, &input, driver::cu_parse, Some(outputs)); crate.expect("parsing should return a crate") } fn find_main(crate: @ast::crate, sess: session::Session, f: &fn(&ast::blk)) { for crate.node.module.items.iter().advance |item| { match item.node { ast::item_fn(_, _, _, _, ref blk) => { if item.ident == sess.ident_of("main") { return f(blk); } } _ => {} } } fail!("main function was expected somewhere..."); } } // Compiles a crate given by the filename as a library if the compiled // version doesn't exist or is older than the source file. Binary is // the name of the compiling executable. Returns Some(true) if it // successfully compiled, Some(false) if the crate wasn't compiled // because it already exists and is newer than the source file, or // None if there were compile errors. fn compile_crate(src_filename: ~str, binary: ~str) -> Option<bool> { match do task::try { let src_path = Path(src_filename); let binary = binary.to_managed(); let options = @session::options { binary: binary, addl_lib_search_paths: @mut ~[os::getcwd()], .. copy *session::basic_options() }; let input = driver::file_input(copy src_path); let sess = driver::build_session(options, diagnostic::emit); *sess.building_library = true; let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames( &input, &None, &None, [], sess); // If the library already exists and is newer than the source // file, skip compilation and return None. let mut should_compile = true; let dir = os::list_dir_path(&Path(outputs.out_filename.dirname())); let maybe_lib_path = do dir.iter().find_ |file| { // The actual file's name has a hash value and version // number in it which is unknown at this time, so looking // for a file that matches out_filename won't work, // instead we guess which file is the library by matching // the prefix and suffix of out_filename to files in the // directory. let file_str = file.filename().get(); file_str.starts_with(outputs.out_filename.filestem().get()) && file_str.ends_with(outputs.out_filename.filetype().get()) }; match maybe_lib_path { Some(lib_path) => { let (src_mtime, _) = src_path.get_mtime().get(); let (lib_mtime, _) = lib_path.get_mtime().get(); if lib_mtime >= src_mtime { should_compile = false; } }, None => { }, } if (should_compile) { println(fmt!("compiling %s...", src_filename)); driver::compile_upto(sess, cfg, &input, driver::cu_everything, Some(outputs)); true } else { false } } { Ok(true) => Some(true), Ok(false) => Some(false), Err(_) => None, } } /// Tries to get a line from rl after outputting a prompt. Returns /// None if no input was read (e.g. EOF was reached). fn get_line(use_rl: bool, prompt: &str) -> Option<~str> { if use_rl { let result = unsafe { rl::read(prompt) }; match result { None => None, Some(line) => { unsafe { rl::add_history(line) }; Some(line) } } } else { if io::stdin().eof() { None } else { Some(io::stdin().read_line()) } } } /// Run a command, e.g. :clear, :exit, etc. fn run_cmd(repl: &mut Repl, _in: @io::Reader, _out: @io::Writer, cmd: ~str, args: ~[~str], use_rl: bool) -> CmdAction { let mut action = action_none; match cmd { ~"exit" => repl.running = false, ~"clear" => { repl.program.clear(); // XXX: Win32 version of linenoise can't do this //rl::clear(); } ~"help" => { println( ":{\\n..lines.. \\n:}\\n - execute multiline command\n\ :load <crate>... - loads given crates as dynamic libraries\n\ :clear - clear the bindings\n\ :exit - exit from the repl\n\ :help - show this message"); } ~"load" => { let mut loaded_crates: ~[~str] = ~[]; for args.iter().advance |arg| { let (crate, filename) = if arg.ends_with(".rs") || arg.ends_with(".rc") { (arg.slice_to(arg.len() - 3).to_owned(), copy *arg) } else { (copy *arg, *arg + ".rs") }; match compile_crate(filename, copy repl.binary) { Some(_) => loaded_crates.push(crate), None => { } } } for loaded_crates.iter().advance |crate| { let crate_path = Path(*crate); let crate_dir = crate_path.dirname(); repl.program.record_extern(fmt!("extern mod %s;", *crate)); if!repl.lib_search_paths.iter().any(|x| x == &crate_dir) { repl.lib_search_paths.push(crate_dir); } } if loaded_crates.is_empty() { println("no crates loaded"); } else { println(fmt!("crates loaded: %s", loaded_crates.connect(", "))); } } ~"{" => { let mut multiline_cmd = ~""; let mut end_multiline = false; while (!end_multiline) { match get_line(use_rl, "rusti| ") { None => fail!("unterminated multiline command :{.. :}"), Some(line) => { if line.trim() == ":}" { end_multiline = true; } else { multiline_cmd.push_str(line); multiline_cmd.push_char('\n'); } } } } action = action_run_line(multiline_cmd); } _ => println(~"unknown cmd: " + cmd) } return action; } /// Executes a line of input, which may either be rust code or a /// :command. Returns a new Repl if it has changed. pub fn run_line(repl: &mut Repl, in: @io::Reader, out: @io::Writer, line: ~str, use_rl: bool) -> Option<Repl> { if line.starts_with(":") { // drop the : and the \n (one byte each) let full = line.slice(1, line.len()); let split: ~[~str] = full.word_iter().transform(|s| s.to_owned()).collect(); let len = split.len(); if len > 0 { let cmd = copy split[0]; if!cmd.is_empty() { let args = if len > 1 { split.slice(1, len).to_owned() } else { ~[] }; match run_cmd(repl, in, out, cmd, args, use_rl) { action_none => { } action_run_line(multiline_cmd) => { if!multiline_cmd.is_empty() { return run_line(repl, in, out, multiline_cmd, use_rl); } } } return None; } } } let line = Cell::new(line); let r = Cell::new(copy *repl); let result = do task::try { run(r.take(), line.take()) }; if result.is_ok() { return Some(result.get()); } return None; } pub fn main() { let args = os::args(); let in = io::stdin(); let out = io::stdout(); let mut repl = Repl { prompt: ~"rusti> ", binary: copy args[0], running: true, lib_search_paths: ~[], program: Program::new(), }; let istty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) }!= 0; // only print this stuff if the user is actually typing into rusti if istty { println("WARNING: The Rust REPL is experimental and may be"); println("unstable. If you encounter problems, please use the"); println("compiler instead. Type :help for help."); unsafe { do rl::complete |line, suggest| { if line.starts_with(":") { suggest(~":clear"); suggest(~":exit"); suggest(~":help"); suggest(~":load"); } } } } while repl.running { match get_line(istty, repl.prompt) { None => break, Some(line) => { if line.is_empty() { if istty { println("()"); } loop; } match run_line(&mut repl, in, out, line, istty) { Some(new_repl) => repl = new_repl, None => { } } } } } } #[cfg(test)] mod tests { use std::io; use std::iterator::IteratorUtil; use program::Program; use super::*; fn
() -> Repl {
repl
identifier_name
rusti.rs
* Rusti works by serializing state between lines of input. This means that each * line can be run in a separate task, and the only limiting factor is that all * local bound variables are encodable. * * This is accomplished by feeding in generated input to rustc for execution in * the JIT compiler. Currently input actually gets fed in three times to get * information about the program. * * - Pass #1 * In this pass, the input is simply thrown at the parser and the input comes * back. This validates the structure of the program, and at this stage the * global items (fns, structs, impls, traits, etc.) are filtered from the * input into the "global namespace". These declarations shadow all previous * declarations of an item by the same name. * * - Pass #2 * After items have been stripped, the remaining input is passed to rustc * along with all local variables declared (initialized to nothing). This pass * runs up to typechecking. From this, we can learn about the types of each * bound variable, what variables are bound, and also ensure that all the * types are encodable (the input can actually be run). * * - Pass #3 * Finally, a program is generated to deserialize the local variable state, * run the code input, and then reserialize all bindings back into a local * hash map. Once this code runs, the input has fully been run and the REPL * waits for new input. * * Encoding/decoding is done with EBML, and there is simply a map of ~str -> * ~[u8] maintaining the values of each local binding (by name). */ #[link(name = "rusti", vers = "0.8-pre", uuid = "7fb5bf52-7d45-4fee-8325-5ad3311149fc", url = "https://github.com/mozilla/rust/tree/master/src/rusti")]; #[license = "MIT/ASL2"]; #[crate_type = "lib"]; extern mod extra; extern mod rustc; extern mod syntax; use std::{libc, io, os, task}; use std::cell::Cell; use extra::rl; use rustc::driver::{driver, session}; use syntax::{ast, diagnostic}; use syntax::ast_util::*; use syntax::parse::token; use syntax::print::pprust; use program::Program; use utils::*; mod program; pub mod utils; /** * A structure shared across REPL instances for storing history * such as statements and view items. I wish the AST was sendable. */ pub struct Repl { prompt: ~str, binary: ~str, running: bool, lib_search_paths: ~[~str], program: Program, } // Action to do after reading a :command enum CmdAction { action_none, action_run_line(~str), } /// Run an input string in a Repl, returning the new Repl. fn run(mut repl: Repl, input: ~str) -> Repl { // Build some necessary rustc boilerplate for compiling things let binary = repl.binary.to_managed(); let options = @session::options { crate_type: session::unknown_crate, binary: binary, addl_lib_search_paths: @mut repl.lib_search_paths.map(|p| Path(*p)), jit: true, .. copy *session::basic_options() }; // Because we assume that everything is encodable (and assert so), add some // extra helpful information if the error crops up. Otherwise people are // bound to be very confused when they find out code is running that they // never typed in... let sess = driver::build_session(options, |cm, msg, lvl| { diagnostic::emit(cm, msg, lvl); if msg.contains("failed to find an implementation of trait") && msg.contains("extra::serialize::Encodable") { diagnostic::emit(cm, "Currrently rusti serializes bound locals between \ different lines of input. This means that all \ values of local variables need to be encodable, \ and this type isn't encodable", diagnostic::note); } }); let intr = token::get_ident_interner(); // // Stage 1: parse the input and filter it into the program (as necessary) // debug!("parsing: %s", input); let crate = parse_input(sess, binary, input); let mut to_run = ~[]; // statements to run (emitted back into code) let new_locals = @mut ~[]; // new locals being defined let mut result = None; // resultant expression (to print via pp) do find_main(crate, sess) |blk| { // Fish out all the view items, be sure to record 'extern mod' items // differently beause they must appear before all 'use' statements for blk.node.view_items.iter().advance |vi| { let s = do with_pp(intr) |pp, _| { pprust::print_view_item(pp, vi); }; match vi.node { ast::view_item_extern_mod(*) => { repl.program.record_extern(s); } ast::view_item_use(*) => { repl.program.record_view_item(s); } } } // Iterate through all of the block's statements, inserting them into // the correct portions of the program for blk.node.stmts.iter().advance |stmt| { let s = do with_pp(intr) |pp, _| { pprust::print_stmt(pp, *stmt); }; match stmt.node { ast::stmt_decl(d, _) => { match d.node { ast::decl_item(it) => { let name = sess.str_of(it.ident); match it.node { // Structs are treated specially because to make // them at all usable they need to be decorated // with #[deriving(Encoable, Decodable)] ast::item_struct(*) => { repl.program.record_struct(name, s); } // Item declarations are hoisted out of main() _ => { repl.program.record_item(name, s); } } } // Local declarations must be specially dealt with, // record all local declarations for use later on ast::decl_local(l) => { let mutbl = l.node.is_mutbl; do each_binding(l) |path, _| { let s = do with_pp(intr) |pp, _| { pprust::print_path(pp, path, false); }; new_locals.push((s, mutbl)); } to_run.push(s); } } } // run statements with expressions (they have effects) ast::stmt_mac(*) | ast::stmt_semi(*) | ast::stmt_expr(*) => { to_run.push(s); } } } result = do blk.node.expr.map_consume |e| { do with_pp(intr) |pp, _| { pprust::print_expr(pp, e); } }; } // return fast for empty inputs if to_run.len() == 0 && result.is_none() { return repl; } // // Stage 2: run everything up to typeck to learn the types of the new // variables introduced into the program // info!("Learning about the new types in the program"); repl.program.set_cache(); // before register_new_vars (which changes them) let input = to_run.connect("\n"); let test = repl.program.test_code(input, &result, *new_locals); debug!("testing with ^^^^^^ %?", (||{ println(test) })()); let dinput = driver::str_input(test.to_managed()); let cfg = driver::build_configuration(sess, binary, &dinput); let outputs = driver::build_output_filenames(&dinput, &None, &None, [], sess); let (crate, tcx) = driver::compile_upto(sess, copy cfg, &dinput, driver::cu_typeck, Some(outputs)); // Once we're typechecked, record the types of all local variables defined // in this input do find_main(crate.expect("crate after cu_typeck"), sess) |blk| { repl.program.register_new_vars(blk, tcx.expect("tcx after cu_typeck")); } // // Stage 3: Actually run the code in the JIT // info!("actually running code"); let code = repl.program.code(input, &result); debug!("actually running ^^^^^^ %?", (||{ println(code) })()); let input = driver::str_input(code.to_managed()); let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames(&input, &None, &None, [], sess); let sess = driver::build_session(options, diagnostic::emit); driver::compile_upto(sess, cfg, &input, driver::cu_everything, Some(outputs)); // // Stage 4: Inform the program that computation is done so it can update all // local variable bindings. // info!("cleaning up after code"); repl.program.consume_cache(); return repl; fn parse_input(sess: session::Session, binary: @str, input: &str) -> @ast::crate { let code = fmt!("fn main() {\n %s \n}", input); let input = driver::str_input(code.to_managed()); let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames(&input, &None, &None, [], sess); let (crate, _) = driver::compile_upto(sess, cfg, &input, driver::cu_parse, Some(outputs)); crate.expect("parsing should return a crate") } fn find_main(crate: @ast::crate, sess: session::Session, f: &fn(&ast::blk)) { for crate.node.module.items.iter().advance |item| { match item.node { ast::item_fn(_, _, _, _, ref blk) => { if item.ident == sess.ident_of("main") { return f(blk); } } _ => {} } } fail!("main function was expected somewhere..."); } } // Compiles a crate given by the filename as a library if the compiled // version doesn't exist or is older than the source file. Binary is // the name of the compiling executable. Returns Some(true) if it // successfully compiled, Some(false) if the crate wasn't compiled // because it already exists and is newer than the source file, or // None if there were compile errors. fn compile_crate(src_filename: ~str, binary: ~str) -> Option<bool> { match do task::try { let src_path = Path(src_filename); let binary = binary.to_managed(); let options = @session::options { binary: binary, addl_lib_search_paths: @mut ~[os::getcwd()], .. copy *session::basic_options() }; let input = driver::file_input(copy src_path); let sess = driver::build_session(options, diagnostic::emit); *sess.building_library = true; let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames( &input, &None, &None, [], sess); // If the library already exists and is newer than the source // file, skip compilation and return None. let mut should_compile = true; let dir = os::list_dir_path(&Path(outputs.out_filename.dirname())); let maybe_lib_path = do dir.iter().find_ |file| { // The actual file's name has a hash value and version // number in it which is unknown at this time, so looking // for a file that matches out_filename won't work, // instead we guess which file is the library by matching // the prefix and suffix of out_filename to files in the // directory. let file_str = file.filename().get(); file_str.starts_with(outputs.out_filename.filestem().get()) && file_str.ends_with(outputs.out_filename.filetype().get()) }; match maybe_lib_path { Some(lib_path) => { let (src_mtime, _) = src_path.get_mtime().get(); let (lib_mtime, _) = lib_path.get_mtime().get(); if lib_mtime >= src_mtime { should_compile = false; } }, None => { }, } if (should_compile) { println(fmt!("compiling %s...", src_filename)); driver::compile_upto(sess, cfg, &input, driver::cu_everything, Some(outputs)); true } else { false } } { Ok(true) => Some(true), Ok(false) => Some(false), Err(_) => None, } } /// Tries to get a line from rl after outputting a prompt. Returns /// None if no input was read (e.g. EOF was reached). fn get_line(use_rl: bool, prompt: &str) -> Option<~str> { if use_rl { let result = unsafe { rl::read(prompt) }; match result { None => None, Some(line) => { unsafe { rl::add_history(line) }; Some(line) } } } else { if io::stdin().eof() { None } else { Some(io::stdin().read_line()) } } } /// Run a command, e.g. :clear, :exit, etc. fn run_cmd(repl: &mut Repl, _in: @io::Reader, _out: @io::Writer, cmd: ~str, args: ~[~str], use_rl: bool) -> CmdAction { let mut action = action_none; match cmd { ~"exit" => repl.running = false, ~"clear" => { repl.program.clear(); // XXX: Win32 version of linenoise can't do this //rl::clear(); } ~"help" => { println( ":{\\n..lines.. \\n:}\\n - execute multiline command\n\ :load <crate>... - loads given crates as dynamic libraries\n\ :clear - clear the bindings\n\ :exit - exit from the repl\n\ :help - show this message"); } ~"load" => { let mut loaded_crates: ~[~str] = ~[]; for args.iter().advance |arg| { let (crate, filename) = if arg.ends_with(".rs") || arg.ends_with(".rc") { (arg.slice_to(arg.len() - 3).to_owned(), copy *arg) } else { (copy *arg, *arg + ".rs") }; match compile_crate(filename, copy repl.binary) { Some(_) => loaded_crates.push(crate), None => { } } } for loaded_crates.iter().advance |crate| { let crate_path = Path(*crate); let crate_dir = crate_path.dirname(); repl.program.record_extern(fmt!("extern mod %s;", *crate)); if!repl.lib_search_paths.iter().any(|x| x == &crate_dir) { repl.lib_search_paths.push(crate_dir); } } if loaded_crates.is_empty() { println("no crates loaded"); } else { println(fmt!("crates loaded: %s", loaded_crates.connect(", "))); } } ~"{" => { let mut multiline_cmd = ~""; let mut end_multiline = false; while (!end_multiline) { match get_line(use_rl, "rusti| ") { None => fail!("unterminated multiline command :{.. :}"), Some(line) => { if line.trim() == ":}" { end_multiline = true; } else { multiline_cmd.push_str(line); multiline_cmd.push_char('\n'); } } } } action = action_run_line(multiline_cmd); } _ => println(~"unknown cmd: " + cmd) } return action; } /// Executes a line of input, which may either be rust code or a /// :command. Returns a new Repl if it has changed. pub fn run_line(repl: &mut Repl, in: @io::Reader, out: @io::Writer, line: ~str, use_rl: bool) -> Option<Repl> { if line.starts_with(":") { // drop the : and the \n (one byte each) let full = line.slice(1, line.len()); let split: ~[~str] = full.word_iter().transform(|s| s.to_owned()).collect(); let len = split.len(); if len > 0 { let cmd = copy split[0]; if!cmd.is_empty() { let args = if len > 1 { split.slice(1, len).to_owned() } else { ~[] }; match run_cmd(repl, in, out, cmd, args, use_rl) { action_none => { } action_run_line(multiline_cmd) => { if!multiline_cmd.is_empty() { return run_line(repl, in, out, multiline_cmd, use_rl); } } } return None; } } } let line = Cell::new(line); let r = Cell::new(copy *repl); let result = do task::try { run(r.take(), line.take()) }; if result.is_ok() { return Some(result.get()); } return None; } pub fn main() { let args = os::args(); let in = io::stdin(); let out = io::stdout(); let mut repl = Repl {
/*! * rusti - A REPL using the JIT backend *
random_line_split
rusti.rs
} // Item declarations are hoisted out of main() _ => { repl.program.record_item(name, s); } } } // Local declarations must be specially dealt with, // record all local declarations for use later on ast::decl_local(l) => { let mutbl = l.node.is_mutbl; do each_binding(l) |path, _| { let s = do with_pp(intr) |pp, _| { pprust::print_path(pp, path, false); }; new_locals.push((s, mutbl)); } to_run.push(s); } } } // run statements with expressions (they have effects) ast::stmt_mac(*) | ast::stmt_semi(*) | ast::stmt_expr(*) => { to_run.push(s); } } } result = do blk.node.expr.map_consume |e| { do with_pp(intr) |pp, _| { pprust::print_expr(pp, e); } }; } // return fast for empty inputs if to_run.len() == 0 && result.is_none() { return repl; } // // Stage 2: run everything up to typeck to learn the types of the new // variables introduced into the program // info!("Learning about the new types in the program"); repl.program.set_cache(); // before register_new_vars (which changes them) let input = to_run.connect("\n"); let test = repl.program.test_code(input, &result, *new_locals); debug!("testing with ^^^^^^ %?", (||{ println(test) })()); let dinput = driver::str_input(test.to_managed()); let cfg = driver::build_configuration(sess, binary, &dinput); let outputs = driver::build_output_filenames(&dinput, &None, &None, [], sess); let (crate, tcx) = driver::compile_upto(sess, copy cfg, &dinput, driver::cu_typeck, Some(outputs)); // Once we're typechecked, record the types of all local variables defined // in this input do find_main(crate.expect("crate after cu_typeck"), sess) |blk| { repl.program.register_new_vars(blk, tcx.expect("tcx after cu_typeck")); } // // Stage 3: Actually run the code in the JIT // info!("actually running code"); let code = repl.program.code(input, &result); debug!("actually running ^^^^^^ %?", (||{ println(code) })()); let input = driver::str_input(code.to_managed()); let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames(&input, &None, &None, [], sess); let sess = driver::build_session(options, diagnostic::emit); driver::compile_upto(sess, cfg, &input, driver::cu_everything, Some(outputs)); // // Stage 4: Inform the program that computation is done so it can update all // local variable bindings. // info!("cleaning up after code"); repl.program.consume_cache(); return repl; fn parse_input(sess: session::Session, binary: @str, input: &str) -> @ast::crate { let code = fmt!("fn main() {\n %s \n}", input); let input = driver::str_input(code.to_managed()); let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames(&input, &None, &None, [], sess); let (crate, _) = driver::compile_upto(sess, cfg, &input, driver::cu_parse, Some(outputs)); crate.expect("parsing should return a crate") } fn find_main(crate: @ast::crate, sess: session::Session, f: &fn(&ast::blk)) { for crate.node.module.items.iter().advance |item| { match item.node { ast::item_fn(_, _, _, _, ref blk) => { if item.ident == sess.ident_of("main") { return f(blk); } } _ => {} } } fail!("main function was expected somewhere..."); } } // Compiles a crate given by the filename as a library if the compiled // version doesn't exist or is older than the source file. Binary is // the name of the compiling executable. Returns Some(true) if it // successfully compiled, Some(false) if the crate wasn't compiled // because it already exists and is newer than the source file, or // None if there were compile errors. fn compile_crate(src_filename: ~str, binary: ~str) -> Option<bool> { match do task::try { let src_path = Path(src_filename); let binary = binary.to_managed(); let options = @session::options { binary: binary, addl_lib_search_paths: @mut ~[os::getcwd()], .. copy *session::basic_options() }; let input = driver::file_input(copy src_path); let sess = driver::build_session(options, diagnostic::emit); *sess.building_library = true; let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames( &input, &None, &None, [], sess); // If the library already exists and is newer than the source // file, skip compilation and return None. let mut should_compile = true; let dir = os::list_dir_path(&Path(outputs.out_filename.dirname())); let maybe_lib_path = do dir.iter().find_ |file| { // The actual file's name has a hash value and version // number in it which is unknown at this time, so looking // for a file that matches out_filename won't work, // instead we guess which file is the library by matching // the prefix and suffix of out_filename to files in the // directory. let file_str = file.filename().get(); file_str.starts_with(outputs.out_filename.filestem().get()) && file_str.ends_with(outputs.out_filename.filetype().get()) }; match maybe_lib_path { Some(lib_path) => { let (src_mtime, _) = src_path.get_mtime().get(); let (lib_mtime, _) = lib_path.get_mtime().get(); if lib_mtime >= src_mtime { should_compile = false; } }, None => { }, } if (should_compile) { println(fmt!("compiling %s...", src_filename)); driver::compile_upto(sess, cfg, &input, driver::cu_everything, Some(outputs)); true } else { false } } { Ok(true) => Some(true), Ok(false) => Some(false), Err(_) => None, } } /// Tries to get a line from rl after outputting a prompt. Returns /// None if no input was read (e.g. EOF was reached). fn get_line(use_rl: bool, prompt: &str) -> Option<~str> { if use_rl { let result = unsafe { rl::read(prompt) }; match result { None => None, Some(line) => { unsafe { rl::add_history(line) }; Some(line) } } } else { if io::stdin().eof() { None } else { Some(io::stdin().read_line()) } } } /// Run a command, e.g. :clear, :exit, etc. fn run_cmd(repl: &mut Repl, _in: @io::Reader, _out: @io::Writer, cmd: ~str, args: ~[~str], use_rl: bool) -> CmdAction { let mut action = action_none; match cmd { ~"exit" => repl.running = false, ~"clear" => { repl.program.clear(); // XXX: Win32 version of linenoise can't do this //rl::clear(); } ~"help" => { println( ":{\\n..lines.. \\n:}\\n - execute multiline command\n\ :load <crate>... - loads given crates as dynamic libraries\n\ :clear - clear the bindings\n\ :exit - exit from the repl\n\ :help - show this message"); } ~"load" => { let mut loaded_crates: ~[~str] = ~[]; for args.iter().advance |arg| { let (crate, filename) = if arg.ends_with(".rs") || arg.ends_with(".rc") { (arg.slice_to(arg.len() - 3).to_owned(), copy *arg) } else { (copy *arg, *arg + ".rs") }; match compile_crate(filename, copy repl.binary) { Some(_) => loaded_crates.push(crate), None => { } } } for loaded_crates.iter().advance |crate| { let crate_path = Path(*crate); let crate_dir = crate_path.dirname(); repl.program.record_extern(fmt!("extern mod %s;", *crate)); if!repl.lib_search_paths.iter().any(|x| x == &crate_dir) { repl.lib_search_paths.push(crate_dir); } } if loaded_crates.is_empty() { println("no crates loaded"); } else { println(fmt!("crates loaded: %s", loaded_crates.connect(", "))); } } ~"{" => { let mut multiline_cmd = ~""; let mut end_multiline = false; while (!end_multiline) { match get_line(use_rl, "rusti| ") { None => fail!("unterminated multiline command :{.. :}"), Some(line) => { if line.trim() == ":}" { end_multiline = true; } else { multiline_cmd.push_str(line); multiline_cmd.push_char('\n'); } } } } action = action_run_line(multiline_cmd); } _ => println(~"unknown cmd: " + cmd) } return action; } /// Executes a line of input, which may either be rust code or a /// :command. Returns a new Repl if it has changed. pub fn run_line(repl: &mut Repl, in: @io::Reader, out: @io::Writer, line: ~str, use_rl: bool) -> Option<Repl> { if line.starts_with(":") { // drop the : and the \n (one byte each) let full = line.slice(1, line.len()); let split: ~[~str] = full.word_iter().transform(|s| s.to_owned()).collect(); let len = split.len(); if len > 0 { let cmd = copy split[0]; if!cmd.is_empty() { let args = if len > 1 { split.slice(1, len).to_owned() } else { ~[] }; match run_cmd(repl, in, out, cmd, args, use_rl) { action_none => { } action_run_line(multiline_cmd) => { if!multiline_cmd.is_empty() { return run_line(repl, in, out, multiline_cmd, use_rl); } } } return None; } } } let line = Cell::new(line); let r = Cell::new(copy *repl); let result = do task::try { run(r.take(), line.take()) }; if result.is_ok() { return Some(result.get()); } return None; } pub fn main() { let args = os::args(); let in = io::stdin(); let out = io::stdout(); let mut repl = Repl { prompt: ~"rusti> ", binary: copy args[0], running: true, lib_search_paths: ~[], program: Program::new(), }; let istty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) }!= 0; // only print this stuff if the user is actually typing into rusti if istty { println("WARNING: The Rust REPL is experimental and may be"); println("unstable. If you encounter problems, please use the"); println("compiler instead. Type :help for help."); unsafe { do rl::complete |line, suggest| { if line.starts_with(":") { suggest(~":clear"); suggest(~":exit"); suggest(~":help"); suggest(~":load"); } } } } while repl.running { match get_line(istty, repl.prompt) { None => break, Some(line) => { if line.is_empty() { if istty { println("()"); } loop; } match run_line(&mut repl, in, out, line, istty) { Some(new_repl) => repl = new_repl, None => { } } } } } } #[cfg(test)] mod tests { use std::io; use std::iterator::IteratorUtil; use program::Program; use super::*; fn repl() -> Repl { Repl { prompt: ~"rusti> ", binary: ~"rusti", running: true, lib_search_paths: ~[], program: Program::new(), } } // FIXME: #7220 rusti on 32bit mac doesn't work. // FIXME: #7641 rusti on 32bit linux cross compile doesn't work // FIXME: #7115 re-enable once LLVM has been upgraded #[cfg(thiswillneverbeacfgflag)] fn run_program(prog: &str) { let mut r = repl(); for prog.split_iter('\n').advance |cmd| { let result = run_line(&mut r, io::stdin(), io::stdout(), cmd.to_owned(), false); r = result.expect(fmt!("the command '%s' failed", cmd)); } } fn run_program(_: &str) {} #[test] fn super_basic() { run_program(""); } #[test] fn regression_5937() { run_program("use std::hashmap;"); } #[test] fn regression_5784() { run_program("let a = 3;"); } #[test] #[ignore] fn new_tasks() { // XXX: can't spawn new tasks because the JIT code is cleaned up // after the main function is done. run_program(" spawn( || println(\"Please don't segfault\") ); do spawn { println(\"Please?\"); } "); } #[test] fn inferred_integers_usable() { run_program("let a = 2;\n()\n"); run_program(" let a = 3; let b = 4u; assert!((a as uint) + b == 7) "); } #[test] fn local_variables_allow_shadowing() { run_program(" let a = 3; let a = 5; assert!(a == 5) "); } #[test] fn string_usable() { run_program(" let a = ~\"\"; let b = \"\"; let c = @\"\"; let d = a + b + c; assert!(d.len() == 0); "); } #[test] fn vectors_usable() { run_program(" let a = ~[1, 2, 3]; let b = &[1, 2, 3]; let c = @[1, 2, 3]; let d = a + b + c; assert!(d.len() == 9); let e: &[int] = []; "); } #[test] fn structs_usable() { run_program(" struct A{ a: int } let b = A{ a: 3 }; assert!(b.a == 3) "); } #[test] fn mutable_variables_work()
{ run_program(" let mut a = 3; a = 5; let mut b = std::hashmap::HashSet::new::<int>(); b.insert(a); assert!(b.contains(&5)) assert!(b.len() == 1) "); }
identifier_body
geometry.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 geom::point::Point2D; use geom::rect::Rect; use geom::size::Size2D; use std::num::{NumCast, One, Zero}; use std::fmt; // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. pub struct Au(i32); // We don't use #[deriving] here for inlining. impl Clone for Au { #[inline] fn clone(&self) -> Au { let Au(i) = *self; Au(i) } } impl fmt::Show for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Au(n) = *self; write!(f.buf, "Au({})", n) }} impl Eq for Au { #[inline] fn eq(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s == o } #[inline] fn ne(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s!= o } } impl Add<Au,Au> for Au { #[inline] fn add(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s + o) } } impl Sub<Au,Au> for Au { #[inline] fn sub(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s - o) } } impl Mul<Au,Au> for Au { #[inline] fn mul(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s * o) } } impl Div<Au,Au> for Au { #[inline] fn div(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s / o) } } impl Rem<Au,Au> for Au { #[inline] fn rem(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s % o) } } impl Neg<Au> for Au { #[inline] fn neg(&self) -> Au { let Au(s) = *self; Au(-s) } } impl Ord for Au { #[inline] fn lt(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s < o } #[inline] fn le(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s <= o } #[inline] fn ge(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s >= o } #[inline] fn gt(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s > o } } impl One for Au { #[inline] fn one() -> Au { Au(1) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } #[inline] fn is_zero(&self) -> bool { let Au(s) = *self; s == 0 } } impl Num for Au {} #[inline] pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } } #[inline] pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } } impl NumCast for Au { #[inline] fn from<T:ToPrimitive>(n: T) -> Option<Au> { Some(Au(n.to_i32().unwrap())) } } impl ToPrimitive for Au { #[inline] fn to_i64(&self) -> Option<i64> { let Au(s) = *self; Some(s as i64) } #[inline] fn to_u64(&self) -> Option<u64> { let Au(s) = *self; Some(s as u64) } #[inline] fn to_f32(&self) -> Option<f32> { let Au(s) = *self; s.to_f32() } #[inline] fn to_f64(&self) -> Option<f64> { let Au(s) = *self; s.to_f64() } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f64) -> Au { let Au(s) = self; Au(((s as f64) * factor) as i32) } #[inline] pub fn from_px(px: int) -> Au { NumCast::from(px * 60).unwrap() } #[inline] pub fn to_nearest_px(&self) -> int { let Au(s) = *self; ((s as f64) / 60f64).round() as int } #[inline] pub fn to_snapped(&self) -> Au { let Au(s) = *self; let res = s % 60i32; return if res >= 30i32 { return Au(s - res + 60i32) } else { return Au(s - res) }; } #[inline] pub fn zero_point() -> Point2D<Au> { Point2D(Au(0), Au(0)) } #[inline] pub fn zero_rect() -> Rect<Au> { let z = Au(0); Rect(Point2D(z, z), Size2D(z, z)) } #[inline] pub fn from_pt(pt: f64) -> Au { from_px(pt_to_px(pt) as int) } #[inline] pub fn from_frac_px(px: f64) -> Au { Au((px * 60f64) as i32) } #[inline] pub fn min(x: Au, y: Au) -> Au { let Au(xi) = x; let Au(yi) = y; if xi < yi { x } else
} #[inline] pub fn max(x: Au, y: Au) -> Au { let Au(xi) = x; let Au(yi) = y; if xi > yi { x } else { y } } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72f64 * 96f64 } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96f64 * 72f64 } pub fn zero_rect() -> Rect<Au> { let z = Au(0); Rect(Point2D(z, z), Size2D(z, z)) } pub fn zero_point() -> Point2D<Au> { Point2D(Au(0), Au(0)) } pub fn zero_size() -> Size2D<Au> { Size2D(Au(0), Au(0)) } pub fn from_frac_px(px: f64) -> Au { Au((px * 60f64) as i32) } pub fn from_px(px: int) -> Au { NumCast::from(px * 60).unwrap() } pub fn to_px(au: Au) -> int { let Au(a) = au; (a / 60) as int } pub fn to_frac_px(au: Au) -> f64 { let Au(a) = au; (a as f64) / 60f64 } // assumes 72 points per inch, and 96 px per inch pub fn from_pt(pt: f64) -> Au { from_px((pt / 72f64 * 96f64) as int) } // assumes 72 points per inch, and 96 px per inch pub fn to_pt(au: Au) -> f64 { let Au(a) = au; (a as f64) / 60f64 * 72f64 / 96f64 } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T:Ord + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height }
{ y }
conditional_block
geometry.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 geom::point::Point2D; use geom::rect::Rect; use geom::size::Size2D; use std::num::{NumCast, One, Zero}; use std::fmt; // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. pub struct Au(i32); // We don't use #[deriving] here for inlining. impl Clone for Au { #[inline] fn clone(&self) -> Au { let Au(i) = *self; Au(i) } } impl fmt::Show for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Au(n) = *self; write!(f.buf, "Au({})", n) }} impl Eq for Au { #[inline] fn eq(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s == o } #[inline] fn ne(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s!= o } } impl Add<Au,Au> for Au { #[inline] fn add(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s + o) } } impl Sub<Au,Au> for Au { #[inline] fn sub(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s - o) } } impl Mul<Au,Au> for Au { #[inline] fn mul(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s * o) } } impl Div<Au,Au> for Au { #[inline] fn div(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s / o) } } impl Rem<Au,Au> for Au { #[inline] fn rem(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s % o) } } impl Neg<Au> for Au { #[inline] fn neg(&self) -> Au { let Au(s) = *self; Au(-s) } } impl Ord for Au { #[inline] fn lt(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s < o } #[inline] fn le(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s <= o } #[inline] fn ge(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s >= o
let Au(s) = *self; let Au(o) = *other; s > o } } impl One for Au { #[inline] fn one() -> Au { Au(1) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } #[inline] fn is_zero(&self) -> bool { let Au(s) = *self; s == 0 } } impl Num for Au {} #[inline] pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } } #[inline] pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } } impl NumCast for Au { #[inline] fn from<T:ToPrimitive>(n: T) -> Option<Au> { Some(Au(n.to_i32().unwrap())) } } impl ToPrimitive for Au { #[inline] fn to_i64(&self) -> Option<i64> { let Au(s) = *self; Some(s as i64) } #[inline] fn to_u64(&self) -> Option<u64> { let Au(s) = *self; Some(s as u64) } #[inline] fn to_f32(&self) -> Option<f32> { let Au(s) = *self; s.to_f32() } #[inline] fn to_f64(&self) -> Option<f64> { let Au(s) = *self; s.to_f64() } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f64) -> Au { let Au(s) = self; Au(((s as f64) * factor) as i32) } #[inline] pub fn from_px(px: int) -> Au { NumCast::from(px * 60).unwrap() } #[inline] pub fn to_nearest_px(&self) -> int { let Au(s) = *self; ((s as f64) / 60f64).round() as int } #[inline] pub fn to_snapped(&self) -> Au { let Au(s) = *self; let res = s % 60i32; return if res >= 30i32 { return Au(s - res + 60i32) } else { return Au(s - res) }; } #[inline] pub fn zero_point() -> Point2D<Au> { Point2D(Au(0), Au(0)) } #[inline] pub fn zero_rect() -> Rect<Au> { let z = Au(0); Rect(Point2D(z, z), Size2D(z, z)) } #[inline] pub fn from_pt(pt: f64) -> Au { from_px(pt_to_px(pt) as int) } #[inline] pub fn from_frac_px(px: f64) -> Au { Au((px * 60f64) as i32) } #[inline] pub fn min(x: Au, y: Au) -> Au { let Au(xi) = x; let Au(yi) = y; if xi < yi { x } else { y } } #[inline] pub fn max(x: Au, y: Au) -> Au { let Au(xi) = x; let Au(yi) = y; if xi > yi { x } else { y } } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72f64 * 96f64 } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96f64 * 72f64 } pub fn zero_rect() -> Rect<Au> { let z = Au(0); Rect(Point2D(z, z), Size2D(z, z)) } pub fn zero_point() -> Point2D<Au> { Point2D(Au(0), Au(0)) } pub fn zero_size() -> Size2D<Au> { Size2D(Au(0), Au(0)) } pub fn from_frac_px(px: f64) -> Au { Au((px * 60f64) as i32) } pub fn from_px(px: int) -> Au { NumCast::from(px * 60).unwrap() } pub fn to_px(au: Au) -> int { let Au(a) = au; (a / 60) as int } pub fn to_frac_px(au: Au) -> f64 { let Au(a) = au; (a as f64) / 60f64 } // assumes 72 points per inch, and 96 px per inch pub fn from_pt(pt: f64) -> Au { from_px((pt / 72f64 * 96f64) as int) } // assumes 72 points per inch, and 96 px per inch pub fn to_pt(au: Au) -> f64 { let Au(a) = au; (a as f64) / 60f64 * 72f64 / 96f64 } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T:Ord + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height }
} #[inline] fn gt(&self, other: &Au) -> bool {
random_line_split
geometry.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 geom::point::Point2D; use geom::rect::Rect; use geom::size::Size2D; use std::num::{NumCast, One, Zero}; use std::fmt; // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. pub struct Au(i32); // We don't use #[deriving] here for inlining. impl Clone for Au { #[inline] fn clone(&self) -> Au { let Au(i) = *self; Au(i) } } impl fmt::Show for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Au(n) = *self; write!(f.buf, "Au({})", n) }} impl Eq for Au { #[inline] fn eq(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s == o } #[inline] fn ne(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s!= o } } impl Add<Au,Au> for Au { #[inline] fn add(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s + o) } } impl Sub<Au,Au> for Au { #[inline] fn sub(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s - o) } } impl Mul<Au,Au> for Au { #[inline] fn mul(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s * o) } } impl Div<Au,Au> for Au { #[inline] fn div(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s / o) } } impl Rem<Au,Au> for Au { #[inline] fn rem(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s % o) } } impl Neg<Au> for Au { #[inline] fn
(&self) -> Au { let Au(s) = *self; Au(-s) } } impl Ord for Au { #[inline] fn lt(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s < o } #[inline] fn le(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s <= o } #[inline] fn ge(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s >= o } #[inline] fn gt(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s > o } } impl One for Au { #[inline] fn one() -> Au { Au(1) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } #[inline] fn is_zero(&self) -> bool { let Au(s) = *self; s == 0 } } impl Num for Au {} #[inline] pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } } #[inline] pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } } impl NumCast for Au { #[inline] fn from<T:ToPrimitive>(n: T) -> Option<Au> { Some(Au(n.to_i32().unwrap())) } } impl ToPrimitive for Au { #[inline] fn to_i64(&self) -> Option<i64> { let Au(s) = *self; Some(s as i64) } #[inline] fn to_u64(&self) -> Option<u64> { let Au(s) = *self; Some(s as u64) } #[inline] fn to_f32(&self) -> Option<f32> { let Au(s) = *self; s.to_f32() } #[inline] fn to_f64(&self) -> Option<f64> { let Au(s) = *self; s.to_f64() } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f64) -> Au { let Au(s) = self; Au(((s as f64) * factor) as i32) } #[inline] pub fn from_px(px: int) -> Au { NumCast::from(px * 60).unwrap() } #[inline] pub fn to_nearest_px(&self) -> int { let Au(s) = *self; ((s as f64) / 60f64).round() as int } #[inline] pub fn to_snapped(&self) -> Au { let Au(s) = *self; let res = s % 60i32; return if res >= 30i32 { return Au(s - res + 60i32) } else { return Au(s - res) }; } #[inline] pub fn zero_point() -> Point2D<Au> { Point2D(Au(0), Au(0)) } #[inline] pub fn zero_rect() -> Rect<Au> { let z = Au(0); Rect(Point2D(z, z), Size2D(z, z)) } #[inline] pub fn from_pt(pt: f64) -> Au { from_px(pt_to_px(pt) as int) } #[inline] pub fn from_frac_px(px: f64) -> Au { Au((px * 60f64) as i32) } #[inline] pub fn min(x: Au, y: Au) -> Au { let Au(xi) = x; let Au(yi) = y; if xi < yi { x } else { y } } #[inline] pub fn max(x: Au, y: Au) -> Au { let Au(xi) = x; let Au(yi) = y; if xi > yi { x } else { y } } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72f64 * 96f64 } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96f64 * 72f64 } pub fn zero_rect() -> Rect<Au> { let z = Au(0); Rect(Point2D(z, z), Size2D(z, z)) } pub fn zero_point() -> Point2D<Au> { Point2D(Au(0), Au(0)) } pub fn zero_size() -> Size2D<Au> { Size2D(Au(0), Au(0)) } pub fn from_frac_px(px: f64) -> Au { Au((px * 60f64) as i32) } pub fn from_px(px: int) -> Au { NumCast::from(px * 60).unwrap() } pub fn to_px(au: Au) -> int { let Au(a) = au; (a / 60) as int } pub fn to_frac_px(au: Au) -> f64 { let Au(a) = au; (a as f64) / 60f64 } // assumes 72 points per inch, and 96 px per inch pub fn from_pt(pt: f64) -> Au { from_px((pt / 72f64 * 96f64) as int) } // assumes 72 points per inch, and 96 px per inch pub fn to_pt(au: Au) -> f64 { let Au(a) = au; (a as f64) / 60f64 * 72f64 / 96f64 } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T:Ord + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height }
neg
identifier_name
geometry.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 geom::point::Point2D; use geom::rect::Rect; use geom::size::Size2D; use std::num::{NumCast, One, Zero}; use std::fmt; // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. pub struct Au(i32); // We don't use #[deriving] here for inlining. impl Clone for Au { #[inline] fn clone(&self) -> Au { let Au(i) = *self; Au(i) } } impl fmt::Show for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Au(n) = *self; write!(f.buf, "Au({})", n) }} impl Eq for Au { #[inline] fn eq(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s == o } #[inline] fn ne(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s!= o } } impl Add<Au,Au> for Au { #[inline] fn add(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s + o) } } impl Sub<Au,Au> for Au { #[inline] fn sub(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s - o) } } impl Mul<Au,Au> for Au { #[inline] fn mul(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s * o) } } impl Div<Au,Au> for Au { #[inline] fn div(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s / o) } } impl Rem<Au,Au> for Au { #[inline] fn rem(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s % o) } } impl Neg<Au> for Au { #[inline] fn neg(&self) -> Au { let Au(s) = *self; Au(-s) } } impl Ord for Au { #[inline] fn lt(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s < o } #[inline] fn le(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s <= o } #[inline] fn ge(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s >= o } #[inline] fn gt(&self, other: &Au) -> bool { let Au(s) = *self; let Au(o) = *other; s > o } } impl One for Au { #[inline] fn one() -> Au { Au(1) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } #[inline] fn is_zero(&self) -> bool { let Au(s) = *self; s == 0 } } impl Num for Au {} #[inline] pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } } #[inline] pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } } impl NumCast for Au { #[inline] fn from<T:ToPrimitive>(n: T) -> Option<Au> { Some(Au(n.to_i32().unwrap())) } } impl ToPrimitive for Au { #[inline] fn to_i64(&self) -> Option<i64> { let Au(s) = *self; Some(s as i64) } #[inline] fn to_u64(&self) -> Option<u64> { let Au(s) = *self; Some(s as u64) } #[inline] fn to_f32(&self) -> Option<f32> { let Au(s) = *self; s.to_f32() } #[inline] fn to_f64(&self) -> Option<f64> { let Au(s) = *self; s.to_f64() } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f64) -> Au { let Au(s) = self; Au(((s as f64) * factor) as i32) } #[inline] pub fn from_px(px: int) -> Au { NumCast::from(px * 60).unwrap() } #[inline] pub fn to_nearest_px(&self) -> int
#[inline] pub fn to_snapped(&self) -> Au { let Au(s) = *self; let res = s % 60i32; return if res >= 30i32 { return Au(s - res + 60i32) } else { return Au(s - res) }; } #[inline] pub fn zero_point() -> Point2D<Au> { Point2D(Au(0), Au(0)) } #[inline] pub fn zero_rect() -> Rect<Au> { let z = Au(0); Rect(Point2D(z, z), Size2D(z, z)) } #[inline] pub fn from_pt(pt: f64) -> Au { from_px(pt_to_px(pt) as int) } #[inline] pub fn from_frac_px(px: f64) -> Au { Au((px * 60f64) as i32) } #[inline] pub fn min(x: Au, y: Au) -> Au { let Au(xi) = x; let Au(yi) = y; if xi < yi { x } else { y } } #[inline] pub fn max(x: Au, y: Au) -> Au { let Au(xi) = x; let Au(yi) = y; if xi > yi { x } else { y } } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72f64 * 96f64 } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96f64 * 72f64 } pub fn zero_rect() -> Rect<Au> { let z = Au(0); Rect(Point2D(z, z), Size2D(z, z)) } pub fn zero_point() -> Point2D<Au> { Point2D(Au(0), Au(0)) } pub fn zero_size() -> Size2D<Au> { Size2D(Au(0), Au(0)) } pub fn from_frac_px(px: f64) -> Au { Au((px * 60f64) as i32) } pub fn from_px(px: int) -> Au { NumCast::from(px * 60).unwrap() } pub fn to_px(au: Au) -> int { let Au(a) = au; (a / 60) as int } pub fn to_frac_px(au: Au) -> f64 { let Au(a) = au; (a as f64) / 60f64 } // assumes 72 points per inch, and 96 px per inch pub fn from_pt(pt: f64) -> Au { from_px((pt / 72f64 * 96f64) as int) } // assumes 72 points per inch, and 96 px per inch pub fn to_pt(au: Au) -> f64 { let Au(a) = au; (a as f64) / 60f64 * 72f64 / 96f64 } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T:Ord + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height }
{ let Au(s) = *self; ((s as f64) / 60f64).round() as int }
identifier_body
random_tuples_from_single.rs
use core::hash::Hash; use itertools::Itertools; use malachite_base::num::random::random_primitive_ints; use malachite_base::random::EXAMPLE_SEED; use malachite_base::tuples::random::{random_pairs_from_single, random_triples_from_single}; use malachite_base_test_util::stats::common_values_map::common_values_map_debug; use malachite_base_test_util::stats::median; use std::fmt::Debug; #[allow(clippy::type_complexity)] fn random_pairs_from_single_helper<I: Clone + Iterator>( xs: I, expected_values: &[(I::Item, I::Item)], expected_common_values: &[((I::Item, I::Item), usize)], expected_median: ((I::Item, I::Item), Option<(I::Item, I::Item)>), ) where I::Item: Clone + Debug + Eq + Hash + Ord, { let xs = random_pairs_from_single(xs); let values = xs.clone().take(20).collect_vec(); let common_values = common_values_map_debug(1000000, 10, xs.clone()); let median = median(xs.take(1000000)); assert_eq!( (values.as_slice(), common_values.as_slice(), median), (expected_values, expected_common_values, expected_median) ); } #[allow(clippy::type_complexity)] fn random_triples_from_single_helper<I: Clone + Iterator>( xs: I, expected_values: &[(I::Item, I::Item, I::Item)], expected_common_values: &[((I::Item, I::Item, I::Item), usize)], expected_median: ( (I::Item, I::Item, I::Item), Option<(I::Item, I::Item, I::Item)>, ), ) where I::Item: Clone + Debug + Eq + Hash + Ord, { let xs = random_triples_from_single(xs); let values = xs.clone().take(20).collect_vec(); let common_values = common_values_map_debug(1000000, 10, xs.clone()); let median = median(xs.take(1000000)); assert_eq!( (values.as_slice(), common_values.as_slice(), median), (expected_values, expected_common_values, expected_median) ); } #[test] fn test_random_tuples_from_single() { random_triples_from_single_helper( random_primitive_ints::<u8>(EXAMPLE_SEED), &[ (113, 239, 69), (108, 228, 210), (168, 161, 87), (32, 110, 83), (188, 34, 89), (238, 93, 200), (149, 115, 189), (149, 217, 201), (117, 146, 31), (72, 151, 169), (174, 33, 7), (38, 81, 144), (72, 127, 113), (128, 233, 107), (46, 119, 12), (18, 164, 243), (114, 174, 59), (247, 39, 174), (160, 184, 104), (37, 100, 252), ], &[ ((222, 60, 79), 4), ((26, 110, 13), 4), ((41, 254, 55), 4), ((109, 134, 76), 4),
((236, 57, 174), 4), ((73, 168, 192), 4), ((89, 197, 244), 4), ((91, 170, 115), 4), ((142, 168, 231), 4), ], ((127, 253, 76), Some((127, 253, 86))), ); random_pairs_from_single_helper( random_pairs_from_single(random_primitive_ints::<u8>(EXAMPLE_SEED)), &[ ((113, 239), (69, 108)), ((228, 210), (168, 161)), ((87, 32), (110, 83)), ((188, 34), (89, 238)), ((93, 200), (149, 115)), ((189, 149), (217, 201)), ((117, 146), (31, 72)), ((151, 169), (174, 33)), ((7, 38), (81, 144)), ((72, 127), (113, 128)), ((233, 107), (46, 119)), ((12, 18), (164, 243)), ((114, 174), (59, 247)), ((39, 174), (160, 184)), ((104, 37), (100, 252)), ((228, 122), (107, 69)), ((242, 248), (179, 142)), ((239, 233), (61, 189)), ((235, 85), (192, 7)), ((200, 90), (185, 178)), ], &[ (((28, 96), (0, 11)), 2), (((2, 43), (64, 233)), 2), (((20, 33), (14, 10)), 2), (((223, 84), (7, 22)), 2), (((43, 33), (131, 6)), 2), (((6, 233), (45, 89)), 2), (((65, 26), (6, 146)), 2), (((71, 80), (68, 88)), 2), (((9, 85), (186, 55)), 2), (((96, 254), (9, 37)), 2), ], (((127, 243), (125, 130)), Some(((127, 243), (134, 100)))), ); }
((165, 174, 73), 4),
random_line_split
random_tuples_from_single.rs
use core::hash::Hash; use itertools::Itertools; use malachite_base::num::random::random_primitive_ints; use malachite_base::random::EXAMPLE_SEED; use malachite_base::tuples::random::{random_pairs_from_single, random_triples_from_single}; use malachite_base_test_util::stats::common_values_map::common_values_map_debug; use malachite_base_test_util::stats::median; use std::fmt::Debug; #[allow(clippy::type_complexity)] fn random_pairs_from_single_helper<I: Clone + Iterator>( xs: I, expected_values: &[(I::Item, I::Item)], expected_common_values: &[((I::Item, I::Item), usize)], expected_median: ((I::Item, I::Item), Option<(I::Item, I::Item)>), ) where I::Item: Clone + Debug + Eq + Hash + Ord,
#[allow(clippy::type_complexity)] fn random_triples_from_single_helper<I: Clone + Iterator>( xs: I, expected_values: &[(I::Item, I::Item, I::Item)], expected_common_values: &[((I::Item, I::Item, I::Item), usize)], expected_median: ( (I::Item, I::Item, I::Item), Option<(I::Item, I::Item, I::Item)>, ), ) where I::Item: Clone + Debug + Eq + Hash + Ord, { let xs = random_triples_from_single(xs); let values = xs.clone().take(20).collect_vec(); let common_values = common_values_map_debug(1000000, 10, xs.clone()); let median = median(xs.take(1000000)); assert_eq!( (values.as_slice(), common_values.as_slice(), median), (expected_values, expected_common_values, expected_median) ); } #[test] fn test_random_tuples_from_single() { random_triples_from_single_helper( random_primitive_ints::<u8>(EXAMPLE_SEED), &[ (113, 239, 69), (108, 228, 210), (168, 161, 87), (32, 110, 83), (188, 34, 89), (238, 93, 200), (149, 115, 189), (149, 217, 201), (117, 146, 31), (72, 151, 169), (174, 33, 7), (38, 81, 144), (72, 127, 113), (128, 233, 107), (46, 119, 12), (18, 164, 243), (114, 174, 59), (247, 39, 174), (160, 184, 104), (37, 100, 252), ], &[ ((222, 60, 79), 4), ((26, 110, 13), 4), ((41, 254, 55), 4), ((109, 134, 76), 4), ((165, 174, 73), 4), ((236, 57, 174), 4), ((73, 168, 192), 4), ((89, 197, 244), 4), ((91, 170, 115), 4), ((142, 168, 231), 4), ], ((127, 253, 76), Some((127, 253, 86))), ); random_pairs_from_single_helper( random_pairs_from_single(random_primitive_ints::<u8>(EXAMPLE_SEED)), &[ ((113, 239), (69, 108)), ((228, 210), (168, 161)), ((87, 32), (110, 83)), ((188, 34), (89, 238)), ((93, 200), (149, 115)), ((189, 149), (217, 201)), ((117, 146), (31, 72)), ((151, 169), (174, 33)), ((7, 38), (81, 144)), ((72, 127), (113, 128)), ((233, 107), (46, 119)), ((12, 18), (164, 243)), ((114, 174), (59, 247)), ((39, 174), (160, 184)), ((104, 37), (100, 252)), ((228, 122), (107, 69)), ((242, 248), (179, 142)), ((239, 233), (61, 189)), ((235, 85), (192, 7)), ((200, 90), (185, 178)), ], &[ (((28, 96), (0, 11)), 2), (((2, 43), (64, 233)), 2), (((20, 33), (14, 10)), 2), (((223, 84), (7, 22)), 2), (((43, 33), (131, 6)), 2), (((6, 233), (45, 89)), 2), (((65, 26), (6, 146)), 2), (((71, 80), (68, 88)), 2), (((9, 85), (186, 55)), 2), (((96, 254), (9, 37)), 2), ], (((127, 243), (125, 130)), Some(((127, 243), (134, 100)))), ); }
{ let xs = random_pairs_from_single(xs); let values = xs.clone().take(20).collect_vec(); let common_values = common_values_map_debug(1000000, 10, xs.clone()); let median = median(xs.take(1000000)); assert_eq!( (values.as_slice(), common_values.as_slice(), median), (expected_values, expected_common_values, expected_median) ); }
identifier_body
random_tuples_from_single.rs
use core::hash::Hash; use itertools::Itertools; use malachite_base::num::random::random_primitive_ints; use malachite_base::random::EXAMPLE_SEED; use malachite_base::tuples::random::{random_pairs_from_single, random_triples_from_single}; use malachite_base_test_util::stats::common_values_map::common_values_map_debug; use malachite_base_test_util::stats::median; use std::fmt::Debug; #[allow(clippy::type_complexity)] fn random_pairs_from_single_helper<I: Clone + Iterator>( xs: I, expected_values: &[(I::Item, I::Item)], expected_common_values: &[((I::Item, I::Item), usize)], expected_median: ((I::Item, I::Item), Option<(I::Item, I::Item)>), ) where I::Item: Clone + Debug + Eq + Hash + Ord, { let xs = random_pairs_from_single(xs); let values = xs.clone().take(20).collect_vec(); let common_values = common_values_map_debug(1000000, 10, xs.clone()); let median = median(xs.take(1000000)); assert_eq!( (values.as_slice(), common_values.as_slice(), median), (expected_values, expected_common_values, expected_median) ); } #[allow(clippy::type_complexity)] fn
<I: Clone + Iterator>( xs: I, expected_values: &[(I::Item, I::Item, I::Item)], expected_common_values: &[((I::Item, I::Item, I::Item), usize)], expected_median: ( (I::Item, I::Item, I::Item), Option<(I::Item, I::Item, I::Item)>, ), ) where I::Item: Clone + Debug + Eq + Hash + Ord, { let xs = random_triples_from_single(xs); let values = xs.clone().take(20).collect_vec(); let common_values = common_values_map_debug(1000000, 10, xs.clone()); let median = median(xs.take(1000000)); assert_eq!( (values.as_slice(), common_values.as_slice(), median), (expected_values, expected_common_values, expected_median) ); } #[test] fn test_random_tuples_from_single() { random_triples_from_single_helper( random_primitive_ints::<u8>(EXAMPLE_SEED), &[ (113, 239, 69), (108, 228, 210), (168, 161, 87), (32, 110, 83), (188, 34, 89), (238, 93, 200), (149, 115, 189), (149, 217, 201), (117, 146, 31), (72, 151, 169), (174, 33, 7), (38, 81, 144), (72, 127, 113), (128, 233, 107), (46, 119, 12), (18, 164, 243), (114, 174, 59), (247, 39, 174), (160, 184, 104), (37, 100, 252), ], &[ ((222, 60, 79), 4), ((26, 110, 13), 4), ((41, 254, 55), 4), ((109, 134, 76), 4), ((165, 174, 73), 4), ((236, 57, 174), 4), ((73, 168, 192), 4), ((89, 197, 244), 4), ((91, 170, 115), 4), ((142, 168, 231), 4), ], ((127, 253, 76), Some((127, 253, 86))), ); random_pairs_from_single_helper( random_pairs_from_single(random_primitive_ints::<u8>(EXAMPLE_SEED)), &[ ((113, 239), (69, 108)), ((228, 210), (168, 161)), ((87, 32), (110, 83)), ((188, 34), (89, 238)), ((93, 200), (149, 115)), ((189, 149), (217, 201)), ((117, 146), (31, 72)), ((151, 169), (174, 33)), ((7, 38), (81, 144)), ((72, 127), (113, 128)), ((233, 107), (46, 119)), ((12, 18), (164, 243)), ((114, 174), (59, 247)), ((39, 174), (160, 184)), ((104, 37), (100, 252)), ((228, 122), (107, 69)), ((242, 248), (179, 142)), ((239, 233), (61, 189)), ((235, 85), (192, 7)), ((200, 90), (185, 178)), ], &[ (((28, 96), (0, 11)), 2), (((2, 43), (64, 233)), 2), (((20, 33), (14, 10)), 2), (((223, 84), (7, 22)), 2), (((43, 33), (131, 6)), 2), (((6, 233), (45, 89)), 2), (((65, 26), (6, 146)), 2), (((71, 80), (68, 88)), 2), (((9, 85), (186, 55)), 2), (((96, 254), (9, 37)), 2), ], (((127, 243), (125, 130)), Some(((127, 243), (134, 100)))), ); }
random_triples_from_single_helper
identifier_name
account.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethcore::ethstore::{EthStore, SecretStore, import_accounts, read_geth_accounts}; use ethcore::ethstore::dir::DiskDirectory; use ethcore::account_provider::AccountProvider; use helpers::{password_prompt, password_from_file}; #[derive(Debug, PartialEq)] pub enum AccountCmd { New(NewAccount), List(String), Import(ImportAccounts), ImportFromGeth(ImportFromGethAccounts) } #[derive(Debug, PartialEq)] pub struct NewAccount { pub iterations: u32, pub path: String, pub password_file: Option<String>, } #[derive(Debug, PartialEq)] pub struct ImportAccounts { pub from: Vec<String>, pub to: String, } /// Parameters for geth accounts' import #[derive(Debug, PartialEq)] pub struct ImportFromGethAccounts { /// import mainnet (false) or testnet (true) accounts pub testnet: bool, /// directory to import accounts to pub to: String, } pub fn execute(cmd: AccountCmd) -> Result<String, String> { match cmd { AccountCmd::New(new_cmd) => new(new_cmd), AccountCmd::List(path) => list(path), AccountCmd::Import(import_cmd) => import(import_cmd), AccountCmd::ImportFromGeth(import_geth_cmd) => import_geth(import_geth_cmd) } } fn keys_dir(path: String) -> Result<DiskDirectory, String> { DiskDirectory::create(path).map_err(|e| format!("Could not open keys directory: {}", e)) } fn secret_store(dir: Box<DiskDirectory>, iterations: Option<u32>) -> Result<EthStore, String> { match iterations { Some(i) => EthStore::open_with_iterations(dir, i), _ => EthStore::open(dir)
} fn new(n: NewAccount) -> Result<String, String> { let password: String = match n.password_file { Some(file) => try!(password_from_file(file)), None => try!(password_prompt()), }; let dir = Box::new(try!(keys_dir(n.path))); let secret_store = Box::new(try!(secret_store(dir, Some(n.iterations)))); let acc_provider = AccountProvider::new(secret_store); let new_account = try!(acc_provider.new_account(&password).map_err(|e| format!("Could not create new account: {}", e))); Ok(format!("{:?}", new_account)) } fn list(path: String) -> Result<String, String> { let dir = Box::new(try!(keys_dir(path))); let secret_store = Box::new(try!(secret_store(dir, None))); let acc_provider = AccountProvider::new(secret_store); let accounts = acc_provider.accounts(); let result = accounts.into_iter() .map(|a| format!("{:?}", a)) .collect::<Vec<String>>() .join("\n"); Ok(result) } fn import(i: ImportAccounts) -> Result<String, String> { let to = try!(keys_dir(i.to)); let mut imported = 0; for path in &i.from { let from = DiskDirectory::at(path); imported += try!(import_accounts(&from, &to).map_err(|_| "Importing accounts failed.")).len(); } Ok(format!("{} account(s) imported", imported)) } fn import_geth(i: ImportFromGethAccounts) -> Result<String, String> { use std::io::ErrorKind; use ethcore::ethstore::Error; let dir = Box::new(try!(keys_dir(i.to))); let secret_store = Box::new(try!(secret_store(dir, None))); let geth_accounts = read_geth_accounts(i.testnet); match secret_store.import_geth_accounts(geth_accounts, i.testnet) { Ok(v) => Ok(format!("Successfully imported {} account(s) from geth.", v.len())), Err(Error::Io(ref io_err)) if io_err.kind() == ErrorKind::NotFound => Err("Failed to find geth keys folder.".into()), Err(err) => Err(format!("Import geth accounts failed. {}", err)) } }
}.map_err(|e| format!("Could not open keys store: {}", e))
random_line_split
account.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethcore::ethstore::{EthStore, SecretStore, import_accounts, read_geth_accounts}; use ethcore::ethstore::dir::DiskDirectory; use ethcore::account_provider::AccountProvider; use helpers::{password_prompt, password_from_file}; #[derive(Debug, PartialEq)] pub enum AccountCmd { New(NewAccount), List(String), Import(ImportAccounts), ImportFromGeth(ImportFromGethAccounts) } #[derive(Debug, PartialEq)] pub struct NewAccount { pub iterations: u32, pub path: String, pub password_file: Option<String>, } #[derive(Debug, PartialEq)] pub struct ImportAccounts { pub from: Vec<String>, pub to: String, } /// Parameters for geth accounts' import #[derive(Debug, PartialEq)] pub struct
{ /// import mainnet (false) or testnet (true) accounts pub testnet: bool, /// directory to import accounts to pub to: String, } pub fn execute(cmd: AccountCmd) -> Result<String, String> { match cmd { AccountCmd::New(new_cmd) => new(new_cmd), AccountCmd::List(path) => list(path), AccountCmd::Import(import_cmd) => import(import_cmd), AccountCmd::ImportFromGeth(import_geth_cmd) => import_geth(import_geth_cmd) } } fn keys_dir(path: String) -> Result<DiskDirectory, String> { DiskDirectory::create(path).map_err(|e| format!("Could not open keys directory: {}", e)) } fn secret_store(dir: Box<DiskDirectory>, iterations: Option<u32>) -> Result<EthStore, String> { match iterations { Some(i) => EthStore::open_with_iterations(dir, i), _ => EthStore::open(dir) }.map_err(|e| format!("Could not open keys store: {}", e)) } fn new(n: NewAccount) -> Result<String, String> { let password: String = match n.password_file { Some(file) => try!(password_from_file(file)), None => try!(password_prompt()), }; let dir = Box::new(try!(keys_dir(n.path))); let secret_store = Box::new(try!(secret_store(dir, Some(n.iterations)))); let acc_provider = AccountProvider::new(secret_store); let new_account = try!(acc_provider.new_account(&password).map_err(|e| format!("Could not create new account: {}", e))); Ok(format!("{:?}", new_account)) } fn list(path: String) -> Result<String, String> { let dir = Box::new(try!(keys_dir(path))); let secret_store = Box::new(try!(secret_store(dir, None))); let acc_provider = AccountProvider::new(secret_store); let accounts = acc_provider.accounts(); let result = accounts.into_iter() .map(|a| format!("{:?}", a)) .collect::<Vec<String>>() .join("\n"); Ok(result) } fn import(i: ImportAccounts) -> Result<String, String> { let to = try!(keys_dir(i.to)); let mut imported = 0; for path in &i.from { let from = DiskDirectory::at(path); imported += try!(import_accounts(&from, &to).map_err(|_| "Importing accounts failed.")).len(); } Ok(format!("{} account(s) imported", imported)) } fn import_geth(i: ImportFromGethAccounts) -> Result<String, String> { use std::io::ErrorKind; use ethcore::ethstore::Error; let dir = Box::new(try!(keys_dir(i.to))); let secret_store = Box::new(try!(secret_store(dir, None))); let geth_accounts = read_geth_accounts(i.testnet); match secret_store.import_geth_accounts(geth_accounts, i.testnet) { Ok(v) => Ok(format!("Successfully imported {} account(s) from geth.", v.len())), Err(Error::Io(ref io_err)) if io_err.kind() == ErrorKind::NotFound => Err("Failed to find geth keys folder.".into()), Err(err) => Err(format!("Import geth accounts failed. {}", err)) } }
ImportFromGethAccounts
identifier_name
metric.rs
// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software
// use super::item; pub trait Metric : Sync + Send { fn log(&self, &str, &str, &str); fn counter(&self, &str) -> item::Counter; fn gauge(&self, &str) -> item::Gauge; fn display(&self); }
// distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.
random_line_split
error.rs
// Copyright (C) 2015 Élisabeth HENRY. // // This file is part of Caribon. // // Caribon 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, either version 2.1 of the License, or // (at your option) any later version. // // Caribon 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 Caribon. If not, see <http://www.gnu.org/licenses/>. use std::error; use std::result; use std::fmt; #[derive(Debug)] /// Caribon error type (just a String currently) pub struct Error { pub content: String, } impl Error { pub fn new(s: &str) -> Error { Error { content: s.to_owned() } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
} impl error::Error for Error { fn description(&self) -> &str { &self.content } } /// Caribon Result, used by some functions pub type Result<T> = result::Result<T, Error>;
f.write_str(&self.content) }
identifier_body
error.rs
// Copyright (C) 2015 Élisabeth HENRY. // // This file is part of Caribon. // // Caribon 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, either version 2.1 of the License, or // (at your option) any later version. // // Caribon 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 Caribon. If not, see <http://www.gnu.org/licenses/>. use std::error; use std::result; use std::fmt; #[derive(Debug)] /// Caribon error type (just a String currently) pub struct Error { pub content: String, } impl Error { pub fn n
s: &str) -> Error { Error { content: s.to_owned() } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.content) } } impl error::Error for Error { fn description(&self) -> &str { &self.content } } /// Caribon Result, used by some functions pub type Result<T> = result::Result<T, Error>;
ew(
identifier_name
error.rs
// Copyright (C) 2015 Élisabeth HENRY. // // This file is part of Caribon. // // Caribon 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, either version 2.1 of the License, or // (at your option) any later version. // // Caribon 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 Caribon. If not, see <http://www.gnu.org/licenses/>. use std::error; use std::result; use std::fmt; #[derive(Debug)] /// Caribon error type (just a String currently) pub struct Error { pub content: String, } impl Error { pub fn new(s: &str) -> Error { Error { content: s.to_owned() } } }
impl error::Error for Error { fn description(&self) -> &str { &self.content } } /// Caribon Result, used by some functions pub type Result<T> = result::Result<T, Error>;
impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.content) } }
random_line_split
testing.rs
#![cfg(test)] use test::Bencher; use types::*; use magics::*; use uci; static mut INITIALIZED: bool = false; pub fn check_init()
#[bench] pub fn move_gen(b: &mut Bencher) { check_init(); let board = Board::start_position(); b.iter(|| board.get_moves()); } // #[bench] // pub fn get_moves(b: &mut Bencher) { // check_init(); // let mut res = 0; // let c = 0; // // b.iter(|| black_box({ // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // })); // }
{ unsafe { if !INITIALIZED { uci::init(); INITIALIZED = true; } } }
identifier_body
testing.rs
#![cfg(test)] use test::Bencher; use types::*;
static mut INITIALIZED: bool = false; pub fn check_init() { unsafe { if!INITIALIZED { uci::init(); INITIALIZED = true; } } } #[bench] pub fn move_gen(b: &mut Bencher) { check_init(); let board = Board::start_position(); b.iter(|| board.get_moves()); } // #[bench] // pub fn get_moves(b: &mut Bencher) { // check_init(); // let mut res = 0; // let c = 0; // // b.iter(|| black_box({ // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // })); // }
use magics::*; use uci;
random_line_split
testing.rs
#![cfg(test)] use test::Bencher; use types::*; use magics::*; use uci; static mut INITIALIZED: bool = false; pub fn
() { unsafe { if!INITIALIZED { uci::init(); INITIALIZED = true; } } } #[bench] pub fn move_gen(b: &mut Bencher) { check_init(); let board = Board::start_position(); b.iter(|| board.get_moves()); } // #[bench] // pub fn get_moves(b: &mut Bencher) { // check_init(); // let mut res = 0; // let c = 0; // // b.iter(|| black_box({ // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // })); // }
check_init
identifier_name
testing.rs
#![cfg(test)] use test::Bencher; use types::*; use magics::*; use uci; static mut INITIALIZED: bool = false; pub fn check_init() { unsafe { if!INITIALIZED
} } #[bench] pub fn move_gen(b: &mut Bencher) { check_init(); let board = Board::start_position(); b.iter(|| board.get_moves()); } // #[bench] // pub fn get_moves(b: &mut Bencher) { // check_init(); // let mut res = 0; // let c = 0; // // b.iter(|| black_box({ // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // res |= bishop_moves(0, c); // // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // res |= rook_moves(0, c); // })); // }
{ uci::init(); INITIALIZED = true; }
conditional_block
small-enums-with-fields.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. // run-pass use std::mem::size_of; #[derive(PartialEq, Debug)] enum Either<T, U> { Left(T), Right(U) } macro_rules! check { ($t:ty, $sz:expr, $($e:expr, $s:expr),*) => {{ assert_eq!(size_of::<$t>(), $sz); $({ static S: $t = $e; let v: $t = $e; assert_eq!(S, v); assert_eq!(format!("{:?}", v), $s); assert_eq!(format!("{:?}", S), $s); });* }} } pub fn main() { check!(Option<u8>, 2,
Some(-20000), "Some(-20000)"); check!(Either<u8, i8>, 2, Either::Left(132), "Left(132)", Either::Right(-32), "Right(-32)"); check!(Either<u8, i16>, 4, Either::Left(132), "Left(132)", Either::Right(-20000), "Right(-20000)"); }
None, "None", Some(129), "Some(129)"); check!(Option<i16>, 4, None, "None",
random_line_split
small-enums-with-fields.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. // run-pass use std::mem::size_of; #[derive(PartialEq, Debug)] enum
<T, U> { Left(T), Right(U) } macro_rules! check { ($t:ty, $sz:expr, $($e:expr, $s:expr),*) => {{ assert_eq!(size_of::<$t>(), $sz); $({ static S: $t = $e; let v: $t = $e; assert_eq!(S, v); assert_eq!(format!("{:?}", v), $s); assert_eq!(format!("{:?}", S), $s); });* }} } pub fn main() { check!(Option<u8>, 2, None, "None", Some(129), "Some(129)"); check!(Option<i16>, 4, None, "None", Some(-20000), "Some(-20000)"); check!(Either<u8, i8>, 2, Either::Left(132), "Left(132)", Either::Right(-32), "Right(-32)"); check!(Either<u8, i16>, 4, Either::Left(132), "Left(132)", Either::Right(-20000), "Right(-20000)"); }
Either
identifier_name
small-enums-with-fields.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. // run-pass use std::mem::size_of; #[derive(PartialEq, Debug)] enum Either<T, U> { Left(T), Right(U) } macro_rules! check { ($t:ty, $sz:expr, $($e:expr, $s:expr),*) => {{ assert_eq!(size_of::<$t>(), $sz); $({ static S: $t = $e; let v: $t = $e; assert_eq!(S, v); assert_eq!(format!("{:?}", v), $s); assert_eq!(format!("{:?}", S), $s); });* }} } pub fn main()
{ check!(Option<u8>, 2, None, "None", Some(129), "Some(129)"); check!(Option<i16>, 4, None, "None", Some(-20000), "Some(-20000)"); check!(Either<u8, i8>, 2, Either::Left(132), "Left(132)", Either::Right(-32), "Right(-32)"); check!(Either<u8, i16>, 4, Either::Left(132), "Left(132)", Either::Right(-20000), "Right(-20000)"); }
identifier_body
reconnect.rs
#![allow(unused_variables)] #![allow(unused_imports)] extern crate fred; extern crate tokio_core; extern crate tokio_timer_patched as tokio_timer; extern crate futures; #[macro_use] extern crate log; extern crate pretty_env_logger; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use fred::error::*; use tokio_core::reactor::Core; use tokio_timer::Timer; use futures::Future; use futures::stream::Stream; use std::time::Duration; fn
() { pretty_env_logger::init(); let config = RedisConfig::default(); let policy = ReconnectPolicy::Constant { delay: 1000, attempts: 0, // retry forever max_attempts: 0 }; let timer = Timer::default(); let mut core = Core::new().unwrap(); let handle = core.handle(); println!("Connecting to {:?} with policy {:?}", config, policy); let client = RedisClient::new(config, Some(timer.clone())); let connection = client.connect_with_policy(&handle, policy); let errors = client.on_error().for_each(|err| { println!("Client error: {:?}", err); Ok(()) }); let reconnects = client.on_reconnect().for_each(|client| { println!("Client reconnected."); Ok(()) }); let commands = client.on_connect().and_then(|client| { println!("Client connected."); client.select(1) }) .and_then(|client| { // sleep for 30 seconds, maybe restart the redis server in another process... println!("Sleeping for 30 seconds..."); timer.sleep(Duration::from_millis(30 * 1000)) .from_err::<RedisError>() .map(move |_| client) }) .and_then(|client| { client.quit() }); let joined = connection.join(commands) .join(errors) .join(reconnects); let _ = core.run(joined).unwrap(); }
main
identifier_name
reconnect.rs
#![allow(unused_variables)] #![allow(unused_imports)] extern crate fred; extern crate tokio_core; extern crate tokio_timer_patched as tokio_timer; extern crate futures; #[macro_use] extern crate log; extern crate pretty_env_logger; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use fred::error::*; use tokio_core::reactor::Core; use tokio_timer::Timer; use futures::Future; use futures::stream::Stream; use std::time::Duration; fn main() { pretty_env_logger::init(); let config = RedisConfig::default(); let policy = ReconnectPolicy::Constant { delay: 1000, attempts: 0, // retry forever max_attempts: 0 }; let timer = Timer::default(); let mut core = Core::new().unwrap(); let handle = core.handle(); println!("Connecting to {:?} with policy {:?}", config, policy); let client = RedisClient::new(config, Some(timer.clone())); let connection = client.connect_with_policy(&handle, policy); let errors = client.on_error().for_each(|err| { println!("Client error: {:?}", err); Ok(()) }); let reconnects = client.on_reconnect().for_each(|client| { println!("Client reconnected."); Ok(()) }); let commands = client.on_connect().and_then(|client| { println!("Client connected."); client.select(1) }) .and_then(|client| { // sleep for 30 seconds, maybe restart the redis server in another process... println!("Sleeping for 30 seconds..."); timer.sleep(Duration::from_millis(30 * 1000)) .from_err::<RedisError>()
}); let joined = connection.join(commands) .join(errors) .join(reconnects); let _ = core.run(joined).unwrap(); }
.map(move |_| client) }) .and_then(|client| { client.quit()
random_line_split
reconnect.rs
#![allow(unused_variables)] #![allow(unused_imports)] extern crate fred; extern crate tokio_core; extern crate tokio_timer_patched as tokio_timer; extern crate futures; #[macro_use] extern crate log; extern crate pretty_env_logger; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use fred::error::*; use tokio_core::reactor::Core; use tokio_timer::Timer; use futures::Future; use futures::stream::Stream; use std::time::Duration; fn main()
let errors = client.on_error().for_each(|err| { println!("Client error: {:?}", err); Ok(()) }); let reconnects = client.on_reconnect().for_each(|client| { println!("Client reconnected."); Ok(()) }); let commands = client.on_connect().and_then(|client| { println!("Client connected."); client.select(1) }) .and_then(|client| { // sleep for 30 seconds, maybe restart the redis server in another process... println!("Sleeping for 30 seconds..."); timer.sleep(Duration::from_millis(30 * 1000)) .from_err::<RedisError>() .map(move |_| client) }) .and_then(|client| { client.quit() }); let joined = connection.join(commands) .join(errors) .join(reconnects); let _ = core.run(joined).unwrap(); }
{ pretty_env_logger::init(); let config = RedisConfig::default(); let policy = ReconnectPolicy::Constant { delay: 1000, attempts: 0, // retry forever max_attempts: 0 }; let timer = Timer::default(); let mut core = Core::new().unwrap(); let handle = core.handle(); println!("Connecting to {:?} with policy {:?}", config, policy); let client = RedisClient::new(config, Some(timer.clone())); let connection = client.connect_with_policy(&handle, policy);
identifier_body
destructured-fn-argument.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print a // check:$1 = 1 // debugger:print b // check:$2 = false // debugger:continue // debugger:finish // debugger:print a // check:$3 = 2 // debugger:print b // check:$4 = 3 // debugger:print c // check:$5 = 4 // debugger:continue // debugger:finish // debugger:print a // check:$6 = 5 // debugger:print b // check:$7 = {6, 7} // debugger:continue // debugger:finish // debugger:print h // check:$8 = 8 // debugger:print i // check:$9 = {a = 9, b = 10} // debugger:print j // check:$10 = 11 // debugger:continue // debugger:finish // debugger:print k // check:$11 = 12 // debugger:print l // check:$12 = 13 // debugger:continue // debugger:finish // debugger:print m // check:$13 = 14 // debugger:print n // check:$14 = 16 // debugger:continue // debugger:finish // debugger:print o // check:$15 = 18 // debugger:continue // debugger:finish // debugger:print p // check:$16 = 19 // debugger:print q // check:$17 = 20 // debugger:print r // check:$18 = {a = 21, b = 22} // debugger:continue // debugger:finish // debugger:print s // check:$19 = 24 // debugger:print t // check:$20 = 23 // debugger:continue // debugger:finish // debugger:print u // check:$21 = 25 // debugger:print v // check:$22 = 26 // debugger:print w // check:$23 = 27 // debugger:print x // check:$24 = 28 // debugger:print y // check:$25 = 29 // debugger:print z // check:$26 = 30 // debugger:print ae // check:$27 = 31 // debugger:print oe
// debugger:continue // debugger:finish // debugger:print aa // check:$30 = {34, 35} // debugger:continue // debugger:finish // debugger:print bb // check:$31 = {36, 37} // debugger:continue // debugger:finish // debugger:print cc // check:$32 = 38 // debugger:continue // debugger:finish // debugger:print dd // check:$33 = {40, 41, 42} // debugger:continue // debugger:finish // debugger:print *ee // check:$34 = {43, 44, 45} // debugger:continue // debugger:finish // debugger:print *ff // check:$35 = 46 // debugger:print gg // check:$36 = {47, 48} // debugger:continue // debugger:finish // debugger:print *hh // check:$37 = 50 // debugger:continue // debugger:finish // debugger:print ii // check:$38 = 51 // debugger:continue // debugger:finish // debugger:print *jj // check:$39 = 52 // debugger:continue // debugger:finish // debugger:print kk // check:$40 = 53 // debugger:print ll // check:$41 = 54 // debugger:continue // debugger:finish // debugger:print mm // check:$42 = 55 // debugger:print *nn // check:$43 = 56 // debugger:continue // debugger:finish // debugger:print oo // check:$44 = 57 // debugger:print pp // check:$45 = 58 // debugger:print qq // check:$46 = 59 // debugger:continue // debugger:finish // debugger:print rr // check:$47 = 60 // debugger:print ss // check:$48 = 61 // debugger:print tt // check:$49 = 62 // debugger:continue #[allow(unused_variable)]; struct Struct { a: i64, b: i32 } enum Univariant { Unit(i32) } struct TupleStruct (f64, int); fn simple_tuple((a, b): (int, bool)) { zzz(); } fn nested_tuple((a, (b, c)): (int, (u16, u16))) { zzz(); } fn destructure_only_first_level((a, b): (int, (u32, u32))) { zzz(); } fn struct_as_tuple_element((h, i, j): (i16, Struct, i16)) { zzz(); } fn struct_pattern(Struct { a: k, b: l }: Struct) { zzz(); } fn ignored_tuple_element((m, _, n): (int, u16, i32)) { zzz(); } fn ignored_struct_field(Struct { b: o,.. }: Struct) { zzz(); } fn one_struct_destructured_one_not((Struct { a: p, b: q }, r): (Struct, Struct)) { zzz(); } fn different_order_of_struct_fields(Struct { b: s, a: t }: Struct ) { zzz(); } fn complex_nesting(((u, v ), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue ): ((i16, i32), ((i64, (i32, Struct, )), Struct ), u16)) { zzz(); } fn managed_box(&aa: &(int, int)) { zzz(); } fn borrowed_pointer(&bb: &(int, int)) { zzz(); } fn contained_borrowed_pointer((&cc, _): (&int, int)) { zzz(); } fn unique_pointer(~dd: ~(int, int, int)) { zzz(); } fn ref_binding(ref ee: (int, int, int)) { zzz(); } fn ref_binding_in_tuple((ref ff, gg): (int, (int, int))) { zzz(); } fn ref_binding_in_struct(Struct { b: ref hh,.. }: Struct) { zzz(); } fn univariant_enum(Unit(ii): Univariant) { zzz(); } fn univariant_enum_with_ref_binding(Unit(ref jj): Univariant) { zzz(); } fn tuple_struct(TupleStruct(kk, ll): TupleStruct) { zzz(); } fn tuple_struct_with_ref_binding(TupleStruct(mm, ref nn): TupleStruct) { zzz(); } fn multiple_arguments((oo, pp): (int, int), qq : int) { zzz(); } fn main() { simple_tuple((1, false)); nested_tuple((2, (3, 4))); destructure_only_first_level((5, (6, 7))); struct_as_tuple_element((8, Struct { a: 9, b: 10 }, 11)); struct_pattern(Struct { a: 12, b: 13 }); ignored_tuple_element((14, 15, 16)); ignored_struct_field(Struct { a: 17, b: 18 }); one_struct_destructured_one_not((Struct { a: 19, b: 20 }, Struct { a: 21, b: 22 })); different_order_of_struct_fields(Struct { a: 23, b: 24 }); complex_nesting(((25, 26), ((27, (28, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33)); managed_box(&(34, 35)); borrowed_pointer(&(36, 37)); contained_borrowed_pointer((&38, 39)); unique_pointer(~(40, 41, 42)); ref_binding((43, 44, 45)); ref_binding_in_tuple((46, (47, 48))); ref_binding_in_struct(Struct { a: 49, b: 50 }); univariant_enum(Unit(51)); univariant_enum_with_ref_binding(Unit(52)); tuple_struct(TupleStruct(53.0, 54)); tuple_struct_with_ref_binding(TupleStruct(55.0, 56)); multiple_arguments((57, 58), 59); fn nested_function(rr: int, (ss, tt): (int, int)) { zzz(); } nested_function(60, (61, 62)); } fn zzz() {()}
// check:$28 = 32 // debugger:print ue // check:$29 = 33
random_line_split
destructured-fn-argument.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print a // check:$1 = 1 // debugger:print b // check:$2 = false // debugger:continue // debugger:finish // debugger:print a // check:$3 = 2 // debugger:print b // check:$4 = 3 // debugger:print c // check:$5 = 4 // debugger:continue // debugger:finish // debugger:print a // check:$6 = 5 // debugger:print b // check:$7 = {6, 7} // debugger:continue // debugger:finish // debugger:print h // check:$8 = 8 // debugger:print i // check:$9 = {a = 9, b = 10} // debugger:print j // check:$10 = 11 // debugger:continue // debugger:finish // debugger:print k // check:$11 = 12 // debugger:print l // check:$12 = 13 // debugger:continue // debugger:finish // debugger:print m // check:$13 = 14 // debugger:print n // check:$14 = 16 // debugger:continue // debugger:finish // debugger:print o // check:$15 = 18 // debugger:continue // debugger:finish // debugger:print p // check:$16 = 19 // debugger:print q // check:$17 = 20 // debugger:print r // check:$18 = {a = 21, b = 22} // debugger:continue // debugger:finish // debugger:print s // check:$19 = 24 // debugger:print t // check:$20 = 23 // debugger:continue // debugger:finish // debugger:print u // check:$21 = 25 // debugger:print v // check:$22 = 26 // debugger:print w // check:$23 = 27 // debugger:print x // check:$24 = 28 // debugger:print y // check:$25 = 29 // debugger:print z // check:$26 = 30 // debugger:print ae // check:$27 = 31 // debugger:print oe // check:$28 = 32 // debugger:print ue // check:$29 = 33 // debugger:continue // debugger:finish // debugger:print aa // check:$30 = {34, 35} // debugger:continue // debugger:finish // debugger:print bb // check:$31 = {36, 37} // debugger:continue // debugger:finish // debugger:print cc // check:$32 = 38 // debugger:continue // debugger:finish // debugger:print dd // check:$33 = {40, 41, 42} // debugger:continue // debugger:finish // debugger:print *ee // check:$34 = {43, 44, 45} // debugger:continue // debugger:finish // debugger:print *ff // check:$35 = 46 // debugger:print gg // check:$36 = {47, 48} // debugger:continue // debugger:finish // debugger:print *hh // check:$37 = 50 // debugger:continue // debugger:finish // debugger:print ii // check:$38 = 51 // debugger:continue // debugger:finish // debugger:print *jj // check:$39 = 52 // debugger:continue // debugger:finish // debugger:print kk // check:$40 = 53 // debugger:print ll // check:$41 = 54 // debugger:continue // debugger:finish // debugger:print mm // check:$42 = 55 // debugger:print *nn // check:$43 = 56 // debugger:continue // debugger:finish // debugger:print oo // check:$44 = 57 // debugger:print pp // check:$45 = 58 // debugger:print qq // check:$46 = 59 // debugger:continue // debugger:finish // debugger:print rr // check:$47 = 60 // debugger:print ss // check:$48 = 61 // debugger:print tt // check:$49 = 62 // debugger:continue #[allow(unused_variable)]; struct Struct { a: i64, b: i32 } enum Univariant { Unit(i32) } struct TupleStruct (f64, int); fn simple_tuple((a, b): (int, bool)) { zzz(); } fn nested_tuple((a, (b, c)): (int, (u16, u16))) { zzz(); } fn destructure_only_first_level((a, b): (int, (u32, u32))) { zzz(); } fn struct_as_tuple_element((h, i, j): (i16, Struct, i16)) { zzz(); } fn struct_pattern(Struct { a: k, b: l }: Struct) { zzz(); } fn ignored_tuple_element((m, _, n): (int, u16, i32)) { zzz(); } fn ignored_struct_field(Struct { b: o,.. }: Struct) { zzz(); } fn one_struct_destructured_one_not((Struct { a: p, b: q }, r): (Struct, Struct)) { zzz(); } fn different_order_of_struct_fields(Struct { b: s, a: t }: Struct ) { zzz(); } fn complex_nesting(((u, v ), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue ): ((i16, i32), ((i64, (i32, Struct, )), Struct ), u16)) { zzz(); } fn managed_box(&aa: &(int, int)) { zzz(); } fn borrowed_pointer(&bb: &(int, int)) { zzz(); } fn
((&cc, _): (&int, int)) { zzz(); } fn unique_pointer(~dd: ~(int, int, int)) { zzz(); } fn ref_binding(ref ee: (int, int, int)) { zzz(); } fn ref_binding_in_tuple((ref ff, gg): (int, (int, int))) { zzz(); } fn ref_binding_in_struct(Struct { b: ref hh,.. }: Struct) { zzz(); } fn univariant_enum(Unit(ii): Univariant) { zzz(); } fn univariant_enum_with_ref_binding(Unit(ref jj): Univariant) { zzz(); } fn tuple_struct(TupleStruct(kk, ll): TupleStruct) { zzz(); } fn tuple_struct_with_ref_binding(TupleStruct(mm, ref nn): TupleStruct) { zzz(); } fn multiple_arguments((oo, pp): (int, int), qq : int) { zzz(); } fn main() { simple_tuple((1, false)); nested_tuple((2, (3, 4))); destructure_only_first_level((5, (6, 7))); struct_as_tuple_element((8, Struct { a: 9, b: 10 }, 11)); struct_pattern(Struct { a: 12, b: 13 }); ignored_tuple_element((14, 15, 16)); ignored_struct_field(Struct { a: 17, b: 18 }); one_struct_destructured_one_not((Struct { a: 19, b: 20 }, Struct { a: 21, b: 22 })); different_order_of_struct_fields(Struct { a: 23, b: 24 }); complex_nesting(((25, 26), ((27, (28, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33)); managed_box(&(34, 35)); borrowed_pointer(&(36, 37)); contained_borrowed_pointer((&38, 39)); unique_pointer(~(40, 41, 42)); ref_binding((43, 44, 45)); ref_binding_in_tuple((46, (47, 48))); ref_binding_in_struct(Struct { a: 49, b: 50 }); univariant_enum(Unit(51)); univariant_enum_with_ref_binding(Unit(52)); tuple_struct(TupleStruct(53.0, 54)); tuple_struct_with_ref_binding(TupleStruct(55.0, 56)); multiple_arguments((57, 58), 59); fn nested_function(rr: int, (ss, tt): (int, int)) { zzz(); } nested_function(60, (61, 62)); } fn zzz() {()}
contained_borrowed_pointer
identifier_name
destructured-fn-argument.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print a // check:$1 = 1 // debugger:print b // check:$2 = false // debugger:continue // debugger:finish // debugger:print a // check:$3 = 2 // debugger:print b // check:$4 = 3 // debugger:print c // check:$5 = 4 // debugger:continue // debugger:finish // debugger:print a // check:$6 = 5 // debugger:print b // check:$7 = {6, 7} // debugger:continue // debugger:finish // debugger:print h // check:$8 = 8 // debugger:print i // check:$9 = {a = 9, b = 10} // debugger:print j // check:$10 = 11 // debugger:continue // debugger:finish // debugger:print k // check:$11 = 12 // debugger:print l // check:$12 = 13 // debugger:continue // debugger:finish // debugger:print m // check:$13 = 14 // debugger:print n // check:$14 = 16 // debugger:continue // debugger:finish // debugger:print o // check:$15 = 18 // debugger:continue // debugger:finish // debugger:print p // check:$16 = 19 // debugger:print q // check:$17 = 20 // debugger:print r // check:$18 = {a = 21, b = 22} // debugger:continue // debugger:finish // debugger:print s // check:$19 = 24 // debugger:print t // check:$20 = 23 // debugger:continue // debugger:finish // debugger:print u // check:$21 = 25 // debugger:print v // check:$22 = 26 // debugger:print w // check:$23 = 27 // debugger:print x // check:$24 = 28 // debugger:print y // check:$25 = 29 // debugger:print z // check:$26 = 30 // debugger:print ae // check:$27 = 31 // debugger:print oe // check:$28 = 32 // debugger:print ue // check:$29 = 33 // debugger:continue // debugger:finish // debugger:print aa // check:$30 = {34, 35} // debugger:continue // debugger:finish // debugger:print bb // check:$31 = {36, 37} // debugger:continue // debugger:finish // debugger:print cc // check:$32 = 38 // debugger:continue // debugger:finish // debugger:print dd // check:$33 = {40, 41, 42} // debugger:continue // debugger:finish // debugger:print *ee // check:$34 = {43, 44, 45} // debugger:continue // debugger:finish // debugger:print *ff // check:$35 = 46 // debugger:print gg // check:$36 = {47, 48} // debugger:continue // debugger:finish // debugger:print *hh // check:$37 = 50 // debugger:continue // debugger:finish // debugger:print ii // check:$38 = 51 // debugger:continue // debugger:finish // debugger:print *jj // check:$39 = 52 // debugger:continue // debugger:finish // debugger:print kk // check:$40 = 53 // debugger:print ll // check:$41 = 54 // debugger:continue // debugger:finish // debugger:print mm // check:$42 = 55 // debugger:print *nn // check:$43 = 56 // debugger:continue // debugger:finish // debugger:print oo // check:$44 = 57 // debugger:print pp // check:$45 = 58 // debugger:print qq // check:$46 = 59 // debugger:continue // debugger:finish // debugger:print rr // check:$47 = 60 // debugger:print ss // check:$48 = 61 // debugger:print tt // check:$49 = 62 // debugger:continue #[allow(unused_variable)]; struct Struct { a: i64, b: i32 } enum Univariant { Unit(i32) } struct TupleStruct (f64, int); fn simple_tuple((a, b): (int, bool)) { zzz(); } fn nested_tuple((a, (b, c)): (int, (u16, u16))) { zzz(); } fn destructure_only_first_level((a, b): (int, (u32, u32))) { zzz(); } fn struct_as_tuple_element((h, i, j): (i16, Struct, i16))
fn struct_pattern(Struct { a: k, b: l }: Struct) { zzz(); } fn ignored_tuple_element((m, _, n): (int, u16, i32)) { zzz(); } fn ignored_struct_field(Struct { b: o,.. }: Struct) { zzz(); } fn one_struct_destructured_one_not((Struct { a: p, b: q }, r): (Struct, Struct)) { zzz(); } fn different_order_of_struct_fields(Struct { b: s, a: t }: Struct ) { zzz(); } fn complex_nesting(((u, v ), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue ): ((i16, i32), ((i64, (i32, Struct, )), Struct ), u16)) { zzz(); } fn managed_box(&aa: &(int, int)) { zzz(); } fn borrowed_pointer(&bb: &(int, int)) { zzz(); } fn contained_borrowed_pointer((&cc, _): (&int, int)) { zzz(); } fn unique_pointer(~dd: ~(int, int, int)) { zzz(); } fn ref_binding(ref ee: (int, int, int)) { zzz(); } fn ref_binding_in_tuple((ref ff, gg): (int, (int, int))) { zzz(); } fn ref_binding_in_struct(Struct { b: ref hh,.. }: Struct) { zzz(); } fn univariant_enum(Unit(ii): Univariant) { zzz(); } fn univariant_enum_with_ref_binding(Unit(ref jj): Univariant) { zzz(); } fn tuple_struct(TupleStruct(kk, ll): TupleStruct) { zzz(); } fn tuple_struct_with_ref_binding(TupleStruct(mm, ref nn): TupleStruct) { zzz(); } fn multiple_arguments((oo, pp): (int, int), qq : int) { zzz(); } fn main() { simple_tuple((1, false)); nested_tuple((2, (3, 4))); destructure_only_first_level((5, (6, 7))); struct_as_tuple_element((8, Struct { a: 9, b: 10 }, 11)); struct_pattern(Struct { a: 12, b: 13 }); ignored_tuple_element((14, 15, 16)); ignored_struct_field(Struct { a: 17, b: 18 }); one_struct_destructured_one_not((Struct { a: 19, b: 20 }, Struct { a: 21, b: 22 })); different_order_of_struct_fields(Struct { a: 23, b: 24 }); complex_nesting(((25, 26), ((27, (28, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33)); managed_box(&(34, 35)); borrowed_pointer(&(36, 37)); contained_borrowed_pointer((&38, 39)); unique_pointer(~(40, 41, 42)); ref_binding((43, 44, 45)); ref_binding_in_tuple((46, (47, 48))); ref_binding_in_struct(Struct { a: 49, b: 50 }); univariant_enum(Unit(51)); univariant_enum_with_ref_binding(Unit(52)); tuple_struct(TupleStruct(53.0, 54)); tuple_struct_with_ref_binding(TupleStruct(55.0, 56)); multiple_arguments((57, 58), 59); fn nested_function(rr: int, (ss, tt): (int, int)) { zzz(); } nested_function(60, (61, 62)); } fn zzz() {()}
{ zzz(); }
identifier_body
mod.rs
use parse_scene::parse_scene; use std::sync::Arc; use image_types::Color; use cgmath::{Point, Vector}; use cgmath::{Vector3, Point3, Ray3, Ray}; use cgmath::dot; use self::util::random_cos_around; pub use self::illuminator::Illuminator; pub use self::intersectable::Intersectable; pub use self::scene_objects::{SceneObject, Sphere}; pub use self::scene_lights::{SceneLight, PointLight, DirectionalLight}; mod util; mod illuminator; mod intersectable; mod scene_objects; mod scene_lights; pub struct Scene { pub objects: Vec<SceneObject>, pub lights: Vec<SceneLight>, pub num_gi_samples: u32, pub num_shadow_samples: u32, pub bounces: u32 } pub struct Material { pub color: Color } pub fn build_scene(filename: &str) -> Scene { let scene = parse_scene(filename); scene } impl Scene { pub fn trace_ray(&self, ray: &Ray3<f32>, depth: u32) -> Color { let intersect = self.find_intersection(ray); match intersect { Some(intersection) => { let diff = self.light_diffuse(&intersection.point, &intersection.normal, depth); diff.mul_c(&intersection.material.color) } None => sky_color(&ray.direction) } } fn find_intersection(&self, ray: &Ray3<f32>) -> Option<Intersection> { let mut closest = None; let mut closest_distance = 99999999999.0; for object in self.objects.iter() { let result = object.intersection(ray); match result { Some(distance) => { if distance < closest_distance { closest = Some(object); closest_distance = distance; } }, None => () } } match closest { Some(object) => { let point = ray.origin.add_v(&ray.direction.mul_s(closest_distance)); let intersection = object.intersection_info(&point); Some(intersection) }, None => None } } pub fn check_ray(&self, ray: &Ray3<f32>) -> bool { for object in self.objects.iter() { match object.intersection(ray) { Some(_) => return true, None => () } } false } pub fn check_ray_distance(&self, ray: &Ray3<f32>, distance: f32) -> bool { for object in self.objects.iter() { match object.intersection(ray) { Some(d) if d <= distance => return true, _ => () } } false } pub fn light_diffuse(&self, point: &Point3<f32>, normal: &Vector3<f32>, depth: u32) -> Color { let mut total_light = Color { r: 0.0, g: 0.0, b: 0.0 }; for light in self.lights.iter() { total_light = total_light.add_c(&light.illuminate(self, point, normal)); } if depth < self.bounces { total_light = total_light.add_c(&self.environment_light(point, normal, depth + 1)); } total_light } fn
(&self, point: &Point3<f32>, normal: &Vector3<f32>, depth: u32) -> Color { let mut total_light = Color { r: 0.0, g: 0.0, b: 0.0 }; let reduced_samples = self.num_gi_samples >> (depth * 2) as uint; if reduced_samples == 0 { return Color { r: 0.0, g: 0.0, b: 0.0 }; }; for _ in range(0, reduced_samples) { let vector = random_cos_around(normal); match self.find_intersection(&Ray::new(*point, vector)) { Some(intersection) => { let incoming = self.light_diffuse(&intersection.point, &intersection.normal, depth); total_light = total_light.add_c(&incoming); }, None => total_light = total_light.add_c(&sky_color(&vector)) } } total_light.mul_s(1.0/reduced_samples as f32) } } fn sky_color(direction: &Vector3<f32>) -> Color { let fac = (dot(*direction, Vector3::unit_z()) + 1.0) * 0.5; Color { r: 0.0, g: 0.0, b: fac } } struct Intersection { point: Point3<f32>, normal: Vector3<f32>, material: Arc<Material> }
environment_light
identifier_name
mod.rs
use parse_scene::parse_scene; use std::sync::Arc; use image_types::Color; use cgmath::{Point, Vector}; use cgmath::{Vector3, Point3, Ray3, Ray}; use cgmath::dot; use self::util::random_cos_around; pub use self::illuminator::Illuminator; pub use self::intersectable::Intersectable; pub use self::scene_objects::{SceneObject, Sphere}; pub use self::scene_lights::{SceneLight, PointLight, DirectionalLight}; mod util; mod illuminator; mod intersectable; mod scene_objects; mod scene_lights; pub struct Scene {
pub objects: Vec<SceneObject>, pub lights: Vec<SceneLight>, pub num_gi_samples: u32, pub num_shadow_samples: u32, pub bounces: u32 } pub struct Material { pub color: Color } pub fn build_scene(filename: &str) -> Scene { let scene = parse_scene(filename); scene } impl Scene { pub fn trace_ray(&self, ray: &Ray3<f32>, depth: u32) -> Color { let intersect = self.find_intersection(ray); match intersect { Some(intersection) => { let diff = self.light_diffuse(&intersection.point, &intersection.normal, depth); diff.mul_c(&intersection.material.color) } None => sky_color(&ray.direction) } } fn find_intersection(&self, ray: &Ray3<f32>) -> Option<Intersection> { let mut closest = None; let mut closest_distance = 99999999999.0; for object in self.objects.iter() { let result = object.intersection(ray); match result { Some(distance) => { if distance < closest_distance { closest = Some(object); closest_distance = distance; } }, None => () } } match closest { Some(object) => { let point = ray.origin.add_v(&ray.direction.mul_s(closest_distance)); let intersection = object.intersection_info(&point); Some(intersection) }, None => None } } pub fn check_ray(&self, ray: &Ray3<f32>) -> bool { for object in self.objects.iter() { match object.intersection(ray) { Some(_) => return true, None => () } } false } pub fn check_ray_distance(&self, ray: &Ray3<f32>, distance: f32) -> bool { for object in self.objects.iter() { match object.intersection(ray) { Some(d) if d <= distance => return true, _ => () } } false } pub fn light_diffuse(&self, point: &Point3<f32>, normal: &Vector3<f32>, depth: u32) -> Color { let mut total_light = Color { r: 0.0, g: 0.0, b: 0.0 }; for light in self.lights.iter() { total_light = total_light.add_c(&light.illuminate(self, point, normal)); } if depth < self.bounces { total_light = total_light.add_c(&self.environment_light(point, normal, depth + 1)); } total_light } fn environment_light(&self, point: &Point3<f32>, normal: &Vector3<f32>, depth: u32) -> Color { let mut total_light = Color { r: 0.0, g: 0.0, b: 0.0 }; let reduced_samples = self.num_gi_samples >> (depth * 2) as uint; if reduced_samples == 0 { return Color { r: 0.0, g: 0.0, b: 0.0 }; }; for _ in range(0, reduced_samples) { let vector = random_cos_around(normal); match self.find_intersection(&Ray::new(*point, vector)) { Some(intersection) => { let incoming = self.light_diffuse(&intersection.point, &intersection.normal, depth); total_light = total_light.add_c(&incoming); }, None => total_light = total_light.add_c(&sky_color(&vector)) } } total_light.mul_s(1.0/reduced_samples as f32) } } fn sky_color(direction: &Vector3<f32>) -> Color { let fac = (dot(*direction, Vector3::unit_z()) + 1.0) * 0.5; Color { r: 0.0, g: 0.0, b: fac } } struct Intersection { point: Point3<f32>, normal: Vector3<f32>, material: Arc<Material> }
random_line_split
mod.rs
use parse_scene::parse_scene; use std::sync::Arc; use image_types::Color; use cgmath::{Point, Vector}; use cgmath::{Vector3, Point3, Ray3, Ray}; use cgmath::dot; use self::util::random_cos_around; pub use self::illuminator::Illuminator; pub use self::intersectable::Intersectable; pub use self::scene_objects::{SceneObject, Sphere}; pub use self::scene_lights::{SceneLight, PointLight, DirectionalLight}; mod util; mod illuminator; mod intersectable; mod scene_objects; mod scene_lights; pub struct Scene { pub objects: Vec<SceneObject>, pub lights: Vec<SceneLight>, pub num_gi_samples: u32, pub num_shadow_samples: u32, pub bounces: u32 } pub struct Material { pub color: Color } pub fn build_scene(filename: &str) -> Scene { let scene = parse_scene(filename); scene } impl Scene { pub fn trace_ray(&self, ray: &Ray3<f32>, depth: u32) -> Color
fn find_intersection(&self, ray: &Ray3<f32>) -> Option<Intersection> { let mut closest = None; let mut closest_distance = 99999999999.0; for object in self.objects.iter() { let result = object.intersection(ray); match result { Some(distance) => { if distance < closest_distance { closest = Some(object); closest_distance = distance; } }, None => () } } match closest { Some(object) => { let point = ray.origin.add_v(&ray.direction.mul_s(closest_distance)); let intersection = object.intersection_info(&point); Some(intersection) }, None => None } } pub fn check_ray(&self, ray: &Ray3<f32>) -> bool { for object in self.objects.iter() { match object.intersection(ray) { Some(_) => return true, None => () } } false } pub fn check_ray_distance(&self, ray: &Ray3<f32>, distance: f32) -> bool { for object in self.objects.iter() { match object.intersection(ray) { Some(d) if d <= distance => return true, _ => () } } false } pub fn light_diffuse(&self, point: &Point3<f32>, normal: &Vector3<f32>, depth: u32) -> Color { let mut total_light = Color { r: 0.0, g: 0.0, b: 0.0 }; for light in self.lights.iter() { total_light = total_light.add_c(&light.illuminate(self, point, normal)); } if depth < self.bounces { total_light = total_light.add_c(&self.environment_light(point, normal, depth + 1)); } total_light } fn environment_light(&self, point: &Point3<f32>, normal: &Vector3<f32>, depth: u32) -> Color { let mut total_light = Color { r: 0.0, g: 0.0, b: 0.0 }; let reduced_samples = self.num_gi_samples >> (depth * 2) as uint; if reduced_samples == 0 { return Color { r: 0.0, g: 0.0, b: 0.0 }; }; for _ in range(0, reduced_samples) { let vector = random_cos_around(normal); match self.find_intersection(&Ray::new(*point, vector)) { Some(intersection) => { let incoming = self.light_diffuse(&intersection.point, &intersection.normal, depth); total_light = total_light.add_c(&incoming); }, None => total_light = total_light.add_c(&sky_color(&vector)) } } total_light.mul_s(1.0/reduced_samples as f32) } } fn sky_color(direction: &Vector3<f32>) -> Color { let fac = (dot(*direction, Vector3::unit_z()) + 1.0) * 0.5; Color { r: 0.0, g: 0.0, b: fac } } struct Intersection { point: Point3<f32>, normal: Vector3<f32>, material: Arc<Material> }
{ let intersect = self.find_intersection(ray); match intersect { Some(intersection) => { let diff = self.light_diffuse(&intersection.point, &intersection.normal, depth); diff.mul_c(&intersection.material.color) } None => sky_color(&ray.direction) } }
identifier_body
factory.rs
//! thread model use std::cmp; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{mpsc, Arc, Mutex}; use std::thread::{self, Builder}; /// Messages the monitor thread sends to worker threads to control their /// activity. #[derive(PartialEq, Eq, Debug)] enum BossMessage { Go, Stop, } /// Messages worker threads send to the monitor thread to allow it to keep /// track of their state and distribute work. #[derive(PartialEq, Eq, Debug)] enum WorkerMessage { WakeUp, Slain, Sleeping(usize), // usize is an id indicating the sleeper } /// The résumé (trait) required of worker threads who wish to work in the /// factory. The general pattern of work is that workers inspect an item (`I`) /// to see whether it can be shipped. If not, they improve it, making some /// number of improved items. pub trait WorkerFun<I: Send +'static>: Send + Sync +'static { fn improve(&self, I) -> Vec<I>; fn inspect(&self, &I) -> bool; } /// Start the factory going. The `roster` is the number of workers. The /// `slop_factor` is multiplied by this number to determine the number of /// items to keep in reserve for workers that run low in their personal work /// queues. The `materials` are the initial items requiring improvement. The /// `fun` provides the specifications for what the workers will do to improve /// or inspect their work. pub fn manufacture<I, W>( roster: usize, slop_factor: usize, materials: Vec<I>, fun: Arc<W>, ) -> (Receiver<Option<I>>, Arc<AtomicBool>) where I: Send +'static, W: WorkerFun<I>, { // set up work sharing mechanism if roster == 0 { panic!("roster must be greater than 0"); } if slop_factor == 0 { panic!("slop_factor must be greater than 0"); } let maximum_shared = roster * slop_factor; let threshold = roster; let had = Arc::new(AtomicUsize::new(materials.len())); // set up factory floor let conveyor_belt = Arc::new(Mutex::new(materials)); let (container, truck) = mpsc::channel::<Option<I>>(); let workers = Arc::new(Mutex::new(Vec::with_capacity(roster))); let (manager, stamps) = mpsc::channel::<WorkerMessage>(); let kill_switch = Arc::new(AtomicBool::new(false)); for i in 0..roster { work( i, had.clone(), conveyor_belt.clone(), container.clone(), manager.clone(), fun.clone(), kill_switch.clone(), workers.clone(), threshold, maximum_shared, ); } thread::spawn(move || supervize(roster, workers, stamps, container)); (truck, kill_switch) } fn wo
, W>( i: usize, had: Arc<AtomicUsize>, belt: Arc<Mutex<Vec<I>>>, container: Sender<Option<I>>, manager: Sender<WorkerMessage>, fun: Arc<W>, kill_switch: Arc<AtomicBool>, workers: Arc<Mutex<Vec<Sender<BossMessage>>>>, threshold: usize, maximum_shared: usize, ) where I: Send +'static, W: WorkerFun<I>, { let (worker, in_box) = mpsc::channel::<BossMessage>(); workers.lock().unwrap().push(worker); let bob = Builder::new().name(format!("{}", i).into()); bob.spawn(move || { let mut hopper = vec![]; for message in in_box { if message == BossMessage::Stop { break; } if kill_switch.load(Ordering::Relaxed) { manager.send(WorkerMessage::Slain).ok(); break; } while let Some(stuff) = { let mut temp = belt.lock().unwrap(); temp.pop() } { // push the stuff into the owned queue and work off that hopper.push(stuff); had.fetch_sub(1, Ordering::Relaxed); while let Some(stuff) = hopper.pop() { if kill_switch.load(Ordering::Relaxed) { manager.send(WorkerMessage::Slain).ok(); break; } if fun.inspect(&stuff) { container.send(Some(stuff)).ok(); } else { let mut widgets = fun.improve(stuff); let currently_shared = had.load(Ordering::Relaxed); if currently_shared < threshold { let own = widgets.len() + hopper.len(); if own > 1 { let mut tithe = cmp::min(own - 1, maximum_shared - currently_shared); had.fetch_add(tithe, Ordering::Relaxed); let mut belt = belt.lock().unwrap(); if widgets.len() > 0 { if widgets.len() <= tithe { tithe -= widgets.len(); for _ in 0..widgets.len() { belt.push(widgets.pop().unwrap()); } } else { for _ in 0..tithe { belt.push(widgets.pop().unwrap()); } tithe = 0; } } for _ in 0..tithe { belt.push(hopper.pop().unwrap()); } manager.send(WorkerMessage::WakeUp).ok(); } } for w in widgets { hopper.push(w); } } } } manager.send(WorkerMessage::Sleeping(i)).ok(); // send I'm empty message } }) .unwrap(); } fn supervize<I>( roster: usize, workers: Arc<Mutex<Vec<Sender<BossMessage>>>>, stamps: Receiver<WorkerMessage>, container: Sender<Option<I>>, ) where I: Send +'static, { let mut idled: Vec<usize> = Vec::with_capacity(roster); for w in workers.lock().unwrap().iter() { w.send(BossMessage::Go).ok(); } for message in stamps { match message { WorkerMessage::Slain => { container.send(None).ok(); let foo = workers.lock().unwrap(); for &i in idled.iter() { if let Some(w) = foo.get(i) { w.send(BossMessage::Go).ok(); } } break; } WorkerMessage::WakeUp => { let foo = workers.lock().unwrap(); for &i in idled.iter() { if let Some(w) = foo.get(i) { w.send(BossMessage::Go).ok(); } } idled.clear(); } WorkerMessage::Sleeping(i) => { idled.push(i); if idled.len() == roster { container.send(None).ok(); for worker in workers.lock().unwrap().iter() { worker.send(BossMessage::Stop).ok(); } } } } } }
rk<I
identifier_name
factory.rs
//! thread model use std::cmp; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{mpsc, Arc, Mutex}; use std::thread::{self, Builder}; /// Messages the monitor thread sends to worker threads to control their /// activity. #[derive(PartialEq, Eq, Debug)] enum BossMessage { Go, Stop, } /// Messages worker threads send to the monitor thread to allow it to keep /// track of their state and distribute work. #[derive(PartialEq, Eq, Debug)] enum WorkerMessage { WakeUp, Slain, Sleeping(usize), // usize is an id indicating the sleeper } /// The résumé (trait) required of worker threads who wish to work in the /// factory. The general pattern of work is that workers inspect an item (`I`) /// to see whether it can be shipped. If not, they improve it, making some /// number of improved items. pub trait WorkerFun<I: Send +'static>: Send + Sync +'static { fn improve(&self, I) -> Vec<I>; fn inspect(&self, &I) -> bool; } /// Start the factory going. The `roster` is the number of workers. The /// `slop_factor` is multiplied by this number to determine the number of /// items to keep in reserve for workers that run low in their personal work /// queues. The `materials` are the initial items requiring improvement. The /// `fun` provides the specifications for what the workers will do to improve /// or inspect their work. pub fn manufacture<I, W>( roster: usize, slop_factor: usize, materials: Vec<I>, fun: Arc<W>, ) -> (Receiver<Option<I>>, Arc<AtomicBool>) where I: Send +'static, W: WorkerFun<I>, { // set up work sharing mechanism if roster == 0 { panic!("roster must be greater than 0"); } if slop_factor == 0 { panic!("slop_factor must be greater than 0"); } let maximum_shared = roster * slop_factor; let threshold = roster; let had = Arc::new(AtomicUsize::new(materials.len())); // set up factory floor let conveyor_belt = Arc::new(Mutex::new(materials)); let (container, truck) = mpsc::channel::<Option<I>>(); let workers = Arc::new(Mutex::new(Vec::with_capacity(roster))); let (manager, stamps) = mpsc::channel::<WorkerMessage>(); let kill_switch = Arc::new(AtomicBool::new(false)); for i in 0..roster { work( i, had.clone(), conveyor_belt.clone(), container.clone(), manager.clone(), fun.clone(), kill_switch.clone(), workers.clone(), threshold, maximum_shared, ); } thread::spawn(move || supervize(roster, workers, stamps, container)); (truck, kill_switch) } fn work<I, W>( i: usize, had: Arc<AtomicUsize>, belt: Arc<Mutex<Vec<I>>>, container: Sender<Option<I>>, manager: Sender<WorkerMessage>, fun: Arc<W>, kill_switch: Arc<AtomicBool>, workers: Arc<Mutex<Vec<Sender<BossMessage>>>>, threshold: usize, maximum_shared: usize, ) where I: Send +'static, W: WorkerFun<I>, { let (worker, in_box) = mpsc::channel::<BossMessage>(); workers.lock().unwrap().push(worker); let bob = Builder::new().name(format!("{}", i).into()); bob.spawn(move || { let mut hopper = vec![]; for message in in_box { if message == BossMessage::Stop { break; } if kill_switch.load(Ordering::Relaxed) { manager.send(WorkerMessage::Slain).ok(); break; } while let Some(stuff) = { let mut temp = belt.lock().unwrap(); temp.pop() } { // push the stuff into the owned queue and work off that hopper.push(stuff); had.fetch_sub(1, Ordering::Relaxed); while let Some(stuff) = hopper.pop() { if kill_switch.load(Ordering::Relaxed) { manager.send(WorkerMessage::Slain).ok(); break; } if fun.inspect(&stuff) { container.send(Some(stuff)).ok(); } else { let mut widgets = fun.improve(stuff); let currently_shared = had.load(Ordering::Relaxed); if currently_shared < threshold { let own = widgets.len() + hopper.len(); if own > 1 { let mut tithe = cmp::min(own - 1, maximum_shared - currently_shared); had.fetch_add(tithe, Ordering::Relaxed); let mut belt = belt.lock().unwrap(); if widgets.len() > 0 { if widgets.len() <= tithe { tithe -= widgets.len(); for _ in 0..widgets.len() { belt.push(widgets.pop().unwrap()); } } else {
} for _ in 0..tithe { belt.push(hopper.pop().unwrap()); } manager.send(WorkerMessage::WakeUp).ok(); } } for w in widgets { hopper.push(w); } } } } manager.send(WorkerMessage::Sleeping(i)).ok(); // send I'm empty message } }) .unwrap(); } fn supervize<I>( roster: usize, workers: Arc<Mutex<Vec<Sender<BossMessage>>>>, stamps: Receiver<WorkerMessage>, container: Sender<Option<I>>, ) where I: Send +'static, { let mut idled: Vec<usize> = Vec::with_capacity(roster); for w in workers.lock().unwrap().iter() { w.send(BossMessage::Go).ok(); } for message in stamps { match message { WorkerMessage::Slain => { container.send(None).ok(); let foo = workers.lock().unwrap(); for &i in idled.iter() { if let Some(w) = foo.get(i) { w.send(BossMessage::Go).ok(); } } break; } WorkerMessage::WakeUp => { let foo = workers.lock().unwrap(); for &i in idled.iter() { if let Some(w) = foo.get(i) { w.send(BossMessage::Go).ok(); } } idled.clear(); } WorkerMessage::Sleeping(i) => { idled.push(i); if idled.len() == roster { container.send(None).ok(); for worker in workers.lock().unwrap().iter() { worker.send(BossMessage::Stop).ok(); } } } } } }
for _ in 0..tithe { belt.push(widgets.pop().unwrap()); } tithe = 0; }
conditional_block
factory.rs
//! thread model use std::cmp; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{mpsc, Arc, Mutex}; use std::thread::{self, Builder}; /// Messages the monitor thread sends to worker threads to control their /// activity. #[derive(PartialEq, Eq, Debug)] enum BossMessage { Go, Stop, } /// Messages worker threads send to the monitor thread to allow it to keep /// track of their state and distribute work. #[derive(PartialEq, Eq, Debug)] enum WorkerMessage { WakeUp, Slain, Sleeping(usize), // usize is an id indicating the sleeper } /// The résumé (trait) required of worker threads who wish to work in the /// factory. The general pattern of work is that workers inspect an item (`I`) /// to see whether it can be shipped. If not, they improve it, making some /// number of improved items. pub trait WorkerFun<I: Send +'static>: Send + Sync +'static { fn improve(&self, I) -> Vec<I>; fn inspect(&self, &I) -> bool; } /// Start the factory going. The `roster` is the number of workers. The /// `slop_factor` is multiplied by this number to determine the number of /// items to keep in reserve for workers that run low in their personal work /// queues. The `materials` are the initial items requiring improvement. The /// `fun` provides the specifications for what the workers will do to improve /// or inspect their work. pub fn manufacture<I, W>( roster: usize, slop_factor: usize, materials: Vec<I>, fun: Arc<W>, ) -> (Receiver<Option<I>>, Arc<AtomicBool>) where I: Send +'static, W: WorkerFun<I>, { // set up work sharing mechanism if roster == 0 { panic!("roster must be greater than 0"); } if slop_factor == 0 { panic!("slop_factor must be greater than 0"); } let maximum_shared = roster * slop_factor; let threshold = roster; let had = Arc::new(AtomicUsize::new(materials.len())); // set up factory floor let conveyor_belt = Arc::new(Mutex::new(materials)); let (container, truck) = mpsc::channel::<Option<I>>(); let workers = Arc::new(Mutex::new(Vec::with_capacity(roster))); let (manager, stamps) = mpsc::channel::<WorkerMessage>(); let kill_switch = Arc::new(AtomicBool::new(false)); for i in 0..roster { work( i, had.clone(), conveyor_belt.clone(), container.clone(), manager.clone(), fun.clone(), kill_switch.clone(), workers.clone(), threshold, maximum_shared, ); } thread::spawn(move || supervize(roster, workers, stamps, container)); (truck, kill_switch) } fn work<I, W>( i: usize, had: Arc<AtomicUsize>, belt: Arc<Mutex<Vec<I>>>, container: Sender<Option<I>>, manager: Sender<WorkerMessage>, fun: Arc<W>, kill_switch: Arc<AtomicBool>, workers: Arc<Mutex<Vec<Sender<BossMessage>>>>, threshold: usize, maximum_shared: usize, ) where I: Send +'static, W: WorkerFun<I>, { let (worker, in_box) = mpsc::channel::<BossMessage>(); workers.lock().unwrap().push(worker); let bob = Builder::new().name(format!("{}", i).into()); bob.spawn(move || { let mut hopper = vec![]; for message in in_box {
break; } if kill_switch.load(Ordering::Relaxed) { manager.send(WorkerMessage::Slain).ok(); break; } while let Some(stuff) = { let mut temp = belt.lock().unwrap(); temp.pop() } { // push the stuff into the owned queue and work off that hopper.push(stuff); had.fetch_sub(1, Ordering::Relaxed); while let Some(stuff) = hopper.pop() { if kill_switch.load(Ordering::Relaxed) { manager.send(WorkerMessage::Slain).ok(); break; } if fun.inspect(&stuff) { container.send(Some(stuff)).ok(); } else { let mut widgets = fun.improve(stuff); let currently_shared = had.load(Ordering::Relaxed); if currently_shared < threshold { let own = widgets.len() + hopper.len(); if own > 1 { let mut tithe = cmp::min(own - 1, maximum_shared - currently_shared); had.fetch_add(tithe, Ordering::Relaxed); let mut belt = belt.lock().unwrap(); if widgets.len() > 0 { if widgets.len() <= tithe { tithe -= widgets.len(); for _ in 0..widgets.len() { belt.push(widgets.pop().unwrap()); } } else { for _ in 0..tithe { belt.push(widgets.pop().unwrap()); } tithe = 0; } } for _ in 0..tithe { belt.push(hopper.pop().unwrap()); } manager.send(WorkerMessage::WakeUp).ok(); } } for w in widgets { hopper.push(w); } } } } manager.send(WorkerMessage::Sleeping(i)).ok(); // send I'm empty message } }) .unwrap(); } fn supervize<I>( roster: usize, workers: Arc<Mutex<Vec<Sender<BossMessage>>>>, stamps: Receiver<WorkerMessage>, container: Sender<Option<I>>, ) where I: Send +'static, { let mut idled: Vec<usize> = Vec::with_capacity(roster); for w in workers.lock().unwrap().iter() { w.send(BossMessage::Go).ok(); } for message in stamps { match message { WorkerMessage::Slain => { container.send(None).ok(); let foo = workers.lock().unwrap(); for &i in idled.iter() { if let Some(w) = foo.get(i) { w.send(BossMessage::Go).ok(); } } break; } WorkerMessage::WakeUp => { let foo = workers.lock().unwrap(); for &i in idled.iter() { if let Some(w) = foo.get(i) { w.send(BossMessage::Go).ok(); } } idled.clear(); } WorkerMessage::Sleeping(i) => { idled.push(i); if idled.len() == roster { container.send(None).ok(); for worker in workers.lock().unwrap().iter() { worker.send(BossMessage::Stop).ok(); } } } } } }
if message == BossMessage::Stop {
random_line_split
method_self_arg1.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. #![crate_type = "lib"] static mut COUNT: u64 = 1;
impl Copy for Foo {} impl Foo { pub fn foo(self, x: &Foo) { unsafe { COUNT *= 2; } // Test internal call. Foo::bar(&self); Foo::bar(x); Foo::baz(self); Foo::baz(*x); Foo::qux(box self); Foo::qux(box *x); } pub fn bar(&self) { unsafe { COUNT *= 3; } } pub fn baz(self) { unsafe { COUNT *= 5; } } pub fn qux(self: Box<Foo>) { unsafe { COUNT *= 7; } } }
pub fn get_count() -> u64 { unsafe { COUNT } } pub struct Foo;
random_line_split
method_self_arg1.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. #![crate_type = "lib"] static mut COUNT: u64 = 1; pub fn get_count() -> u64 { unsafe { COUNT } } pub struct Foo; impl Copy for Foo {} impl Foo { pub fn foo(self, x: &Foo)
pub fn bar(&self) { unsafe { COUNT *= 3; } } pub fn baz(self) { unsafe { COUNT *= 5; } } pub fn qux(self: Box<Foo>) { unsafe { COUNT *= 7; } } }
{ unsafe { COUNT *= 2; } // Test internal call. Foo::bar(&self); Foo::bar(x); Foo::baz(self); Foo::baz(*x); Foo::qux(box self); Foo::qux(box *x); }
identifier_body
method_self_arg1.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. #![crate_type = "lib"] static mut COUNT: u64 = 1; pub fn
() -> u64 { unsafe { COUNT } } pub struct Foo; impl Copy for Foo {} impl Foo { pub fn foo(self, x: &Foo) { unsafe { COUNT *= 2; } // Test internal call. Foo::bar(&self); Foo::bar(x); Foo::baz(self); Foo::baz(*x); Foo::qux(box self); Foo::qux(box *x); } pub fn bar(&self) { unsafe { COUNT *= 3; } } pub fn baz(self) { unsafe { COUNT *= 5; } } pub fn qux(self: Box<Foo>) { unsafe { COUNT *= 7; } } }
get_count
identifier_name
router.rs
//! This example shows how to serve static files at specific //! mount points, and then delegate the rest of the paths to a router. //! //! It serves the docs from target/doc at the /docs/ mount point //! and delegates the rest to a router, which itself defines a //! handler for route /hello //! //! Make sure to generate the docs first with `cargo doc`, //! then build the tests with `cargo test`, //! then run the example with `./target/router` //! //! Visit http://127.0.0.1:3000/hello to view the routed path. //! //! Visit http://127.0.0.1:3000/docs/mount/ to view the mounted docs. extern crate iron; extern crate mount; extern crate router; extern crate static_file; use std::io::net::ip::Ipv4Addr; use iron::status; use iron::{Iron, Request, Response, IronResult}; use mount::Mount; use router::Router; use static_file::Static; fn say_hello(req: &mut Request) -> IronResult<Response> { println!("Running send_hello handler, URL path: {}", req.url.path); Ok(Response::with(status::Ok, "This request was routed!")) } fn
() { let mut router = Router::new(); router .get("/hello", say_hello); let mut mount = Mount::new(); mount .mount("/", router) .mount("/docs/", Static::new(Path::new("target/doc"))); Iron::new(mount).listen(Ipv4Addr(127, 0, 0, 1), 3000); }
main
identifier_name
router.rs
//! This example shows how to serve static files at specific //! mount points, and then delegate the rest of the paths to a router. //! //! It serves the docs from target/doc at the /docs/ mount point //! and delegates the rest to a router, which itself defines a //! handler for route /hello //! //! Make sure to generate the docs first with `cargo doc`, //! then build the tests with `cargo test`, //! then run the example with `./target/router` //! //! Visit http://127.0.0.1:3000/hello to view the routed path. //! //! Visit http://127.0.0.1:3000/docs/mount/ to view the mounted docs. extern crate iron; extern crate mount; extern crate router; extern crate static_file; use std::io::net::ip::Ipv4Addr; use iron::status; use iron::{Iron, Request, Response, IronResult}; use mount::Mount; use router::Router; use static_file::Static; fn say_hello(req: &mut Request) -> IronResult<Response> { println!("Running send_hello handler, URL path: {}", req.url.path); Ok(Response::with(status::Ok, "This request was routed!")) } fn main() { let mut router = Router::new(); router .get("/hello", say_hello); let mut mount = Mount::new(); mount .mount("/", router) .mount("/docs/", Static::new(Path::new("target/doc")));
Iron::new(mount).listen(Ipv4Addr(127, 0, 0, 1), 3000); }
random_line_split
router.rs
//! This example shows how to serve static files at specific //! mount points, and then delegate the rest of the paths to a router. //! //! It serves the docs from target/doc at the /docs/ mount point //! and delegates the rest to a router, which itself defines a //! handler for route /hello //! //! Make sure to generate the docs first with `cargo doc`, //! then build the tests with `cargo test`, //! then run the example with `./target/router` //! //! Visit http://127.0.0.1:3000/hello to view the routed path. //! //! Visit http://127.0.0.1:3000/docs/mount/ to view the mounted docs. extern crate iron; extern crate mount; extern crate router; extern crate static_file; use std::io::net::ip::Ipv4Addr; use iron::status; use iron::{Iron, Request, Response, IronResult}; use mount::Mount; use router::Router; use static_file::Static; fn say_hello(req: &mut Request) -> IronResult<Response> { println!("Running send_hello handler, URL path: {}", req.url.path); Ok(Response::with(status::Ok, "This request was routed!")) } fn main()
{ let mut router = Router::new(); router .get("/hello", say_hello); let mut mount = Mount::new(); mount .mount("/", router) .mount("/docs/", Static::new(Path::new("target/doc"))); Iron::new(mount).listen(Ipv4Addr(127, 0, 0, 1), 3000); }
identifier_body
mod.rs
//! The module contains a simple HTTP/2 server implementation. use http::{Response, HttpResult, HttpError, HttpScheme, Header, StreamId}; use http::transport::TransportStream; use http::connection::{HttpConnection, EndStream, SendStatus}; use http::session::{DefaultSessionState, SessionState, Stream}; use http::server::ServerConnection; /// The struct represents a fully received request. pub struct ServerRequest<'a> { pub stream_id: StreamId, pub headers: &'a [Header], pub body: &'a [u8], } /// The struct implements a simple HTTP/2 server that allows users to register a request handler (a /// callback taking a `ServerRequest` and returning a `Response`) which is run on all received /// requests. /// /// The `handle_next` method needs to be called regularly in order to have the server process /// received frames, as well as send out the responses. /// /// This is an exceedingly simple implementation of an HTTP/2 server and is mostly an example of /// how the `solicit::http` API can be used to make one. /// /// # Examples /// /// ```no_run /// extern crate solicit; /// use std::str; /// use std::net::{TcpListener, TcpStream}; /// use std::thread; /// /// use solicit::server::SimpleServer; /// /// use solicit::http::Response; /// /// fn main() { /// fn handle_client(stream: TcpStream) { /// let mut server = SimpleServer::new(stream, |req| { /// println!("Received request:"); /// for header in req.headers.iter() { /// println!(" {}: {}", /// str::from_utf8(&header.0).unwrap(), /// str::from_utf8(&header.1).unwrap()); /// } /// println!("Body:\n{}", str::from_utf8(&req.body).unwrap()); /// /// // Return a dummy response for every request /// Response { /// headers: vec![ /// (b":status".to_vec(), b"200".to_vec()), /// (b"x-solicit".to_vec(), b"Hello, World!".to_vec()), /// ], /// body: vec![65], /// stream_id: req.stream_id, /// } /// }).unwrap(); /// while let Ok(_) = server.handle_next() {} /// println!("Server done (client disconnected)"); /// } /// /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); /// for stream in listener.incoming() { /// let stream = stream.unwrap(); /// thread::spawn(move || { /// handle_client(stream) /// }); /// } /// } /// ``` pub struct SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response { conn: ServerConnection<TS, TS>, handler: H, } impl<TS, H> SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response { /// Creates a new `SimpleServer` that will use the given `TransportStream` to communicate to /// the client. Assumes that the stream is fully uninitialized -- no preface sent or read yet. pub fn new(mut stream: TS, handler: H) -> HttpResult<SimpleServer<TS, H>> { // First assert that the preface is received let mut preface = [0; 24]; TransportStream::read_exact(&mut stream, &mut preface).unwrap(); if &preface!= b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" { return Err(HttpError::UnableToConnect); } let conn = HttpConnection::<TS, TS>::with_stream(stream, HttpScheme::Http); let mut server = SimpleServer { conn: ServerConnection::with_connection(conn, DefaultSessionState::new()), handler: handler, }; // Initialize the connection -- send own settings and process the peer's try!(server.conn.init()); // Set up done Ok(server) } /// Handles the next incoming frame, blocking to receive it if nothing is available on the /// underlying stream. /// /// Handling the frame can trigger the handler callback. Any responses returned by the handler /// are immediately flushed out to the client (blocking the call until it's done). pub fn handle_next(&mut self) -> HttpResult<()> { try!(self.conn.handle_next_frame()); let responses = try!(self.handle_requests()); try!(self.prepare_responses(responses)); try!(self.flush_streams()); try!(self.reap_streams()); Ok(()) } /// Invokes the request handler for each fully received request. Collects all the responses /// into the returned `Vec`. fn handle_requests(&mut self) -> HttpResult<Vec<Response>> { let handler = &mut self.handler; Ok(self.conn.state.iter().filter(|s| s.is_closed_remote()).map(|stream| { let req = ServerRequest { stream_id: stream.stream_id, headers: stream.headers.as_ref().unwrap(), body: &stream.body, }; handler(req) }).collect()) } /// Prepares the streams for each of the given responses. Headers for each response are /// immediately sent and the data staged into the streams' outgoing buffer. fn
(&mut self, responses: Vec<Response>) -> HttpResult<()> { for response in responses.into_iter() { try!(self.conn.start_response( response.headers, response.stream_id, EndStream::No)); let mut stream = self.conn.state.get_stream_mut(response.stream_id).unwrap(); stream.set_full_data(response.body); } Ok(()) } /// Flushes the outgoing buffers of all streams. #[inline] fn flush_streams(&mut self) -> HttpResult<()> { while let SendStatus::Sent = try!(self.conn.send_next_data()) {} Ok(()) } /// Removes closed streams from the connection state. #[inline] fn reap_streams(&mut self) -> HttpResult<()> { // Moves the streams out of the state and then drops them let _ = self.conn.state.get_closed(); Ok(()) } }
prepare_responses
identifier_name
mod.rs
//! The module contains a simple HTTP/2 server implementation. use http::{Response, HttpResult, HttpError, HttpScheme, Header, StreamId}; use http::transport::TransportStream; use http::connection::{HttpConnection, EndStream, SendStatus}; use http::session::{DefaultSessionState, SessionState, Stream}; use http::server::ServerConnection; /// The struct represents a fully received request. pub struct ServerRequest<'a> { pub stream_id: StreamId, pub headers: &'a [Header], pub body: &'a [u8], } /// The struct implements a simple HTTP/2 server that allows users to register a request handler (a /// callback taking a `ServerRequest` and returning a `Response`) which is run on all received /// requests. /// /// The `handle_next` method needs to be called regularly in order to have the server process /// received frames, as well as send out the responses. /// /// This is an exceedingly simple implementation of an HTTP/2 server and is mostly an example of /// how the `solicit::http` API can be used to make one. /// /// # Examples /// /// ```no_run /// extern crate solicit; /// use std::str; /// use std::net::{TcpListener, TcpStream}; /// use std::thread; /// /// use solicit::server::SimpleServer; /// /// use solicit::http::Response; /// /// fn main() { /// fn handle_client(stream: TcpStream) { /// let mut server = SimpleServer::new(stream, |req| { /// println!("Received request:"); /// for header in req.headers.iter() { /// println!(" {}: {}", /// str::from_utf8(&header.0).unwrap(), /// str::from_utf8(&header.1).unwrap()); /// } /// println!("Body:\n{}", str::from_utf8(&req.body).unwrap()); /// /// // Return a dummy response for every request /// Response { /// headers: vec![ /// (b":status".to_vec(), b"200".to_vec()), /// (b"x-solicit".to_vec(), b"Hello, World!".to_vec()), /// ], /// body: vec![65], /// stream_id: req.stream_id, /// } /// }).unwrap(); /// while let Ok(_) = server.handle_next() {} /// println!("Server done (client disconnected)"); /// } /// /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); /// for stream in listener.incoming() { /// let stream = stream.unwrap(); /// thread::spawn(move || { /// handle_client(stream) /// }); /// } /// } /// ``` pub struct SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response { conn: ServerConnection<TS, TS>, handler: H, } impl<TS, H> SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response { /// Creates a new `SimpleServer` that will use the given `TransportStream` to communicate to /// the client. Assumes that the stream is fully uninitialized -- no preface sent or read yet. pub fn new(mut stream: TS, handler: H) -> HttpResult<SimpleServer<TS, H>> { // First assert that the preface is received let mut preface = [0; 24]; TransportStream::read_exact(&mut stream, &mut preface).unwrap(); if &preface!= b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" { return Err(HttpError::UnableToConnect); } let conn = HttpConnection::<TS, TS>::with_stream(stream, HttpScheme::Http); let mut server = SimpleServer { conn: ServerConnection::with_connection(conn, DefaultSessionState::new()), handler: handler, }; // Initialize the connection -- send own settings and process the peer's try!(server.conn.init()); // Set up done Ok(server) } /// Handles the next incoming frame, blocking to receive it if nothing is available on the /// underlying stream. /// /// Handling the frame can trigger the handler callback. Any responses returned by the handler /// are immediately flushed out to the client (blocking the call until it's done). pub fn handle_next(&mut self) -> HttpResult<()> { try!(self.conn.handle_next_frame()); let responses = try!(self.handle_requests()); try!(self.prepare_responses(responses)); try!(self.flush_streams()); try!(self.reap_streams()); Ok(()) } /// Invokes the request handler for each fully received request. Collects all the responses /// into the returned `Vec`. fn handle_requests(&mut self) -> HttpResult<Vec<Response>> { let handler = &mut self.handler; Ok(self.conn.state.iter().filter(|s| s.is_closed_remote()).map(|stream| { let req = ServerRequest { stream_id: stream.stream_id, headers: stream.headers.as_ref().unwrap(), body: &stream.body, }; handler(req) }).collect()) } /// Prepares the streams for each of the given responses. Headers for each response are /// immediately sent and the data staged into the streams' outgoing buffer. fn prepare_responses(&mut self, responses: Vec<Response>) -> HttpResult<()> { for response in responses.into_iter() { try!(self.conn.start_response( response.headers, response.stream_id, EndStream::No)); let mut stream = self.conn.state.get_stream_mut(response.stream_id).unwrap(); stream.set_full_data(response.body); } Ok(()) } /// Flushes the outgoing buffers of all streams. #[inline] fn flush_streams(&mut self) -> HttpResult<()>
/// Removes closed streams from the connection state. #[inline] fn reap_streams(&mut self) -> HttpResult<()> { // Moves the streams out of the state and then drops them let _ = self.conn.state.get_closed(); Ok(()) } }
{ while let SendStatus::Sent = try!(self.conn.send_next_data()) {} Ok(()) }
identifier_body
mod.rs
//! The module contains a simple HTTP/2 server implementation. use http::{Response, HttpResult, HttpError, HttpScheme, Header, StreamId}; use http::transport::TransportStream; use http::connection::{HttpConnection, EndStream, SendStatus}; use http::session::{DefaultSessionState, SessionState, Stream}; use http::server::ServerConnection; /// The struct represents a fully received request. pub struct ServerRequest<'a> { pub stream_id: StreamId, pub headers: &'a [Header], pub body: &'a [u8], } /// The struct implements a simple HTTP/2 server that allows users to register a request handler (a /// callback taking a `ServerRequest` and returning a `Response`) which is run on all received /// requests. /// /// The `handle_next` method needs to be called regularly in order to have the server process /// received frames, as well as send out the responses. /// /// This is an exceedingly simple implementation of an HTTP/2 server and is mostly an example of /// how the `solicit::http` API can be used to make one. /// /// # Examples /// /// ```no_run /// extern crate solicit; /// use std::str; /// use std::net::{TcpListener, TcpStream}; /// use std::thread; /// /// use solicit::server::SimpleServer; /// /// use solicit::http::Response; /// /// fn main() { /// fn handle_client(stream: TcpStream) { /// let mut server = SimpleServer::new(stream, |req| { /// println!("Received request:"); /// for header in req.headers.iter() { /// println!(" {}: {}", /// str::from_utf8(&header.0).unwrap(), /// str::from_utf8(&header.1).unwrap()); /// } /// println!("Body:\n{}", str::from_utf8(&req.body).unwrap()); /// /// // Return a dummy response for every request /// Response { /// headers: vec![ /// (b":status".to_vec(), b"200".to_vec()), /// (b"x-solicit".to_vec(), b"Hello, World!".to_vec()), /// ], /// body: vec![65], /// stream_id: req.stream_id, /// } /// }).unwrap(); /// while let Ok(_) = server.handle_next() {} /// println!("Server done (client disconnected)"); /// } /// /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); /// for stream in listener.incoming() { /// let stream = stream.unwrap(); /// thread::spawn(move || { /// handle_client(stream) /// }); /// } /// } /// ``` pub struct SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response { conn: ServerConnection<TS, TS>, handler: H, } impl<TS, H> SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response { /// Creates a new `SimpleServer` that will use the given `TransportStream` to communicate to /// the client. Assumes that the stream is fully uninitialized -- no preface sent or read yet. pub fn new(mut stream: TS, handler: H) -> HttpResult<SimpleServer<TS, H>> { // First assert that the preface is received let mut preface = [0; 24]; TransportStream::read_exact(&mut stream, &mut preface).unwrap(); if &preface!= b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" { return Err(HttpError::UnableToConnect); } let conn = HttpConnection::<TS, TS>::with_stream(stream, HttpScheme::Http); let mut server = SimpleServer { conn: ServerConnection::with_connection(conn, DefaultSessionState::new()), handler: handler, }; // Initialize the connection -- send own settings and process the peer's try!(server.conn.init()); // Set up done Ok(server) } /// Handles the next incoming frame, blocking to receive it if nothing is available on the /// underlying stream. /// /// Handling the frame can trigger the handler callback. Any responses returned by the handler /// are immediately flushed out to the client (blocking the call until it's done). pub fn handle_next(&mut self) -> HttpResult<()> { try!(self.conn.handle_next_frame()); let responses = try!(self.handle_requests()); try!(self.prepare_responses(responses)); try!(self.flush_streams()); try!(self.reap_streams()); Ok(()) } /// Invokes the request handler for each fully received request. Collects all the responses /// into the returned `Vec`. fn handle_requests(&mut self) -> HttpResult<Vec<Response>> { let handler = &mut self.handler; Ok(self.conn.state.iter().filter(|s| s.is_closed_remote()).map(|stream| { let req = ServerRequest { stream_id: stream.stream_id, headers: stream.headers.as_ref().unwrap(), body: &stream.body, }; handler(req) }).collect()) } /// Prepares the streams for each of the given responses. Headers for each response are /// immediately sent and the data staged into the streams' outgoing buffer. fn prepare_responses(&mut self, responses: Vec<Response>) -> HttpResult<()> { for response in responses.into_iter() { try!(self.conn.start_response( response.headers, response.stream_id, EndStream::No)); let mut stream = self.conn.state.get_stream_mut(response.stream_id).unwrap(); stream.set_full_data(response.body); } Ok(()) } /// Flushes the outgoing buffers of all streams. #[inline] fn flush_streams(&mut self) -> HttpResult<()> { while let SendStatus::Sent = try!(self.conn.send_next_data()) {}
/// Removes closed streams from the connection state. #[inline] fn reap_streams(&mut self) -> HttpResult<()> { // Moves the streams out of the state and then drops them let _ = self.conn.state.get_closed(); Ok(()) } }
Ok(()) }
random_line_split
mod.rs
//! The module contains a simple HTTP/2 server implementation. use http::{Response, HttpResult, HttpError, HttpScheme, Header, StreamId}; use http::transport::TransportStream; use http::connection::{HttpConnection, EndStream, SendStatus}; use http::session::{DefaultSessionState, SessionState, Stream}; use http::server::ServerConnection; /// The struct represents a fully received request. pub struct ServerRequest<'a> { pub stream_id: StreamId, pub headers: &'a [Header], pub body: &'a [u8], } /// The struct implements a simple HTTP/2 server that allows users to register a request handler (a /// callback taking a `ServerRequest` and returning a `Response`) which is run on all received /// requests. /// /// The `handle_next` method needs to be called regularly in order to have the server process /// received frames, as well as send out the responses. /// /// This is an exceedingly simple implementation of an HTTP/2 server and is mostly an example of /// how the `solicit::http` API can be used to make one. /// /// # Examples /// /// ```no_run /// extern crate solicit; /// use std::str; /// use std::net::{TcpListener, TcpStream}; /// use std::thread; /// /// use solicit::server::SimpleServer; /// /// use solicit::http::Response; /// /// fn main() { /// fn handle_client(stream: TcpStream) { /// let mut server = SimpleServer::new(stream, |req| { /// println!("Received request:"); /// for header in req.headers.iter() { /// println!(" {}: {}", /// str::from_utf8(&header.0).unwrap(), /// str::from_utf8(&header.1).unwrap()); /// } /// println!("Body:\n{}", str::from_utf8(&req.body).unwrap()); /// /// // Return a dummy response for every request /// Response { /// headers: vec![ /// (b":status".to_vec(), b"200".to_vec()), /// (b"x-solicit".to_vec(), b"Hello, World!".to_vec()), /// ], /// body: vec![65], /// stream_id: req.stream_id, /// } /// }).unwrap(); /// while let Ok(_) = server.handle_next() {} /// println!("Server done (client disconnected)"); /// } /// /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); /// for stream in listener.incoming() { /// let stream = stream.unwrap(); /// thread::spawn(move || { /// handle_client(stream) /// }); /// } /// } /// ``` pub struct SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response { conn: ServerConnection<TS, TS>, handler: H, } impl<TS, H> SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response { /// Creates a new `SimpleServer` that will use the given `TransportStream` to communicate to /// the client. Assumes that the stream is fully uninitialized -- no preface sent or read yet. pub fn new(mut stream: TS, handler: H) -> HttpResult<SimpleServer<TS, H>> { // First assert that the preface is received let mut preface = [0; 24]; TransportStream::read_exact(&mut stream, &mut preface).unwrap(); if &preface!= b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
let conn = HttpConnection::<TS, TS>::with_stream(stream, HttpScheme::Http); let mut server = SimpleServer { conn: ServerConnection::with_connection(conn, DefaultSessionState::new()), handler: handler, }; // Initialize the connection -- send own settings and process the peer's try!(server.conn.init()); // Set up done Ok(server) } /// Handles the next incoming frame, blocking to receive it if nothing is available on the /// underlying stream. /// /// Handling the frame can trigger the handler callback. Any responses returned by the handler /// are immediately flushed out to the client (blocking the call until it's done). pub fn handle_next(&mut self) -> HttpResult<()> { try!(self.conn.handle_next_frame()); let responses = try!(self.handle_requests()); try!(self.prepare_responses(responses)); try!(self.flush_streams()); try!(self.reap_streams()); Ok(()) } /// Invokes the request handler for each fully received request. Collects all the responses /// into the returned `Vec`. fn handle_requests(&mut self) -> HttpResult<Vec<Response>> { let handler = &mut self.handler; Ok(self.conn.state.iter().filter(|s| s.is_closed_remote()).map(|stream| { let req = ServerRequest { stream_id: stream.stream_id, headers: stream.headers.as_ref().unwrap(), body: &stream.body, }; handler(req) }).collect()) } /// Prepares the streams for each of the given responses. Headers for each response are /// immediately sent and the data staged into the streams' outgoing buffer. fn prepare_responses(&mut self, responses: Vec<Response>) -> HttpResult<()> { for response in responses.into_iter() { try!(self.conn.start_response( response.headers, response.stream_id, EndStream::No)); let mut stream = self.conn.state.get_stream_mut(response.stream_id).unwrap(); stream.set_full_data(response.body); } Ok(()) } /// Flushes the outgoing buffers of all streams. #[inline] fn flush_streams(&mut self) -> HttpResult<()> { while let SendStatus::Sent = try!(self.conn.send_next_data()) {} Ok(()) } /// Removes closed streams from the connection state. #[inline] fn reap_streams(&mut self) -> HttpResult<()> { // Moves the streams out of the state and then drops them let _ = self.conn.state.get_closed(); Ok(()) } }
{ return Err(HttpError::UnableToConnect); }
conditional_block
plugin_io.rs
use std::os::raw::{c_char, c_void}; use prodbg_api::io::{CPDLoadState, CPDSaveState, LoadState}; use prodbg_api::cfixed_string::CFixedString; use std::ffi::CStr; use std::mem::transmute; use std::ptr; struct WriterData { data: Vec<String>, read_index: usize, } impl WriterData { fn new() -> WriterData { WriterData { data: Vec::new(), read_index: 0, } } fn
(data: &Vec<String>) -> WriterData { WriterData { data: data.clone(), read_index: 0, } } } fn write_int(priv_data: *mut c_void, data: i64) { unsafe { println!("saving {}", data); let t = priv_data as *mut WriterData; let v = format!("{}", data); (*t).data.push(v); } } fn write_double(priv_data: *mut c_void, data: f64) { unsafe { println!("saving {}", data); let t = priv_data as *mut WriterData; let v = format!("{}", data); (*t).data.push(v); } } fn write_string(priv_data: *mut c_void, data: *const c_char) { unsafe { let t = priv_data as *mut WriterData; let v = CStr::from_ptr(data).to_string_lossy().into_owned(); println!("saving {}", v); (*t).data.push(v); } } // TODO: error handling fn read_int(priv_data: *mut c_void, data: *mut i64) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = (*t).data[(*t).read_index].parse::<i64>().unwrap(); (*t).read_index += 1; *data = v; LoadState::Ok } } fn read_double(priv_data: *mut c_void, data: *mut f64) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = (*t).data[(*t).read_index].parse::<f64>().unwrap(); (*t).read_index += 1; *data = v; LoadState::Ok } } fn read_string(priv_data: *mut c_void, data: *mut c_char, max_len: i32) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = &(*t).data[(*t).read_index]; (*t).read_index += 1; let mut len = v.len(); if len > max_len as usize { len = max_len as usize; } let tstring = CFixedString::from_str(&v); ptr::copy(tstring.as_ptr(), data as *mut i8, len); LoadState::Ok } } pub fn get_writer_funcs() -> CPDSaveState { CPDSaveState { priv_data: unsafe { transmute(Box::new(WriterData::new())) }, write_int: write_int, write_double: write_double, write_string: write_string, } } pub fn get_data(save_state: &mut CPDSaveState) -> Vec<String> { let writer_data: Box<WriterData> = unsafe { transmute(save_state.priv_data) }; writer_data.data.clone() } pub fn get_loader_funcs(data: &Vec<String>) -> CPDLoadState { CPDLoadState { priv_data: unsafe { transmute(Box::new(WriterData::new_load(data))) }, read_int: read_int, read_double: read_double, read_string: read_string, } }
new_load
identifier_name
plugin_io.rs
use std::os::raw::{c_char, c_void}; use prodbg_api::io::{CPDLoadState, CPDSaveState, LoadState}; use prodbg_api::cfixed_string::CFixedString; use std::ffi::CStr; use std::mem::transmute; use std::ptr; struct WriterData { data: Vec<String>, read_index: usize, } impl WriterData { fn new() -> WriterData { WriterData { data: Vec::new(), read_index: 0, } } fn new_load(data: &Vec<String>) -> WriterData { WriterData { data: data.clone(), read_index: 0, } } } fn write_int(priv_data: *mut c_void, data: i64) { unsafe { println!("saving {}", data); let t = priv_data as *mut WriterData; let v = format!("{}", data); (*t).data.push(v); } } fn write_double(priv_data: *mut c_void, data: f64)
fn write_string(priv_data: *mut c_void, data: *const c_char) { unsafe { let t = priv_data as *mut WriterData; let v = CStr::from_ptr(data).to_string_lossy().into_owned(); println!("saving {}", v); (*t).data.push(v); } } // TODO: error handling fn read_int(priv_data: *mut c_void, data: *mut i64) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = (*t).data[(*t).read_index].parse::<i64>().unwrap(); (*t).read_index += 1; *data = v; LoadState::Ok } } fn read_double(priv_data: *mut c_void, data: *mut f64) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = (*t).data[(*t).read_index].parse::<f64>().unwrap(); (*t).read_index += 1; *data = v; LoadState::Ok } } fn read_string(priv_data: *mut c_void, data: *mut c_char, max_len: i32) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = &(*t).data[(*t).read_index]; (*t).read_index += 1; let mut len = v.len(); if len > max_len as usize { len = max_len as usize; } let tstring = CFixedString::from_str(&v); ptr::copy(tstring.as_ptr(), data as *mut i8, len); LoadState::Ok } } pub fn get_writer_funcs() -> CPDSaveState { CPDSaveState { priv_data: unsafe { transmute(Box::new(WriterData::new())) }, write_int: write_int, write_double: write_double, write_string: write_string, } } pub fn get_data(save_state: &mut CPDSaveState) -> Vec<String> { let writer_data: Box<WriterData> = unsafe { transmute(save_state.priv_data) }; writer_data.data.clone() } pub fn get_loader_funcs(data: &Vec<String>) -> CPDLoadState { CPDLoadState { priv_data: unsafe { transmute(Box::new(WriterData::new_load(data))) }, read_int: read_int, read_double: read_double, read_string: read_string, } }
{ unsafe { println!("saving {}", data); let t = priv_data as *mut WriterData; let v = format!("{}", data); (*t).data.push(v); } }
identifier_body
plugin_io.rs
use std::os::raw::{c_char, c_void}; use prodbg_api::io::{CPDLoadState, CPDSaveState, LoadState}; use prodbg_api::cfixed_string::CFixedString; use std::ffi::CStr; use std::mem::transmute; use std::ptr; struct WriterData { data: Vec<String>, read_index: usize, } impl WriterData { fn new() -> WriterData { WriterData { data: Vec::new(), read_index: 0, } } fn new_load(data: &Vec<String>) -> WriterData { WriterData { data: data.clone(), read_index: 0, } } } fn write_int(priv_data: *mut c_void, data: i64) { unsafe { println!("saving {}", data); let t = priv_data as *mut WriterData; let v = format!("{}", data); (*t).data.push(v); } } fn write_double(priv_data: *mut c_void, data: f64) { unsafe { println!("saving {}", data); let t = priv_data as *mut WriterData; let v = format!("{}", data); (*t).data.push(v); } } fn write_string(priv_data: *mut c_void, data: *const c_char) { unsafe { let t = priv_data as *mut WriterData; let v = CStr::from_ptr(data).to_string_lossy().into_owned(); println!("saving {}", v); (*t).data.push(v); } } // TODO: error handling fn read_int(priv_data: *mut c_void, data: *mut i64) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = (*t).data[(*t).read_index].parse::<i64>().unwrap(); (*t).read_index += 1; *data = v; LoadState::Ok } } fn read_double(priv_data: *mut c_void, data: *mut f64) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = (*t).data[(*t).read_index].parse::<f64>().unwrap(); (*t).read_index += 1; *data = v; LoadState::Ok } } fn read_string(priv_data: *mut c_void, data: *mut c_char, max_len: i32) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = &(*t).data[(*t).read_index]; (*t).read_index += 1; let mut len = v.len(); if len > max_len as usize
let tstring = CFixedString::from_str(&v); ptr::copy(tstring.as_ptr(), data as *mut i8, len); LoadState::Ok } } pub fn get_writer_funcs() -> CPDSaveState { CPDSaveState { priv_data: unsafe { transmute(Box::new(WriterData::new())) }, write_int: write_int, write_double: write_double, write_string: write_string, } } pub fn get_data(save_state: &mut CPDSaveState) -> Vec<String> { let writer_data: Box<WriterData> = unsafe { transmute(save_state.priv_data) }; writer_data.data.clone() } pub fn get_loader_funcs(data: &Vec<String>) -> CPDLoadState { CPDLoadState { priv_data: unsafe { transmute(Box::new(WriterData::new_load(data))) }, read_int: read_int, read_double: read_double, read_string: read_string, } }
{ len = max_len as usize; }
conditional_block
plugin_io.rs
use std::os::raw::{c_char, c_void}; use prodbg_api::io::{CPDLoadState, CPDSaveState, LoadState}; use prodbg_api::cfixed_string::CFixedString; use std::ffi::CStr; use std::mem::transmute; use std::ptr; struct WriterData { data: Vec<String>, read_index: usize, } impl WriterData { fn new() -> WriterData { WriterData { data: Vec::new(), read_index: 0, } } fn new_load(data: &Vec<String>) -> WriterData { WriterData { data: data.clone(), read_index: 0, } } } fn write_int(priv_data: *mut c_void, data: i64) { unsafe { println!("saving {}", data); let t = priv_data as *mut WriterData; let v = format!("{}", data); (*t).data.push(v); } } fn write_double(priv_data: *mut c_void, data: f64) { unsafe { println!("saving {}", data); let t = priv_data as *mut WriterData;
let v = format!("{}", data); (*t).data.push(v); } } fn write_string(priv_data: *mut c_void, data: *const c_char) { unsafe { let t = priv_data as *mut WriterData; let v = CStr::from_ptr(data).to_string_lossy().into_owned(); println!("saving {}", v); (*t).data.push(v); } } // TODO: error handling fn read_int(priv_data: *mut c_void, data: *mut i64) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = (*t).data[(*t).read_index].parse::<i64>().unwrap(); (*t).read_index += 1; *data = v; LoadState::Ok } } fn read_double(priv_data: *mut c_void, data: *mut f64) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = (*t).data[(*t).read_index].parse::<f64>().unwrap(); (*t).read_index += 1; *data = v; LoadState::Ok } } fn read_string(priv_data: *mut c_void, data: *mut c_char, max_len: i32) -> LoadState { unsafe { let t = priv_data as *mut WriterData; let v = &(*t).data[(*t).read_index]; (*t).read_index += 1; let mut len = v.len(); if len > max_len as usize { len = max_len as usize; } let tstring = CFixedString::from_str(&v); ptr::copy(tstring.as_ptr(), data as *mut i8, len); LoadState::Ok } } pub fn get_writer_funcs() -> CPDSaveState { CPDSaveState { priv_data: unsafe { transmute(Box::new(WriterData::new())) }, write_int: write_int, write_double: write_double, write_string: write_string, } } pub fn get_data(save_state: &mut CPDSaveState) -> Vec<String> { let writer_data: Box<WriterData> = unsafe { transmute(save_state.priv_data) }; writer_data.data.clone() } pub fn get_loader_funcs(data: &Vec<String>) -> CPDLoadState { CPDLoadState { priv_data: unsafe { transmute(Box::new(WriterData::new_load(data))) }, read_int: read_int, read_double: read_double, read_string: read_string, } }
random_line_split
bg.rs
all background layers. The cache is created lazily /// (when BG layer pixels are looked up), so we will not waste time caching a disabled BG layer. #[derive(Default)] pub struct BgCache { layers: [BgLayerCache; 4], } /// Data that's stored in the BG layer caches for a single pixel #[derive(Copy, Clone, Default)] struct CachedPixel { // These are just copied from `TilemapEntry`. /// Tile priority bit (0-1) priority: u8, /// Precalculated color of the pixel (15-bit RGB). `None` = transparent. color: Option<SnesRgb>, } /// BG cache for a single layer struct BgLayerCache { /// Whether this cache contains valid data. If `false`, the cache will be refreshed on next /// access. valid: bool, /// Stores the prerendered scanline scanline: [CachedPixel; super::SCREEN_WIDTH as usize], } impl Default for BgLayerCache { fn default() -> Self { BgLayerCache { valid: false, scanline: [CachedPixel::default(); super::SCREEN_WIDTH as usize], } } } impl BgLayerCache { /// Invalidates the cache of this layer, causing it to be rebuilt on next access. #[allow(dead_code)] // FIXME Use in the right locations fn invalidate(&mut self) { self.valid = false; } } impl BgCache { /// Invalidates the BG cache of all layers fn invalidate_all(&mut self) { self.layers[0].valid = false; self.layers[1].valid = false; self.layers[2].valid = false; self.layers[3].valid = false; } } /// Collected background settings struct BgSettings { /// Mosaic pixel size (1-16). 1 = Normal pixels. /// FIXME: I think there's a difference between disabled and enabled with 1x1 mosaic size in /// some modes (highres presumably) #[allow(dead_code)] // FIXME NYI mosaic: u8, /// Tilemap word address in VRAM /// "Starting at the tilemap address, the first $800 bytes are for tilemap A. Then come the /// $800 bytes for B, then C then D." tilemap_word_addr: u16, /// When `true`, this BGs tilemaps are repeated sideways tilemap_mirror_h: bool, /// When `true`, this BGs tilemaps are repeated downwards tilemap_mirror_v: bool, /// If `true`, BG tiles are 16x16 pixels. If `false`, they are 8x8 pixels. tile_size_16: bool, /// Character Data start address in VRAM chr_addr: u16, /// Horizontal scroll offset. Moves the BG layer to the left by some number of pixels. hofs: u16, /// Vertical scroll offset. Moves the BG layer up by some number of pixels. vofs: u16, } /// Unpacked tilemap entry for internal (rendering) use. /// /// A tilemap entry is 2 bytes large and contains informations about a single background layer tile. struct TilemapEntry { /// Flip this tile vertically (flips top and down of the tile) vflip: bool, /// Flip horizontally (flips left and right side) hflip: bool, /// Priority bit (0-1) priority: u8, /// Tile palette (0-7) palette: u8, /// Index into the character/tile data, where the actual tile character data is stored in /// bitplanes (10 bits) tile_number: u16, } impl Ppu { /// Determines whether the given BG layer (1-4) is enabled fn bg_enabled(&self, bg: u8, subscreen: bool) -> bool { let reg = if subscreen { self.ts } else { self.tm }; reg & (1 << (bg - 1))!= 0 } /// Reads the tilemap entry at the given VRAM word address. /// vhopppcc cccccccc (high, low) /// v/h = Vertical/Horizontal flip this tile. /// o = Tile priority. /// ppp = Tile palette base. /// cccccccccc = Tile number. fn tilemap_entry(&self, word_address: u16) -> TilemapEntry { let byte_address = word_address << 1; let lo = self.vram[byte_address]; let hi = self.vram[byte_address + 1]; TilemapEntry { vflip: hi & 0x80!= 0, hflip: hi & 0x40!= 0, priority: (hi & 0x20) >> 5, palette: (hi & 0x1c) >> 2, tile_number: ((hi as u16 & 0x03) << 8) | lo as u16, } } /// Collects properties of a background layer fn bg_settings(&self, bg: u8) -> BgSettings { // The BGxSC register for our background layer let bgsc = match bg { 1 => self.bg1sc, 2 => self.bg2sc, 3 => self.bg3sc, 4 => self.bg4sc, _ => unreachable!(), }; // Chr (Tileset, not Tilemap) start (word?) address >> 12 let chr = match bg { 1 => self.bg12nba & 0x0f, 2 => (self.bg12nba & 0xf0) >> 4, 3 => self.bg34nba & 0x0f, 4 => (self.bg34nba & 0xf0) >> 4, _ => unreachable!(), }; let (hofs, vofs) = match bg { 1 => (self.bg1hofs, self.bg1vofs), 2 => (self.bg2hofs, self.bg2vofs), 3 => (self.bg3hofs, self.bg3vofs), 4 => (self.bg4hofs, self.bg4vofs), _ => unreachable!(), }; BgSettings { mosaic: if self.mosaic & (1 << (bg-1)) == 0 { 1 } else { ((self.mosaic & 0xf0) >> 4) + 1 }, tilemap_word_addr: ((bgsc as u16 & 0xfc) >> 2) << 10, tilemap_mirror_h: bgsc & 0b01 == 0, // inverted bit value tilemap_mirror_v: bgsc & 0b10 == 0, // inverted bit value tile_size_16: match self.bg_mode() { // "If the BG character size for BG1/BG2/BG3/BG4 bit is set, then the BG is made of // 16x16 tiles. Otherwise, 8x8 tiles are used. However, note that Modes 5 and 6 // always use 16-pixel wide tiles, and Mode 7 always uses 8x8 tiles." 5 | 6 => true, 7 => false, _ => { // BGMODE: `4321----` (`-` = not relevant here) - Use 16x16 tiles? self.bgmode & (1 << (bg + 3))!= 0 } }, chr_addr: (chr as u16) << 12, hofs: hofs, vofs: vofs, } } /// Returns the number of color bits in the given BG layer in the current BG mode (2, 4, 7 or /// 8). To get the number of colors, use `1 << color_bits_for_bg`. /// /// Table of colors for BG layers (not what this function returns!). `X` denotes a BG for /// offset-per-tile data. /// ```text /// Mode # Colors for BG /// 1 2 3 4 /// ======---=---=---=---= /// 0 4 4 4 4 /// 1 16 16 4 - /// 2 16 16 X - /// 3 256 16 - - /// 4 256 4 X - /// 5 16 4 - - /// 6 16 - X - /// 7 256 - - - /// 7EXTBG 256 128 - - /// ``` fn color_bits_for_bg(&self, bg: u8) -> u8 { match (self.bg_mode(), bg) { (0, _) => 2, (1, 1) | (1, 2) => 4, (1, 3) => 2, (2, _) => 4, (3, 1) => 8, (3, 2) => 4, (4, 1) => 8, (4, 2) => 2, (5, 1) => 4, (5, 2) => 2, (6, _) => 4, (7, _) => panic!("unreachable: color_count_for_bg for mode 7"), _ => unreachable!(), } } /// Calculates the palette base index for a tile in the given background layer. `palette_num` /// is the palette number stored in the tilemap entry (the 3 `p` bits). fn palette_base_for_bg_tile(&self, bg: u8, palette_num: u8) -> u8 { debug_assert!(bg >= 1 && bg <= 4); match (self.bg_mode(), bg) { (0, _) => palette_num * 4 + (bg - 1) * 32, (1, _) | (5, _) => palette_num * (1 << self.color_bits_for_bg(bg) as u8), (2, _) => palette_num * 16, (3, 1) => 0, (3, 2) => palette_num * 16, (4, 1) => 0, (4, 2) => palette_num * 4, (6, _) => palette_num * 16, // BG1 has 16 colors (7, _) => panic!("unreachable: palette_base_for_bg_tile for mode 7"), _ => unreachable!(), } } fn render_mode7_scanline(&mut self) { // TODO Figure out how to integrate EXTBG assert!(self.setini & 0x40 == 0, "NYI: Mode 7 EXTBG"); // FIXME consider changing the type of `Ppu.m7a,...` to `i16` let vflip = self.m7sel & 0x02!= 0; let hflip = self.m7sel & 0x01!= 0; // 0/1: Wrap // 2: Transparent // 3: Fill with tile 0 let screen_over = self.m7sel >> 6; let y = self.scanline; for x in self.x..super::SCREEN_WIDTH as u16 { // Code taken from http://problemkaputt.de/fullsnes.htm // FIXME: The above source also has a much faster way to render whole scanlines! let screen_x = x ^ if hflip { 0xff } else
; let screen_y = y ^ if vflip { 0xff } else { 0x00 }; let mut org_x = (self.m7hofs as i16 - self.m7x as i16) &!0x1c00; if org_x < 0 { org_x |= 0x1c00; } let mut org_y = (self.m7vofs as i16 - self.m7y as i16) &!0x1c00; if org_y < 0 { org_y |= 0x1c00; } let mut vram_x: i32 = ((self.m7a as i16 as i32 * org_x as i32) &!0x3f) + ((self.m7b as i16 as i32 * org_y as i32) &!0x3f) + self.m7x as i16 as i32 * 0x100; let mut vram_y: i32 = ((self.m7c as i16 as i32 * org_x as i32) &!0x3f) + ((self.m7d as i16 as i32 * org_y as i32) &!0x3f) + self.m7y as i16 as i32 * 0x100; vram_x += ((self.m7b as i16 as i32 * screen_y as i32) &!0x3f) + self.m7a as i16 as i32 * screen_x as i32; vram_y += ((self.m7d as i16 as i32 * screen_y as i32) &!0x3f) + self.m7c as i16 as i32 * screen_x as i32; let out_of_bounds = vram_x & (1 << 18)!= 0 || vram_y & (1 << 18)!= 0; let palette_index = match screen_over { 2 if out_of_bounds => { // transparent 0 }, _ => { let (tile_x, tile_y) = if screen_over == 3 && out_of_bounds { (0, 0) // 3 -> use tile 0 } else { let tile_x: u16 = ((vram_x as u32 >> 11) & 0x7f) as u16; let tile_y: u16 = ((vram_y as u32 >> 11) & 0x7f) as u16; (tile_x, tile_y) }; let off_x: u16 = (vram_x as u16 >> 8) & 0x07; let off_y: u16 = (vram_y as u16 >> 8) & 0x07; // Tilemap address for (7-bit) tile X/Y coordinates (BG1 is 128x128 tiles): // `0yyyyyyy xxxxxxx0` let tilemap_addr: u16 = (tile_y << 8) | (tile_x << 1); // The "tilemap" in mode 7 just consists of "tile numbers" (or pixel addresses) let tile_number = self.vram[tilemap_addr] as u16; // The CHR address is calculated like this (where `t` is `tile_number` and `x` and `y` // are pixel offsets inside the tile): // `tttttttt tyyyxxx1` let chr_addr = (tile_number << 7) | (off_y << 4) | (off_x << 1) | 1; self.vram[chr_addr] }, }; let rgb = match palette_index { 0 => None, _ => Some(self.cgram.get_color(palette_index)), }; self.bg_cache.layers[0].scanline[x as usize] = CachedPixel { priority: 0, // Ignored anyways color: rgb, }; } } /// Render the current scanline of the given BG layer into its cache. /// /// We render starting at `self.x` (the pixel we actually need) until the end of the /// scanline. Note that this means that the `valid` flag is only relevant for the /// leftover part of the scanline, not the entire cached scanline. fn render_bg_scanline(&mut self, bg_num: u8) { // Apply BG scrolling and get the tile coordinates // FIXME Apply mosaic filter // FIXME Fix this: "Note that many games will set their vertical scroll values to -1 rather // than 0. This is because the SNES loads OBJ data for each scanline during the previous // scanline. The very first line, though, wouldn’t have any OBJ data loaded! So the SNES // doesn’t actually output scanline 0, although it does everything to render it. These // games want the first line of their tilemap to be the first line output, so they set // their VOFS registers in this manner. Note that an interlace screen needs -2 rather than // -1 to properly correct for the missing line 0 (and an emulator would need to add 2 // instead of 1 to account for this)." // -> I guess we should just decrement the physical screen height by 1 if self.bg_mode() == 7 { self.render_mode7_scanline(); return; } let mut x = self.x; let y = self.scanline; let bg = self.bg_settings(bg_num); let tile_size = if bg.tile_size_16 { 16 } else { 8 }; let (hofs, vofs) = (bg.hofs, bg.vofs); let (sx, sy) = (!bg.tilemap_mirror_h,!bg.tilemap_mirror_v); let color_bits = self.color_bits_for_bg(bg_num); if color_bits == 8 { // can use direct color mode debug_assert!(self.cgwsel & 0x01 == 0, "NYI: direct color mode"); } let mut tile_x = x.wrapping_add(hofs) / tile_size as u16; let tile_y = y.wrapping_add(vofs) / tile_size as u16; let mut off_x = (x.wrapping_add(hofs) % tile_size as u16) as u8; let off_y = (y.wrapping_add(vofs) % tile_size as u16) as u8; while x < super::SCREEN_WIDTH as u16 { // Render current tile (`tile_x`) starting at `off_x` until the end of the tile, // then go to next tile and set `off_x = 0` // Calculate the VRAM word address, where the tilemap entry for our tile is stored let tilemap_entry_word_address = bg.tilemap_word_addr | ((tile_y & 0x1f) << 5) | (tile_x & 0x1f) | if sy {(tile_y & 0x20) << if sx {6} else {5}} else {0} | if sx {(tile_x & 0x20) << 5} else {0}; let tilemap_entry = self.tilemap_entry(tilemap_entry_word_address); let bitplane_start_addr = (bg.chr_addr << 1) + (tilemap_entry.tile_number * 8 * color_bits as u16); // 8 bytes per bitplane let palette_base = self.palette_base_for_bg_tile(bg_num, tilemap_entry.palette); while off_x < tile_size && x < super::SCREEN_WIDTH as u16 { let palette_index = self.read_chr_entry(color_bits, bitplane_start_addr, tile_size, (off_x, off_y), (tilemap_entry.vflip, tilemap_entry.hflip)); let rgb = match palette_index { 0 => None, _ => Some(self.cgram.get_color(palette_base + palette_index)), }; self.bg_cache.layers[bg_num as usize - 1].scanline[x as usize] = CachedPixel { priority: tilemap_entry.priority, color: rgb, }; x += 1; off_x += 1; } tile_x += 1; off_x = 0; } } /// Main entry point into the BG layer renderer. /// /// Lookup the color of the given background layer (1-4) at the current pixel, using the given /// priority (0-1) only. This will also scroll backgrounds accordingly. /// /// This may only be called with BG layer numbers which are actually valid in the current BG /// mode (the renderer code makes sure that this is the case). /// /// Returns `None` if the pixel is transparent, `Some(SnesRgb)` otherwise. pub fn lookup_bg_color(&mut self, bg_num: u8, prio: u8, subscreen: bool) -> Option<SnesRgb> { debug_assert!(bg_num >= 1 && bg_num <= 4); debug_assert!(prio == 0 || prio == 1); if!self.bg_enabled(bg_num, subscreen) { return None; } if self.x == 0 { // Before we draw the first pixel, make sure that we invalidate the cache so it is // rebuilt first. self.bg_cache.invalidate_all(); } if!self.bg_cache.layers[bg_num as usize - 1].valid { // Call actual render code to render the scanline into the cache self.render_bg_scanline(bg_num); self.bg_cache.layers[bg_num as usize - 1].valid = true; } // Cache must be valid now, so we can access the pixel we need: let pixel = &self.bg_cache.layers
{ 0x00 }
conditional_block
bg.rs
of all background layers. The cache is created lazily /// (when BG layer pixels are looked up), so we will not waste time caching a disabled BG layer. #[derive(Default)] pub struct BgCache { layers: [BgLayerCache; 4], } /// Data that's stored in the BG layer caches for a single pixel #[derive(Copy, Clone, Default)] struct CachedPixel { // These are just copied from `TilemapEntry`. /// Tile priority bit (0-1) priority: u8, /// Precalculated color of the pixel (15-bit RGB). `None` = transparent. color: Option<SnesRgb>, } /// BG cache for a single layer struct BgLayerCache { /// Whether this cache contains valid data. If `false`, the cache will be refreshed on next /// access. valid: bool, /// Stores the prerendered scanline scanline: [CachedPixel; super::SCREEN_WIDTH as usize], } impl Default for BgLayerCache { fn default() -> Self { BgLayerCache { valid: false, scanline: [CachedPixel::default(); super::SCREEN_WIDTH as usize], } } } impl BgLayerCache { /// Invalidates the cache of this layer, causing it to be rebuilt on next access. #[allow(dead_code)] // FIXME Use in the right locations fn invalidate(&mut self) { self.valid = false; } } impl BgCache { /// Invalidates the BG cache of all layers fn invalidate_all(&mut self) { self.layers[0].valid = false; self.layers[1].valid = false; self.layers[2].valid = false; self.layers[3].valid = false; } } /// Collected background settings struct BgSettings { /// Mosaic pixel size (1-16). 1 = Normal pixels. /// FIXME: I think there's a difference between disabled and enabled with 1x1 mosaic size in /// some modes (highres presumably) #[allow(dead_code)] // FIXME NYI mosaic: u8, /// Tilemap word address in VRAM /// "Starting at the tilemap address, the first $800 bytes are for tilemap A. Then come the /// $800 bytes for B, then C then D." tilemap_word_addr: u16, /// When `true`, this BGs tilemaps are repeated sideways tilemap_mirror_h: bool, /// When `true`, this BGs tilemaps are repeated downwards tilemap_mirror_v: bool, /// If `true`, BG tiles are 16x16 pixels. If `false`, they are 8x8 pixels. tile_size_16: bool, /// Character Data start address in VRAM chr_addr: u16, /// Horizontal scroll offset. Moves the BG layer to the left by some number of pixels. hofs: u16, /// Vertical scroll offset. Moves the BG layer up by some number of pixels. vofs: u16, } /// Unpacked tilemap entry for internal (rendering) use. /// /// A tilemap entry is 2 bytes large and contains informations about a single background layer tile. struct TilemapEntry { /// Flip this tile vertically (flips top and down of the tile) vflip: bool, /// Flip horizontally (flips left and right side) hflip: bool, /// Priority bit (0-1) priority: u8, /// Tile palette (0-7) palette: u8, /// Index into the character/tile data, where the actual tile character data is stored in /// bitplanes (10 bits) tile_number: u16, } impl Ppu { /// Determines whether the given BG layer (1-4) is enabled fn bg_enabled(&self, bg: u8, subscreen: bool) -> bool { let reg = if subscreen { self.ts } else { self.tm }; reg & (1 << (bg - 1))!= 0 } /// Reads the tilemap entry at the given VRAM word address. /// vhopppcc cccccccc (high, low) /// v/h = Vertical/Horizontal flip this tile. /// o = Tile priority. /// ppp = Tile palette base. /// cccccccccc = Tile number. fn tilemap_entry(&self, word_address: u16) -> TilemapEntry { let byte_address = word_address << 1; let lo = self.vram[byte_address]; let hi = self.vram[byte_address + 1]; TilemapEntry { vflip: hi & 0x80!= 0, hflip: hi & 0x40!= 0, priority: (hi & 0x20) >> 5, palette: (hi & 0x1c) >> 2, tile_number: ((hi as u16 & 0x03) << 8) | lo as u16, } } /// Collects properties of a background layer fn bg_settings(&self, bg: u8) -> BgSettings { // The BGxSC register for our background layer let bgsc = match bg { 1 => self.bg1sc, 2 => self.bg2sc, 3 => self.bg3sc, 4 => self.bg4sc, _ => unreachable!(), }; // Chr (Tileset, not Tilemap) start (word?) address >> 12 let chr = match bg { 1 => self.bg12nba & 0x0f, 2 => (self.bg12nba & 0xf0) >> 4, 3 => self.bg34nba & 0x0f, 4 => (self.bg34nba & 0xf0) >> 4, _ => unreachable!(), }; let (hofs, vofs) = match bg { 1 => (self.bg1hofs, self.bg1vofs), 2 => (self.bg2hofs, self.bg2vofs), 3 => (self.bg3hofs, self.bg3vofs), 4 => (self.bg4hofs, self.bg4vofs), _ => unreachable!(), }; BgSettings { mosaic: if self.mosaic & (1 << (bg-1)) == 0 { 1 } else { ((self.mosaic & 0xf0) >> 4) + 1 }, tilemap_word_addr: ((bgsc as u16 & 0xfc) >> 2) << 10, tilemap_mirror_h: bgsc & 0b01 == 0, // inverted bit value tilemap_mirror_v: bgsc & 0b10 == 0, // inverted bit value tile_size_16: match self.bg_mode() { // "If the BG character size for BG1/BG2/BG3/BG4 bit is set, then the BG is made of // 16x16 tiles. Otherwise, 8x8 tiles are used. However, note that Modes 5 and 6 // always use 16-pixel wide tiles, and Mode 7 always uses 8x8 tiles." 5 | 6 => true, 7 => false, _ => { // BGMODE: `4321----` (`-` = not relevant here) - Use 16x16 tiles? self.bgmode & (1 << (bg + 3))!= 0 } }, chr_addr: (chr as u16) << 12, hofs: hofs, vofs: vofs, } } /// Returns the number of color bits in the given BG layer in the current BG mode (2, 4, 7 or /// 8). To get the number of colors, use `1 << color_bits_for_bg`. /// /// Table of colors for BG layers (not what this function returns!). `X` denotes a BG for /// offset-per-tile data. /// ```text /// Mode # Colors for BG /// 1 2 3 4 /// ======---=---=---=---= /// 0 4 4 4 4 /// 1 16 16 4 - /// 2 16 16 X - /// 3 256 16 - - /// 4 256 4 X - /// 5 16 4 - - /// 6 16 - X - /// 7 256 - - - /// 7EXTBG 256 128 - - /// ``` fn color_bits_for_bg(&self, bg: u8) -> u8 { match (self.bg_mode(), bg) { (0, _) => 2, (1, 1) | (1, 2) => 4, (1, 3) => 2, (2, _) => 4, (3, 1) => 8, (3, 2) => 4, (4, 1) => 8, (4, 2) => 2, (5, 1) => 4, (5, 2) => 2, (6, _) => 4, (7, _) => panic!("unreachable: color_count_for_bg for mode 7"), _ => unreachable!(), } } /// Calculates the palette base index for a tile in the given background layer. `palette_num` /// is the palette number stored in the tilemap entry (the 3 `p` bits). fn palette_base_for_bg_tile(&self, bg: u8, palette_num: u8) -> u8 { debug_assert!(bg >= 1 && bg <= 4); match (self.bg_mode(), bg) { (0, _) => palette_num * 4 + (bg - 1) * 32, (1, _) | (5, _) => palette_num * (1 << self.color_bits_for_bg(bg) as u8), (2, _) => palette_num * 16, (3, 1) => 0, (3, 2) => palette_num * 16, (4, 1) => 0, (4, 2) => palette_num * 4, (6, _) => palette_num * 16, // BG1 has 16 colors (7, _) => panic!("unreachable: palette_base_for_bg_tile for mode 7"), _ => unreachable!(), } } fn render_mode7_scanline(&mut self) { // TODO Figure out how to integrate EXTBG assert!(self.setini & 0x40 == 0, "NYI: Mode 7 EXTBG"); // FIXME consider changing the type of `Ppu.m7a,...` to `i16` let vflip = self.m7sel & 0x02!= 0; let hflip = self.m7sel & 0x01!= 0; // 0/1: Wrap // 2: Transparent // 3: Fill with tile 0 let screen_over = self.m7sel >> 6; let y = self.scanline; for x in self.x..super::SCREEN_WIDTH as u16 { // Code taken from http://problemkaputt.de/fullsnes.htm // FIXME: The above source also has a much faster way to render whole scanlines! let screen_x = x ^ if hflip { 0xff } else { 0x00 }; let screen_y = y ^ if vflip { 0xff } else { 0x00 }; let mut org_x = (self.m7hofs as i16 - self.m7x as i16) &!0x1c00; if org_x < 0 { org_x |= 0x1c00; } let mut org_y = (self.m7vofs as i16 - self.m7y as i16) &!0x1c00; if org_y < 0 { org_y |= 0x1c00; } let mut vram_x: i32 = ((self.m7a as i16 as i32 * org_x as i32) &!0x3f) + ((self.m7b as i16 as i32 * org_y as i32) &!0x3f) + self.m7x as i16 as i32 * 0x100; let mut vram_y: i32 = ((self.m7c as i16 as i32 * org_x as i32) &!0x3f) + ((self.m7d as i16 as i32 * org_y as i32) &!0x3f) + self.m7y as i16 as i32 * 0x100; vram_x += ((self.m7b as i16 as i32 * screen_y as i32) &!0x3f) + self.m7a as i16 as i32 * screen_x as i32; vram_y += ((self.m7d as i16 as i32 * screen_y as i32) &!0x3f) + self.m7c as i16 as i32 * screen_x as i32; let out_of_bounds = vram_x & (1 << 18)!= 0 || vram_y & (1 << 18)!= 0; let palette_index = match screen_over { 2 if out_of_bounds => { // transparent 0 }, _ => { let (tile_x, tile_y) = if screen_over == 3 && out_of_bounds { (0, 0) // 3 -> use tile 0 } else { let tile_x: u16 = ((vram_x as u32 >> 11) & 0x7f) as u16; let tile_y: u16 = ((vram_y as u32 >> 11) & 0x7f) as u16; (tile_x, tile_y) }; let off_x: u16 = (vram_x as u16 >> 8) & 0x07; let off_y: u16 = (vram_y as u16 >> 8) & 0x07; // Tilemap address for (7-bit) tile X/Y coordinates (BG1 is 128x128 tiles): // `0yyyyyyy xxxxxxx0` let tilemap_addr: u16 = (tile_y << 8) | (tile_x << 1); // The "tilemap" in mode 7 just consists of "tile numbers" (or pixel addresses) let tile_number = self.vram[tilemap_addr] as u16; // The CHR address is calculated like this (where `t` is `tile_number` and `x` and `y` // are pixel offsets inside the tile): // `tttttttt tyyyxxx1` let chr_addr = (tile_number << 7) | (off_y << 4) | (off_x << 1) | 1; self.vram[chr_addr] }, }; let rgb = match palette_index { 0 => None, _ => Some(self.cgram.get_color(palette_index)), }; self.bg_cache.layers[0].scanline[x as usize] = CachedPixel { priority: 0, // Ignored anyways color: rgb, }; } } /// Render the current scanline of the given BG layer into its cache. /// /// We render starting at `self.x` (the pixel we actually need) until the end of the /// scanline. Note that this means that the `valid` flag is only relevant for the /// leftover part of the scanline, not the entire cached scanline. fn
(&mut self, bg_num: u8) { // Apply BG scrolling and get the tile coordinates // FIXME Apply mosaic filter // FIXME Fix this: "Note that many games will set their vertical scroll values to -1 rather // than 0. This is because the SNES loads OBJ data for each scanline during the previous // scanline. The very first line, though, wouldn’t have any OBJ data loaded! So the SNES // doesn’t actually output scanline 0, although it does everything to render it. These // games want the first line of their tilemap to be the first line output, so they set // their VOFS registers in this manner. Note that an interlace screen needs -2 rather than // -1 to properly correct for the missing line 0 (and an emulator would need to add 2 // instead of 1 to account for this)." // -> I guess we should just decrement the physical screen height by 1 if self.bg_mode() == 7 { self.render_mode7_scanline(); return; } let mut x = self.x; let y = self.scanline; let bg = self.bg_settings(bg_num); let tile_size = if bg.tile_size_16 { 16 } else { 8 }; let (hofs, vofs) = (bg.hofs, bg.vofs); let (sx, sy) = (!bg.tilemap_mirror_h,!bg.tilemap_mirror_v); let color_bits = self.color_bits_for_bg(bg_num); if color_bits == 8 { // can use direct color mode debug_assert!(self.cgwsel & 0x01 == 0, "NYI: direct color mode"); } let mut tile_x = x.wrapping_add(hofs) / tile_size as u16; let tile_y = y.wrapping_add(vofs) / tile_size as u16; let mut off_x = (x.wrapping_add(hofs) % tile_size as u16) as u8; let off_y = (y.wrapping_add(vofs) % tile_size as u16) as u8; while x < super::SCREEN_WIDTH as u16 { // Render current tile (`tile_x`) starting at `off_x` until the end of the tile, // then go to next tile and set `off_x = 0` // Calculate the VRAM word address, where the tilemap entry for our tile is stored let tilemap_entry_word_address = bg.tilemap_word_addr | ((tile_y & 0x1f) << 5) | (tile_x & 0x1f) | if sy {(tile_y & 0x20) << if sx {6} else {5}} else {0} | if sx {(tile_x & 0x20) << 5} else {0}; let tilemap_entry = self.tilemap_entry(tilemap_entry_word_address); let bitplane_start_addr = (bg.chr_addr << 1) + (tilemap_entry.tile_number * 8 * color_bits as u16); // 8 bytes per bitplane let palette_base = self.palette_base_for_bg_tile(bg_num, tilemap_entry.palette); while off_x < tile_size && x < super::SCREEN_WIDTH as u16 { let palette_index = self.read_chr_entry(color_bits, bitplane_start_addr, tile_size, (off_x, off_y), (tilemap_entry.vflip, tilemap_entry.hflip)); let rgb = match palette_index { 0 => None, _ => Some(self.cgram.get_color(palette_base + palette_index)), }; self.bg_cache.layers[bg_num as usize - 1].scanline[x as usize] = CachedPixel { priority: tilemap_entry.priority, color: rgb, }; x += 1; off_x += 1; } tile_x += 1; off_x = 0; } } /// Main entry point into the BG layer renderer. /// /// Lookup the color of the given background layer (1-4) at the current pixel, using the given /// priority (0-1) only. This will also scroll backgrounds accordingly. /// /// This may only be called with BG layer numbers which are actually valid in the current BG /// mode (the renderer code makes sure that this is the case). /// /// Returns `None` if the pixel is transparent, `Some(SnesRgb)` otherwise. pub fn lookup_bg_color(&mut self, bg_num: u8, prio: u8, subscreen: bool) -> Option<SnesRgb> { debug_assert!(bg_num >= 1 && bg_num <= 4); debug_assert!(prio == 0 || prio == 1); if!self.bg_enabled(bg_num, subscreen) { return None; } if self.x == 0 { // Before we draw the first pixel, make sure that we invalidate the cache so it is // rebuilt first. self.bg_cache.invalidate_all(); } if!self.bg_cache.layers[bg_num as usize - 1].valid { // Call actual render code to render the scanline into the cache self.render_bg_scanline(bg_num); self.bg_cache.layers[bg_num as usize - 1].valid = true; } // Cache must be valid now, so we can access the pixel we need: let pixel = &self.bg_cache.layers
render_bg_scanline
identifier_name
bg.rs
line of all background layers. The cache is created lazily /// (when BG layer pixels are looked up), so we will not waste time caching a disabled BG layer. #[derive(Default)] pub struct BgCache { layers: [BgLayerCache; 4], } /// Data that's stored in the BG layer caches for a single pixel #[derive(Copy, Clone, Default)] struct CachedPixel { // These are just copied from `TilemapEntry`. /// Tile priority bit (0-1) priority: u8, /// Precalculated color of the pixel (15-bit RGB). `None` = transparent. color: Option<SnesRgb>, } /// BG cache for a single layer struct BgLayerCache { /// Whether this cache contains valid data. If `false`, the cache will be refreshed on next /// access. valid: bool, /// Stores the prerendered scanline scanline: [CachedPixel; super::SCREEN_WIDTH as usize], } impl Default for BgLayerCache { fn default() -> Self { BgLayerCache { valid: false, scanline: [CachedPixel::default(); super::SCREEN_WIDTH as usize], } } } impl BgLayerCache { /// Invalidates the cache of this layer, causing it to be rebuilt on next access. #[allow(dead_code)] // FIXME Use in the right locations fn invalidate(&mut self) { self.valid = false; } } impl BgCache { /// Invalidates the BG cache of all layers fn invalidate_all(&mut self) { self.layers[0].valid = false; self.layers[1].valid = false; self.layers[2].valid = false; self.layers[3].valid = false; } } /// Collected background settings struct BgSettings { /// Mosaic pixel size (1-16). 1 = Normal pixels. /// FIXME: I think there's a difference between disabled and enabled with 1x1 mosaic size in /// some modes (highres presumably) #[allow(dead_code)] // FIXME NYI mosaic: u8, /// Tilemap word address in VRAM /// "Starting at the tilemap address, the first $800 bytes are for tilemap A. Then come the /// $800 bytes for B, then C then D." tilemap_word_addr: u16, /// When `true`, this BGs tilemaps are repeated sideways tilemap_mirror_h: bool, /// When `true`, this BGs tilemaps are repeated downwards tilemap_mirror_v: bool, /// If `true`, BG tiles are 16x16 pixels. If `false`, they are 8x8 pixels. tile_size_16: bool, /// Character Data start address in VRAM chr_addr: u16, /// Horizontal scroll offset. Moves the BG layer to the left by some number of pixels. hofs: u16, /// Vertical scroll offset. Moves the BG layer up by some number of pixels. vofs: u16, } /// Unpacked tilemap entry for internal (rendering) use. /// /// A tilemap entry is 2 bytes large and contains informations about a single background layer tile. struct TilemapEntry { /// Flip this tile vertically (flips top and down of the tile) vflip: bool, /// Flip horizontally (flips left and right side) hflip: bool, /// Priority bit (0-1) priority: u8, /// Tile palette (0-7) palette: u8, /// Index into the character/tile data, where the actual tile character data is stored in /// bitplanes (10 bits) tile_number: u16, } impl Ppu { /// Determines whether the given BG layer (1-4) is enabled fn bg_enabled(&self, bg: u8, subscreen: bool) -> bool { let reg = if subscreen { self.ts } else { self.tm }; reg & (1 << (bg - 1))!= 0 } /// Reads the tilemap entry at the given VRAM word address. /// vhopppcc cccccccc (high, low) /// v/h = Vertical/Horizontal flip this tile. /// o = Tile priority. /// ppp = Tile palette base. /// cccccccccc = Tile number. fn tilemap_entry(&self, word_address: u16) -> TilemapEntry { let byte_address = word_address << 1; let lo = self.vram[byte_address]; let hi = self.vram[byte_address + 1]; TilemapEntry { vflip: hi & 0x80!= 0, hflip: hi & 0x40!= 0, priority: (hi & 0x20) >> 5, palette: (hi & 0x1c) >> 2, tile_number: ((hi as u16 & 0x03) << 8) | lo as u16, } } /// Collects properties of a background layer fn bg_settings(&self, bg: u8) -> BgSettings { // The BGxSC register for our background layer let bgsc = match bg { 1 => self.bg1sc, 2 => self.bg2sc, 3 => self.bg3sc, 4 => self.bg4sc, _ => unreachable!(), }; // Chr (Tileset, not Tilemap) start (word?) address >> 12 let chr = match bg { 1 => self.bg12nba & 0x0f, 2 => (self.bg12nba & 0xf0) >> 4, 3 => self.bg34nba & 0x0f, 4 => (self.bg34nba & 0xf0) >> 4, _ => unreachable!(), }; let (hofs, vofs) = match bg { 1 => (self.bg1hofs, self.bg1vofs), 2 => (self.bg2hofs, self.bg2vofs), 3 => (self.bg3hofs, self.bg3vofs), 4 => (self.bg4hofs, self.bg4vofs), _ => unreachable!(), }; BgSettings { mosaic: if self.mosaic & (1 << (bg-1)) == 0 { 1 } else { ((self.mosaic & 0xf0) >> 4) + 1 }, tilemap_word_addr: ((bgsc as u16 & 0xfc) >> 2) << 10, tilemap_mirror_h: bgsc & 0b01 == 0, // inverted bit value tilemap_mirror_v: bgsc & 0b10 == 0, // inverted bit value tile_size_16: match self.bg_mode() { // "If the BG character size for BG1/BG2/BG3/BG4 bit is set, then the BG is made of // 16x16 tiles. Otherwise, 8x8 tiles are used. However, note that Modes 5 and 6 // always use 16-pixel wide tiles, and Mode 7 always uses 8x8 tiles." 5 | 6 => true, 7 => false, _ => { // BGMODE: `4321----` (`-` = not relevant here) - Use 16x16 tiles? self.bgmode & (1 << (bg + 3))!= 0 } }, chr_addr: (chr as u16) << 12, hofs: hofs, vofs: vofs, } } /// Returns the number of color bits in the given BG layer in the current BG mode (2, 4, 7 or /// 8). To get the number of colors, use `1 << color_bits_for_bg`. /// /// Table of colors for BG layers (not what this function returns!). `X` denotes a BG for /// offset-per-tile data. /// ```text /// Mode # Colors for BG /// 1 2 3 4 /// ======---=---=---=---= /// 0 4 4 4 4 /// 1 16 16 4 - /// 2 16 16 X - /// 3 256 16 - - /// 4 256 4 X - /// 5 16 4 - - /// 6 16 - X - /// 7 256 - - - /// 7EXTBG 256 128 - - /// ``` fn color_bits_for_bg(&self, bg: u8) -> u8 { match (self.bg_mode(), bg) { (0, _) => 2, (1, 1) | (1, 2) => 4, (1, 3) => 2, (2, _) => 4, (3, 1) => 8, (3, 2) => 4, (4, 1) => 8, (4, 2) => 2, (5, 1) => 4, (5, 2) => 2, (6, _) => 4, (7, _) => panic!("unreachable: color_count_for_bg for mode 7"), _ => unreachable!(), } } /// Calculates the palette base index for a tile in the given background layer. `palette_num` /// is the palette number stored in the tilemap entry (the 3 `p` bits). fn palette_base_for_bg_tile(&self, bg: u8, palette_num: u8) -> u8 { debug_assert!(bg >= 1 && bg <= 4); match (self.bg_mode(), bg) { (0, _) => palette_num * 4 + (bg - 1) * 32, (1, _) | (5, _) => palette_num * (1 << self.color_bits_for_bg(bg) as u8), (2, _) => palette_num * 16,
(6, _) => palette_num * 16, // BG1 has 16 colors (7, _) => panic!("unreachable: palette_base_for_bg_tile for mode 7"), _ => unreachable!(), } } fn render_mode7_scanline(&mut self) { // TODO Figure out how to integrate EXTBG assert!(self.setini & 0x40 == 0, "NYI: Mode 7 EXTBG"); // FIXME consider changing the type of `Ppu.m7a,...` to `i16` let vflip = self.m7sel & 0x02!= 0; let hflip = self.m7sel & 0x01!= 0; // 0/1: Wrap // 2: Transparent // 3: Fill with tile 0 let screen_over = self.m7sel >> 6; let y = self.scanline; for x in self.x..super::SCREEN_WIDTH as u16 { // Code taken from http://problemkaputt.de/fullsnes.htm // FIXME: The above source also has a much faster way to render whole scanlines! let screen_x = x ^ if hflip { 0xff } else { 0x00 }; let screen_y = y ^ if vflip { 0xff } else { 0x00 }; let mut org_x = (self.m7hofs as i16 - self.m7x as i16) &!0x1c00; if org_x < 0 { org_x |= 0x1c00; } let mut org_y = (self.m7vofs as i16 - self.m7y as i16) &!0x1c00; if org_y < 0 { org_y |= 0x1c00; } let mut vram_x: i32 = ((self.m7a as i16 as i32 * org_x as i32) &!0x3f) + ((self.m7b as i16 as i32 * org_y as i32) &!0x3f) + self.m7x as i16 as i32 * 0x100; let mut vram_y: i32 = ((self.m7c as i16 as i32 * org_x as i32) &!0x3f) + ((self.m7d as i16 as i32 * org_y as i32) &!0x3f) + self.m7y as i16 as i32 * 0x100; vram_x += ((self.m7b as i16 as i32 * screen_y as i32) &!0x3f) + self.m7a as i16 as i32 * screen_x as i32; vram_y += ((self.m7d as i16 as i32 * screen_y as i32) &!0x3f) + self.m7c as i16 as i32 * screen_x as i32; let out_of_bounds = vram_x & (1 << 18)!= 0 || vram_y & (1 << 18)!= 0; let palette_index = match screen_over { 2 if out_of_bounds => { // transparent 0 }, _ => { let (tile_x, tile_y) = if screen_over == 3 && out_of_bounds { (0, 0) // 3 -> use tile 0 } else { let tile_x: u16 = ((vram_x as u32 >> 11) & 0x7f) as u16; let tile_y: u16 = ((vram_y as u32 >> 11) & 0x7f) as u16; (tile_x, tile_y) }; let off_x: u16 = (vram_x as u16 >> 8) & 0x07; let off_y: u16 = (vram_y as u16 >> 8) & 0x07; // Tilemap address for (7-bit) tile X/Y coordinates (BG1 is 128x128 tiles): // `0yyyyyyy xxxxxxx0` let tilemap_addr: u16 = (tile_y << 8) | (tile_x << 1); // The "tilemap" in mode 7 just consists of "tile numbers" (or pixel addresses) let tile_number = self.vram[tilemap_addr] as u16; // The CHR address is calculated like this (where `t` is `tile_number` and `x` and `y` // are pixel offsets inside the tile): // `tttttttt tyyyxxx1` let chr_addr = (tile_number << 7) | (off_y << 4) | (off_x << 1) | 1; self.vram[chr_addr] }, }; let rgb = match palette_index { 0 => None, _ => Some(self.cgram.get_color(palette_index)), }; self.bg_cache.layers[0].scanline[x as usize] = CachedPixel { priority: 0, // Ignored anyways color: rgb, }; } } /// Render the current scanline of the given BG layer into its cache. /// /// We render starting at `self.x` (the pixel we actually need) until the end of the /// scanline. Note that this means that the `valid` flag is only relevant for the /// leftover part of the scanline, not the entire cached scanline. fn render_bg_scanline(&mut self, bg_num: u8) { // Apply BG scrolling and get the tile coordinates // FIXME Apply mosaic filter // FIXME Fix this: "Note that many games will set their vertical scroll values to -1 rather // than 0. This is because the SNES loads OBJ data for each scanline during the previous // scanline. The very first line, though, wouldn’t have any OBJ data loaded! So the SNES // doesn’t actually output scanline 0, although it does everything to render it. These // games want the first line of their tilemap to be the first line output, so they set // their VOFS registers in this manner. Note that an interlace screen needs -2 rather than // -1 to properly correct for the missing line 0 (and an emulator would need to add 2 // instead of 1 to account for this)." // -> I guess we should just decrement the physical screen height by 1 if self.bg_mode() == 7 { self.render_mode7_scanline(); return; } let mut x = self.x; let y = self.scanline; let bg = self.bg_settings(bg_num); let tile_size = if bg.tile_size_16 { 16 } else { 8 }; let (hofs, vofs) = (bg.hofs, bg.vofs); let (sx, sy) = (!bg.tilemap_mirror_h,!bg.tilemap_mirror_v); let color_bits = self.color_bits_for_bg(bg_num); if color_bits == 8 { // can use direct color mode debug_assert!(self.cgwsel & 0x01 == 0, "NYI: direct color mode"); } let mut tile_x = x.wrapping_add(hofs) / tile_size as u16; let tile_y = y.wrapping_add(vofs) / tile_size as u16; let mut off_x = (x.wrapping_add(hofs) % tile_size as u16) as u8; let off_y = (y.wrapping_add(vofs) % tile_size as u16) as u8; while x < super::SCREEN_WIDTH as u16 { // Render current tile (`tile_x`) starting at `off_x` until the end of the tile, // then go to next tile and set `off_x = 0` // Calculate the VRAM word address, where the tilemap entry for our tile is stored let tilemap_entry_word_address = bg.tilemap_word_addr | ((tile_y & 0x1f) << 5) | (tile_x & 0x1f) | if sy {(tile_y & 0x20) << if sx {6} else {5}} else {0} | if sx {(tile_x & 0x20) << 5} else {0}; let tilemap_entry = self.tilemap_entry(tilemap_entry_word_address); let bitplane_start_addr = (bg.chr_addr << 1) + (tilemap_entry.tile_number * 8 * color_bits as u16); // 8 bytes per bitplane let palette_base = self.palette_base_for_bg_tile(bg_num, tilemap_entry.palette); while off_x < tile_size && x < super::SCREEN_WIDTH as u16 { let palette_index = self.read_chr_entry(color_bits, bitplane_start_addr, tile_size, (off_x, off_y), (tilemap_entry.vflip, tilemap_entry.hflip)); let rgb = match palette_index { 0 => None, _ => Some(self.cgram.get_color(palette_base + palette_index)), }; self.bg_cache.layers[bg_num as usize - 1].scanline[x as usize] = CachedPixel { priority: tilemap_entry.priority, color: rgb, }; x += 1; off_x += 1; } tile_x += 1; off_x = 0; } } /// Main entry point into the BG layer renderer. /// /// Lookup the color of the given background layer (1-4) at the current pixel, using the given /// priority (0-1) only. This will also scroll backgrounds accordingly. /// /// This may only be called with BG layer numbers which are actually valid in the current BG /// mode (the renderer code makes sure that this is the case). /// /// Returns `None` if the pixel is transparent, `Some(SnesRgb)` otherwise. pub fn lookup_bg_color(&mut self, bg_num: u8, prio: u8, subscreen: bool) -> Option<SnesRgb> { debug_assert!(bg_num >= 1 && bg_num <= 4); debug_assert!(prio == 0 || prio == 1); if!self.bg_enabled(bg_num, subscreen) { return None; } if self.x == 0 { // Before we draw the first pixel, make sure that we invalidate the cache so it is // rebuilt first. self.bg_cache.invalidate_all(); } if!self.bg_cache.layers[bg_num as usize - 1].valid { // Call actual render code to render the scanline into the cache self.render_bg_scanline(bg_num); self.bg_cache.layers[bg_num as usize - 1].valid = true; } // Cache must be valid now, so we can access the pixel we need: let pixel = &self.bg_cache.layers[bg
(3, 1) => 0, (3, 2) => palette_num * 16, (4, 1) => 0, (4, 2) => palette_num * 4,
random_line_split
9linkedlist.rs
use List::*; enum List { Cons(u32, Box<List>), Nil } impl List { fn new() -> List { Nil } fn prepend(self, val: u32) -> List { Cons(val, Box::new(self)) } fn len(&self) -> i32 { match *self { Cons(_, ref tail) => 1 + tail.len(), Nil => 0 } } fn stringify(&self) -> String { match *self { Cons(head, ref tail) => { format!("{}, {}", head, tail.stringify()) }, Nil => format!("Nil") } } } fn main()
{ let mut list = List::new(); list = list.prepend(4); list = list.prepend(3); list = list.prepend(2); list = list.prepend(1); println!("{}", list.stringify()); println!("Length: {}", list.len()); }
identifier_body
9linkedlist.rs
use List::*; enum
{ Cons(u32, Box<List>), Nil } impl List { fn new() -> List { Nil } fn prepend(self, val: u32) -> List { Cons(val, Box::new(self)) } fn len(&self) -> i32 { match *self { Cons(_, ref tail) => 1 + tail.len(), Nil => 0 } } fn stringify(&self) -> String { match *self { Cons(head, ref tail) => { format!("{}, {}", head, tail.stringify()) }, Nil => format!("Nil") } } } fn main() { let mut list = List::new(); list = list.prepend(4); list = list.prepend(3); list = list.prepend(2); list = list.prepend(1); println!("{}", list.stringify()); println!("Length: {}", list.len()); }
List
identifier_name
9linkedlist.rs
use List::*; enum List { Cons(u32, Box<List>), Nil } impl List { fn new() -> List { Nil } fn prepend(self, val: u32) -> List { Cons(val, Box::new(self)) } fn len(&self) -> i32 { match *self { Cons(_, ref tail) => 1 + tail.len(), Nil => 0 } } fn stringify(&self) -> String { match *self { Cons(head, ref tail) => { format!("{}, {}", head, tail.stringify()) }, Nil => format!("Nil") } } } fn main() { let mut list = List::new();
println!("{}", list.stringify()); println!("Length: {}", list.len()); }
list = list.prepend(4); list = list.prepend(3); list = list.prepend(2); list = list.prepend(1);
random_line_split
names.rs
use errors::{ParseError, make_error}; use nom::{IResult, ErrorKind}; use nom::IResult::*; use std::error; use std::fmt; use std::io; use std::io::Write; use std::str::FromStr; /// Representation of a domain name /// /// Domain names consist of one or more labels, broken up by the character '.'. /// /// ``` /// # use martin::Name; /// let name: Name = "test.example.com.".parse().unwrap(); /// assert_eq!("test", name.label()); /// assert_eq!("test.example.com.", name.to_string()); /// assert!(name!= "test2.example.com.".parse().unwrap()); /// ``` #[derive(Debug,Hash,PartialEq,PartialOrd,Eq,Ord,Clone)] pub struct Name { name: Vec<u8>, } impl Name { /// Returns the first label for this `Name` /// /// Labels in a domain name are broken up by the '.' character. A label is composed of the /// characters 'a'-'z', 'A'-'Z', and '-'. pub fn label(&self) -> &str { use std::str; let length: usize = self.name[0] as usize; str::from_utf8(&self.name[1..(length + 1)]).unwrap() } /// The parent is this `Name` without the left-most label pub fn parent(&self) -> Option<Name> { match self.name[0] { 0 => None, skip => { let index: usize = 1 + skip as usize; let p = self.name[index..].to_vec(); Some(Name { name: p }) } } } /// Determines whether this name represents the root name. pub fn is_root(&self) -> bool { self.name == vec![0] } } /// An error returned when parsing a domain name #[derive(Debug,PartialEq,Clone,Copy)] pub enum NameParseError { /// Name length cannot exceed 255 TotalLengthGreaterThan255(usize), /// Label length cannot exceed 63 LabelLengthGreaterThan63(usize), /// Valid characters are 'a-z', 'A-z', '0-9', and '-' InvalidCharacter(char), /// '-' cannot be the first character in a label HypenFirstCharacterInLabel, /// The last label of a name must be the root label '.' NameMustEndInRootLabel, /// An empty label is not allowed except for the root label EmptyNonRootLabel, } impl fmt::Display for NameParseError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use self::NameParseError::*; match *self { TotalLengthGreaterThan255(x) => { write!(fmt, "Name length must be less than 255, was {}", x) } LabelLengthGreaterThan63(x) => { write!(fmt, "Label length must be less than 63, was {}", x) } InvalidCharacter(x) => { write!(fmt, "Valid characters are a-z, A-Z, and '-'. Found: '\\x{:x}'", x as u32) } HypenFirstCharacterInLabel => { write!(fmt, "Hyphen ('-') cannot be the first character in a label") } NameMustEndInRootLabel => write!(fmt, "Names must end in the root label ('.')"), EmptyNonRootLabel => { write!(fmt, "The root label is only allowed at the end of names (found \"..\")") } } } } impl error::Error for NameParseError { fn description(&self) -> &str { use self::NameParseError::*; match *self { TotalLengthGreaterThan255(_) => "Name length must be less than 255", LabelLengthGreaterThan63(_) => "Label length must be less than 63", InvalidCharacter(_) => "Valid characters are a-z, A-Z, and '-'.", HypenFirstCharacterInLabel => "Hyphen ('-') cannot be the first character in a label", NameMustEndInRootLabel => "Names must end in the root label ('.')", EmptyNonRootLabel => "The root label is only allowed at the end of names", } } } impl FromStr for Name { type Err = NameParseError; fn from_str(s: &str) -> Result<Name, NameParseError> { use self::NameParseError::*; // Counting the `0` bit for the root label length, the str length must be < 254 if s.len() > 254 { return Err(TotalLengthGreaterThan255(s.len())); } if s == "." { return Ok(Name { name: vec![0] }); } let mut name: Vec<u8> = Vec::with_capacity(s.len() + 1); let mut last_label_index = 0; let mut label_len = 0; name.push(0); // First length byte for c in s.chars() { match c { '.' if label_len == 0 => return Err(EmptyNonRootLabel), '.' if label_len > 63 => return Err(LabelLengthGreaterThan63(label_len)), '.' => { name[last_label_index] = label_len as u8; last_label_index = name.len(); name.push(0); label_len = 0; } '-' if label_len == 0 => return Err(HypenFirstCharacterInLabel), 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' => { label_len += 1; name.push(c as u8); } c => return Err(InvalidCharacter(c)), } } if label_len!= 0 { return Err(NameMustEndInRootLabel); } Ok(Name { name: name }) } } impl fmt::Display for Name { fn
(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::str; let mut pos = 0; loop { match self.name[pos] { 0 => break, length => { let start = (pos + 1) as usize; let end = start + length as usize; let label = str::from_utf8(&self.name[start..end]).unwrap(); try!(write!(fmt, "{}.", label)); pos = end; } } } Ok(()) } } /// Parses a byte stream into a `Name` pub fn parse_name<'a>(i: &'a [u8], data: &'a [u8]) -> IResult<&'a [u8], Name, ParseError> { map!(i, apply!(do_parse_name, data, Vec::with_capacity(255)), |name_data: Vec<u8>| Name { name: name_data }) } fn do_parse_name<'a>(i: &'a [u8], data: &'a [u8], mut name: Vec<u8>) -> IResult<&'a [u8], Vec<u8>, ParseError> { use self::NameParseError::*; use nom::Needed; if i.len() < 1 { return Incomplete(Needed::Size(1)); } let length = i[0] as usize; let out = &i[1..]; match length { 0 => { name.push(0); if name.len() > 255 { Error(ErrorKind::Custom(ParseError::from(TotalLengthGreaterThan255(name.len())))) } else { Done(out, name) } } 1...63 => { name.push(length as u8); let newlength = name.len() + length + 1; if newlength > 255 { // Plus the ending '0' makes this > 255. return Error(make_error(TotalLengthGreaterThan255(newlength))); } if out.len() < length { return Incomplete(Needed::Size(length)); } for (index, c) in out[..length].iter().enumerate() { match *c as char { '-' if index == 0 => return Error(make_error(HypenFirstCharacterInLabel)), 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' => name.push(*c), c => return Error(make_error(InvalidCharacter(c))), } } do_parse_name(&out[length..], data, name) } // Offsets: 192...255 => { if i.len() < 2 { return Incomplete(Needed::Size(2)); } let offset = (((i[0] & 0b0011_1111) as usize) << 8) + i[1] as usize; if data.len() < offset { return Incomplete(Needed::Size(offset)); } let out = &i[2..]; match do_parse_name(&data[offset..], data, name) { Done(_, name) => Done(out, name), x => x, } } // Unknown: reserved bits. _ => Error(make_error(LabelLengthGreaterThan63(length))), } } pub fn write_name(name: &Name, writer: &mut Write) -> io::Result<()> { // TODO: Add name compression writer.write_all(&name.name) } #[cfg(test)] mod tests { use super::*; use nom::IResult::Done; #[test] fn parse_str_root_label() { let name = "".parse::<Name>().unwrap(); assert_eq!("", name.label()); assert_eq!("", name.to_string()); assert!(name.is_root()); assert_eq!(None, name.parent()); } #[test] fn parse_str_simple_label() { let name = "raspberry.".parse::<Name>().unwrap(); println!("{}, {:?}", name.to_string(), name); assert_eq!("raspberry", name.label()); assert_eq!("raspberry.", name.to_string()); assert!(!name.is_root()); assert!(name.parent().unwrap().is_root()); } #[test] fn parse_str_multi_label() { let name = "test.example.com.".parse::<Name>().unwrap(); assert_eq!("test", name.label()); assert_eq!("test.example.com.", name.to_string()); assert!(!name.is_root()); let parent = name.parent().unwrap(); assert!(!parent.is_root()); assert_eq!("example", parent.label()); assert_eq!("example.com.", parent.to_string()); let parent = parent.parent().unwrap(); assert!(!parent.is_root()); assert_eq!("com", parent.label()); assert_eq!("com.", parent.to_string()); assert!(parent.parent().unwrap().is_root()); } #[test] fn name_parse_bytes_test() { // Contained names: // 20: F.ISI.ARPA. // 22: ISI.ARPA. // 26: ARPA. // 40: FOO.F.ISI.ARPA. // 46: <root> let a = b"12345678901234567890\x01F\x03ISI\x04ARPA\x0012345678\x03FOO\xC0\x14\x00abcd"; assert_eq!(parse_name(&a[20..], &a[..]), Done(&a[32..], Name { name: b"\x01F\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[22..], &a[..]), Done(&a[32..], Name { name: b"\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[40..], &a[..]), Done(&a[46..], Name { name: b"\x03FOO\x01F\x03ISI\x04ARPA\x00".to_vec() })); // This one is fun: make sure that extra names aren't swallowed or parsed: assert_eq!(parse_name(&a[44..], &a[..]), Done(&b"\x00abcd"[..], Name { name: b"\x01F\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[46..], &a[..]), Done(&b"abcd"[..], Name { name: b"\x00".to_vec() })); } #[test] fn name_parse_errors() { use super::NameParseError::*; let name = { let mut s = String::from("test."); while s.len() < 255 { s += "test."; } s }; assert_eq!(name.parse::<Name>(), Err(TotalLengthGreaterThan255(name.len()))); let name = { let mut s = String::from("test"); while s.len() < 63 { s += "test"; } s += "."; s }; assert_eq!(name.parse::<Name>(), Err(LabelLengthGreaterThan63(name.len() - 1))); let name = "test!."; assert_eq!(name.parse::<Name>(), Err(InvalidCharacter('!'))); let name = "-test."; assert_eq!(name.parse::<Name>(), Err(HypenFirstCharacterInLabel)); let name = "te.st"; assert_eq!(name.parse::<Name>(), Err(NameMustEndInRootLabel)); let name = "test.."; assert_eq!(name.parse::<Name>(), Err(EmptyNonRootLabel)); } }
fmt
identifier_name
names.rs
use errors::{ParseError, make_error}; use nom::{IResult, ErrorKind}; use nom::IResult::*; use std::error; use std::fmt; use std::io; use std::io::Write; use std::str::FromStr; /// Representation of a domain name /// /// Domain names consist of one or more labels, broken up by the character '.'. /// /// ``` /// # use martin::Name; /// let name: Name = "test.example.com.".parse().unwrap(); /// assert_eq!("test", name.label()); /// assert_eq!("test.example.com.", name.to_string()); /// assert!(name!= "test2.example.com.".parse().unwrap()); /// ``` #[derive(Debug,Hash,PartialEq,PartialOrd,Eq,Ord,Clone)] pub struct Name { name: Vec<u8>, } impl Name { /// Returns the first label for this `Name` /// /// Labels in a domain name are broken up by the '.' character. A label is composed of the /// characters 'a'-'z', 'A'-'Z', and '-'. pub fn label(&self) -> &str { use std::str; let length: usize = self.name[0] as usize; str::from_utf8(&self.name[1..(length + 1)]).unwrap() } /// The parent is this `Name` without the left-most label pub fn parent(&self) -> Option<Name> { match self.name[0] { 0 => None, skip => { let index: usize = 1 + skip as usize; let p = self.name[index..].to_vec(); Some(Name { name: p }) } } } /// Determines whether this name represents the root name. pub fn is_root(&self) -> bool { self.name == vec![0] } } /// An error returned when parsing a domain name #[derive(Debug,PartialEq,Clone,Copy)] pub enum NameParseError { /// Name length cannot exceed 255 TotalLengthGreaterThan255(usize), /// Label length cannot exceed 63 LabelLengthGreaterThan63(usize), /// Valid characters are 'a-z', 'A-z', '0-9', and '-' InvalidCharacter(char), /// '-' cannot be the first character in a label HypenFirstCharacterInLabel, /// The last label of a name must be the root label '.' NameMustEndInRootLabel, /// An empty label is not allowed except for the root label EmptyNonRootLabel, } impl fmt::Display for NameParseError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use self::NameParseError::*; match *self { TotalLengthGreaterThan255(x) => { write!(fmt, "Name length must be less than 255, was {}", x) } LabelLengthGreaterThan63(x) => { write!(fmt, "Label length must be less than 63, was {}", x) } InvalidCharacter(x) => { write!(fmt, "Valid characters are a-z, A-Z, and '-'. Found: '\\x{:x}'", x as u32) } HypenFirstCharacterInLabel => { write!(fmt, "Hyphen ('-') cannot be the first character in a label") } NameMustEndInRootLabel => write!(fmt, "Names must end in the root label ('.')"), EmptyNonRootLabel => { write!(fmt, "The root label is only allowed at the end of names (found \"..\")") } } } } impl error::Error for NameParseError { fn description(&self) -> &str { use self::NameParseError::*; match *self { TotalLengthGreaterThan255(_) => "Name length must be less than 255", LabelLengthGreaterThan63(_) => "Label length must be less than 63", InvalidCharacter(_) => "Valid characters are a-z, A-Z, and '-'.", HypenFirstCharacterInLabel => "Hyphen ('-') cannot be the first character in a label", NameMustEndInRootLabel => "Names must end in the root label ('.')", EmptyNonRootLabel => "The root label is only allowed at the end of names", } } } impl FromStr for Name { type Err = NameParseError; fn from_str(s: &str) -> Result<Name, NameParseError> { use self::NameParseError::*; // Counting the `0` bit for the root label length, the str length must be < 254 if s.len() > 254 { return Err(TotalLengthGreaterThan255(s.len())); } if s == "." { return Ok(Name { name: vec![0] }); } let mut name: Vec<u8> = Vec::with_capacity(s.len() + 1); let mut last_label_index = 0; let mut label_len = 0; name.push(0); // First length byte for c in s.chars() { match c { '.' if label_len == 0 => return Err(EmptyNonRootLabel), '.' if label_len > 63 => return Err(LabelLengthGreaterThan63(label_len)), '.' => { name[last_label_index] = label_len as u8; last_label_index = name.len(); name.push(0); label_len = 0; } '-' if label_len == 0 => return Err(HypenFirstCharacterInLabel), 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' => { label_len += 1; name.push(c as u8); } c => return Err(InvalidCharacter(c)), } } if label_len!= 0 { return Err(NameMustEndInRootLabel); } Ok(Name { name: name }) } } impl fmt::Display for Name { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::str; let mut pos = 0; loop { match self.name[pos] { 0 => break, length => { let start = (pos + 1) as usize; let end = start + length as usize; let label = str::from_utf8(&self.name[start..end]).unwrap(); try!(write!(fmt, "{}.", label)); pos = end; } } } Ok(()) } } /// Parses a byte stream into a `Name` pub fn parse_name<'a>(i: &'a [u8], data: &'a [u8]) -> IResult<&'a [u8], Name, ParseError> { map!(i, apply!(do_parse_name, data, Vec::with_capacity(255)), |name_data: Vec<u8>| Name { name: name_data }) } fn do_parse_name<'a>(i: &'a [u8], data: &'a [u8], mut name: Vec<u8>) -> IResult<&'a [u8], Vec<u8>, ParseError> { use self::NameParseError::*; use nom::Needed; if i.len() < 1 { return Incomplete(Needed::Size(1)); } let length = i[0] as usize; let out = &i[1..]; match length { 0 => { name.push(0); if name.len() > 255
else { Done(out, name) } } 1...63 => { name.push(length as u8); let newlength = name.len() + length + 1; if newlength > 255 { // Plus the ending '0' makes this > 255. return Error(make_error(TotalLengthGreaterThan255(newlength))); } if out.len() < length { return Incomplete(Needed::Size(length)); } for (index, c) in out[..length].iter().enumerate() { match *c as char { '-' if index == 0 => return Error(make_error(HypenFirstCharacterInLabel)), 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' => name.push(*c), c => return Error(make_error(InvalidCharacter(c))), } } do_parse_name(&out[length..], data, name) } // Offsets: 192...255 => { if i.len() < 2 { return Incomplete(Needed::Size(2)); } let offset = (((i[0] & 0b0011_1111) as usize) << 8) + i[1] as usize; if data.len() < offset { return Incomplete(Needed::Size(offset)); } let out = &i[2..]; match do_parse_name(&data[offset..], data, name) { Done(_, name) => Done(out, name), x => x, } } // Unknown: reserved bits. _ => Error(make_error(LabelLengthGreaterThan63(length))), } } pub fn write_name(name: &Name, writer: &mut Write) -> io::Result<()> { // TODO: Add name compression writer.write_all(&name.name) } #[cfg(test)] mod tests { use super::*; use nom::IResult::Done; #[test] fn parse_str_root_label() { let name = "".parse::<Name>().unwrap(); assert_eq!("", name.label()); assert_eq!("", name.to_string()); assert!(name.is_root()); assert_eq!(None, name.parent()); } #[test] fn parse_str_simple_label() { let name = "raspberry.".parse::<Name>().unwrap(); println!("{}, {:?}", name.to_string(), name); assert_eq!("raspberry", name.label()); assert_eq!("raspberry.", name.to_string()); assert!(!name.is_root()); assert!(name.parent().unwrap().is_root()); } #[test] fn parse_str_multi_label() { let name = "test.example.com.".parse::<Name>().unwrap(); assert_eq!("test", name.label()); assert_eq!("test.example.com.", name.to_string()); assert!(!name.is_root()); let parent = name.parent().unwrap(); assert!(!parent.is_root()); assert_eq!("example", parent.label()); assert_eq!("example.com.", parent.to_string()); let parent = parent.parent().unwrap(); assert!(!parent.is_root()); assert_eq!("com", parent.label()); assert_eq!("com.", parent.to_string()); assert!(parent.parent().unwrap().is_root()); } #[test] fn name_parse_bytes_test() { // Contained names: // 20: F.ISI.ARPA. // 22: ISI.ARPA. // 26: ARPA. // 40: FOO.F.ISI.ARPA. // 46: <root> let a = b"12345678901234567890\x01F\x03ISI\x04ARPA\x0012345678\x03FOO\xC0\x14\x00abcd"; assert_eq!(parse_name(&a[20..], &a[..]), Done(&a[32..], Name { name: b"\x01F\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[22..], &a[..]), Done(&a[32..], Name { name: b"\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[40..], &a[..]), Done(&a[46..], Name { name: b"\x03FOO\x01F\x03ISI\x04ARPA\x00".to_vec() })); // This one is fun: make sure that extra names aren't swallowed or parsed: assert_eq!(parse_name(&a[44..], &a[..]), Done(&b"\x00abcd"[..], Name { name: b"\x01F\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[46..], &a[..]), Done(&b"abcd"[..], Name { name: b"\x00".to_vec() })); } #[test] fn name_parse_errors() { use super::NameParseError::*; let name = { let mut s = String::from("test."); while s.len() < 255 { s += "test."; } s }; assert_eq!(name.parse::<Name>(), Err(TotalLengthGreaterThan255(name.len()))); let name = { let mut s = String::from("test"); while s.len() < 63 { s += "test"; } s += "."; s }; assert_eq!(name.parse::<Name>(), Err(LabelLengthGreaterThan63(name.len() - 1))); let name = "test!."; assert_eq!(name.parse::<Name>(), Err(InvalidCharacter('!'))); let name = "-test."; assert_eq!(name.parse::<Name>(), Err(HypenFirstCharacterInLabel)); let name = "te.st"; assert_eq!(name.parse::<Name>(), Err(NameMustEndInRootLabel)); let name = "test.."; assert_eq!(name.parse::<Name>(), Err(EmptyNonRootLabel)); } }
{ Error(ErrorKind::Custom(ParseError::from(TotalLengthGreaterThan255(name.len())))) }
conditional_block
names.rs
use errors::{ParseError, make_error}; use nom::{IResult, ErrorKind}; use nom::IResult::*; use std::error; use std::fmt; use std::io; use std::io::Write; use std::str::FromStr; /// Representation of a domain name /// /// Domain names consist of one or more labels, broken up by the character '.'. /// /// ``` /// # use martin::Name; /// let name: Name = "test.example.com.".parse().unwrap(); /// assert_eq!("test", name.label()); /// assert_eq!("test.example.com.", name.to_string()); /// assert!(name!= "test2.example.com.".parse().unwrap()); /// ``` #[derive(Debug,Hash,PartialEq,PartialOrd,Eq,Ord,Clone)] pub struct Name { name: Vec<u8>, } impl Name { /// Returns the first label for this `Name` /// /// Labels in a domain name are broken up by the '.' character. A label is composed of the /// characters 'a'-'z', 'A'-'Z', and '-'. pub fn label(&self) -> &str { use std::str; let length: usize = self.name[0] as usize; str::from_utf8(&self.name[1..(length + 1)]).unwrap() } /// The parent is this `Name` without the left-most label pub fn parent(&self) -> Option<Name> { match self.name[0] { 0 => None, skip => { let index: usize = 1 + skip as usize; let p = self.name[index..].to_vec(); Some(Name { name: p }) } } } /// Determines whether this name represents the root name. pub fn is_root(&self) -> bool { self.name == vec![0] } } /// An error returned when parsing a domain name #[derive(Debug,PartialEq,Clone,Copy)] pub enum NameParseError { /// Name length cannot exceed 255 TotalLengthGreaterThan255(usize), /// Label length cannot exceed 63 LabelLengthGreaterThan63(usize), /// Valid characters are 'a-z', 'A-z', '0-9', and '-' InvalidCharacter(char), /// '-' cannot be the first character in a label HypenFirstCharacterInLabel, /// The last label of a name must be the root label '.' NameMustEndInRootLabel, /// An empty label is not allowed except for the root label EmptyNonRootLabel, } impl fmt::Display for NameParseError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use self::NameParseError::*; match *self { TotalLengthGreaterThan255(x) => { write!(fmt, "Name length must be less than 255, was {}", x) } LabelLengthGreaterThan63(x) => { write!(fmt, "Label length must be less than 63, was {}", x) } InvalidCharacter(x) => { write!(fmt, "Valid characters are a-z, A-Z, and '-'. Found: '\\x{:x}'", x as u32) } HypenFirstCharacterInLabel => { write!(fmt, "Hyphen ('-') cannot be the first character in a label") } NameMustEndInRootLabel => write!(fmt, "Names must end in the root label ('.')"), EmptyNonRootLabel => { write!(fmt, "The root label is only allowed at the end of names (found \"..\")") } } } } impl error::Error for NameParseError { fn description(&self) -> &str { use self::NameParseError::*; match *self { TotalLengthGreaterThan255(_) => "Name length must be less than 255", LabelLengthGreaterThan63(_) => "Label length must be less than 63", InvalidCharacter(_) => "Valid characters are a-z, A-Z, and '-'.", HypenFirstCharacterInLabel => "Hyphen ('-') cannot be the first character in a label", NameMustEndInRootLabel => "Names must end in the root label ('.')", EmptyNonRootLabel => "The root label is only allowed at the end of names", } } } impl FromStr for Name { type Err = NameParseError; fn from_str(s: &str) -> Result<Name, NameParseError> { use self::NameParseError::*; // Counting the `0` bit for the root label length, the str length must be < 254 if s.len() > 254 { return Err(TotalLengthGreaterThan255(s.len())); } if s == "." { return Ok(Name { name: vec![0] }); } let mut name: Vec<u8> = Vec::with_capacity(s.len() + 1); let mut last_label_index = 0; let mut label_len = 0; name.push(0); // First length byte for c in s.chars() { match c { '.' if label_len == 0 => return Err(EmptyNonRootLabel), '.' if label_len > 63 => return Err(LabelLengthGreaterThan63(label_len)), '.' => { name[last_label_index] = label_len as u8; last_label_index = name.len(); name.push(0); label_len = 0; } '-' if label_len == 0 => return Err(HypenFirstCharacterInLabel), 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' => { label_len += 1; name.push(c as u8); } c => return Err(InvalidCharacter(c)), } } if label_len!= 0 { return Err(NameMustEndInRootLabel); } Ok(Name { name: name }) } } impl fmt::Display for Name { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::str; let mut pos = 0; loop { match self.name[pos] { 0 => break, length => { let start = (pos + 1) as usize; let end = start + length as usize; let label = str::from_utf8(&self.name[start..end]).unwrap(); try!(write!(fmt, "{}.", label)); pos = end; } } } Ok(()) } } /// Parses a byte stream into a `Name` pub fn parse_name<'a>(i: &'a [u8], data: &'a [u8]) -> IResult<&'a [u8], Name, ParseError> { map!(i, apply!(do_parse_name, data, Vec::with_capacity(255)), |name_data: Vec<u8>| Name { name: name_data }) } fn do_parse_name<'a>(i: &'a [u8], data: &'a [u8], mut name: Vec<u8>) -> IResult<&'a [u8], Vec<u8>, ParseError> { use self::NameParseError::*; use nom::Needed; if i.len() < 1 { return Incomplete(Needed::Size(1)); } let length = i[0] as usize; let out = &i[1..]; match length { 0 => { name.push(0); if name.len() > 255 { Error(ErrorKind::Custom(ParseError::from(TotalLengthGreaterThan255(name.len())))) } else { Done(out, name) } } 1...63 => { name.push(length as u8); let newlength = name.len() + length + 1; if newlength > 255 { // Plus the ending '0' makes this > 255. return Error(make_error(TotalLengthGreaterThan255(newlength))); } if out.len() < length { return Incomplete(Needed::Size(length)); } for (index, c) in out[..length].iter().enumerate() { match *c as char { '-' if index == 0 => return Error(make_error(HypenFirstCharacterInLabel)), 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' => name.push(*c), c => return Error(make_error(InvalidCharacter(c))), } } do_parse_name(&out[length..], data, name) } // Offsets:
} let offset = (((i[0] & 0b0011_1111) as usize) << 8) + i[1] as usize; if data.len() < offset { return Incomplete(Needed::Size(offset)); } let out = &i[2..]; match do_parse_name(&data[offset..], data, name) { Done(_, name) => Done(out, name), x => x, } } // Unknown: reserved bits. _ => Error(make_error(LabelLengthGreaterThan63(length))), } } pub fn write_name(name: &Name, writer: &mut Write) -> io::Result<()> { // TODO: Add name compression writer.write_all(&name.name) } #[cfg(test)] mod tests { use super::*; use nom::IResult::Done; #[test] fn parse_str_root_label() { let name = "".parse::<Name>().unwrap(); assert_eq!("", name.label()); assert_eq!("", name.to_string()); assert!(name.is_root()); assert_eq!(None, name.parent()); } #[test] fn parse_str_simple_label() { let name = "raspberry.".parse::<Name>().unwrap(); println!("{}, {:?}", name.to_string(), name); assert_eq!("raspberry", name.label()); assert_eq!("raspberry.", name.to_string()); assert!(!name.is_root()); assert!(name.parent().unwrap().is_root()); } #[test] fn parse_str_multi_label() { let name = "test.example.com.".parse::<Name>().unwrap(); assert_eq!("test", name.label()); assert_eq!("test.example.com.", name.to_string()); assert!(!name.is_root()); let parent = name.parent().unwrap(); assert!(!parent.is_root()); assert_eq!("example", parent.label()); assert_eq!("example.com.", parent.to_string()); let parent = parent.parent().unwrap(); assert!(!parent.is_root()); assert_eq!("com", parent.label()); assert_eq!("com.", parent.to_string()); assert!(parent.parent().unwrap().is_root()); } #[test] fn name_parse_bytes_test() { // Contained names: // 20: F.ISI.ARPA. // 22: ISI.ARPA. // 26: ARPA. // 40: FOO.F.ISI.ARPA. // 46: <root> let a = b"12345678901234567890\x01F\x03ISI\x04ARPA\x0012345678\x03FOO\xC0\x14\x00abcd"; assert_eq!(parse_name(&a[20..], &a[..]), Done(&a[32..], Name { name: b"\x01F\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[22..], &a[..]), Done(&a[32..], Name { name: b"\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[40..], &a[..]), Done(&a[46..], Name { name: b"\x03FOO\x01F\x03ISI\x04ARPA\x00".to_vec() })); // This one is fun: make sure that extra names aren't swallowed or parsed: assert_eq!(parse_name(&a[44..], &a[..]), Done(&b"\x00abcd"[..], Name { name: b"\x01F\x03ISI\x04ARPA\x00".to_vec() })); assert_eq!(parse_name(&a[46..], &a[..]), Done(&b"abcd"[..], Name { name: b"\x00".to_vec() })); } #[test] fn name_parse_errors() { use super::NameParseError::*; let name = { let mut s = String::from("test."); while s.len() < 255 { s += "test."; } s }; assert_eq!(name.parse::<Name>(), Err(TotalLengthGreaterThan255(name.len()))); let name = { let mut s = String::from("test"); while s.len() < 63 { s += "test"; } s += "."; s }; assert_eq!(name.parse::<Name>(), Err(LabelLengthGreaterThan63(name.len() - 1))); let name = "test!."; assert_eq!(name.parse::<Name>(), Err(InvalidCharacter('!'))); let name = "-test."; assert_eq!(name.parse::<Name>(), Err(HypenFirstCharacterInLabel)); let name = "te.st"; assert_eq!(name.parse::<Name>(), Err(NameMustEndInRootLabel)); let name = "test.."; assert_eq!(name.parse::<Name>(), Err(EmptyNonRootLabel)); } }
192...255 => { if i.len() < 2 { return Incomplete(Needed::Size(2));
random_line_split
foreign-dupe.rs
// Copyright 2012-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. // calling pin_thread and that's having weird side-effects. // pretty-expanded FIXME #23616 #![feature(libc)] mod rustrt1 { extern crate libc; #[link(name = "rust_test_helpers")] extern { pub fn rust_get_test_int() -> libc::intptr_t; } } mod rustrt2 { extern crate libc; extern { pub fn rust_get_test_int() -> libc::intptr_t; } } pub fn main()
{ unsafe { rustrt1::rust_get_test_int(); rustrt2::rust_get_test_int(); } }
identifier_body
foreign-dupe.rs
// Copyright 2012-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. // calling pin_thread and that's having weird side-effects. // pretty-expanded FIXME #23616 #![feature(libc)] mod rustrt1 { extern crate libc; #[link(name = "rust_test_helpers")] extern { pub fn rust_get_test_int() -> libc::intptr_t; } } mod rustrt2 { extern crate libc; extern { pub fn rust_get_test_int() -> libc::intptr_t; } } pub fn main() { unsafe {
rustrt1::rust_get_test_int(); rustrt2::rust_get_test_int(); } }
random_line_split
foreign-dupe.rs
// Copyright 2012-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. // calling pin_thread and that's having weird side-effects. // pretty-expanded FIXME #23616 #![feature(libc)] mod rustrt1 { extern crate libc; #[link(name = "rust_test_helpers")] extern { pub fn rust_get_test_int() -> libc::intptr_t; } } mod rustrt2 { extern crate libc; extern { pub fn rust_get_test_int() -> libc::intptr_t; } } pub fn
() { unsafe { rustrt1::rust_get_test_int(); rustrt2::rust_get_test_int(); } }
main
identifier_name