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
mode.rs
use state::State; use std::marker::PhantomData; use typeahead::Parse; pub trait Transition<K> where K: Ord, K: Copy, K: Parse, { fn name(&self) -> &'static str; fn transition(&self, state: &mut State<K>) -> Mode<K>; } #[derive(Clone, Copy, Debug)] pub struct NormalMode<K> { t: PhantomData<K>, } /// Used by `PendingMode` to remember what mode to transition to next. #[derive(Clone, Copy, Debug)] pub enum NextMode { Normal, Insert, } #[derive(Clone, Copy, Debug)] pub struct PendingMode<K> { t: PhantomData<K>, pub next_mode: NextMode, // Mode to return to after motion or text object. } #[derive(Clone, Copy, Debug)] pub struct InsertMode<K> { t: PhantomData<K>, replace_mode: bool, } #[derive(Clone, Copy, Debug)] pub enum Mode<K> { Normal(NormalMode<K>), Pending(PendingMode<K>), Insert(InsertMode<K>), } pub fn normal<K>() -> Mode<K> { Mode::Normal(NormalMode::<K> { t: PhantomData::<K> {} }) } pub fn recast_normal<K>(orig: &NormalMode<K>) -> Mode<K> { Mode::Normal(NormalMode::<K> { t: PhantomData::<K> {} }) } pub fn pending<K>(next_mode: NextMode) -> Mode<K> { Mode::Pending(PendingMode::<K> { t: PhantomData::<K> {}, next_mode: next_mode, }) } pub fn recast_pending<K>(orig: &PendingMode<K>) -> Mode<K>
pub fn insert<K>() -> Mode<K> { Mode::Insert(InsertMode::<K> { t: PhantomData::<K> {}, replace_mode: false, }) } pub fn replace<K>() -> Mode<K> { Mode::Insert(InsertMode::<K> { t: PhantomData::<K> {}, replace_mode: true, }) } impl<K> Transition<K> for Mode<K> where K: Ord, K: Copy, K: Parse, { fn name(&self) -> &'static str { match *self { Mode::Normal(x) => x.name(), Mode::Pending(x) => x.name(), Mode::Insert(x) => x.name(), } } fn transition(&self, state: &mut State<K>) -> Mode<K> { match *self { Mode::Normal(x) => x.transition(state), Mode::Pending(x) => x.transition(state), Mode::Insert(x) => x.transition(state), } } }
{ Mode::Pending(PendingMode::<K> { t: PhantomData::<K> {}, next_mode: orig.next_mode, }) }
identifier_body
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum WserverFailure { NoServerFound, RequestError(hyper::Error) } impl From<hyper::Error> for WserverFailure { fn from(err: hyper::Error) -> WserverFailure { WserverFailure::RequestError(err) } } fn get_wserver_result(urlstr: &str) -> Result<String, WserverFailure> { let mut url = urlstr.to_string(); if!urlstr.starts_with("http") { url = format!("http://{}", urlstr); } let client = hyper::Client::new(); let resp = try!(client.head(&url).send()); match resp.headers.get::<Server>() { Some(&Server(ref server)) => Ok(server.clone()), None => Err(WserverFailure::NoServerFound) } } fn format_wserver_response(resp: String) -> String { format!("running: {}", resp) } struct WserverInternalState; impl WserverInternalState { fn new() -> WserverInternalState { WserverInternalState } fn handle_wserver(&mut self, m: &CommandMapperDispatch) { let host = match m.command().get::<String>("host") { Some(host) => host, None => return }; match get_wserver_result(&host) { Ok(res) => { m.reply(&format_wserver_response(res)); } Err(err) =>
} } fn start(&mut self, rx: Receiver<CommandMapperDispatch>) { for m in rx.iter() { match m.command().token { CMD_WSERVER => self.handle_wserver(&m), _ => () } } } } pub struct WserverPlugin { sender: Option<SyncSender<CommandMapperDispatch>> } impl WserverPlugin { pub fn new() -> WserverPlugin { WserverPlugin { sender: None } } pub fn get_plugin_name() -> &'static str { "wserver" } } impl RustBotPlugin for WserverPlugin { fn configure(&mut self, configurator: &mut IrcBotConfigurator) { configurator.map_format(CMD_WSERVER, Format::from_str("wserver {host:s}").unwrap()); } fn start(&mut self) { let (tx, rx) = sync_channel(10); let _ = ::std::thread::Builder::new().name("plugin-wserver".to_string()).spawn(move || { let mut internal_state = WserverInternalState::new(); internal_state.start(rx); }); self.sender = Some(tx); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, _message: &IrcMsg) { match self.sender { Some(ref sender) => { if let Err(err) = sender.send(m.clone()) { m.reply(&format!("Service ``wserver'' unavailable: {:?}", err)); } } None => () } } }
{ m.reply(&format!("Error: {:?}", err)); }
conditional_block
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum WserverFailure { NoServerFound, RequestError(hyper::Error) } impl From<hyper::Error> for WserverFailure { fn from(err: hyper::Error) -> WserverFailure { WserverFailure::RequestError(err) } } fn get_wserver_result(urlstr: &str) -> Result<String, WserverFailure> { let mut url = urlstr.to_string(); if!urlstr.starts_with("http") { url = format!("http://{}", urlstr); } let client = hyper::Client::new(); let resp = try!(client.head(&url).send()); match resp.headers.get::<Server>() { Some(&Server(ref server)) => Ok(server.clone()), None => Err(WserverFailure::NoServerFound) } } fn format_wserver_response(resp: String) -> String { format!("running: {}", resp) } struct WserverInternalState; impl WserverInternalState { fn new() -> WserverInternalState { WserverInternalState } fn handle_wserver(&mut self, m: &CommandMapperDispatch) { let host = match m.command().get::<String>("host") { Some(host) => host, None => return }; match get_wserver_result(&host) { Ok(res) => { m.reply(&format_wserver_response(res)); } Err(err) => { m.reply(&format!("Error: {:?}", err)); } } } fn start(&mut self, rx: Receiver<CommandMapperDispatch>) { for m in rx.iter() { match m.command().token { CMD_WSERVER => self.handle_wserver(&m), _ => () } } } } pub struct WserverPlugin { sender: Option<SyncSender<CommandMapperDispatch>> } impl WserverPlugin { pub fn new() -> WserverPlugin { WserverPlugin { sender: None } } pub fn get_plugin_name() -> &'static str { "wserver" } } impl RustBotPlugin for WserverPlugin { fn configure(&mut self, configurator: &mut IrcBotConfigurator) { configurator.map_format(CMD_WSERVER, Format::from_str("wserver {host:s}").unwrap()); } fn
(&mut self) { let (tx, rx) = sync_channel(10); let _ = ::std::thread::Builder::new().name("plugin-wserver".to_string()).spawn(move || { let mut internal_state = WserverInternalState::new(); internal_state.start(rx); }); self.sender = Some(tx); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, _message: &IrcMsg) { match self.sender { Some(ref sender) => { if let Err(err) = sender.send(m.clone()) { m.reply(&format!("Service ``wserver'' unavailable: {:?}", err)); } } None => () } } }
start
identifier_name
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum WserverFailure { NoServerFound, RequestError(hyper::Error) } impl From<hyper::Error> for WserverFailure { fn from(err: hyper::Error) -> WserverFailure { WserverFailure::RequestError(err) } } fn get_wserver_result(urlstr: &str) -> Result<String, WserverFailure> { let mut url = urlstr.to_string(); if!urlstr.starts_with("http") { url = format!("http://{}", urlstr); } let client = hyper::Client::new(); let resp = try!(client.head(&url).send()); match resp.headers.get::<Server>() { Some(&Server(ref server)) => Ok(server.clone()), None => Err(WserverFailure::NoServerFound) } } fn format_wserver_response(resp: String) -> String { format!("running: {}", resp) } struct WserverInternalState; impl WserverInternalState { fn new() -> WserverInternalState { WserverInternalState } fn handle_wserver(&mut self, m: &CommandMapperDispatch) { let host = match m.command().get::<String>("host") { Some(host) => host, None => return }; match get_wserver_result(&host) { Ok(res) => { m.reply(&format_wserver_response(res)); } Err(err) => { m.reply(&format!("Error: {:?}", err)); } } } fn start(&mut self, rx: Receiver<CommandMapperDispatch>) { for m in rx.iter() { match m.command().token { CMD_WSERVER => self.handle_wserver(&m), _ => () } } } } pub struct WserverPlugin { sender: Option<SyncSender<CommandMapperDispatch>> } impl WserverPlugin { pub fn new() -> WserverPlugin { WserverPlugin { sender: None } } pub fn get_plugin_name() -> &'static str { "wserver" } } impl RustBotPlugin for WserverPlugin { fn configure(&mut self, configurator: &mut IrcBotConfigurator) { configurator.map_format(CMD_WSERVER, Format::from_str("wserver {host:s}").unwrap()); } fn start(&mut self) { let (tx, rx) = sync_channel(10); let _ = ::std::thread::Builder::new().name("plugin-wserver".to_string()).spawn(move || { let mut internal_state = WserverInternalState::new(); internal_state.start(rx); }); self.sender = Some(tx); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, _message: &IrcMsg)
}
{ match self.sender { Some(ref sender) => { if let Err(err) = sender.send(m.clone()) { m.reply(&format!("Service ``wserver'' unavailable: {:?}", err)); } } None => () } }
identifier_body
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum WserverFailure { NoServerFound, RequestError(hyper::Error) } impl From<hyper::Error> for WserverFailure { fn from(err: hyper::Error) -> WserverFailure { WserverFailure::RequestError(err) } } fn get_wserver_result(urlstr: &str) -> Result<String, WserverFailure> { let mut url = urlstr.to_string(); if!urlstr.starts_with("http") { url = format!("http://{}", urlstr); } let client = hyper::Client::new(); let resp = try!(client.head(&url).send()); match resp.headers.get::<Server>() { Some(&Server(ref server)) => Ok(server.clone()), None => Err(WserverFailure::NoServerFound) } } fn format_wserver_response(resp: String) -> String { format!("running: {}", resp) } struct WserverInternalState; impl WserverInternalState { fn new() -> WserverInternalState { WserverInternalState } fn handle_wserver(&mut self, m: &CommandMapperDispatch) { let host = match m.command().get::<String>("host") { Some(host) => host, None => return }; match get_wserver_result(&host) { Ok(res) => { m.reply(&format_wserver_response(res)); } Err(err) => { m.reply(&format!("Error: {:?}", err)); } } } fn start(&mut self, rx: Receiver<CommandMapperDispatch>) { for m in rx.iter() { match m.command().token { CMD_WSERVER => self.handle_wserver(&m), _ => () } } } } pub struct WserverPlugin { sender: Option<SyncSender<CommandMapperDispatch>> } impl WserverPlugin { pub fn new() -> WserverPlugin { WserverPlugin {
} pub fn get_plugin_name() -> &'static str { "wserver" } } impl RustBotPlugin for WserverPlugin { fn configure(&mut self, configurator: &mut IrcBotConfigurator) { configurator.map_format(CMD_WSERVER, Format::from_str("wserver {host:s}").unwrap()); } fn start(&mut self) { let (tx, rx) = sync_channel(10); let _ = ::std::thread::Builder::new().name("plugin-wserver".to_string()).spawn(move || { let mut internal_state = WserverInternalState::new(); internal_state.start(rx); }); self.sender = Some(tx); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, _message: &IrcMsg) { match self.sender { Some(ref sender) => { if let Err(err) = sender.send(m.clone()) { m.reply(&format!("Service ``wserver'' unavailable: {:?}", err)); } } None => () } } }
sender: None }
random_line_split
material.rs
use std::io::{Cursor, Read}; use anyhow::Error; use image::{self, GenericImage, GenericImageView}; use zip::ZipArchive; use cache::{AssetLoadContext, GeneratedAsset, WebAsset}; use srgb::{LINEAR_TO_SRGB, SRGB_TO_LINEAR}; #[derive(Clone, Copy)] pub enum MaterialType { Dirt = 0, Grass = 1, GrassRocky = 2, Rock = 3, RockSteep = 4,
struct MaterialTypeRaw(MaterialType); impl WebAsset for MaterialTypeRaw { type Type = MaterialRaw; fn url(&self) -> String { match self.0 { _ => "https://opengameart.org/sites/default/files/terrain_0.zip", }.to_owned() } fn filename(&self) -> String { let name = match self.0 { _ => "terrain.zip", }; format!("materials/raw/{}", name) } fn parse(&self, _context: &mut AssetLoadContext, data: Vec<u8>) -> Result<Self::Type, Error> { let name = match self.0 { MaterialType::Dirt => "ground_mud2_d.jpg", MaterialType::Grass => "grass_green_d.jpg", MaterialType::GrassRocky => "grass_rocky_d.jpg", MaterialType::Rock => "mntn_gray_d.jpg", MaterialType::RockSteep => "mntn_gray_d.jpg", }; let mut raw = MaterialRaw::default(); let mut zip = ZipArchive::new(Cursor::new(data))?; for i in 0..zip.len() { let mut file = zip.by_index(i)?; if file.name().contains(name) { raw.albedo.clear(); file.read_to_end(&mut raw.albedo)?; return Ok(raw); } } Err(format_err!("Material file not found {}", name)) } } struct MaterialTypeFiltered(MaterialType); impl GeneratedAsset for MaterialTypeFiltered { type Type = Material; fn filename(&self) -> String { let name = match self.0 { MaterialType::Dirt => "dirt.bin", MaterialType::Grass => "grass.bin", MaterialType::GrassRocky => "grassrocky.bin", MaterialType::Rock => "rock.bin", MaterialType::RockSteep => "rocksteep.bin", }; format!("materials/filtered/{}", name) } fn generate(&self, context: &mut AssetLoadContext) -> Result<Self::Type, Error> { context.set_progress_and_total(0, 7); let resolution = 1024; let mipmaps = 11; let raw = MaterialTypeRaw(self.0).load(context)?; let mut albedo_image = image::DynamicImage::ImageRgba8(image::load_from_memory(&raw.albedo[..])?.to_rgba()); if albedo_image.width()!= resolution || albedo_image.height()!= resolution { albedo_image = albedo_image.resize_exact(resolution, resolution, image::FilterType::Triangle); } let albedo_image_blurred = { let sigma = 8; context.set_progress(1); let tiled = image::RgbaImage::from_fn( resolution + 4 * sigma, resolution + 4 * sigma, |x, y| { albedo_image.get_pixel( (x + resolution - 2 * sigma) % resolution, (y + resolution - 2 * sigma) % resolution, ) }, ); context.set_progress(2); let mut tiled = image::DynamicImage::ImageRgba8(tiled).blur(sigma as f32); context.set_progress(3); tiled.crop(2 * sigma, 2 * sigma, resolution, resolution) }; context.set_progress(4); let mut albedo_sum = [0u64; 4]; for (_, _, color) in albedo_image.pixels() { for i in 0..4 { albedo_sum[i] += color[i] as u64; } } let num_pixels = (albedo_image.width() * albedo_image.height()) as u64; let average_albedo: [u8; 4] = [ (albedo_sum[0] / num_pixels) as u8, (albedo_sum[1] / num_pixels) as u8, (albedo_sum[2] / num_pixels) as u8, (albedo_sum[3] / num_pixels) as u8, ]; context.set_progress(5); for (x, y, blurred_color) in albedo_image_blurred.pixels() { let mut color = albedo_image.get_pixel(x, y); for i in 0..4 { use image::math::utils::clamp; color[i] = clamp( (color[i] as i16) - (blurred_color[i] as i16) + (average_albedo[i] as i16), 0, 255, ) as u8; } albedo_image.put_pixel(x, y, color); } context.set_progress(6); let mut albedo = Vec::new(); for level in 0..mipmaps { let level_resolution = (resolution >> level) as u32; if albedo_image.width()!= level_resolution || albedo_image.height()!= level_resolution { albedo_image = albedo_image.resize_exact( level_resolution, level_resolution, image::FilterType::Triangle, ); } albedo.push( albedo_image.to_rgba().to_vec()[..] .chunks(4) .map(|c| [c[0], c[1], c[2], c[3]]) .collect(), ); } context.set_progress(7); Ok(Material { resolution: resolution as u16, mipmaps, albedo, }) } } /// Holds the raw bytes of the image files for each map of a material. #[derive(Serialize, Deserialize, Default)] struct MaterialRaw { albedo: Vec<u8>, } #[derive(Serialize, Deserialize)] struct Material { resolution: u16, mipmaps: u8, albedo: Vec<Vec<[u8; 4]>>, } pub struct MaterialSet<R: gfx::Resources> { pub(crate) texture_view: gfx_core::handle::ShaderResourceView<R, [f32; 4]>, pub(crate) _texture: gfx_core::handle::Texture<R, gfx_core::format::R8_G8_B8_A8>, average_albedos: Vec<[u8; 4]>, } impl<R: gfx::Resources> MaterialSet<R> { pub(crate) fn load<F: gfx::Factory<R>, C: gfx_core::command::Buffer<R>>( factory: &mut F, encoder: &mut gfx::Encoder<R, C>, context: &mut AssetLoadContext, ) -> Result<Self, Error> { let resolution = 1024; let mipmaps = 11; let materials = vec![ MaterialTypeFiltered(MaterialType::Dirt).load(context)?, MaterialTypeFiltered(MaterialType::Grass).load(context)?, MaterialTypeFiltered(MaterialType::GrassRocky).load(context)?, MaterialTypeFiltered(MaterialType::Rock).load(context)?, MaterialTypeFiltered(MaterialType::RockSteep).load(context)?, ]; let mut average_albedos = Vec::new(); let texture = factory .create_texture::<R8_G8_B8_A8>( gfx::texture::Kind::D2Array( resolution, resolution, materials.len() as u16, gfx::texture::AaMode::Single, ), mipmaps, gfx::memory::Bind::SHADER_RESOURCE, gfx::memory::Usage::Dynamic, Some(ChannelType::Srgb), ).unwrap(); for (layer, material) in materials.iter().enumerate() { assert_eq!(mipmaps, material.mipmaps); assert_eq!(mipmaps as usize, material.albedo.len()); for (level, albedo) in material.albedo.iter().enumerate() { encoder .update_texture::<R8_G8_B8_A8, gfx::format::Srgba8>( &texture, None, gfx_core::texture::NewImageInfo { xoffset: 0, yoffset: 0, zoffset: layer as u16, width: resolution >> level, height: resolution >> level, depth: 1, format: (), mipmap: level as u8, }, &albedo[..], ).unwrap(); } average_albedos.push(material.albedo.last().unwrap()[0]); } // TODO: get rid of this hack. let s = |v: &mut u8, s: f32| *v = LINEAR_TO_SRGB[(SRGB_TO_LINEAR[*v] as f32 * s) as u8]; for i in 0..4 { s(&mut average_albedos[MaterialType::Rock as usize][i], 0.5); s( &mut average_albedos[MaterialType::RockSteep as usize][i], 0.4, ); } let texture_view = factory .view_texture_as_shader_resource::<gfx::format::Srgba8>( &texture, (0, mipmaps), Swizzle::new(), ).unwrap(); Ok(Self { texture_view, _texture: texture, average_albedos, }) } pub(crate) fn get_average_albedo(&self, material: MaterialType) -> [u8; 4] { self.average_albedos[material as usize].clone() } }
}
random_line_split
material.rs
use std::io::{Cursor, Read}; use anyhow::Error; use image::{self, GenericImage, GenericImageView}; use zip::ZipArchive; use cache::{AssetLoadContext, GeneratedAsset, WebAsset}; use srgb::{LINEAR_TO_SRGB, SRGB_TO_LINEAR}; #[derive(Clone, Copy)] pub enum MaterialType { Dirt = 0, Grass = 1, GrassRocky = 2, Rock = 3, RockSteep = 4, } struct MaterialTypeRaw(MaterialType); impl WebAsset for MaterialTypeRaw { type Type = MaterialRaw; fn
(&self) -> String { match self.0 { _ => "https://opengameart.org/sites/default/files/terrain_0.zip", }.to_owned() } fn filename(&self) -> String { let name = match self.0 { _ => "terrain.zip", }; format!("materials/raw/{}", name) } fn parse(&self, _context: &mut AssetLoadContext, data: Vec<u8>) -> Result<Self::Type, Error> { let name = match self.0 { MaterialType::Dirt => "ground_mud2_d.jpg", MaterialType::Grass => "grass_green_d.jpg", MaterialType::GrassRocky => "grass_rocky_d.jpg", MaterialType::Rock => "mntn_gray_d.jpg", MaterialType::RockSteep => "mntn_gray_d.jpg", }; let mut raw = MaterialRaw::default(); let mut zip = ZipArchive::new(Cursor::new(data))?; for i in 0..zip.len() { let mut file = zip.by_index(i)?; if file.name().contains(name) { raw.albedo.clear(); file.read_to_end(&mut raw.albedo)?; return Ok(raw); } } Err(format_err!("Material file not found {}", name)) } } struct MaterialTypeFiltered(MaterialType); impl GeneratedAsset for MaterialTypeFiltered { type Type = Material; fn filename(&self) -> String { let name = match self.0 { MaterialType::Dirt => "dirt.bin", MaterialType::Grass => "grass.bin", MaterialType::GrassRocky => "grassrocky.bin", MaterialType::Rock => "rock.bin", MaterialType::RockSteep => "rocksteep.bin", }; format!("materials/filtered/{}", name) } fn generate(&self, context: &mut AssetLoadContext) -> Result<Self::Type, Error> { context.set_progress_and_total(0, 7); let resolution = 1024; let mipmaps = 11; let raw = MaterialTypeRaw(self.0).load(context)?; let mut albedo_image = image::DynamicImage::ImageRgba8(image::load_from_memory(&raw.albedo[..])?.to_rgba()); if albedo_image.width()!= resolution || albedo_image.height()!= resolution { albedo_image = albedo_image.resize_exact(resolution, resolution, image::FilterType::Triangle); } let albedo_image_blurred = { let sigma = 8; context.set_progress(1); let tiled = image::RgbaImage::from_fn( resolution + 4 * sigma, resolution + 4 * sigma, |x, y| { albedo_image.get_pixel( (x + resolution - 2 * sigma) % resolution, (y + resolution - 2 * sigma) % resolution, ) }, ); context.set_progress(2); let mut tiled = image::DynamicImage::ImageRgba8(tiled).blur(sigma as f32); context.set_progress(3); tiled.crop(2 * sigma, 2 * sigma, resolution, resolution) }; context.set_progress(4); let mut albedo_sum = [0u64; 4]; for (_, _, color) in albedo_image.pixels() { for i in 0..4 { albedo_sum[i] += color[i] as u64; } } let num_pixels = (albedo_image.width() * albedo_image.height()) as u64; let average_albedo: [u8; 4] = [ (albedo_sum[0] / num_pixels) as u8, (albedo_sum[1] / num_pixels) as u8, (albedo_sum[2] / num_pixels) as u8, (albedo_sum[3] / num_pixels) as u8, ]; context.set_progress(5); for (x, y, blurred_color) in albedo_image_blurred.pixels() { let mut color = albedo_image.get_pixel(x, y); for i in 0..4 { use image::math::utils::clamp; color[i] = clamp( (color[i] as i16) - (blurred_color[i] as i16) + (average_albedo[i] as i16), 0, 255, ) as u8; } albedo_image.put_pixel(x, y, color); } context.set_progress(6); let mut albedo = Vec::new(); for level in 0..mipmaps { let level_resolution = (resolution >> level) as u32; if albedo_image.width()!= level_resolution || albedo_image.height()!= level_resolution { albedo_image = albedo_image.resize_exact( level_resolution, level_resolution, image::FilterType::Triangle, ); } albedo.push( albedo_image.to_rgba().to_vec()[..] .chunks(4) .map(|c| [c[0], c[1], c[2], c[3]]) .collect(), ); } context.set_progress(7); Ok(Material { resolution: resolution as u16, mipmaps, albedo, }) } } /// Holds the raw bytes of the image files for each map of a material. #[derive(Serialize, Deserialize, Default)] struct MaterialRaw { albedo: Vec<u8>, } #[derive(Serialize, Deserialize)] struct Material { resolution: u16, mipmaps: u8, albedo: Vec<Vec<[u8; 4]>>, } pub struct MaterialSet<R: gfx::Resources> { pub(crate) texture_view: gfx_core::handle::ShaderResourceView<R, [f32; 4]>, pub(crate) _texture: gfx_core::handle::Texture<R, gfx_core::format::R8_G8_B8_A8>, average_albedos: Vec<[u8; 4]>, } impl<R: gfx::Resources> MaterialSet<R> { pub(crate) fn load<F: gfx::Factory<R>, C: gfx_core::command::Buffer<R>>( factory: &mut F, encoder: &mut gfx::Encoder<R, C>, context: &mut AssetLoadContext, ) -> Result<Self, Error> { let resolution = 1024; let mipmaps = 11; let materials = vec![ MaterialTypeFiltered(MaterialType::Dirt).load(context)?, MaterialTypeFiltered(MaterialType::Grass).load(context)?, MaterialTypeFiltered(MaterialType::GrassRocky).load(context)?, MaterialTypeFiltered(MaterialType::Rock).load(context)?, MaterialTypeFiltered(MaterialType::RockSteep).load(context)?, ]; let mut average_albedos = Vec::new(); let texture = factory .create_texture::<R8_G8_B8_A8>( gfx::texture::Kind::D2Array( resolution, resolution, materials.len() as u16, gfx::texture::AaMode::Single, ), mipmaps, gfx::memory::Bind::SHADER_RESOURCE, gfx::memory::Usage::Dynamic, Some(ChannelType::Srgb), ).unwrap(); for (layer, material) in materials.iter().enumerate() { assert_eq!(mipmaps, material.mipmaps); assert_eq!(mipmaps as usize, material.albedo.len()); for (level, albedo) in material.albedo.iter().enumerate() { encoder .update_texture::<R8_G8_B8_A8, gfx::format::Srgba8>( &texture, None, gfx_core::texture::NewImageInfo { xoffset: 0, yoffset: 0, zoffset: layer as u16, width: resolution >> level, height: resolution >> level, depth: 1, format: (), mipmap: level as u8, }, &albedo[..], ).unwrap(); } average_albedos.push(material.albedo.last().unwrap()[0]); } // TODO: get rid of this hack. let s = |v: &mut u8, s: f32| *v = LINEAR_TO_SRGB[(SRGB_TO_LINEAR[*v] as f32 * s) as u8]; for i in 0..4 { s(&mut average_albedos[MaterialType::Rock as usize][i], 0.5); s( &mut average_albedos[MaterialType::RockSteep as usize][i], 0.4, ); } let texture_view = factory .view_texture_as_shader_resource::<gfx::format::Srgba8>( &texture, (0, mipmaps), Swizzle::new(), ).unwrap(); Ok(Self { texture_view, _texture: texture, average_albedos, }) } pub(crate) fn get_average_albedo(&self, material: MaterialType) -> [u8; 4] { self.average_albedos[material as usize].clone() } }
url
identifier_name
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a request-target derived from the /// > target URI. There are four distinct formats for the request-target, /// > depending on both the method being requested and whether the request /// > is to a proxy. /// > /// > ```notrust /// > request-target = origin-form /// > / absolute-form /// > / authority-form /// > / asterisk-form /// > ``` #[derive(Debug, PartialEq, Clone)] pub enum RequestUri { /// The most common request target, an absolute path and optional query. /// /// For example, the line `GET /where?q=now HTTP/1.1` would parse the URI /// as `AbsolutePath("/where?q=now".to_string())`. AbsolutePath(String), /// An absolute URI. Used in conjunction with proxies. /// /// > When making a request to a proxy, other than a CONNECT or server-wide /// > OPTIONS request (as detailed below), a client MUST send the target /// > URI in absolute-form as the request-target. /// /// An example StartLine with an `AbsoluteUri` would be /// `GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1`. AbsoluteUri(Url), /// The authority form is only for use with `CONNECT` requests. /// /// An example StartLine: `CONNECT www.example.com:80 HTTP/1.1`. Authority(String), /// The star is used to target the entire server, instead of a specific resource. /// /// This is only used for a server-wide `OPTIONS` request. Star, } impl FromStr for RequestUri { type Err = HttpError; fn
(s: &str) -> Result<RequestUri, HttpError> { match s.as_bytes() { [] => Err(HttpError::HttpUriError(UrlError::InvalidCharacter)), [b'*'] => Ok(RequestUri::Star), [b'/',..] => Ok(RequestUri::AbsolutePath(s.to_string())), bytes if bytes.contains(&b'/') => { Ok(RequestUri::AbsoluteUri(try!(Url::parse(s)))) } _ => { let mut temp = "http://".to_string(); temp.push_str(s); try!(Url::parse(&temp[..])); todo!("compare vs u.authority()"); Ok(RequestUri::Authority(s.to_string())) } } } } #[test] fn test_uri_fromstr() { use error::HttpResult; fn read(s: &str, result: HttpResult<RequestUri>) { assert_eq!(s.parse(), result); } read("*", Ok(RequestUri::Star)); read("http://hyper.rs/", Ok(RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()))); read("hyper.rs", Ok(RequestUri::Authority("hyper.rs".to_string()))); read("/", Ok(RequestUri::AbsolutePath("/".to_string()))); }
from_str
identifier_name
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a request-target derived from the
/// > /// > ```notrust /// > request-target = origin-form /// > / absolute-form /// > / authority-form /// > / asterisk-form /// > ``` #[derive(Debug, PartialEq, Clone)] pub enum RequestUri { /// The most common request target, an absolute path and optional query. /// /// For example, the line `GET /where?q=now HTTP/1.1` would parse the URI /// as `AbsolutePath("/where?q=now".to_string())`. AbsolutePath(String), /// An absolute URI. Used in conjunction with proxies. /// /// > When making a request to a proxy, other than a CONNECT or server-wide /// > OPTIONS request (as detailed below), a client MUST send the target /// > URI in absolute-form as the request-target. /// /// An example StartLine with an `AbsoluteUri` would be /// `GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1`. AbsoluteUri(Url), /// The authority form is only for use with `CONNECT` requests. /// /// An example StartLine: `CONNECT www.example.com:80 HTTP/1.1`. Authority(String), /// The star is used to target the entire server, instead of a specific resource. /// /// This is only used for a server-wide `OPTIONS` request. Star, } impl FromStr for RequestUri { type Err = HttpError; fn from_str(s: &str) -> Result<RequestUri, HttpError> { match s.as_bytes() { [] => Err(HttpError::HttpUriError(UrlError::InvalidCharacter)), [b'*'] => Ok(RequestUri::Star), [b'/',..] => Ok(RequestUri::AbsolutePath(s.to_string())), bytes if bytes.contains(&b'/') => { Ok(RequestUri::AbsoluteUri(try!(Url::parse(s)))) } _ => { let mut temp = "http://".to_string(); temp.push_str(s); try!(Url::parse(&temp[..])); todo!("compare vs u.authority()"); Ok(RequestUri::Authority(s.to_string())) } } } } #[test] fn test_uri_fromstr() { use error::HttpResult; fn read(s: &str, result: HttpResult<RequestUri>) { assert_eq!(s.parse(), result); } read("*", Ok(RequestUri::Star)); read("http://hyper.rs/", Ok(RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()))); read("hyper.rs", Ok(RequestUri::Authority("hyper.rs".to_string()))); read("/", Ok(RequestUri::AbsolutePath("/".to_string()))); }
/// > target URI. There are four distinct formats for the request-target, /// > depending on both the method being requested and whether the request /// > is to a proxy.
random_line_split
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a request-target derived from the /// > target URI. There are four distinct formats for the request-target, /// > depending on both the method being requested and whether the request /// > is to a proxy. /// > /// > ```notrust /// > request-target = origin-form /// > / absolute-form /// > / authority-form /// > / asterisk-form /// > ``` #[derive(Debug, PartialEq, Clone)] pub enum RequestUri { /// The most common request target, an absolute path and optional query. /// /// For example, the line `GET /where?q=now HTTP/1.1` would parse the URI /// as `AbsolutePath("/where?q=now".to_string())`. AbsolutePath(String), /// An absolute URI. Used in conjunction with proxies. /// /// > When making a request to a proxy, other than a CONNECT or server-wide /// > OPTIONS request (as detailed below), a client MUST send the target /// > URI in absolute-form as the request-target. /// /// An example StartLine with an `AbsoluteUri` would be /// `GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1`. AbsoluteUri(Url), /// The authority form is only for use with `CONNECT` requests. /// /// An example StartLine: `CONNECT www.example.com:80 HTTP/1.1`. Authority(String), /// The star is used to target the entire server, instead of a specific resource. /// /// This is only used for a server-wide `OPTIONS` request. Star, } impl FromStr for RequestUri { type Err = HttpError; fn from_str(s: &str) -> Result<RequestUri, HttpError> { match s.as_bytes() { [] => Err(HttpError::HttpUriError(UrlError::InvalidCharacter)), [b'*'] => Ok(RequestUri::Star), [b'/',..] => Ok(RequestUri::AbsolutePath(s.to_string())), bytes if bytes.contains(&b'/') => { Ok(RequestUri::AbsoluteUri(try!(Url::parse(s)))) } _ =>
} } } #[test] fn test_uri_fromstr() { use error::HttpResult; fn read(s: &str, result: HttpResult<RequestUri>) { assert_eq!(s.parse(), result); } read("*", Ok(RequestUri::Star)); read("http://hyper.rs/", Ok(RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()))); read("hyper.rs", Ok(RequestUri::Authority("hyper.rs".to_string()))); read("/", Ok(RequestUri::AbsolutePath("/".to_string()))); }
{ let mut temp = "http://".to_string(); temp.push_str(s); try!(Url::parse(&temp[..])); todo!("compare vs u.authority()"); Ok(RequestUri::Authority(s.to_string())) }
conditional_block
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct Ctxt { options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, options: Options) -> (Ident, Option<Code>) { let mut ctxt = Ctxt { options }; let ident = "".to_string(); let value = type_from_shape(&mut ctxt, name, shape); let code = ::serde_json::to_string_pretty(&value); (ident, code.ok()) } fn type_from_shape(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { use crate::shape::Shape::*; match *shape { Null => Value::Null, Any => json!("any"), Bottom => json!("bottom"), Bool => json!("bool"), StringT => json!("string"), Integer => json!("integer"), Floating => json!("floating"), Tuple(ref shapes, _n) => {
if folded == Any && shapes.iter().any(|s| s!= &Any) { generate_tuple_type(ctxt, path, shapes) } else { generate_vec_type(ctxt, path, &folded) } } VecT { elem_type: ref e } => generate_vec_type(ctxt, path, e), Struct { fields: ref map } => generate_struct_from_field_shapes(ctxt, path, map), MapT { val_type: ref v } => generate_map_type(ctxt, path, v), Opaque(ref t) => json!(t), Optional(ref e) => json!({ "__type__": "optional", "item": type_from_shape(ctxt, path, e), }), } } fn generate_vec_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { let singular = path.to_singular(); let inner = type_from_shape(ctxt, &singular, shape); json!([inner]) } fn generate_map_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { let singular = path.to_singular(); let inner = type_from_shape(ctxt, &singular, shape); json!({ "__type__": "map", "values": inner }) } fn generate_tuple_type(ctxt: &mut Ctxt, path: &str, shapes: &[Shape]) -> Value { let mut types = Vec::new(); for shape in shapes { let typ = type_from_shape(ctxt, path, shape); types.push(typ); } json!({ "__type__": "tuple", "items": types, }) } fn collapse_option(typ: &Shape) -> (bool, &Shape) { if let Shape::Optional(inner) = typ { return (true, &**inner); } (false, typ) } fn generate_struct_from_field_shapes( ctxt: &mut Ctxt, _path: &str, map: &LinkedHashMap<String, Shape>, ) -> Value { let mut properties = json!({}); for (name, typ) in map.iter() { let (was_optional, collapsed) = collapse_option(typ); let annotated_name = if was_optional { name.to_owned() + "?" } else { name.to_owned() }; let field_code = type_from_shape(ctxt, name, collapsed); properties[annotated_name] = field_code; } properties }
let folded = shape::fold_shapes(shapes.clone());
random_line_split
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct
{ options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, options: Options) -> (Ident, Option<Code>) { let mut ctxt = Ctxt { options }; let ident = "".to_string(); let value = type_from_shape(&mut ctxt, name, shape); let code = ::serde_json::to_string_pretty(&value); (ident, code.ok()) } fn type_from_shape(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { use crate::shape::Shape::*; match *shape { Null => Value::Null, Any => json!("any"), Bottom => json!("bottom"), Bool => json!("bool"), StringT => json!("string"), Integer => json!("integer"), Floating => json!("floating"), Tuple(ref shapes, _n) => { let folded = shape::fold_shapes(shapes.clone()); if folded == Any && shapes.iter().any(|s| s!= &Any) { generate_tuple_type(ctxt, path, shapes) } else { generate_vec_type(ctxt, path, &folded) } } VecT { elem_type: ref e } => generate_vec_type(ctxt, path, e), Struct { fields: ref map } => generate_struct_from_field_shapes(ctxt, path, map), MapT { val_type: ref v } => generate_map_type(ctxt, path, v), Opaque(ref t) => json!(t), Optional(ref e) => json!({ "__type__": "optional", "item": type_from_shape(ctxt, path, e), }), } } fn generate_vec_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { let singular = path.to_singular(); let inner = type_from_shape(ctxt, &singular, shape); json!([inner]) } fn generate_map_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { let singular = path.to_singular(); let inner = type_from_shape(ctxt, &singular, shape); json!({ "__type__": "map", "values": inner }) } fn generate_tuple_type(ctxt: &mut Ctxt, path: &str, shapes: &[Shape]) -> Value { let mut types = Vec::new(); for shape in shapes { let typ = type_from_shape(ctxt, path, shape); types.push(typ); } json!({ "__type__": "tuple", "items": types, }) } fn collapse_option(typ: &Shape) -> (bool, &Shape) { if let Shape::Optional(inner) = typ { return (true, &**inner); } (false, typ) } fn generate_struct_from_field_shapes( ctxt: &mut Ctxt, _path: &str, map: &LinkedHashMap<String, Shape>, ) -> Value { let mut properties = json!({}); for (name, typ) in map.iter() { let (was_optional, collapsed) = collapse_option(typ); let annotated_name = if was_optional { name.to_owned() + "?" } else { name.to_owned() }; let field_code = type_from_shape(ctxt, name, collapsed); properties[annotated_name] = field_code; } properties }
Ctxt
identifier_name
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct Ctxt { options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, options: Options) -> (Ident, Option<Code>) { let mut ctxt = Ctxt { options }; let ident = "".to_string(); let value = type_from_shape(&mut ctxt, name, shape); let code = ::serde_json::to_string_pretty(&value); (ident, code.ok()) } fn type_from_shape(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { use crate::shape::Shape::*; match *shape { Null => Value::Null, Any => json!("any"), Bottom => json!("bottom"), Bool => json!("bool"), StringT => json!("string"), Integer => json!("integer"), Floating => json!("floating"), Tuple(ref shapes, _n) => { let folded = shape::fold_shapes(shapes.clone()); if folded == Any && shapes.iter().any(|s| s!= &Any) { generate_tuple_type(ctxt, path, shapes) } else { generate_vec_type(ctxt, path, &folded) } } VecT { elem_type: ref e } => generate_vec_type(ctxt, path, e), Struct { fields: ref map } => generate_struct_from_field_shapes(ctxt, path, map), MapT { val_type: ref v } => generate_map_type(ctxt, path, v), Opaque(ref t) => json!(t), Optional(ref e) => json!({ "__type__": "optional", "item": type_from_shape(ctxt, path, e), }), } } fn generate_vec_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { let singular = path.to_singular(); let inner = type_from_shape(ctxt, &singular, shape); json!([inner]) } fn generate_map_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> Value { let singular = path.to_singular(); let inner = type_from_shape(ctxt, &singular, shape); json!({ "__type__": "map", "values": inner }) } fn generate_tuple_type(ctxt: &mut Ctxt, path: &str, shapes: &[Shape]) -> Value
fn collapse_option(typ: &Shape) -> (bool, &Shape) { if let Shape::Optional(inner) = typ { return (true, &**inner); } (false, typ) } fn generate_struct_from_field_shapes( ctxt: &mut Ctxt, _path: &str, map: &LinkedHashMap<String, Shape>, ) -> Value { let mut properties = json!({}); for (name, typ) in map.iter() { let (was_optional, collapsed) = collapse_option(typ); let annotated_name = if was_optional { name.to_owned() + "?" } else { name.to_owned() }; let field_code = type_from_shape(ctxt, name, collapsed); properties[annotated_name] = field_code; } properties }
{ let mut types = Vec::new(); for shape in shapes { let typ = type_from_shape(ctxt, path, shape); types.push(typ); } json!({ "__type__": "tuple", "items": types, }) }
identifier_body
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth, } impl Authenticator { pub fn new(auth: Auth) -> Self { Self { auth } } } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication // HTTP/1.0 401 Authorization Required // WWW-Authenticate: Basic realm="Secure Area" // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== // tips: base64encode(Aladdin:open sesame)=QWxhZGRpbjpvcGVuIHNlc2FtZQ== impl MiddleWare for Authenticator { fn before(&self, req: &Request, addr: &SocketAddr, _ctx: &mut Ctx) -> Result<(), Response>
let www = req.headers().get_str(authorization); let auth = match www_base64_to_auth(www) { Ok(a) => a, Err(e) => return Err(f(e)), }; debug!("addr: {}, www: {}, auth: {:?}", addr, www, auth); if auth!= self.auth { return Err(f("wrong username or password")); } Ok(()) } } fn www_base64_to_auth(value: &str) -> Result<Auth, &'static str> { let value = value.trim(); if value.len() <= "basic".len() || value[0.."basic".len()].to_lowercase()!= "basic" { return Err("not basic"); } let value = (&value["basic".len()..]).trim(); decode_config(value, URL_SAFE) .map_err(|_| "invalid basic value") .and_then(|bs| String::from_utf8(bs).map_err(|_| "invalid string")) .and_then(|str| str.parse().map_err(|_| "invalid authorised infomation")) }
{ // info!("url: {:?}", req.uri()); // info!("header: {:?}", req.headers()); let method_is_proxy = method_maybe_proxy(req).is_some(); let (authorization, code, authenticate) = if method_is_proxy { (header::PROXY_AUTHORIZATION, 407, header::PROXY_AUTHENTICATE) } else { (header::AUTHORIZATION, 401, header::WWW_AUTHENTICATE) }; let f = move |desc: &'static str| { response() .status(code) .header(authenticate, "Basic realm=\"User:Password\"") .body(desc.into()) .unwrap() };
identifier_body
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth, } impl Authenticator { pub fn new(auth: Auth) -> Self { Self { auth } } } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication // HTTP/1.0 401 Authorization Required // WWW-Authenticate: Basic realm="Secure Area" // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== // tips: base64encode(Aladdin:open sesame)=QWxhZGRpbjpvcGVuIHNlc2FtZQ== impl MiddleWare for Authenticator { fn before(&self, req: &Request, addr: &SocketAddr, _ctx: &mut Ctx) -> Result<(), Response> { // info!("url: {:?}", req.uri()); // info!("header: {:?}", req.headers()); let method_is_proxy = method_maybe_proxy(req).is_some(); let (authorization, code, authenticate) = if method_is_proxy { (header::PROXY_AUTHORIZATION, 407, header::PROXY_AUTHENTICATE) } else { (header::AUTHORIZATION, 401, header::WWW_AUTHENTICATE) }; let f = move |desc: &'static str| { response() .status(code) .header(authenticate, "Basic realm=\"User:Password\"") .body(desc.into()) .unwrap() }; let www = req.headers().get_str(authorization); let auth = match www_base64_to_auth(www) { Ok(a) => a, Err(e) => return Err(f(e)), }; debug!("addr: {}, www: {}, auth: {:?}", addr, www, auth); if auth!= self.auth { return Err(f("wrong username or password")); } Ok(()) } } fn
(value: &str) -> Result<Auth, &'static str> { let value = value.trim(); if value.len() <= "basic".len() || value[0.."basic".len()].to_lowercase()!= "basic" { return Err("not basic"); } let value = (&value["basic".len()..]).trim(); decode_config(value, URL_SAFE) .map_err(|_| "invalid basic value") .and_then(|bs| String::from_utf8(bs).map_err(|_| "invalid string")) .and_then(|str| str.parse().map_err(|_| "invalid authorised infomation")) }
www_base64_to_auth
identifier_name
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth,
impl Authenticator { pub fn new(auth: Auth) -> Self { Self { auth } } } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication // HTTP/1.0 401 Authorization Required // WWW-Authenticate: Basic realm="Secure Area" // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== // tips: base64encode(Aladdin:open sesame)=QWxhZGRpbjpvcGVuIHNlc2FtZQ== impl MiddleWare for Authenticator { fn before(&self, req: &Request, addr: &SocketAddr, _ctx: &mut Ctx) -> Result<(), Response> { // info!("url: {:?}", req.uri()); // info!("header: {:?}", req.headers()); let method_is_proxy = method_maybe_proxy(req).is_some(); let (authorization, code, authenticate) = if method_is_proxy { (header::PROXY_AUTHORIZATION, 407, header::PROXY_AUTHENTICATE) } else { (header::AUTHORIZATION, 401, header::WWW_AUTHENTICATE) }; let f = move |desc: &'static str| { response() .status(code) .header(authenticate, "Basic realm=\"User:Password\"") .body(desc.into()) .unwrap() }; let www = req.headers().get_str(authorization); let auth = match www_base64_to_auth(www) { Ok(a) => a, Err(e) => return Err(f(e)), }; debug!("addr: {}, www: {}, auth: {:?}", addr, www, auth); if auth!= self.auth { return Err(f("wrong username or password")); } Ok(()) } } fn www_base64_to_auth(value: &str) -> Result<Auth, &'static str> { let value = value.trim(); if value.len() <= "basic".len() || value[0.."basic".len()].to_lowercase()!= "basic" { return Err("not basic"); } let value = (&value["basic".len()..]).trim(); decode_config(value, URL_SAFE) .map_err(|_| "invalid basic value") .and_then(|bs| String::from_utf8(bs).map_err(|_| "invalid string")) .and_then(|str| str.parse().map_err(|_| "invalid authorised infomation")) }
}
random_line_split
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #![forbid(unsafe_code)] #![recursion_limit="256"] #![deny( dead_code, non_camel_case_types, non_snake_case,
trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] extern crate filters; extern crate chrono; extern crate toml; extern crate toml_query; #[macro_use] extern crate lazy_static; #[macro_use] extern crate is_match; #[macro_use] extern crate anyhow; #[macro_use] extern crate libimagstore; #[macro_use] extern crate libimagentryutil; extern crate libimagentrydatetime; extern crate libimagentrytag; extern crate libimagerror; mod constants; pub mod timetracking; pub mod iter; pub mod tag; pub mod store; module_entry_path_mod!("timetrack");
path_statements,
random_line_split
cryptocurrency-migration.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use exonum_cli::{NodeBuilder, Spec}; use exonum_rust_runtime::spec::JustFactory; use exonum_cryptocurrency_advanced::CryptocurrencyService; use old_cryptocurrency::contracts::CryptocurrencyService as OldService; #[tokio::main] async fn
() -> anyhow::Result<()> { exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
main
identifier_name
cryptocurrency-migration.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use exonum_cli::{NodeBuilder, Spec}; use exonum_rust_runtime::spec::JustFactory;
async fn main() -> anyhow::Result<()> { exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
use exonum_cryptocurrency_advanced::CryptocurrencyService; use old_cryptocurrency::contracts::CryptocurrencyService as OldService; #[tokio::main]
random_line_split
cryptocurrency-migration.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use exonum_cli::{NodeBuilder, Spec}; use exonum_rust_runtime::spec::JustFactory; use exonum_cryptocurrency_advanced::CryptocurrencyService; use old_cryptocurrency::contracts::CryptocurrencyService as OldService; #[tokio::main] async fn main() -> anyhow::Result<()>
{ exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
identifier_body
typedrw.rs
use std::mem; // use core::raw::Slice as RawSlice; use mmap::MapOption::{MapReadable, MapFd}; use mmap::MemoryMap; use std::os::unix::prelude::AsRawFd; use std::slice; use std::ops; use std::fs::File; use std::marker::PhantomData; pub struct TypedMemoryMap<T:Copy> { map: MemoryMap, // mapped file len: usize, // in bytes (needed because map extends to full block) phn: PhantomData<T>, } impl<T:Copy> TypedMemoryMap<T> { pub fn new(filename: String) -> TypedMemoryMap<T> { let file = File::open(filename).unwrap(); let size = file.metadata().unwrap().len() as usize; TypedMemoryMap { map: MemoryMap::new(size, &[MapReadable, MapFd(file.as_raw_fd())]).unwrap(), len: size / mem::size_of::<T>(), phn: PhantomData, } } } impl<T:Copy> ops::Index<ops::RangeFull> for TypedMemoryMap<T> { type Output = [T]; #[inline] fn index(&self, _index: ops::RangeFull) -> &[T] { // assert!(self.len <= self.map.len()); // unsafe { mem::transmute(RawSlice { // data: self.map.data() as *const u8, // len: self.len,
// })} unsafe { slice::from_raw_parts(self.map.data() as *const T, self.len) } } }
random_line_split
typedrw.rs
use std::mem; // use core::raw::Slice as RawSlice; use mmap::MapOption::{MapReadable, MapFd}; use mmap::MemoryMap; use std::os::unix::prelude::AsRawFd; use std::slice; use std::ops; use std::fs::File; use std::marker::PhantomData; pub struct TypedMemoryMap<T:Copy> { map: MemoryMap, // mapped file len: usize, // in bytes (needed because map extends to full block) phn: PhantomData<T>, } impl<T:Copy> TypedMemoryMap<T> { pub fn
(filename: String) -> TypedMemoryMap<T> { let file = File::open(filename).unwrap(); let size = file.metadata().unwrap().len() as usize; TypedMemoryMap { map: MemoryMap::new(size, &[MapReadable, MapFd(file.as_raw_fd())]).unwrap(), len: size / mem::size_of::<T>(), phn: PhantomData, } } } impl<T:Copy> ops::Index<ops::RangeFull> for TypedMemoryMap<T> { type Output = [T]; #[inline] fn index(&self, _index: ops::RangeFull) -> &[T] { // assert!(self.len <= self.map.len()); // unsafe { mem::transmute(RawSlice { // data: self.map.data() as *const u8, // len: self.len, // })} unsafe { slice::from_raw_parts(self.map.data() as *const T, self.len) } } }
new
identifier_name
function.rs
use ast::{Node, Loc, IdentifierNode, ExpressionNode}; use ast::{BlockNode, Statement, PatternList, PropertyKey}; pub trait Name<'ast>: Copy { fn empty() -> Self; } #[derive(Debug, PartialEq, Clone, Copy)] pub struct EmptyName; #[derive(Debug, PartialEq, Clone, Copy)] pub struct MandatoryName<'ast>(pub IdentifierNode<'ast>);
pub type Method<'ast> = Function<'ast, EmptyName>; impl<'ast> Name<'ast> for EmptyName { fn empty() -> Self { EmptyName } } impl<'ast> Name<'ast> for MandatoryName<'ast> { fn empty() -> Self { MandatoryName(Node::new(&Loc { start: 0, end: 0, item: "" })) } } impl<'ast> Name<'ast> for OptionalName<'ast> { fn empty() -> Self { OptionalName(None) } } #[cfg(test)] impl<'ast> From<IdentifierNode<'ast>> for MandatoryName<'ast> { #[inline] fn from(name: IdentifierNode<'ast>) -> Self { MandatoryName(name) } } #[cfg(test)] impl<'ast> From<IdentifierNode<'ast>> for OptionalName<'ast> { #[inline] fn from(name: IdentifierNode<'ast>) -> Self { OptionalName(Some(name)) } } #[cfg(test)] impl<'ast> From<Option<IdentifierNode<'ast>>> for OptionalName<'ast> { #[inline] fn from(name: Option<IdentifierNode<'ast>>) -> Self { OptionalName(name) } } #[derive(Debug, PartialEq, Clone, Copy)] pub struct Function<'ast, N: Name<'ast>> { pub name: N, pub generator: bool, pub params: PatternList<'ast>, pub body: BlockNode<'ast, Statement<'ast>>, } #[derive(Debug, PartialEq, Clone, Copy)] pub enum MethodKind { Constructor, Method, Get, Set, } #[derive(Debug, PartialEq, Clone, Copy)] pub enum ClassMember<'ast> { Error, Method { is_static: bool, key: Node<'ast, PropertyKey<'ast>>, kind: MethodKind, value: Node<'ast, Function<'ast, EmptyName>>, }, Literal { is_static: bool, key: Node<'ast, PropertyKey<'ast>>, value: ExpressionNode<'ast>, } } #[derive(Debug, PartialEq, Clone, Copy)] pub struct Class<'ast, N: Name<'ast>> { pub name: N, pub extends: Option<ExpressionNode<'ast>>, pub body: BlockNode<'ast, ClassMember<'ast>>, }
#[derive(Debug, PartialEq, Clone, Copy)] pub struct OptionalName<'ast>(pub Option<IdentifierNode<'ast>>);
random_line_split
function.rs
use ast::{Node, Loc, IdentifierNode, ExpressionNode}; use ast::{BlockNode, Statement, PatternList, PropertyKey}; pub trait Name<'ast>: Copy { fn empty() -> Self; } #[derive(Debug, PartialEq, Clone, Copy)] pub struct EmptyName; #[derive(Debug, PartialEq, Clone, Copy)] pub struct MandatoryName<'ast>(pub IdentifierNode<'ast>); #[derive(Debug, PartialEq, Clone, Copy)] pub struct OptionalName<'ast>(pub Option<IdentifierNode<'ast>>); pub type Method<'ast> = Function<'ast, EmptyName>; impl<'ast> Name<'ast> for EmptyName { fn empty() -> Self { EmptyName } } impl<'ast> Name<'ast> for MandatoryName<'ast> { fn
() -> Self { MandatoryName(Node::new(&Loc { start: 0, end: 0, item: "" })) } } impl<'ast> Name<'ast> for OptionalName<'ast> { fn empty() -> Self { OptionalName(None) } } #[cfg(test)] impl<'ast> From<IdentifierNode<'ast>> for MandatoryName<'ast> { #[inline] fn from(name: IdentifierNode<'ast>) -> Self { MandatoryName(name) } } #[cfg(test)] impl<'ast> From<IdentifierNode<'ast>> for OptionalName<'ast> { #[inline] fn from(name: IdentifierNode<'ast>) -> Self { OptionalName(Some(name)) } } #[cfg(test)] impl<'ast> From<Option<IdentifierNode<'ast>>> for OptionalName<'ast> { #[inline] fn from(name: Option<IdentifierNode<'ast>>) -> Self { OptionalName(name) } } #[derive(Debug, PartialEq, Clone, Copy)] pub struct Function<'ast, N: Name<'ast>> { pub name: N, pub generator: bool, pub params: PatternList<'ast>, pub body: BlockNode<'ast, Statement<'ast>>, } #[derive(Debug, PartialEq, Clone, Copy)] pub enum MethodKind { Constructor, Method, Get, Set, } #[derive(Debug, PartialEq, Clone, Copy)] pub enum ClassMember<'ast> { Error, Method { is_static: bool, key: Node<'ast, PropertyKey<'ast>>, kind: MethodKind, value: Node<'ast, Function<'ast, EmptyName>>, }, Literal { is_static: bool, key: Node<'ast, PropertyKey<'ast>>, value: ExpressionNode<'ast>, } } #[derive(Debug, PartialEq, Clone, Copy)] pub struct Class<'ast, N: Name<'ast>> { pub name: N, pub extends: Option<ExpressionNode<'ast>>, pub body: BlockNode<'ast, ClassMember<'ast>>, }
empty
identifier_name
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal; mod input; use std::fmt::Write; fn main()
term.set_foreground( Colour::def_yellow() ); let _ = write!(&mut term, " {}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 1, &mut buf)); // Kernel 1: Build line term.set_foreground( Colour::white() ); let _ = write!(&mut term, "Simple console\n"); } window.show(); // Initial prompt term.write_str("> ").unwrap(); term.flush(); let mut shell = ShellState::new(); loop { // Bind to receive events relating to the window let mut events = [window.get_wait( ::syscalls::gui::WindowWaits::new().input() )]; ::syscalls::threads::wait(&mut events,!0); while let Some(ev) = window.pop_event() { if let Some(buf) = input.handle_event(ev, |a| render_input(&mut term, a)) { kernel_log!("buf = {:?}", buf); term.write_str("\n").unwrap(); term.flush(); window.redraw(); // XXX: Lazy option really... would maybe be cleaner to either have a flag in `shell` or just explicitly // exit when the exit command is invoked if buf == "exit" { return ; } shell.handle_command(&mut term, buf); // - If the command didn't print a newline, print one for it if term.cur_col()!= 0 { term.write_str("\n").unwrap(); } // New prompt term.write_str("> ").unwrap(); } term.flush(); window.redraw(); } window.check_wait(&events[0]); } } // Render callback for input stack fn render_input(term: &mut terminal::Terminal, action: input::Action) { use input::Action; match action { Action::Backspace => term.delete_left(), Action::Delete => term.delete_right(), Action::Puts(s) => term.write_str(s).unwrap(), } } #[derive(Default)] struct ShellState { /// Current working directory, relative to / cwd_rel: String, } macro_rules! print { ($term:expr, $($t:tt)*) => ({use std::fmt::Write; let _ = write!($term, $($t)*);}); } impl ShellState { pub fn new() -> ShellState { Default::default() } /// Handle a command pub fn handle_command(&mut self, term: &mut terminal::Terminal, mut cmdline: String) { use cmdline_words_parser::StrExt; let mut args = cmdline.parse_cmdline_words(); match args.next() { None => {}, // 'pwd' - Print working directory Some("pwd") => print!(term, "/{}", self.cwd_rel), // 'cd' - Change directory Some("cd") => if let Some(p) = args.next() { print!(term, "TODO: cd '{}'", p); } else { self.cwd_rel = String::new(); }, // 'ls' - Print the contents of a directory Some("ls") => if let Some(dir) = args.next() { // TODO: Parse 'dir' as relative correctly command_ls(term, dir); } else { command_ls(term, &format!("/{}", self.cwd_rel)); }, // 'cat' - Dump the contents of a file // TODO: Implement Some("cat") => print!(term, "TODO: cat"), // 'echo' - Prints all arguments space-separated Some("echo") => while let Some(v) = args.next() { print!(term, "{} ", v); }, Some("help") => { print!(term, "Builtins: pwd, cd, ls, cat, help, echo"); }, Some(cmd @_) => { print!(term, "Unkown command '{}'", cmd); }, } } } /// List the contents of a directory fn command_ls(term: &mut terminal::Terminal, path: &str) { use syscalls::vfs::{NodeType, Node, Dir, File, Symlink}; let mut handle = match Dir::open(path) { Ok(v) => v, Err(e) => { print!(term, "Unable to open '{}': {:?}", path, e); return ; }, }; let mut buf = [0; 256]; loop { let name_bytes = match handle.read_ent(&mut buf) { Ok(v) => v, Err(e) => { print!(term, "Read error: {:?}", e); return ; }, }; if name_bytes == b"" { break ; } let name = ::std::str::from_utf8(name_bytes).expect("Filename not utf-8"); print!(term, "- {}", name); let file_node = match Node::open(&format!("{}/{}", if path!= "/" { path } else { "" }, name)[..])//handle.open_node(node_id) { Ok(v) => v, Err(e) => { print!(term, "(Error: {:?})\n", e); continue ; }, }; match file_node.class() { NodeType::File => {}, NodeType::Dir => print!(term, "/"), NodeType::Symlink => { let mut link_path_buf = [0; 256]; let dest = match file_node.into_symlink().and_then(|h| h.read_target(&mut link_path_buf)) { Ok(v) => v, Err(e) => { print!(term, "(Error: {:?})\n", e); continue ; }, }; print!(term, " => {:?}", ::std::str::from_utf8(dest)); }, NodeType::Special => print!(term, "*"), } print!(term, "\n"); } }
{ use syscalls::gui::{Group,Window}; use syscalls::threads::{S_THIS_PROCESS,ThisProcessWaits}; ::syscalls::threads::wait(&mut [S_THIS_PROCESS.get_wait(ThisProcessWaits::new().recv_obj())], !0); ::syscalls::gui::set_group( S_THIS_PROCESS.receive_object::<Group>(0).unwrap() ); // Create maximised window let window = Window::new("Console").unwrap(); window.maximise(); window.fill_rect(0,0, !0,!0, 0x33_00_00); // A nice rust-like red :) // Create terminal let mut term = terminal::Terminal::new(&window, ::syscalls::gui::Rect::new(0,0, 1920,1080)); let mut input = input::InputStack::new(); // Print header { let mut buf = [0; 128]; term.set_foreground( Colour::def_green() ); let _ = write!(&mut term, "{}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 0, &mut buf)); // Kernel 0: Version line
identifier_body
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal; mod input;
fn main() { use syscalls::gui::{Group,Window}; use syscalls::threads::{S_THIS_PROCESS,ThisProcessWaits}; ::syscalls::threads::wait(&mut [S_THIS_PROCESS.get_wait(ThisProcessWaits::new().recv_obj())],!0); ::syscalls::gui::set_group( S_THIS_PROCESS.receive_object::<Group>(0).unwrap() ); // Create maximised window let window = Window::new("Console").unwrap(); window.maximise(); window.fill_rect(0,0,!0,!0, 0x33_00_00); // A nice rust-like red :) // Create terminal let mut term = terminal::Terminal::new(&window, ::syscalls::gui::Rect::new(0,0, 1920,1080)); let mut input = input::InputStack::new(); // Print header { let mut buf = [0; 128]; term.set_foreground( Colour::def_green() ); let _ = write!(&mut term, "{}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 0, &mut buf)); // Kernel 0: Version line term.set_foreground( Colour::def_yellow() ); let _ = write!(&mut term, " {}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 1, &mut buf)); // Kernel 1: Build line term.set_foreground( Colour::white() ); let _ = write!(&mut term, "Simple console\n"); } window.show(); // Initial prompt term.write_str("> ").unwrap(); term.flush(); let mut shell = ShellState::new(); loop { // Bind to receive events relating to the window let mut events = [window.get_wait( ::syscalls::gui::WindowWaits::new().input() )]; ::syscalls::threads::wait(&mut events,!0); while let Some(ev) = window.pop_event() { if let Some(buf) = input.handle_event(ev, |a| render_input(&mut term, a)) { kernel_log!("buf = {:?}", buf); term.write_str("\n").unwrap(); term.flush(); window.redraw(); // XXX: Lazy option really... would maybe be cleaner to either have a flag in `shell` or just explicitly // exit when the exit command is invoked if buf == "exit" { return ; } shell.handle_command(&mut term, buf); // - If the command didn't print a newline, print one for it if term.cur_col()!= 0 { term.write_str("\n").unwrap(); } // New prompt term.write_str("> ").unwrap(); } term.flush(); window.redraw(); } window.check_wait(&events[0]); } } // Render callback for input stack fn render_input(term: &mut terminal::Terminal, action: input::Action) { use input::Action; match action { Action::Backspace => term.delete_left(), Action::Delete => term.delete_right(), Action::Puts(s) => term.write_str(s).unwrap(), } } #[derive(Default)] struct ShellState { /// Current working directory, relative to / cwd_rel: String, } macro_rules! print { ($term:expr, $($t:tt)*) => ({use std::fmt::Write; let _ = write!($term, $($t)*);}); } impl ShellState { pub fn new() -> ShellState { Default::default() } /// Handle a command pub fn handle_command(&mut self, term: &mut terminal::Terminal, mut cmdline: String) { use cmdline_words_parser::StrExt; let mut args = cmdline.parse_cmdline_words(); match args.next() { None => {}, // 'pwd' - Print working directory Some("pwd") => print!(term, "/{}", self.cwd_rel), // 'cd' - Change directory Some("cd") => if let Some(p) = args.next() { print!(term, "TODO: cd '{}'", p); } else { self.cwd_rel = String::new(); }, // 'ls' - Print the contents of a directory Some("ls") => if let Some(dir) = args.next() { // TODO: Parse 'dir' as relative correctly command_ls(term, dir); } else { command_ls(term, &format!("/{}", self.cwd_rel)); }, // 'cat' - Dump the contents of a file // TODO: Implement Some("cat") => print!(term, "TODO: cat"), // 'echo' - Prints all arguments space-separated Some("echo") => while let Some(v) = args.next() { print!(term, "{} ", v); }, Some("help") => { print!(term, "Builtins: pwd, cd, ls, cat, help, echo"); }, Some(cmd @_) => { print!(term, "Unkown command '{}'", cmd); }, } } } /// List the contents of a directory fn command_ls(term: &mut terminal::Terminal, path: &str) { use syscalls::vfs::{NodeType, Node, Dir, File, Symlink}; let mut handle = match Dir::open(path) { Ok(v) => v, Err(e) => { print!(term, "Unable to open '{}': {:?}", path, e); return ; }, }; let mut buf = [0; 256]; loop { let name_bytes = match handle.read_ent(&mut buf) { Ok(v) => v, Err(e) => { print!(term, "Read error: {:?}", e); return ; }, }; if name_bytes == b"" { break ; } let name = ::std::str::from_utf8(name_bytes).expect("Filename not utf-8"); print!(term, "- {}", name); let file_node = match Node::open(&format!("{}/{}", if path!= "/" { path } else { "" }, name)[..])//handle.open_node(node_id) { Ok(v) => v, Err(e) => { print!(term, "(Error: {:?})\n", e); continue ; }, }; match file_node.class() { NodeType::File => {}, NodeType::Dir => print!(term, "/"), NodeType::Symlink => { let mut link_path_buf = [0; 256]; let dest = match file_node.into_symlink().and_then(|h| h.read_target(&mut link_path_buf)) { Ok(v) => v, Err(e) => { print!(term, "(Error: {:?})\n", e); continue ; }, }; print!(term, " => {:?}", ::std::str::from_utf8(dest)); }, NodeType::Special => print!(term, "*"), } print!(term, "\n"); } }
use std::fmt::Write;
random_line_split
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal; mod input; use std::fmt::Write; fn main() { use syscalls::gui::{Group,Window}; use syscalls::threads::{S_THIS_PROCESS,ThisProcessWaits}; ::syscalls::threads::wait(&mut [S_THIS_PROCESS.get_wait(ThisProcessWaits::new().recv_obj())],!0); ::syscalls::gui::set_group( S_THIS_PROCESS.receive_object::<Group>(0).unwrap() ); // Create maximised window let window = Window::new("Console").unwrap(); window.maximise(); window.fill_rect(0,0,!0,!0, 0x33_00_00); // A nice rust-like red :) // Create terminal let mut term = terminal::Terminal::new(&window, ::syscalls::gui::Rect::new(0,0, 1920,1080)); let mut input = input::InputStack::new(); // Print header { let mut buf = [0; 128]; term.set_foreground( Colour::def_green() ); let _ = write!(&mut term, "{}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 0, &mut buf)); // Kernel 0: Version line term.set_foreground( Colour::def_yellow() ); let _ = write!(&mut term, " {}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 1, &mut buf)); // Kernel 1: Build line term.set_foreground( Colour::white() ); let _ = write!(&mut term, "Simple console\n"); } window.show(); // Initial prompt term.write_str("> ").unwrap(); term.flush(); let mut shell = ShellState::new(); loop { // Bind to receive events relating to the window let mut events = [window.get_wait( ::syscalls::gui::WindowWaits::new().input() )]; ::syscalls::threads::wait(&mut events,!0); while let Some(ev) = window.pop_event() { if let Some(buf) = input.handle_event(ev, |a| render_input(&mut term, a)) { kernel_log!("buf = {:?}", buf); term.write_str("\n").unwrap(); term.flush(); window.redraw(); // XXX: Lazy option really... would maybe be cleaner to either have a flag in `shell` or just explicitly // exit when the exit command is invoked if buf == "exit" { return ; } shell.handle_command(&mut term, buf); // - If the command didn't print a newline, print one for it if term.cur_col()!= 0 { term.write_str("\n").unwrap(); } // New prompt term.write_str("> ").unwrap(); } term.flush(); window.redraw(); } window.check_wait(&events[0]); } } // Render callback for input stack fn render_input(term: &mut terminal::Terminal, action: input::Action) { use input::Action; match action { Action::Backspace => term.delete_left(), Action::Delete => term.delete_right(), Action::Puts(s) => term.write_str(s).unwrap(), } } #[derive(Default)] struct ShellState { /// Current working directory, relative to / cwd_rel: String, } macro_rules! print { ($term:expr, $($t:tt)*) => ({use std::fmt::Write; let _ = write!($term, $($t)*);}); } impl ShellState { pub fn new() -> ShellState { Default::default() } /// Handle a command pub fn handle_command(&mut self, term: &mut terminal::Terminal, mut cmdline: String) { use cmdline_words_parser::StrExt; let mut args = cmdline.parse_cmdline_words(); match args.next() { None => {}, // 'pwd' - Print working directory Some("pwd") => print!(term, "/{}", self.cwd_rel), // 'cd' - Change directory Some("cd") => if let Some(p) = args.next() { print!(term, "TODO: cd '{}'", p); } else { self.cwd_rel = String::new(); }, // 'ls' - Print the contents of a directory Some("ls") => if let Some(dir) = args.next() { // TODO: Parse 'dir' as relative correctly command_ls(term, dir); } else { command_ls(term, &format!("/{}", self.cwd_rel)); }, // 'cat' - Dump the contents of a file // TODO: Implement Some("cat") => print!(term, "TODO: cat"), // 'echo' - Prints all arguments space-separated Some("echo") => while let Some(v) = args.next() { print!(term, "{} ", v); }, Some("help") => { print!(term, "Builtins: pwd, cd, ls, cat, help, echo"); }, Some(cmd @_) => { print!(term, "Unkown command '{}'", cmd); }, } } } /// List the contents of a directory fn command_ls(term: &mut terminal::Terminal, path: &str) { use syscalls::vfs::{NodeType, Node, Dir, File, Symlink}; let mut handle = match Dir::open(path) { Ok(v) => v, Err(e) =>
, }; let mut buf = [0; 256]; loop { let name_bytes = match handle.read_ent(&mut buf) { Ok(v) => v, Err(e) => { print!(term, "Read error: {:?}", e); return ; }, }; if name_bytes == b"" { break ; } let name = ::std::str::from_utf8(name_bytes).expect("Filename not utf-8"); print!(term, "- {}", name); let file_node = match Node::open(&format!("{}/{}", if path!= "/" { path } else { "" }, name)[..])//handle.open_node(node_id) { Ok(v) => v, Err(e) => { print!(term, "(Error: {:?})\n", e); continue ; }, }; match file_node.class() { NodeType::File => {}, NodeType::Dir => print!(term, "/"), NodeType::Symlink => { let mut link_path_buf = [0; 256]; let dest = match file_node.into_symlink().and_then(|h| h.read_target(&mut link_path_buf)) { Ok(v) => v, Err(e) => { print!(term, "(Error: {:?})\n", e); continue ; }, }; print!(term, " => {:?}", ::std::str::from_utf8(dest)); }, NodeType::Special => print!(term, "*"), } print!(term, "\n"); } }
{ print!(term, "Unable to open '{}': {:?}", path, e); return ; }
conditional_block
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal; mod input; use std::fmt::Write; fn main() { use syscalls::gui::{Group,Window}; use syscalls::threads::{S_THIS_PROCESS,ThisProcessWaits}; ::syscalls::threads::wait(&mut [S_THIS_PROCESS.get_wait(ThisProcessWaits::new().recv_obj())],!0); ::syscalls::gui::set_group( S_THIS_PROCESS.receive_object::<Group>(0).unwrap() ); // Create maximised window let window = Window::new("Console").unwrap(); window.maximise(); window.fill_rect(0,0,!0,!0, 0x33_00_00); // A nice rust-like red :) // Create terminal let mut term = terminal::Terminal::new(&window, ::syscalls::gui::Rect::new(0,0, 1920,1080)); let mut input = input::InputStack::new(); // Print header { let mut buf = [0; 128]; term.set_foreground( Colour::def_green() ); let _ = write!(&mut term, "{}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 0, &mut buf)); // Kernel 0: Version line term.set_foreground( Colour::def_yellow() ); let _ = write!(&mut term, " {}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 1, &mut buf)); // Kernel 1: Build line term.set_foreground( Colour::white() ); let _ = write!(&mut term, "Simple console\n"); } window.show(); // Initial prompt term.write_str("> ").unwrap(); term.flush(); let mut shell = ShellState::new(); loop { // Bind to receive events relating to the window let mut events = [window.get_wait( ::syscalls::gui::WindowWaits::new().input() )]; ::syscalls::threads::wait(&mut events,!0); while let Some(ev) = window.pop_event() { if let Some(buf) = input.handle_event(ev, |a| render_input(&mut term, a)) { kernel_log!("buf = {:?}", buf); term.write_str("\n").unwrap(); term.flush(); window.redraw(); // XXX: Lazy option really... would maybe be cleaner to either have a flag in `shell` or just explicitly // exit when the exit command is invoked if buf == "exit" { return ; } shell.handle_command(&mut term, buf); // - If the command didn't print a newline, print one for it if term.cur_col()!= 0 { term.write_str("\n").unwrap(); } // New prompt term.write_str("> ").unwrap(); } term.flush(); window.redraw(); } window.check_wait(&events[0]); } } // Render callback for input stack fn render_input(term: &mut terminal::Terminal, action: input::Action) { use input::Action; match action { Action::Backspace => term.delete_left(), Action::Delete => term.delete_right(), Action::Puts(s) => term.write_str(s).unwrap(), } } #[derive(Default)] struct ShellState { /// Current working directory, relative to / cwd_rel: String, } macro_rules! print { ($term:expr, $($t:tt)*) => ({use std::fmt::Write; let _ = write!($term, $($t)*);}); } impl ShellState { pub fn new() -> ShellState { Default::default() } /// Handle a command pub fn
(&mut self, term: &mut terminal::Terminal, mut cmdline: String) { use cmdline_words_parser::StrExt; let mut args = cmdline.parse_cmdline_words(); match args.next() { None => {}, // 'pwd' - Print working directory Some("pwd") => print!(term, "/{}", self.cwd_rel), // 'cd' - Change directory Some("cd") => if let Some(p) = args.next() { print!(term, "TODO: cd '{}'", p); } else { self.cwd_rel = String::new(); }, // 'ls' - Print the contents of a directory Some("ls") => if let Some(dir) = args.next() { // TODO: Parse 'dir' as relative correctly command_ls(term, dir); } else { command_ls(term, &format!("/{}", self.cwd_rel)); }, // 'cat' - Dump the contents of a file // TODO: Implement Some("cat") => print!(term, "TODO: cat"), // 'echo' - Prints all arguments space-separated Some("echo") => while let Some(v) = args.next() { print!(term, "{} ", v); }, Some("help") => { print!(term, "Builtins: pwd, cd, ls, cat, help, echo"); }, Some(cmd @_) => { print!(term, "Unkown command '{}'", cmd); }, } } } /// List the contents of a directory fn command_ls(term: &mut terminal::Terminal, path: &str) { use syscalls::vfs::{NodeType, Node, Dir, File, Symlink}; let mut handle = match Dir::open(path) { Ok(v) => v, Err(e) => { print!(term, "Unable to open '{}': {:?}", path, e); return ; }, }; let mut buf = [0; 256]; loop { let name_bytes = match handle.read_ent(&mut buf) { Ok(v) => v, Err(e) => { print!(term, "Read error: {:?}", e); return ; }, }; if name_bytes == b"" { break ; } let name = ::std::str::from_utf8(name_bytes).expect("Filename not utf-8"); print!(term, "- {}", name); let file_node = match Node::open(&format!("{}/{}", if path!= "/" { path } else { "" }, name)[..])//handle.open_node(node_id) { Ok(v) => v, Err(e) => { print!(term, "(Error: {:?})\n", e); continue ; }, }; match file_node.class() { NodeType::File => {}, NodeType::Dir => print!(term, "/"), NodeType::Symlink => { let mut link_path_buf = [0; 256]; let dest = match file_node.into_symlink().and_then(|h| h.read_target(&mut link_path_buf)) { Ok(v) => v, Err(e) => { print!(term, "(Error: {:?})\n", e); continue ; }, }; print!(term, " => {:?}", ::std::str::from_utf8(dest)); }, NodeType::Special => print!(term, "*"), } print!(term, "\n"); } }
handle_command
identifier_name
tabs.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use bit_vec::BitVec; #[derive(Debug)] pub struct Tabs { cols: u32, rows: u32, inner: BitVec, } impl Tabs { pub fn new(cols: u32, rows: u32) -> Self { Tabs { cols: cols, rows: rows, inner: BitVec::from_fn(cols as usize, |i| i % 8 == 0) } } pub fn resize(&mut self, cols: u32, rows: u32) { self.inner.grow(cols as usize, false); if cols > self.cols { for i in (self.cols.. cols).filter(|i| i % 8 == 0) { self.inner.set(i as usize, true); } } self.cols = cols; self.rows = rows; } pub fn set(&mut self, x: u32, value: bool) { self.inner.set(x as usize, value); } pub fn get(&self, x: u32) -> bool { self.inner.get(x as usize).unwrap_or(false) } pub fn clear(&mut self) {
pub fn next(&self, n: i32, start: u32) -> u32 { let mut end = start; if n > 0 { while end < self.cols { end += 1; if self.get(end) { break; } } } else { while end!= 0 { end -= 1; if self.get(end) { break; } } } if end == self.cols &&!self.get(end) { start } else { end } } }
self.inner.clear() }
identifier_body
tabs.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use bit_vec::BitVec; #[derive(Debug)] pub struct Tabs { cols: u32, rows: u32, inner: BitVec, } impl Tabs { pub fn ne
ols: u32, rows: u32) -> Self { Tabs { cols: cols, rows: rows, inner: BitVec::from_fn(cols as usize, |i| i % 8 == 0) } } pub fn resize(&mut self, cols: u32, rows: u32) { self.inner.grow(cols as usize, false); if cols > self.cols { for i in (self.cols.. cols).filter(|i| i % 8 == 0) { self.inner.set(i as usize, true); } } self.cols = cols; self.rows = rows; } pub fn set(&mut self, x: u32, value: bool) { self.inner.set(x as usize, value); } pub fn get(&self, x: u32) -> bool { self.inner.get(x as usize).unwrap_or(false) } pub fn clear(&mut self) { self.inner.clear() } pub fn next(&self, n: i32, start: u32) -> u32 { let mut end = start; if n > 0 { while end < self.cols { end += 1; if self.get(end) { break; } } } else { while end!= 0 { end -= 1; if self.get(end) { break; } } } if end == self.cols &&!self.get(end) { start } else { end } } }
w(c
identifier_name
tabs.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use bit_vec::BitVec; #[derive(Debug)] pub struct Tabs { cols: u32, rows: u32, inner: BitVec, } impl Tabs { pub fn new(cols: u32, rows: u32) -> Self { Tabs { cols: cols, rows: rows, inner: BitVec::from_fn(cols as usize, |i| i % 8 == 0) } } pub fn resize(&mut self, cols: u32, rows: u32) { self.inner.grow(cols as usize, false); if cols > self.cols {
self.cols = cols; self.rows = rows; } pub fn set(&mut self, x: u32, value: bool) { self.inner.set(x as usize, value); } pub fn get(&self, x: u32) -> bool { self.inner.get(x as usize).unwrap_or(false) } pub fn clear(&mut self) { self.inner.clear() } pub fn next(&self, n: i32, start: u32) -> u32 { let mut end = start; if n > 0 { while end < self.cols { end += 1; if self.get(end) { break; } } } else { while end!= 0 { end -= 1; if self.get(end) { break; } } } if end == self.cols &&!self.get(end) { start } else { end } } }
for i in (self.cols .. cols).filter(|i| i % 8 == 0) { self.inner.set(i as usize, true); } }
conditional_block
tabs.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use bit_vec::BitVec; #[derive(Debug)] pub struct Tabs { cols: u32, rows: u32, inner: BitVec, } impl Tabs { pub fn new(cols: u32, rows: u32) -> Self { Tabs { cols: cols, rows: rows, inner: BitVec::from_fn(cols as usize, |i| i % 8 == 0) } } pub fn resize(&mut self, cols: u32, rows: u32) { self.inner.grow(cols as usize, false); if cols > self.cols { for i in (self.cols.. cols).filter(|i| i % 8 == 0) { self.inner.set(i as usize, true); } } self.cols = cols; self.rows = rows; } pub fn set(&mut self, x: u32, value: bool) { self.inner.set(x as usize, value); } pub fn get(&self, x: u32) -> bool { self.inner.get(x as usize).unwrap_or(false) } pub fn clear(&mut self) { self.inner.clear() } pub fn next(&self, n: i32, start: u32) -> u32 { let mut end = start;
if n > 0 { while end < self.cols { end += 1; if self.get(end) { break; } } } else { while end!= 0 { end -= 1; if self.get(end) { break; } } } if end == self.cols &&!self.get(end) { start } else { end } } }
random_line_split
operator-multidispatch.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
// points can be added, and a point can be added to an integer. use std::ops; #[derive(Show,PartialEq,Eq)] struct Point { x: int, y: int } impl ops::Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point {x: self.x + other.x, y: self.y + other.y} } } impl ops::Add<int> for Point { type Output = Point; fn add(self, other: int) -> Point { Point {x: self.x + other, y: self.y + other} } } pub fn main() { let mut p = Point {x: 10, y: 20}; p = p + Point {x: 101, y: 102}; assert_eq!(p, Point {x: 111, y: 122}); p = p + 1; assert_eq!(p, Point {x: 112, y: 123}); }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we can overload the `+` operator for points so that two
random_line_split
operator-multidispatch.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we can overload the `+` operator for points so that two // points can be added, and a point can be added to an integer. use std::ops; #[derive(Show,PartialEq,Eq)] struct Point { x: int, y: int } impl ops::Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point {x: self.x + other.x, y: self.y + other.y} } } impl ops::Add<int> for Point { type Output = Point; fn
(self, other: int) -> Point { Point {x: self.x + other, y: self.y + other} } } pub fn main() { let mut p = Point {x: 10, y: 20}; p = p + Point {x: 101, y: 102}; assert_eq!(p, Point {x: 111, y: 122}); p = p + 1; assert_eq!(p, Point {x: 112, y: 123}); }
add
identifier_name
operator-multidispatch.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we can overload the `+` operator for points so that two // points can be added, and a point can be added to an integer. use std::ops; #[derive(Show,PartialEq,Eq)] struct Point { x: int, y: int } impl ops::Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point {x: self.x + other.x, y: self.y + other.y} } } impl ops::Add<int> for Point { type Output = Point; fn add(self, other: int) -> Point
} pub fn main() { let mut p = Point {x: 10, y: 20}; p = p + Point {x: 101, y: 102}; assert_eq!(p, Point {x: 111, y: 122}); p = p + 1; assert_eq!(p, Point {x: 112, y: 123}); }
{ Point {x: self.x + other, y: self.y + other} }
identifier_body
alg_runner.rs
use std::collections::HashMap; use network::{ DoubleVec, Network, NodeId }; use network::algorithms::{ dijkstra, pagerank }; use usage::{ DEFAULT_BETA, DEFAULT_EPS, DEFAULT_START_ID, Args }; #[derive(Debug, RustcDecodable)] pub enum Algorithm { dijkstra, pagerank } pub fn run_algorithm<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { match args.arg_algorithm { Algorithm::dijkstra => run_dijkstra(network, args, node_to_id), Algorithm::pagerank => run_pagerank(network, args, node_to_id), } } fn run_dijkstra<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { let start_id = match args.flag_start_node.as_ref() { Some(name) => node_to_id[name], None => DEFAULT_START_ID, }; let use_heap = args.flag_use_heap; let (pred, cost) = dijkstra(network, start_id, use_heap); print_dijkstra_result(&pred, &cost, &node_to_id) } fn run_pagerank<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { let beta = args.flag_beta.unwrap_or(DEFAULT_BETA); let eps = args.flag_eps.unwrap_or(DEFAULT_EPS); let ranks = pagerank(network, beta, eps); let target_node = args.flag_target_node.as_ref(); print_pagerank_results(&ranks, node_to_id, target_node); } fn get_node_name(i: &NodeId, id_to_node: &HashMap<NodeId, String>) -> String { id_to_node.get(i).unwrap_or(&"NONE".to_string()).to_string()
} fn print_dijkstra_result(pred: &Vec<NodeId>, cost: &DoubleVec, node_to_id: &HashMap<String, NodeId>) { let id_to_node: HashMap<NodeId, String> = node_to_id.iter() .map(|(k,v)| (*v,k.clone())) .collect(); for i in (0..pred.len()).take(100) { let to_id = i as NodeId; let from_node = get_node_name(pred.get(i).unwrap(), &id_to_node); let to_node = get_node_name(&to_id, &id_to_node); let cum_cost = cost.get(i).unwrap(); println!("{} -> {} : {:4}", from_node, to_node, cum_cost); } } fn print_pagerank_results(ranks: &Vec<f64>, node_to_id: &HashMap<String, NodeId>, target_node: Option<&String>) { match target_node { None => println!("No target node given."), Some(name) => { let id = node_to_id[name] as usize; println!("Rank of node {}: {} ({:e})", name, ranks[id], ranks[id]); } } }
random_line_split
alg_runner.rs
use std::collections::HashMap; use network::{ DoubleVec, Network, NodeId }; use network::algorithms::{ dijkstra, pagerank }; use usage::{ DEFAULT_BETA, DEFAULT_EPS, DEFAULT_START_ID, Args }; #[derive(Debug, RustcDecodable)] pub enum
{ dijkstra, pagerank } pub fn run_algorithm<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { match args.arg_algorithm { Algorithm::dijkstra => run_dijkstra(network, args, node_to_id), Algorithm::pagerank => run_pagerank(network, args, node_to_id), } } fn run_dijkstra<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { let start_id = match args.flag_start_node.as_ref() { Some(name) => node_to_id[name], None => DEFAULT_START_ID, }; let use_heap = args.flag_use_heap; let (pred, cost) = dijkstra(network, start_id, use_heap); print_dijkstra_result(&pred, &cost, &node_to_id) } fn run_pagerank<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { let beta = args.flag_beta.unwrap_or(DEFAULT_BETA); let eps = args.flag_eps.unwrap_or(DEFAULT_EPS); let ranks = pagerank(network, beta, eps); let target_node = args.flag_target_node.as_ref(); print_pagerank_results(&ranks, node_to_id, target_node); } fn get_node_name(i: &NodeId, id_to_node: &HashMap<NodeId, String>) -> String { id_to_node.get(i).unwrap_or(&"NONE".to_string()).to_string() } fn print_dijkstra_result(pred: &Vec<NodeId>, cost: &DoubleVec, node_to_id: &HashMap<String, NodeId>) { let id_to_node: HashMap<NodeId, String> = node_to_id.iter() .map(|(k,v)| (*v,k.clone())) .collect(); for i in (0..pred.len()).take(100) { let to_id = i as NodeId; let from_node = get_node_name(pred.get(i).unwrap(), &id_to_node); let to_node = get_node_name(&to_id, &id_to_node); let cum_cost = cost.get(i).unwrap(); println!("{} -> {} : {:4}", from_node, to_node, cum_cost); } } fn print_pagerank_results(ranks: &Vec<f64>, node_to_id: &HashMap<String, NodeId>, target_node: Option<&String>) { match target_node { None => println!("No target node given."), Some(name) => { let id = node_to_id[name] as usize; println!("Rank of node {}: {} ({:e})", name, ranks[id], ranks[id]); } } }
Algorithm
identifier_name
alg_runner.rs
use std::collections::HashMap; use network::{ DoubleVec, Network, NodeId }; use network::algorithms::{ dijkstra, pagerank }; use usage::{ DEFAULT_BETA, DEFAULT_EPS, DEFAULT_START_ID, Args }; #[derive(Debug, RustcDecodable)] pub enum Algorithm { dijkstra, pagerank } pub fn run_algorithm<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { match args.arg_algorithm { Algorithm::dijkstra => run_dijkstra(network, args, node_to_id), Algorithm::pagerank => run_pagerank(network, args, node_to_id), } } fn run_dijkstra<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { let start_id = match args.flag_start_node.as_ref() { Some(name) => node_to_id[name], None => DEFAULT_START_ID, }; let use_heap = args.flag_use_heap; let (pred, cost) = dijkstra(network, start_id, use_heap); print_dijkstra_result(&pred, &cost, &node_to_id) } fn run_pagerank<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { let beta = args.flag_beta.unwrap_or(DEFAULT_BETA); let eps = args.flag_eps.unwrap_or(DEFAULT_EPS); let ranks = pagerank(network, beta, eps); let target_node = args.flag_target_node.as_ref(); print_pagerank_results(&ranks, node_to_id, target_node); } fn get_node_name(i: &NodeId, id_to_node: &HashMap<NodeId, String>) -> String { id_to_node.get(i).unwrap_or(&"NONE".to_string()).to_string() } fn print_dijkstra_result(pred: &Vec<NodeId>, cost: &DoubleVec, node_to_id: &HashMap<String, NodeId>)
fn print_pagerank_results(ranks: &Vec<f64>, node_to_id: &HashMap<String, NodeId>, target_node: Option<&String>) { match target_node { None => println!("No target node given."), Some(name) => { let id = node_to_id[name] as usize; println!("Rank of node {}: {} ({:e})", name, ranks[id], ranks[id]); } } }
{ let id_to_node: HashMap<NodeId, String> = node_to_id.iter() .map(|(k,v)| (*v,k.clone())) .collect(); for i in (0..pred.len()).take(100) { let to_id = i as NodeId; let from_node = get_node_name(pred.get(i).unwrap(), &id_to_node); let to_node = get_node_name(&to_id, &id_to_node); let cum_cost = cost.get(i).unwrap(); println!("{} -> {} : {:4}", from_node, to_node, cum_cost); } }
identifier_body
syntax_extension_with_dll_deps_2.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. // force-host #![crate_type = "dylib"] #![feature(plugin_registrar, quote, rustc_private)] extern crate syntax_extension_with_dll_deps_1 as other; extern crate syntax; extern crate syntax_pos; extern crate rustc; extern crate rustc_plugin; use syntax::ast::{Item, MetaItem}; use syntax::ext::base::*; use syntax::tokenstream::TokenTree; use syntax_pos::Span; use rustc_plugin::Registry;
fn expand_foo(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { let answer = other::the_answer(); MacEager::expr(quote_expr!(cx, $answer)) }
#[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("foo", expand_foo); }
random_line_split
syntax_extension_with_dll_deps_2.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. // force-host #![crate_type = "dylib"] #![feature(plugin_registrar, quote, rustc_private)] extern crate syntax_extension_with_dll_deps_1 as other; extern crate syntax; extern crate syntax_pos; extern crate rustc; extern crate rustc_plugin; use syntax::ast::{Item, MetaItem}; use syntax::ext::base::*; use syntax::tokenstream::TokenTree; use syntax_pos::Span; use rustc_plugin::Registry; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("foo", expand_foo); } fn expand_foo(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static>
{ let answer = other::the_answer(); MacEager::expr(quote_expr!(cx, $answer)) }
identifier_body
syntax_extension_with_dll_deps_2.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. // force-host #![crate_type = "dylib"] #![feature(plugin_registrar, quote, rustc_private)] extern crate syntax_extension_with_dll_deps_1 as other; extern crate syntax; extern crate syntax_pos; extern crate rustc; extern crate rustc_plugin; use syntax::ast::{Item, MetaItem}; use syntax::ext::base::*; use syntax::tokenstream::TokenTree; use syntax_pos::Span; use rustc_plugin::Registry; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("foo", expand_foo); } fn
(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { let answer = other::the_answer(); MacEager::expr(quote_expr!(cx, $answer)) }
expand_foo
identifier_name
ui_ffi.rs
// Disable this warning until all code has been fixed #[allow(non_upper_case_globals)] extern crate bitflags; use std::os::raw::{c_char, c_float, c_int, c_uint, c_ushort, c_void}; use scintilla::PDUISCInterface; include!("ui_ffi_autogen.rs"); #[repr(C)] pub enum
{ Tab, // for tabbing through fields LeftArrow, // for text edit RightArrow,// for text edit UpArrow, // for text edit DownArrow, // for text edit PageUp, PageDown, Home, // for text edit End, // for text edit Delete, // for text edit Backspace, // for text edit Enter, // for text edit Escape, // for text edit A, // for text edit CTRL+A: select all C, // for text edit CTRL+C: copy V, // for text edit CTRL+V: paste X, // for text edit CTRL+X: cut Y, // for text edit CTRL+Y: redo Z, // for text edit CTRL+Z: undo }
ImguiKey
identifier_name
ui_ffi.rs
// Disable this warning until all code has been fixed #[allow(non_upper_case_globals)] extern crate bitflags; use std::os::raw::{c_char, c_float, c_int, c_uint, c_ushort, c_void}; use scintilla::PDUISCInterface; include!("ui_ffi_autogen.rs"); #[repr(C)] pub enum ImguiKey { Tab, // for tabbing through fields LeftArrow, // for text edit RightArrow,// for text edit UpArrow, // for text edit DownArrow, // for text edit PageUp, PageDown, Home, // for text edit End, // for text edit Delete, // for text edit Backspace, // for text edit Enter, // for text edit Escape, // for text edit A, // for text edit CTRL+A: select all
Z, // for text edit CTRL+Z: undo }
C, // for text edit CTRL+C: copy V, // for text edit CTRL+V: paste X, // for text edit CTRL+X: cut Y, // for text edit CTRL+Y: redo
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/. */ #![feature(append)] #![feature(arc_unique)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_raw)] #![feature(box_syntax)] #![feature(core)] #![feature(core_intrinsics)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(drain)] #![feature(hashmap_hasher)] #![feature(mpsc_select)] #![feature(nonzero)] #![feature(owned_ascii_ext)] #![feature(plugin)] #![feature(rc_unique)]
#![feature(vec_push_all)] #![deny(unsafe_code)] #![allow(non_snake_case)] #![doc="The script crate contains all matters DOM."] #![plugin(string_cache_plugin)] #![plugin(plugins)] #[macro_use] extern crate log; #[macro_use] extern crate bitflags; extern crate core; extern crate devtools_traits; extern crate cssparser; extern crate euclid; extern crate html5ever; extern crate encoding; extern crate fnv; extern crate hyper; extern crate ipc_channel; extern crate js; extern crate layout_traits; extern crate libc; extern crate msg; extern crate net_traits; extern crate num; extern crate rustc_serialize; extern crate rustc_unicode; extern crate serde; extern crate time; extern crate canvas; extern crate canvas_traits; extern crate rand; #[macro_use] extern crate profile_traits; extern crate script_traits; extern crate selectors; extern crate smallvec; extern crate util; extern crate websocket; #[macro_use] extern crate style; extern crate unicase; extern crate url; extern crate uuid; extern crate string_cache; extern crate offscreen_gl_context; extern crate tendril; pub mod cors; pub mod document_loader; #[macro_use] pub mod dom; pub mod parse; pub mod layout_interface; mod network_listener; pub mod page; pub mod script_task; mod timers; pub mod textinput; pub mod clipboard_provider; mod devtools; mod horribly_inefficient_timers; mod webdriver_handlers; #[allow(unsafe_code)] pub fn init() { unsafe { assert_eq!(js::jsapi::JS_Init(), 1); } }
#![feature(slice_chars)] #![feature(str_utf16)] #![feature(unicode)]
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/. */ #![feature(append)] #![feature(arc_unique)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_raw)] #![feature(box_syntax)] #![feature(core)] #![feature(core_intrinsics)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(drain)] #![feature(hashmap_hasher)] #![feature(mpsc_select)] #![feature(nonzero)] #![feature(owned_ascii_ext)] #![feature(plugin)] #![feature(rc_unique)] #![feature(slice_chars)] #![feature(str_utf16)] #![feature(unicode)] #![feature(vec_push_all)] #![deny(unsafe_code)] #![allow(non_snake_case)] #![doc="The script crate contains all matters DOM."] #![plugin(string_cache_plugin)] #![plugin(plugins)] #[macro_use] extern crate log; #[macro_use] extern crate bitflags; extern crate core; extern crate devtools_traits; extern crate cssparser; extern crate euclid; extern crate html5ever; extern crate encoding; extern crate fnv; extern crate hyper; extern crate ipc_channel; extern crate js; extern crate layout_traits; extern crate libc; extern crate msg; extern crate net_traits; extern crate num; extern crate rustc_serialize; extern crate rustc_unicode; extern crate serde; extern crate time; extern crate canvas; extern crate canvas_traits; extern crate rand; #[macro_use] extern crate profile_traits; extern crate script_traits; extern crate selectors; extern crate smallvec; extern crate util; extern crate websocket; #[macro_use] extern crate style; extern crate unicase; extern crate url; extern crate uuid; extern crate string_cache; extern crate offscreen_gl_context; extern crate tendril; pub mod cors; pub mod document_loader; #[macro_use] pub mod dom; pub mod parse; pub mod layout_interface; mod network_listener; pub mod page; pub mod script_task; mod timers; pub mod textinput; pub mod clipboard_provider; mod devtools; mod horribly_inefficient_timers; mod webdriver_handlers; #[allow(unsafe_code)] pub fn
() { unsafe { assert_eq!(js::jsapi::JS_Init(), 1); } }
init
identifier_name
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/. */ #![feature(append)] #![feature(arc_unique)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_raw)] #![feature(box_syntax)] #![feature(core)] #![feature(core_intrinsics)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(drain)] #![feature(hashmap_hasher)] #![feature(mpsc_select)] #![feature(nonzero)] #![feature(owned_ascii_ext)] #![feature(plugin)] #![feature(rc_unique)] #![feature(slice_chars)] #![feature(str_utf16)] #![feature(unicode)] #![feature(vec_push_all)] #![deny(unsafe_code)] #![allow(non_snake_case)] #![doc="The script crate contains all matters DOM."] #![plugin(string_cache_plugin)] #![plugin(plugins)] #[macro_use] extern crate log; #[macro_use] extern crate bitflags; extern crate core; extern crate devtools_traits; extern crate cssparser; extern crate euclid; extern crate html5ever; extern crate encoding; extern crate fnv; extern crate hyper; extern crate ipc_channel; extern crate js; extern crate layout_traits; extern crate libc; extern crate msg; extern crate net_traits; extern crate num; extern crate rustc_serialize; extern crate rustc_unicode; extern crate serde; extern crate time; extern crate canvas; extern crate canvas_traits; extern crate rand; #[macro_use] extern crate profile_traits; extern crate script_traits; extern crate selectors; extern crate smallvec; extern crate util; extern crate websocket; #[macro_use] extern crate style; extern crate unicase; extern crate url; extern crate uuid; extern crate string_cache; extern crate offscreen_gl_context; extern crate tendril; pub mod cors; pub mod document_loader; #[macro_use] pub mod dom; pub mod parse; pub mod layout_interface; mod network_listener; pub mod page; pub mod script_task; mod timers; pub mod textinput; pub mod clipboard_provider; mod devtools; mod horribly_inefficient_timers; mod webdriver_handlers; #[allow(unsafe_code)] pub fn init()
{ unsafe { assert_eq!(js::jsapi::JS_Init(), 1); } }
identifier_body
webgluniformlocation.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use webrender_traits::WebGLProgramId; #[dom_struct] pub struct WebGLUniformLocation { reflector_: Reflector, id: i32, program_id: WebGLProgramId, } impl WebGLUniformLocation { fn new_inherited(id: i32, program_id: WebGLProgramId) -> WebGLUniformLocation { WebGLUniformLocation { reflector_: Reflector::new(), id: id, program_id: program_id, } } pub fn new(global: GlobalRef, id: i32, program_id: WebGLProgramId) -> Root<WebGLUniformLocation> { reflect_dom_object(box WebGLUniformLocation::new_inherited(id, program_id), global, WebGLUniformLocationBinding::Wrap) } pub fn
(&self) -> i32 { self.id } pub fn program_id(&self) -> WebGLProgramId { self.program_id } }
id
identifier_name
webgluniformlocation.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use webrender_traits::WebGLProgramId; #[dom_struct] pub struct WebGLUniformLocation { reflector_: Reflector, id: i32, program_id: WebGLProgramId, } impl WebGLUniformLocation { fn new_inherited(id: i32, program_id: WebGLProgramId) -> WebGLUniformLocation { WebGLUniformLocation { reflector_: Reflector::new(), id: id, program_id: program_id, } } pub fn new(global: GlobalRef, id: i32, program_id: WebGLProgramId) -> Root<WebGLUniformLocation>
pub fn id(&self) -> i32 { self.id } pub fn program_id(&self) -> WebGLProgramId { self.program_id } }
{ reflect_dom_object(box WebGLUniformLocation::new_inherited(id, program_id), global, WebGLUniformLocationBinding::Wrap) }
identifier_body
problem-039.rs
// Copyright 2016 Peter Beard // Distributed under the GNU GPL v2. For full terms, see the LICENSE file. // // If p is the perimeter of a right angle triangle with integral length sides, // {a,b,c}, there are exactly three solutions for p = 120. // // {20,48,52}, {24,45,51}, {30,40,50} // // For which value of p ≤ 1000, is the number of solutions maximised? // #![feature(test)] extern crate test; /// Find the number of right triangles with integral sides for a given perimeter fn num_triangles(p: u32) -> u32 {
pub fn solution() -> u32 { let mut max = 0; let mut max_p = 0; for p in 1..1001 { // Perimeter will always be even if p % 2!= 0 { continue; } let count = num_triangles(p); if count > max { max = count; max_p = p; } } max_p } fn main() { println!("p = {} has the maximum number of solutions.", solution()); } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn correct() { assert_eq!(840, solution()); } #[bench] fn bench(b: &mut Bencher) { b.iter(|| solution()); } }
let mut count = 0; let psq = p*p; // a^2 + b^2 = c^2, a + b + c = p; substitute c = p - a - b and rearrange // solutions must satisfy 2p(a+b) = p^2 + ab // TODO: This can probably be simplified further, but algebra for a in 1..p { for b in 1..p { if 2*p*(a + b) == psq + a*b { count += 1; } } } count }
identifier_body
problem-039.rs
// Copyright 2016 Peter Beard // Distributed under the GNU GPL v2. For full terms, see the LICENSE file. // // If p is the perimeter of a right angle triangle with integral length sides, // {a,b,c}, there are exactly three solutions for p = 120. // // {20,48,52}, {24,45,51}, {30,40,50} // // For which value of p ≤ 1000, is the number of solutions maximised? // #![feature(test)] extern crate test; /// Find the number of right triangles with integral sides for a given perimeter fn num_triangles(p: u32) -> u32 { let mut count = 0; let psq = p*p; // a^2 + b^2 = c^2, a + b + c = p; substitute c = p - a - b and rearrange // solutions must satisfy 2p(a+b) = p^2 + ab // TODO: This can probably be simplified further, but algebra for a in 1..p { for b in 1..p {
} } } count } pub fn solution() -> u32 { let mut max = 0; let mut max_p = 0; for p in 1..1001 { // Perimeter will always be even if p % 2!= 0 { continue; } let count = num_triangles(p); if count > max { max = count; max_p = p; } } max_p } fn main() { println!("p = {} has the maximum number of solutions.", solution()); } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn correct() { assert_eq!(840, solution()); } #[bench] fn bench(b: &mut Bencher) { b.iter(|| solution()); } }
if 2*p*(a + b) == psq + a*b { count += 1;
random_line_split
problem-039.rs
// Copyright 2016 Peter Beard // Distributed under the GNU GPL v2. For full terms, see the LICENSE file. // // If p is the perimeter of a right angle triangle with integral length sides, // {a,b,c}, there are exactly three solutions for p = 120. // // {20,48,52}, {24,45,51}, {30,40,50} // // For which value of p ≤ 1000, is the number of solutions maximised? // #![feature(test)] extern crate test; /// Find the number of right triangles with integral sides for a given perimeter fn num_triangles(p: u32) -> u32 { let mut count = 0; let psq = p*p; // a^2 + b^2 = c^2, a + b + c = p; substitute c = p - a - b and rearrange // solutions must satisfy 2p(a+b) = p^2 + ab // TODO: This can probably be simplified further, but algebra for a in 1..p { for b in 1..p { if 2*p*(a + b) == psq + a*b { count += 1; } } } count } pub fn solution() -> u32 { let mut max = 0; let mut max_p = 0; for p in 1..1001 { // Perimeter will always be even if p % 2!= 0 { continue; } let count = num_triangles(p); if count > max { max = count; max_p = p; } } max_p } fn ma
{ println!("p = {} has the maximum number of solutions.", solution()); } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn correct() { assert_eq!(840, solution()); } #[bench] fn bench(b: &mut Bencher) { b.iter(|| solution()); } }
in()
identifier_name
problem-039.rs
// Copyright 2016 Peter Beard // Distributed under the GNU GPL v2. For full terms, see the LICENSE file. // // If p is the perimeter of a right angle triangle with integral length sides, // {a,b,c}, there are exactly three solutions for p = 120. // // {20,48,52}, {24,45,51}, {30,40,50} // // For which value of p ≤ 1000, is the number of solutions maximised? // #![feature(test)] extern crate test; /// Find the number of right triangles with integral sides for a given perimeter fn num_triangles(p: u32) -> u32 { let mut count = 0; let psq = p*p; // a^2 + b^2 = c^2, a + b + c = p; substitute c = p - a - b and rearrange // solutions must satisfy 2p(a+b) = p^2 + ab // TODO: This can probably be simplified further, but algebra for a in 1..p { for b in 1..p { if 2*p*(a + b) == psq + a*b {
} } count } pub fn solution() -> u32 { let mut max = 0; let mut max_p = 0; for p in 1..1001 { // Perimeter will always be even if p % 2!= 0 { continue; } let count = num_triangles(p); if count > max { max = count; max_p = p; } } max_p } fn main() { println!("p = {} has the maximum number of solutions.", solution()); } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn correct() { assert_eq!(840, solution()); } #[bench] fn bench(b: &mut Bencher) { b.iter(|| solution()); } }
count += 1; }
conditional_block
sub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{BuiltinBounds}; use middle::ty; use middle::ty::TyVar; use middle::typeck::check::regionmanip::replace_late_bound_regions_in_fn_sig; use middle::typeck::infer::combine::*; use middle::typeck::infer::{cres, CresCompare}; use middle::typeck::infer::glb::Glb; use middle::typeck::infer::InferCtxt; use middle::typeck::infer::lattice::CombineFieldsLatticeMethods; use middle::typeck::infer::lub::Lub; use middle::typeck::infer::then; use middle::typeck::infer::to_str::InferStr; use middle::typeck::infer::{TypeTrace, Subtype}; use util::common::{indenter}; use util::ppaux::bound_region_to_str; use syntax::ast::{Onceness, FnStyle}; pub struct Sub<'f>(pub CombineFields<'f>); // "subtype", "subregion" etc impl<'f> Sub<'f> { pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> { let Sub(ref v) = *self; v } } impl<'f> Combine for Sub<'f> { fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx } fn tag(&self) -> ~str { ~"sub" } fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected } fn trace(&self) -> TypeTrace { self.get_ref().trace } fn sub<'a>(&'a self) -> Sub<'a> { Sub(*self.get_ref()) } fn lub<'a>(&'a self) -> Lub<'a> { Lub(*self.get_ref()) } fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) } fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t> { let opp = CombineFields { a_is_expected:!self.get_ref().a_is_expected,.. *self.get_ref() }; Sub(opp).tys(b, a) } fn contraregions(&self, a: ty::Region, b: ty::Region) -> cres<ty::Region> { let opp = CombineFields { a_is_expected:!self.get_ref().a_is_expected,.. *self.get_ref() }; Sub(opp).regions(b, a) } fn regions(&self, a: ty::Region, b: ty::Region) -> cres<ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); self.get_ref().infcx.region_vars.make_subregion(Subtype(self.get_ref().trace), a, b); Ok(a) } fn mts(&self, a: &ty::mt, b: &ty::mt) -> cres<ty::mt> { debug!("mts({} <: {})", a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); if a.mutbl!= b.mutbl { return Err(ty::terr_mutability); } match b.mutbl { MutMutable => { // If supertype is mut, subtype must match exactly // (i.e., invariant if mut): eq_tys(self, a.ty, b.ty).then(|| Ok(*a)) } MutImmutable => { // Otherwise we can be covariant: self.tys(a.ty, b.ty).and_then(|_t| Ok(*a) ) } } } fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<FnStyle> { self.lub().fn_styles(a, b).compare(b, || { ty::terr_fn_style_mismatch(expected_found(self, a, b)) }) } fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<Onceness> { self.lub().oncenesses(a, b).compare(b, || { ty::terr_onceness_mismatch(expected_found(self, a, b)) }) } fn bounds(&self, a: BuiltinBounds, b: BuiltinBounds) -> cres<BuiltinBounds> { // More bounds is a subtype of fewer bounds. // // e.g., fn:Copy() <: fn(), because the former is a function // that only closes over copyable things, but the latter is // any function at all. if a.contains(b) { Ok(a) } else { Err(ty::terr_builtin_bounds(expected_found(self, a, b))) } } fn tys(&self, a: ty::t, b: ty::t) -> cres<ty::t> { debug!("{}.tys({}, {})", self.tag(), a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); if a == b { return Ok(a); } let _indenter = indenter(); match (&ty::get(a).sty, &ty::get(b).sty) { (&ty::ty_bot, _) => { Ok(a) } (&ty::ty_infer(TyVar(a_id)), &ty::ty_infer(TyVar(b_id))) => { if_ok!(self.get_ref().var_sub_var(a_id, b_id)); Ok(a) } (&ty::ty_infer(TyVar(a_id)), _) => { if_ok!(self.get_ref().var_sub_t(a_id, b)); Ok(a) } (_, &ty::ty_infer(TyVar(b_id))) => { if_ok!(self.get_ref().t_sub_var(a, b_id)); Ok(a) } (_, &ty::ty_bot) => { Err(ty::terr_sorts(expected_found(self, a, b))) } _ => { super_tys(self, a, b) } } } fn fn_sigs(&self, a: &ty::FnSig, b: &ty::FnSig) -> cres<ty::FnSig> { debug!("fn_sigs(a={}, b={})", a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); let _indenter = indenter(); // Rather than checking the subtype relationship between `a` and `b` // as-is, we need to do some extra work here in order to make sure // that function subtyping works correctly with respect to regions // // Note: this is a subtle algorithm. For a full explanation, // please see the large comment in `region_inference.rs`. // Take a snapshot. We'll never roll this back, but in later // phases we do want to be able to examine "all bindings that // were created as part of this type comparison", and making a // snapshot is a convenient way to do that. let snapshot = self.get_ref().infcx.region_vars.start_snapshot(); // First, we instantiate each bound region in the subtype with a fresh // region variable. let (a_sig, _) = self.get_ref().infcx.replace_late_bound_regions_with_fresh_regions( self.get_ref().trace, a); // Second, we instantiate each bound region in the supertype with a // fresh concrete region. let (skol_map, b_sig) = { replace_late_bound_regions_in_fn_sig(self.get_ref().infcx.tcx, b, |br| { let skol = self.get_ref().infcx.region_vars.new_skolemized(br); debug!("Bound region {} skolemized to {:?}", bound_region_to_str(self.get_ref().infcx.tcx, "", false, br), skol); skol }) }; debug!("a_sig={}", a_sig.inf_str(self.get_ref().infcx)); debug!("b_sig={}", b_sig.inf_str(self.get_ref().infcx)); // Compare types now that bound regions have been replaced. let sig = if_ok!(super_fn_sigs(self, &a_sig, &b_sig)); // Presuming type comparison succeeds, we need to check // that the skolemized regions do not "leak". let new_vars = self.get_ref().infcx.region_vars.vars_created_since_snapshot(snapshot); for (&skol_br, &skol) in skol_map.iter() { let tainted = self.get_ref().infcx.region_vars.tainted(snapshot, skol); for tainted_region in tainted.iter() { // Each skolemized should only be relatable to itself // or new variables: match *tainted_region { ty::ReInfer(ty::ReVar(ref vid)) => { if new_vars.iter().any(|x| x == vid) { continue; } } _ => { if *tainted_region == skol { continue; } } }; // A is not as polymorphic as B: if self.a_is_expected() { return Err(ty::terr_regions_insufficiently_polymorphic( skol_br, *tainted_region)); } else { return Err(ty::terr_regions_overly_polymorphic( skol_br, *tainted_region)); } } } return Ok(sig); } }
random_line_split
sub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{BuiltinBounds}; use middle::ty; use middle::ty::TyVar; use middle::typeck::check::regionmanip::replace_late_bound_regions_in_fn_sig; use middle::typeck::infer::combine::*; use middle::typeck::infer::{cres, CresCompare}; use middle::typeck::infer::glb::Glb; use middle::typeck::infer::InferCtxt; use middle::typeck::infer::lattice::CombineFieldsLatticeMethods; use middle::typeck::infer::lub::Lub; use middle::typeck::infer::then; use middle::typeck::infer::to_str::InferStr; use middle::typeck::infer::{TypeTrace, Subtype}; use util::common::{indenter}; use util::ppaux::bound_region_to_str; use syntax::ast::{Onceness, FnStyle}; pub struct Sub<'f>(pub CombineFields<'f>); // "subtype", "subregion" etc impl<'f> Sub<'f> { pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> { let Sub(ref v) = *self; v } } impl<'f> Combine for Sub<'f> { fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx } fn tag(&self) -> ~str { ~"sub" } fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected } fn trace(&self) -> TypeTrace { self.get_ref().trace } fn sub<'a>(&'a self) -> Sub<'a> { Sub(*self.get_ref()) } fn
<'a>(&'a self) -> Lub<'a> { Lub(*self.get_ref()) } fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) } fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t> { let opp = CombineFields { a_is_expected:!self.get_ref().a_is_expected,.. *self.get_ref() }; Sub(opp).tys(b, a) } fn contraregions(&self, a: ty::Region, b: ty::Region) -> cres<ty::Region> { let opp = CombineFields { a_is_expected:!self.get_ref().a_is_expected,.. *self.get_ref() }; Sub(opp).regions(b, a) } fn regions(&self, a: ty::Region, b: ty::Region) -> cres<ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); self.get_ref().infcx.region_vars.make_subregion(Subtype(self.get_ref().trace), a, b); Ok(a) } fn mts(&self, a: &ty::mt, b: &ty::mt) -> cres<ty::mt> { debug!("mts({} <: {})", a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); if a.mutbl!= b.mutbl { return Err(ty::terr_mutability); } match b.mutbl { MutMutable => { // If supertype is mut, subtype must match exactly // (i.e., invariant if mut): eq_tys(self, a.ty, b.ty).then(|| Ok(*a)) } MutImmutable => { // Otherwise we can be covariant: self.tys(a.ty, b.ty).and_then(|_t| Ok(*a) ) } } } fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<FnStyle> { self.lub().fn_styles(a, b).compare(b, || { ty::terr_fn_style_mismatch(expected_found(self, a, b)) }) } fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<Onceness> { self.lub().oncenesses(a, b).compare(b, || { ty::terr_onceness_mismatch(expected_found(self, a, b)) }) } fn bounds(&self, a: BuiltinBounds, b: BuiltinBounds) -> cres<BuiltinBounds> { // More bounds is a subtype of fewer bounds. // // e.g., fn:Copy() <: fn(), because the former is a function // that only closes over copyable things, but the latter is // any function at all. if a.contains(b) { Ok(a) } else { Err(ty::terr_builtin_bounds(expected_found(self, a, b))) } } fn tys(&self, a: ty::t, b: ty::t) -> cres<ty::t> { debug!("{}.tys({}, {})", self.tag(), a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); if a == b { return Ok(a); } let _indenter = indenter(); match (&ty::get(a).sty, &ty::get(b).sty) { (&ty::ty_bot, _) => { Ok(a) } (&ty::ty_infer(TyVar(a_id)), &ty::ty_infer(TyVar(b_id))) => { if_ok!(self.get_ref().var_sub_var(a_id, b_id)); Ok(a) } (&ty::ty_infer(TyVar(a_id)), _) => { if_ok!(self.get_ref().var_sub_t(a_id, b)); Ok(a) } (_, &ty::ty_infer(TyVar(b_id))) => { if_ok!(self.get_ref().t_sub_var(a, b_id)); Ok(a) } (_, &ty::ty_bot) => { Err(ty::terr_sorts(expected_found(self, a, b))) } _ => { super_tys(self, a, b) } } } fn fn_sigs(&self, a: &ty::FnSig, b: &ty::FnSig) -> cres<ty::FnSig> { debug!("fn_sigs(a={}, b={})", a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); let _indenter = indenter(); // Rather than checking the subtype relationship between `a` and `b` // as-is, we need to do some extra work here in order to make sure // that function subtyping works correctly with respect to regions // // Note: this is a subtle algorithm. For a full explanation, // please see the large comment in `region_inference.rs`. // Take a snapshot. We'll never roll this back, but in later // phases we do want to be able to examine "all bindings that // were created as part of this type comparison", and making a // snapshot is a convenient way to do that. let snapshot = self.get_ref().infcx.region_vars.start_snapshot(); // First, we instantiate each bound region in the subtype with a fresh // region variable. let (a_sig, _) = self.get_ref().infcx.replace_late_bound_regions_with_fresh_regions( self.get_ref().trace, a); // Second, we instantiate each bound region in the supertype with a // fresh concrete region. let (skol_map, b_sig) = { replace_late_bound_regions_in_fn_sig(self.get_ref().infcx.tcx, b, |br| { let skol = self.get_ref().infcx.region_vars.new_skolemized(br); debug!("Bound region {} skolemized to {:?}", bound_region_to_str(self.get_ref().infcx.tcx, "", false, br), skol); skol }) }; debug!("a_sig={}", a_sig.inf_str(self.get_ref().infcx)); debug!("b_sig={}", b_sig.inf_str(self.get_ref().infcx)); // Compare types now that bound regions have been replaced. let sig = if_ok!(super_fn_sigs(self, &a_sig, &b_sig)); // Presuming type comparison succeeds, we need to check // that the skolemized regions do not "leak". let new_vars = self.get_ref().infcx.region_vars.vars_created_since_snapshot(snapshot); for (&skol_br, &skol) in skol_map.iter() { let tainted = self.get_ref().infcx.region_vars.tainted(snapshot, skol); for tainted_region in tainted.iter() { // Each skolemized should only be relatable to itself // or new variables: match *tainted_region { ty::ReInfer(ty::ReVar(ref vid)) => { if new_vars.iter().any(|x| x == vid) { continue; } } _ => { if *tainted_region == skol { continue; } } }; // A is not as polymorphic as B: if self.a_is_expected() { return Err(ty::terr_regions_insufficiently_polymorphic( skol_br, *tainted_region)); } else { return Err(ty::terr_regions_overly_polymorphic( skol_br, *tainted_region)); } } } return Ok(sig); } }
lub
identifier_name
sub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{BuiltinBounds}; use middle::ty; use middle::ty::TyVar; use middle::typeck::check::regionmanip::replace_late_bound_regions_in_fn_sig; use middle::typeck::infer::combine::*; use middle::typeck::infer::{cres, CresCompare}; use middle::typeck::infer::glb::Glb; use middle::typeck::infer::InferCtxt; use middle::typeck::infer::lattice::CombineFieldsLatticeMethods; use middle::typeck::infer::lub::Lub; use middle::typeck::infer::then; use middle::typeck::infer::to_str::InferStr; use middle::typeck::infer::{TypeTrace, Subtype}; use util::common::{indenter}; use util::ppaux::bound_region_to_str; use syntax::ast::{Onceness, FnStyle}; pub struct Sub<'f>(pub CombineFields<'f>); // "subtype", "subregion" etc impl<'f> Sub<'f> { pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> { let Sub(ref v) = *self; v } } impl<'f> Combine for Sub<'f> { fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx } fn tag(&self) -> ~str { ~"sub" } fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected } fn trace(&self) -> TypeTrace { self.get_ref().trace } fn sub<'a>(&'a self) -> Sub<'a> { Sub(*self.get_ref()) } fn lub<'a>(&'a self) -> Lub<'a>
fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) } fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t> { let opp = CombineFields { a_is_expected:!self.get_ref().a_is_expected,.. *self.get_ref() }; Sub(opp).tys(b, a) } fn contraregions(&self, a: ty::Region, b: ty::Region) -> cres<ty::Region> { let opp = CombineFields { a_is_expected:!self.get_ref().a_is_expected,.. *self.get_ref() }; Sub(opp).regions(b, a) } fn regions(&self, a: ty::Region, b: ty::Region) -> cres<ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); self.get_ref().infcx.region_vars.make_subregion(Subtype(self.get_ref().trace), a, b); Ok(a) } fn mts(&self, a: &ty::mt, b: &ty::mt) -> cres<ty::mt> { debug!("mts({} <: {})", a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); if a.mutbl!= b.mutbl { return Err(ty::terr_mutability); } match b.mutbl { MutMutable => { // If supertype is mut, subtype must match exactly // (i.e., invariant if mut): eq_tys(self, a.ty, b.ty).then(|| Ok(*a)) } MutImmutable => { // Otherwise we can be covariant: self.tys(a.ty, b.ty).and_then(|_t| Ok(*a) ) } } } fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<FnStyle> { self.lub().fn_styles(a, b).compare(b, || { ty::terr_fn_style_mismatch(expected_found(self, a, b)) }) } fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<Onceness> { self.lub().oncenesses(a, b).compare(b, || { ty::terr_onceness_mismatch(expected_found(self, a, b)) }) } fn bounds(&self, a: BuiltinBounds, b: BuiltinBounds) -> cres<BuiltinBounds> { // More bounds is a subtype of fewer bounds. // // e.g., fn:Copy() <: fn(), because the former is a function // that only closes over copyable things, but the latter is // any function at all. if a.contains(b) { Ok(a) } else { Err(ty::terr_builtin_bounds(expected_found(self, a, b))) } } fn tys(&self, a: ty::t, b: ty::t) -> cres<ty::t> { debug!("{}.tys({}, {})", self.tag(), a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); if a == b { return Ok(a); } let _indenter = indenter(); match (&ty::get(a).sty, &ty::get(b).sty) { (&ty::ty_bot, _) => { Ok(a) } (&ty::ty_infer(TyVar(a_id)), &ty::ty_infer(TyVar(b_id))) => { if_ok!(self.get_ref().var_sub_var(a_id, b_id)); Ok(a) } (&ty::ty_infer(TyVar(a_id)), _) => { if_ok!(self.get_ref().var_sub_t(a_id, b)); Ok(a) } (_, &ty::ty_infer(TyVar(b_id))) => { if_ok!(self.get_ref().t_sub_var(a, b_id)); Ok(a) } (_, &ty::ty_bot) => { Err(ty::terr_sorts(expected_found(self, a, b))) } _ => { super_tys(self, a, b) } } } fn fn_sigs(&self, a: &ty::FnSig, b: &ty::FnSig) -> cres<ty::FnSig> { debug!("fn_sigs(a={}, b={})", a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); let _indenter = indenter(); // Rather than checking the subtype relationship between `a` and `b` // as-is, we need to do some extra work here in order to make sure // that function subtyping works correctly with respect to regions // // Note: this is a subtle algorithm. For a full explanation, // please see the large comment in `region_inference.rs`. // Take a snapshot. We'll never roll this back, but in later // phases we do want to be able to examine "all bindings that // were created as part of this type comparison", and making a // snapshot is a convenient way to do that. let snapshot = self.get_ref().infcx.region_vars.start_snapshot(); // First, we instantiate each bound region in the subtype with a fresh // region variable. let (a_sig, _) = self.get_ref().infcx.replace_late_bound_regions_with_fresh_regions( self.get_ref().trace, a); // Second, we instantiate each bound region in the supertype with a // fresh concrete region. let (skol_map, b_sig) = { replace_late_bound_regions_in_fn_sig(self.get_ref().infcx.tcx, b, |br| { let skol = self.get_ref().infcx.region_vars.new_skolemized(br); debug!("Bound region {} skolemized to {:?}", bound_region_to_str(self.get_ref().infcx.tcx, "", false, br), skol); skol }) }; debug!("a_sig={}", a_sig.inf_str(self.get_ref().infcx)); debug!("b_sig={}", b_sig.inf_str(self.get_ref().infcx)); // Compare types now that bound regions have been replaced. let sig = if_ok!(super_fn_sigs(self, &a_sig, &b_sig)); // Presuming type comparison succeeds, we need to check // that the skolemized regions do not "leak". let new_vars = self.get_ref().infcx.region_vars.vars_created_since_snapshot(snapshot); for (&skol_br, &skol) in skol_map.iter() { let tainted = self.get_ref().infcx.region_vars.tainted(snapshot, skol); for tainted_region in tainted.iter() { // Each skolemized should only be relatable to itself // or new variables: match *tainted_region { ty::ReInfer(ty::ReVar(ref vid)) => { if new_vars.iter().any(|x| x == vid) { continue; } } _ => { if *tainted_region == skol { continue; } } }; // A is not as polymorphic as B: if self.a_is_expected() { return Err(ty::terr_regions_insufficiently_polymorphic( skol_br, *tainted_region)); } else { return Err(ty::terr_regions_overly_polymorphic( skol_br, *tainted_region)); } } } return Ok(sig); } }
{ Lub(*self.get_ref()) }
identifier_body
overloaded-deref-count.rs
// run-pass use std::cell::Cell; use std::ops::{Deref, DerefMut}; use std::vec::Vec; struct DerefCounter<T> { count_imm: Cell<usize>, count_mut: usize, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts(&self) -> (usize, usize) { (self.count_imm.get(), self.count_mut) } } impl<T> Deref for DerefCounter<T> { type Target = T; fn deref(&self) -> &T { self.count_imm.set(self.count_imm.get() + 1); &self.value } } impl<T> DerefMut for DerefCounter<T> { fn deref_mut(&mut self) -> &mut T
} pub fn main() { let mut n = DerefCounter::new(0); let mut v = DerefCounter::new(Vec::new()); let _ = *n; // Immutable deref + copy a POD. assert_eq!(n.counts(), (1, 0)); let _ = (&*n, &*v); // Immutable deref + borrow. assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0)); let _ = (&mut *n, &mut *v); // Mutable deref + mutable borrow. assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1)); let mut v2 = Vec::new(); v2.push(1); *n = 5; *v = v2; // Mutable deref + assignment. assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2)); *n -= 3; // Mutable deref + assignment with binary operation. assert_eq!(n.counts(), (2, 3)); // Immutable deref used for calling a method taking &self. (The // typechecker is smarter now about doing this.) (*n).to_string(); assert_eq!(n.counts(), (3, 3)); // Mutable deref used for calling a method taking &mut self. (*v).push(2); assert_eq!(v.counts(), (1, 3)); // Check the final states. assert_eq!(*n, 2); let expected: &[_] = &[1, 2]; assert_eq!((*v), expected); }
{ self.count_mut += 1; &mut self.value }
identifier_body
overloaded-deref-count.rs
// run-pass
use std::vec::Vec; struct DerefCounter<T> { count_imm: Cell<usize>, count_mut: usize, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts(&self) -> (usize, usize) { (self.count_imm.get(), self.count_mut) } } impl<T> Deref for DerefCounter<T> { type Target = T; fn deref(&self) -> &T { self.count_imm.set(self.count_imm.get() + 1); &self.value } } impl<T> DerefMut for DerefCounter<T> { fn deref_mut(&mut self) -> &mut T { self.count_mut += 1; &mut self.value } } pub fn main() { let mut n = DerefCounter::new(0); let mut v = DerefCounter::new(Vec::new()); let _ = *n; // Immutable deref + copy a POD. assert_eq!(n.counts(), (1, 0)); let _ = (&*n, &*v); // Immutable deref + borrow. assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0)); let _ = (&mut *n, &mut *v); // Mutable deref + mutable borrow. assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1)); let mut v2 = Vec::new(); v2.push(1); *n = 5; *v = v2; // Mutable deref + assignment. assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2)); *n -= 3; // Mutable deref + assignment with binary operation. assert_eq!(n.counts(), (2, 3)); // Immutable deref used for calling a method taking &self. (The // typechecker is smarter now about doing this.) (*n).to_string(); assert_eq!(n.counts(), (3, 3)); // Mutable deref used for calling a method taking &mut self. (*v).push(2); assert_eq!(v.counts(), (1, 3)); // Check the final states. assert_eq!(*n, 2); let expected: &[_] = &[1, 2]; assert_eq!((*v), expected); }
use std::cell::Cell; use std::ops::{Deref, DerefMut};
random_line_split
overloaded-deref-count.rs
// run-pass use std::cell::Cell; use std::ops::{Deref, DerefMut}; use std::vec::Vec; struct
<T> { count_imm: Cell<usize>, count_mut: usize, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts(&self) -> (usize, usize) { (self.count_imm.get(), self.count_mut) } } impl<T> Deref for DerefCounter<T> { type Target = T; fn deref(&self) -> &T { self.count_imm.set(self.count_imm.get() + 1); &self.value } } impl<T> DerefMut for DerefCounter<T> { fn deref_mut(&mut self) -> &mut T { self.count_mut += 1; &mut self.value } } pub fn main() { let mut n = DerefCounter::new(0); let mut v = DerefCounter::new(Vec::new()); let _ = *n; // Immutable deref + copy a POD. assert_eq!(n.counts(), (1, 0)); let _ = (&*n, &*v); // Immutable deref + borrow. assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0)); let _ = (&mut *n, &mut *v); // Mutable deref + mutable borrow. assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1)); let mut v2 = Vec::new(); v2.push(1); *n = 5; *v = v2; // Mutable deref + assignment. assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2)); *n -= 3; // Mutable deref + assignment with binary operation. assert_eq!(n.counts(), (2, 3)); // Immutable deref used for calling a method taking &self. (The // typechecker is smarter now about doing this.) (*n).to_string(); assert_eq!(n.counts(), (3, 3)); // Mutable deref used for calling a method taking &mut self. (*v).push(2); assert_eq!(v.counts(), (1, 3)); // Check the final states. assert_eq!(*n, 2); let expected: &[_] = &[1, 2]; assert_eq!((*v), expected); }
DerefCounter
identifier_name
uuid.rs
//! Conversions between ULID and UUID. use crate::Ulid; use uuid::Uuid; impl From<Uuid> for Ulid { fn from(uuid: Uuid) -> Self { Ulid(uuid.as_u128()) } } impl From<Ulid> for Uuid { fn from(ulid: Ulid) -> Self { Uuid::from_u128(ulid.0) } } #[cfg(test)] mod test { use super::*; #[test] fn uuid_cycle() { let ulid = Ulid::new(); let uuid: Uuid = ulid.into(); let ulid2: Ulid = uuid.into(); assert_eq!(ulid, ulid2); } #[test] fn
() { let uuid_txt = "771a3bce-02e9-4428-a68e-b1e7e82b7f9f"; let ulid_txt = "3Q38XWW0Q98GMAD3NHWZM2PZWZ"; let ulid: Ulid = Uuid::parse_str(uuid_txt).unwrap().into(); assert_eq!(ulid.to_string(), ulid_txt); let uuid: Uuid = ulid.into(); assert_eq!(uuid.to_string(), uuid_txt); } }
uuid_str_cycle
identifier_name
uuid.rs
//! Conversions between ULID and UUID. use crate::Ulid; use uuid::Uuid; impl From<Uuid> for Ulid { fn from(uuid: Uuid) -> Self { Ulid(uuid.as_u128()) } } impl From<Ulid> for Uuid { fn from(ulid: Ulid) -> Self
} #[cfg(test)] mod test { use super::*; #[test] fn uuid_cycle() { let ulid = Ulid::new(); let uuid: Uuid = ulid.into(); let ulid2: Ulid = uuid.into(); assert_eq!(ulid, ulid2); } #[test] fn uuid_str_cycle() { let uuid_txt = "771a3bce-02e9-4428-a68e-b1e7e82b7f9f"; let ulid_txt = "3Q38XWW0Q98GMAD3NHWZM2PZWZ"; let ulid: Ulid = Uuid::parse_str(uuid_txt).unwrap().into(); assert_eq!(ulid.to_string(), ulid_txt); let uuid: Uuid = ulid.into(); assert_eq!(uuid.to_string(), uuid_txt); } }
{ Uuid::from_u128(ulid.0) }
identifier_body
uuid.rs
//! Conversions between ULID and UUID.
fn from(uuid: Uuid) -> Self { Ulid(uuid.as_u128()) } } impl From<Ulid> for Uuid { fn from(ulid: Ulid) -> Self { Uuid::from_u128(ulid.0) } } #[cfg(test)] mod test { use super::*; #[test] fn uuid_cycle() { let ulid = Ulid::new(); let uuid: Uuid = ulid.into(); let ulid2: Ulid = uuid.into(); assert_eq!(ulid, ulid2); } #[test] fn uuid_str_cycle() { let uuid_txt = "771a3bce-02e9-4428-a68e-b1e7e82b7f9f"; let ulid_txt = "3Q38XWW0Q98GMAD3NHWZM2PZWZ"; let ulid: Ulid = Uuid::parse_str(uuid_txt).unwrap().into(); assert_eq!(ulid.to_string(), ulid_txt); let uuid: Uuid = ulid.into(); assert_eq!(uuid.to_string(), uuid_txt); } }
use crate::Ulid; use uuid::Uuid; impl From<Uuid> for Ulid {
random_line_split
mv.rs
#![crate_name = "uu_mv"] /* * This file is part of the uutils coreutils package. * * (c) Orvar Segerström <[email protected]> * (c) Sokovikov Evgeniy <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use std::fs; use std::io::{BufRead, BufReader, Result, stdin, Write}; use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; static NAME: &'static str = "mv"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub struct Behaviour { overwrite: OverwriteMode, backup: BackupMode, suffix: String, update: bool, target_dir: Option<String>, no_target_dir: bool, verbose: bool, } #[derive(Clone, Eq, PartialEq)] pub enum OverwriteMode { NoClobber, Interactive, Force, } #[derive(Clone, Eq, PartialEq)] pub enum BackupMode { NoBackup, SimpleBackup, NumberedBackup, ExistingBackup, } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflagopt("", "backup", "make a backup of each existing destination file", "CONTROL"); opts.optflag("b", "", "like --backup but does not accept an argument"); opts.optflag("f", "force", "do not prompt before overwriting"); opts.optflag("i", "interactive", "prompt before override"); opts.optflag("n", "no-clobber", "do not overwrite an existing file"); opts.optflag("", "strip-trailing-slashes", "remove any trailing slashes from each SOURCE\n \ argument"); opts.optopt("S", "suffix", "override the usual backup suffix", "SUFFIX"); opts.optopt("t", "target-directory", "move all SOURCE arguments into DIRECTORY", "DIRECTORY"); opts.optflag("T", "no-target-directory", "treat DEST as a normal file"); opts.optflag("u", "update", "move only when the SOURCE file is newer\n \ than the destination file or when the\n \ destination file is missing"); opts.optflag("v", "verbose", "explain what is being done"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("Invalid options\n{}", f); return 1; } }; let usage = opts.usage("Move SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY."); /* This does not exactly match the GNU implementation: * The GNU mv defaults to Force, but if more than one of the * overwrite options are supplied, only the last takes effect. * To default to no-clobber in that situation seems safer: */ let overwrite_mode = if matches.opt_present("no-clobber") { OverwriteMode::NoClobber } else if matches.opt_present("interactive") { OverwriteMode::Interactive } else { OverwriteMode::Force }; let backup_mode = if matches.opt_present("b") { BackupMode::SimpleBackup } else if matches.opt_present("backup") { match matches.opt_str("backup") { None => BackupMode::SimpleBackup, Some(mode) => match &mode[..] { "simple" | "never" => BackupMode::SimpleBackup, "numbered" | "t" => BackupMode::NumberedBackup, "existing" | "nil" => BackupMode::ExistingBackup, "none" | "off" => BackupMode::NoBackup, x => { show_error!("invalid argument ‘{}’ for ‘backup type’\n\ Try '{} --help' for more information.", x, NAME); return 1; } } } } else { BackupMode::NoBackup }; if overwrite_mode == OverwriteMode::NoClobber && backup_mode!= BackupMode::NoBackup { show_error!("options --backup and --no-clobber are mutually exclusive\n\ Try '{} --help' for more information.", NAME); return 1; } let backup_suffix = if matches.opt_present("suffix") { match matches.opt_str("suffix") { Some(x) => x, None => { show_error!("option '--suffix' requires an argument\n\ Try '{} --help' for more information.", NAME); return 1; } } } else { "~".to_owned() }; if matches.opt_present("T") && matches.opt_present("t") { show_error!("cannot combine --target-directory (-t) and --no-target-directory (-T)"); return 1; } let behaviour = Behaviour { overwrite: overwrite_mode, backup: backup_mode, suffix: backup_suffix, update: matches.opt_present("u"), target_dir: matches.opt_str("t"), no_target_dir: matches.opt_present("T"), verbose: matches.opt_present("v"), }; let paths: Vec<PathBuf> = { fn string_to_path<'a>(s: &'a String) -> &'a Path { Path::new(s) }; fn strip_slashes<'a>(p: &'a Path) -> &'a Path { p.components().as_path() } let to_owned = |p: &Path| p.to_owned(); let arguments = matches.free.iter().map(string_to_path); if matches.opt_present("strip-trailing-slashes") { arguments.map(strip_slashes).map(to_owned).collect() } else { arguments.map(to_owned).collect() } }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); 0 } else if matches.opt_present("help") { help(&usage); 0 } else { exec(&paths[..], behaviour) } } fn help(usage: &str) { println!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n\n\ {2}", NAME, VERSION, usage); } fn exec(files: &[PathBuf], b: Behaviour) -> i32 { match b.target_dir { Some(ref name) => return move_files_into_dir(files, &PathBuf::from(name), &b), None => {} } match files.len() { 0 | 1 => { show_error!("missing file operand\n\ Try '{} --help' for more information.", NAME); return 1; }, 2 => { let source = &files[0]; let target = &files[1]; if!source.exists() { show_error!("cannot stat ‘{}’: No such file or directory", source.display()); return 1; } if target.is_dir() { if b.no_target_dir { if!source.is_dir() { show_error!("cannot overwrite directory ‘{}’ with non-directory", target.display()); return 1; } return match rename(source, target, &b) { Err(e) => { show_error!("{}", e); 1 }, _ => 0 } } return move_files_into_dir(&[source.clone()], target, &b); } if let Err(e) = rename(source, target, &b) { show_error!("{}", e); return 1; } } _ => { if b.no_target_dir { show_error!("mv: extra operand ‘{}’\n\ Try '{} --help' for more information.", files[2].display(), NAME); return 1; } let target_dir = files.last().unwrap(); move_files_into_dir(&files[0..files.len()-1], target_dir, &b); } } 0 } fn move_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behaviour) -> i32 { if!target_dir.is_dir() { show_error!("target ‘{}’ is not a directory", target_dir.display()); return 1; } let mut all_successful = true; for sourcepath in files.iter() { let targetpath = match sourcepath.as_os_str().to_str() { Some(name) => target_dir.join(name), None => { show_error!("cannot stat ‘{}’: No such file or directory", sourcepath.display()); all_successful = false; continue; } }; if let Err(e) = rename(sourcepath, &targetpath, b) { show_error!("mv: cannot move ‘{}’ to ‘{}’: {}", sourcepath.display(), targetpath.display(), e); all_successful = false; } }; if all_successful { 0 } else { 1 } } fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> { let mut backup_path = None; if to.exists() { match b.overwrite { OverwriteMode::NoClobber => return Ok(()), OverwriteMode::Interactive => { print!("{}: overwrite ‘{}’? ", NAME, to.display()); if!read_yes() { return Ok(()); } }, OverwriteMode::Force => {} }; backup_path = match b.backup { BackupMode::NoBackup => None, BackupMode::SimpleBackup => Some(simple_backup_path(to, &b.suffix)), BackupMode::NumberedBackup => Some(numbered_backup_path(to)), BackupMode::ExistingBackup => Some(existing_backup_path(to, &b.suffix)) }; if let Some(ref p) = backup_path { try!(fs::rename(to, p)); } if b.update { if try!(fs::metadata(from)).mtime() <= try!(fs::metadata(to)).mtime() { return Ok(()); } } } try!(fs::rename(from, to)); if b.verbose { print!("‘{}’ -> ‘{}’", from.display(), to.display()); match backup_path { Some(path) => println!(" (backup: ‘{}’)", path.display()), None => println!("") } } Ok(()) } fn read_yes() -> bool { let mut s = String::new(); match BufReader::new(stdin()).read_line(&mut s) { Ok(_) => match s.char_indices().nth(0) { Some((_, x)) => x == 'y' || x == 'Y', _ => false }, _ => false } } fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { let mut p = path.as_os_str().to_str().unwrap().to_owned(); p.push_str(suffix); PathBuf::from(p) } fn numbered_backup_path(path: &PathBuf) -> PathBuf {
loop { let new_path = simple_backup_path(path, &format!(".~{}~", i)); if!new_path.exists() { return new_path; } i = i + 1; } } fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { let test_path = simple_backup_path(path, &".~1~".to_owned()); if test_path.exists() { return numbered_backup_path(path); } simple_backup_path(path, suffix) }
let mut i: u64 = 1;
identifier_name
mv.rs
#![crate_name = "uu_mv"] /* * This file is part of the uutils coreutils package. * * (c) Orvar Segerström <[email protected]> * (c) Sokovikov Evgeniy <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use std::fs; use std::io::{BufRead, BufReader, Result, stdin, Write}; use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; static NAME: &'static str = "mv"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub struct Behaviour { overwrite: OverwriteMode, backup: BackupMode, suffix: String, update: bool, target_dir: Option<String>, no_target_dir: bool, verbose: bool, } #[derive(Clone, Eq, PartialEq)] pub enum OverwriteMode { NoClobber, Interactive, Force, } #[derive(Clone, Eq, PartialEq)] pub enum BackupMode { NoBackup, SimpleBackup, NumberedBackup, ExistingBackup, } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflagopt("", "backup", "make a backup of each existing destination file", "CONTROL"); opts.optflag("b", "", "like --backup but does not accept an argument"); opts.optflag("f", "force", "do not prompt before overwriting"); opts.optflag("i", "interactive", "prompt before override"); opts.optflag("n", "no-clobber", "do not overwrite an existing file"); opts.optflag("", "strip-trailing-slashes", "remove any trailing slashes from each SOURCE\n \ argument"); opts.optopt("S", "suffix", "override the usual backup suffix", "SUFFIX"); opts.optopt("t", "target-directory", "move all SOURCE arguments into DIRECTORY", "DIRECTORY"); opts.optflag("T", "no-target-directory", "treat DEST as a normal file"); opts.optflag("u", "update", "move only when the SOURCE file is newer\n \ than the destination file or when the\n \ destination file is missing"); opts.optflag("v", "verbose", "explain what is being done"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("Invalid options\n{}", f); return 1; } }; let usage = opts.usage("Move SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY."); /* This does not exactly match the GNU implementation: * The GNU mv defaults to Force, but if more than one of the * overwrite options are supplied, only the last takes effect. * To default to no-clobber in that situation seems safer: */ let overwrite_mode = if matches.opt_present("no-clobber") { OverwriteMode::NoClobber } else if matches.opt_present("interactive") { OverwriteMode::Interactive } else { OverwriteMode::Force }; let backup_mode = if matches.opt_present("b") { BackupMode::SimpleBackup } else if matches.opt_present("backup") { match matches.opt_str("backup") { None => BackupMode::SimpleBackup, Some(mode) => match &mode[..] { "simple" | "never" => BackupMode::SimpleBackup, "numbered" | "t" => BackupMode::NumberedBackup, "existing" | "nil" => BackupMode::ExistingBackup, "none" | "off" => BackupMode::NoBackup, x => { show_error!("invalid argument ‘{}’ for ‘backup type’\n\ Try '{} --help' for more information.", x, NAME); return 1; } } } } else { BackupMode::NoBackup }; if overwrite_mode == OverwriteMode::NoClobber && backup_mode!= BackupMode::NoBackup { show_error!("options --backup and --no-clobber are mutually exclusive\n\ Try '{} --help' for more information.", NAME); return 1; }
Some(x) => x, None => { show_error!("option '--suffix' requires an argument\n\ Try '{} --help' for more information.", NAME); return 1; } } } else { "~".to_owned() }; if matches.opt_present("T") && matches.opt_present("t") { show_error!("cannot combine --target-directory (-t) and --no-target-directory (-T)"); return 1; } let behaviour = Behaviour { overwrite: overwrite_mode, backup: backup_mode, suffix: backup_suffix, update: matches.opt_present("u"), target_dir: matches.opt_str("t"), no_target_dir: matches.opt_present("T"), verbose: matches.opt_present("v"), }; let paths: Vec<PathBuf> = { fn string_to_path<'a>(s: &'a String) -> &'a Path { Path::new(s) }; fn strip_slashes<'a>(p: &'a Path) -> &'a Path { p.components().as_path() } let to_owned = |p: &Path| p.to_owned(); let arguments = matches.free.iter().map(string_to_path); if matches.opt_present("strip-trailing-slashes") { arguments.map(strip_slashes).map(to_owned).collect() } else { arguments.map(to_owned).collect() } }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); 0 } else if matches.opt_present("help") { help(&usage); 0 } else { exec(&paths[..], behaviour) } } fn help(usage: &str) { println!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n\n\ {2}", NAME, VERSION, usage); } fn exec(files: &[PathBuf], b: Behaviour) -> i32 { match b.target_dir { Some(ref name) => return move_files_into_dir(files, &PathBuf::from(name), &b), None => {} } match files.len() { 0 | 1 => { show_error!("missing file operand\n\ Try '{} --help' for more information.", NAME); return 1; }, 2 => { let source = &files[0]; let target = &files[1]; if!source.exists() { show_error!("cannot stat ‘{}’: No such file or directory", source.display()); return 1; } if target.is_dir() { if b.no_target_dir { if!source.is_dir() { show_error!("cannot overwrite directory ‘{}’ with non-directory", target.display()); return 1; } return match rename(source, target, &b) { Err(e) => { show_error!("{}", e); 1 }, _ => 0 } } return move_files_into_dir(&[source.clone()], target, &b); } if let Err(e) = rename(source, target, &b) { show_error!("{}", e); return 1; } } _ => { if b.no_target_dir { show_error!("mv: extra operand ‘{}’\n\ Try '{} --help' for more information.", files[2].display(), NAME); return 1; } let target_dir = files.last().unwrap(); move_files_into_dir(&files[0..files.len()-1], target_dir, &b); } } 0 } fn move_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behaviour) -> i32 { if!target_dir.is_dir() { show_error!("target ‘{}’ is not a directory", target_dir.display()); return 1; } let mut all_successful = true; for sourcepath in files.iter() { let targetpath = match sourcepath.as_os_str().to_str() { Some(name) => target_dir.join(name), None => { show_error!("cannot stat ‘{}’: No such file or directory", sourcepath.display()); all_successful = false; continue; } }; if let Err(e) = rename(sourcepath, &targetpath, b) { show_error!("mv: cannot move ‘{}’ to ‘{}’: {}", sourcepath.display(), targetpath.display(), e); all_successful = false; } }; if all_successful { 0 } else { 1 } } fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> { let mut backup_path = None; if to.exists() { match b.overwrite { OverwriteMode::NoClobber => return Ok(()), OverwriteMode::Interactive => { print!("{}: overwrite ‘{}’? ", NAME, to.display()); if!read_yes() { return Ok(()); } }, OverwriteMode::Force => {} }; backup_path = match b.backup { BackupMode::NoBackup => None, BackupMode::SimpleBackup => Some(simple_backup_path(to, &b.suffix)), BackupMode::NumberedBackup => Some(numbered_backup_path(to)), BackupMode::ExistingBackup => Some(existing_backup_path(to, &b.suffix)) }; if let Some(ref p) = backup_path { try!(fs::rename(to, p)); } if b.update { if try!(fs::metadata(from)).mtime() <= try!(fs::metadata(to)).mtime() { return Ok(()); } } } try!(fs::rename(from, to)); if b.verbose { print!("‘{}’ -> ‘{}’", from.display(), to.display()); match backup_path { Some(path) => println!(" (backup: ‘{}’)", path.display()), None => println!("") } } Ok(()) } fn read_yes() -> bool { let mut s = String::new(); match BufReader::new(stdin()).read_line(&mut s) { Ok(_) => match s.char_indices().nth(0) { Some((_, x)) => x == 'y' || x == 'Y', _ => false }, _ => false } } fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { let mut p = path.as_os_str().to_str().unwrap().to_owned(); p.push_str(suffix); PathBuf::from(p) } fn numbered_backup_path(path: &PathBuf) -> PathBuf { let mut i: u64 = 1; loop { let new_path = simple_backup_path(path, &format!(".~{}~", i)); if!new_path.exists() { return new_path; } i = i + 1; } } fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { let test_path = simple_backup_path(path, &".~1~".to_owned()); if test_path.exists() { return numbered_backup_path(path); } simple_backup_path(path, suffix) }
let backup_suffix = if matches.opt_present("suffix") { match matches.opt_str("suffix") {
random_line_split
mv.rs
#![crate_name = "uu_mv"] /* * This file is part of the uutils coreutils package. * * (c) Orvar Segerström <[email protected]> * (c) Sokovikov Evgeniy <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use std::fs; use std::io::{BufRead, BufReader, Result, stdin, Write}; use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; static NAME: &'static str = "mv"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub struct Behaviour { overwrite: OverwriteMode, backup: BackupMode, suffix: String, update: bool, target_dir: Option<String>, no_target_dir: bool, verbose: bool, } #[derive(Clone, Eq, PartialEq)] pub enum OverwriteMode { NoClobber, Interactive, Force, } #[derive(Clone, Eq, PartialEq)] pub enum BackupMode { NoBackup, SimpleBackup, NumberedBackup, ExistingBackup, } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflagopt("", "backup", "make a backup of each existing destination file", "CONTROL"); opts.optflag("b", "", "like --backup but does not accept an argument"); opts.optflag("f", "force", "do not prompt before overwriting"); opts.optflag("i", "interactive", "prompt before override"); opts.optflag("n", "no-clobber", "do not overwrite an existing file"); opts.optflag("", "strip-trailing-slashes", "remove any trailing slashes from each SOURCE\n \ argument"); opts.optopt("S", "suffix", "override the usual backup suffix", "SUFFIX"); opts.optopt("t", "target-directory", "move all SOURCE arguments into DIRECTORY", "DIRECTORY"); opts.optflag("T", "no-target-directory", "treat DEST as a normal file"); opts.optflag("u", "update", "move only when the SOURCE file is newer\n \ than the destination file or when the\n \ destination file is missing"); opts.optflag("v", "verbose", "explain what is being done"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("Invalid options\n{}", f); return 1; } }; let usage = opts.usage("Move SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY."); /* This does not exactly match the GNU implementation: * The GNU mv defaults to Force, but if more than one of the * overwrite options are supplied, only the last takes effect. * To default to no-clobber in that situation seems safer: */ let overwrite_mode = if matches.opt_present("no-clobber") { OverwriteMode::NoClobber } else if matches.opt_present("interactive") { OverwriteMode::Interactive } else { OverwriteMode::Force }; let backup_mode = if matches.opt_present("b") { BackupMode::SimpleBackup } else if matches.opt_present("backup") { match matches.opt_str("backup") { None => BackupMode::SimpleBackup, Some(mode) => match &mode[..] { "simple" | "never" => BackupMode::SimpleBackup, "numbered" | "t" => BackupMode::NumberedBackup, "existing" | "nil" => BackupMode::ExistingBackup, "none" | "off" => BackupMode::NoBackup, x => { show_error!("invalid argument ‘{}’ for ‘backup type’\n\ Try '{} --help' for more information.", x, NAME); return 1; } } } } else { BackupMode::NoBackup }; if overwrite_mode == OverwriteMode::NoClobber && backup_mode!= BackupMode::NoBackup { show_error!("options --backup and --no-clobber are mutually exclusive\n\ Try '{} --help' for more information.", NAME); return 1; } let backup_suffix = if matches.opt_present("suffix") { match matches.opt_str("suffix") { Some(x) => x, None => { show_error!("option '--suffix' requires an argument\n\ Try '{} --help' for more information.", NAME); return 1; } } } else { "~".to_owned() }; if matches.opt_present("T") && matches.opt_present("t") { show_error!("cannot combine --target-directory (-t) and --no-target-directory (-T)"); return 1; } let behaviour = Behaviour { overwrite: overwrite_mode, backup: backup_mode, suffix: backup_suffix, update: matches.opt_present("u"), target_dir: matches.opt_str("t"), no_target_dir: matches.opt_present("T"), verbose: matches.opt_present("v"), }; let paths: Vec<PathBuf> = { fn string_to_path<'a>(s: &'a String) -> &'a Path { Path::new(s) }; fn strip_slashes<'a>(p: &'a Path) -> &'a Path { p.components().as_path() } let to_owned = |p: &Path| p.to_owned(); let arguments = matches.free.iter().map(string_to_path); if matches.opt_present("strip-trailing-slashes") { arguments.map(strip_slashes).map(to_owned).collect() } else { arguments.map(to_owned).collect() } }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); 0 } else if matches.opt_present("help") { help(&usage); 0 } else { exec(&paths[..], behaviour) } } fn help(usage: &str) { println!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n\n\ {2}", NAME, VERSION, usage); } fn exec(files: &[PathBuf], b: Behaviour) -> i32 { mat
if!source.is_dir() { show_error!("cannot overwrite directory ‘{}’ with non-directory", target.display()); return 1; } return match rename(source, target, &b) { Err(e) => { show_error!("{}", e); 1 }, _ => 0 } } return move_files_into_dir(&[source.clone()], target, &b); } if let Err(e) = rename(source, target, &b) { show_error!("{}", e); return 1; } } _ => { if b.no_target_dir { show_error!("mv: extra operand ‘{}’\n\ Try '{} --help' for more information.", files[2].display(), NAME); return 1; } let target_dir = files.last().unwrap(); move_files_into_dir(&files[0..files.len()-1], target_dir, &b); } } 0 } fn move_files_into_ dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behaviour) -> i32 { if!target_dir.is_dir() { show_error!("target ‘{}’ is not a directory", target_dir.display()); return 1; } let mut all_successful = true; for sourcepath in files.iter() { let targetpath = match sourcepath.as_os_str().to_str() { Some(name) => target_dir.join(name), None => { show_error!("cannot stat ‘{}’: No such file or directory", sourcepath.display()); all_successful = false; continue; } }; if let Err(e) = rename(sourcepath, &targetpath, b) { show_error!("mv: cannot move ‘{}’ to ‘{}’: {}", sourcepath.display(), targetpath.display(), e); all_successful = false; } }; if all_successful { 0 } else { 1 } } fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> { let mut backup_path = None; if to.exists() { match b.overwrite { OverwriteMode::NoClobber => return Ok(()), OverwriteMode::Interactive => { print!("{}: overwrite ‘{}’? ", NAME, to.display()); if!read_yes() { return Ok(()); } }, OverwriteMode::Force => {} }; backup_path = match b.backup { BackupMode::NoBackup => None, BackupMode::SimpleBackup => Some(simple_backup_path(to, &b.suffix)), BackupMode::NumberedBackup => Some(numbered_backup_path(to)), BackupMode::ExistingBackup => Some(existing_backup_path(to, &b.suffix)) }; if let Some(ref p) = backup_path { try!(fs::rename(to, p)); } if b.update { if try!(fs::metadata(from)).mtime() <= try!(fs::metadata(to)).mtime() { return Ok(()); } } } try!(fs::rename(from, to)); if b.verbose { print!("‘{}’ -> ‘{}’", from.display(), to.display()); match backup_path { Some(path) => println!(" (backup: ‘{}’)", path.display()), None => println!("") } } Ok(()) } fn read_yes() -> bool { let mut s = String::new(); match BufReader::new(stdin()).read_line(&mut s) { Ok(_) => match s.char_indices().nth(0) { Some((_, x)) => x == 'y' || x == 'Y', _ => false }, _ => false } } fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { let mut p = path.as_os_str().to_str().unwrap().to_owned(); p.push_str(suffix); PathBuf::from(p) } fn numbered_backup_path(path: &PathBuf) -> PathBuf { let mut i: u64 = 1; loop { let new_path = simple_backup_path(path, &format!(".~{}~", i)); if!new_path.exists() { return new_path; } i = i + 1; } } fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { let test_path = simple_backup_path(path, &".~1~".to_owned()); if test_path.exists() { return numbered_backup_path(path); } simple_backup_path(path, suffix) }
ch b.target_dir { Some(ref name) => return move_files_into_dir(files, &PathBuf::from(name), &b), None => {} } match files.len() { 0 | 1 => { show_error!("missing file operand\n\ Try '{} --help' for more information.", NAME); return 1; }, 2 => { let source = &files[0]; let target = &files[1]; if !source.exists() { show_error!("cannot stat ‘{}’: No such file or directory", source.display()); return 1; } if target.is_dir() { if b.no_target_dir {
identifier_body
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity}; use matching::{ElementSelectorFlags, LocalMatchingContext, MatchingContext, RelevantLinkStatus}; use parser::SelectorImpl; use std::fmt::Debug; pub trait Element: Sized + Debug { type Impl: SelectorImpl; fn parent_element(&self) -> Option<Self>; /// The parent of a given pseudo-element, after matching a pseudo-element /// selector. /// /// This is guaranteed to be called in a pseudo-element. fn pseudo_element_originating_element(&self) -> Option<Self> { self.parent_element() } /// Skips non-element nodes fn first_child_element(&self) -> Option<Self>; /// Skips non-element nodes fn last_child_element(&self) -> Option<Self>; /// Skips non-element nodes fn prev_sibling_element(&self) -> Option<Self>; /// Skips non-element nodes fn next_sibling_element(&self) -> Option<Self>; fn is_html_element_in_html_document(&self) -> bool; fn get_local_name(&self) -> &<Self::Impl as SelectorImpl>::BorrowedLocalName; /// Empty string for no namespace fn get_namespace(&self) -> &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl; fn attr_matches(&self, ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>, local_name: &<Self::Impl as SelectorImpl>::LocalName, operation: &AttrSelectorOperation<&<Self::Impl as SelectorImpl>::AttrValue>) -> bool; fn match_non_ts_pseudo_class<F>(&self, pc: &<Self::Impl as SelectorImpl>::NonTSPseudoClass, context: &mut LocalMatchingContext<Self::Impl>, relevant_link: &RelevantLinkStatus, flags_setter: &mut F) -> bool where F: FnMut(&Self, ElementSelectorFlags); fn match_pseudo_element(&self, pe: &<Self::Impl as SelectorImpl>::PseudoElement, context: &mut MatchingContext) -> bool; /// Whether this element is a `link`. fn is_link(&self) -> bool; fn has_id(&self, id: &<Self::Impl as SelectorImpl>::Identifier, case_sensitivity: CaseSensitivity) -> bool; fn has_class(&self, name: &<Self::Impl as SelectorImpl>::ClassName, case_sensitivity: CaseSensitivity) -> bool; /// Returns whether this element matches `:empty`. /// /// That is, whether it does not contain any child element or any non-zero-length text node. /// See http://dev.w3.org/csswg/selectors-3/#empty-pseudo fn is_empty(&self) -> bool; /// Returns whether this element matches `:root`, /// i.e. whether it is the root element of a document. /// /// Note: this can be false even if `.parent_element()` is `None` /// if the parent node is a `DocumentFragment`. fn is_root(&self) -> bool; /// Returns whether this element should ignore matching nth child /// selector. fn ignores_nth_child_selectors(&self) -> bool { false } /// Return true if we want to stop lookup ancestor of the current /// element while matching complex selectors with descendant/child /// combinator. fn blocks_ancestor_combinators(&self) -> bool
}
{ false }
identifier_body
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity}; use matching::{ElementSelectorFlags, LocalMatchingContext, MatchingContext, RelevantLinkStatus}; use parser::SelectorImpl; use std::fmt::Debug; pub trait Element: Sized + Debug { type Impl: SelectorImpl; fn parent_element(&self) -> Option<Self>; /// The parent of a given pseudo-element, after matching a pseudo-element /// selector. /// /// This is guaranteed to be called in a pseudo-element. fn pseudo_element_originating_element(&self) -> Option<Self> { self.parent_element() } /// Skips non-element nodes fn first_child_element(&self) -> Option<Self>; /// Skips non-element nodes fn last_child_element(&self) -> Option<Self>; /// Skips non-element nodes fn prev_sibling_element(&self) -> Option<Self>; /// Skips non-element nodes fn next_sibling_element(&self) -> Option<Self>; fn is_html_element_in_html_document(&self) -> bool; fn get_local_name(&self) -> &<Self::Impl as SelectorImpl>::BorrowedLocalName; /// Empty string for no namespace fn get_namespace(&self) -> &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl; fn attr_matches(&self, ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>, local_name: &<Self::Impl as SelectorImpl>::LocalName, operation: &AttrSelectorOperation<&<Self::Impl as SelectorImpl>::AttrValue>) -> bool; fn match_non_ts_pseudo_class<F>(&self, pc: &<Self::Impl as SelectorImpl>::NonTSPseudoClass, context: &mut LocalMatchingContext<Self::Impl>, relevant_link: &RelevantLinkStatus, flags_setter: &mut F) -> bool where F: FnMut(&Self, ElementSelectorFlags); fn match_pseudo_element(&self, pe: &<Self::Impl as SelectorImpl>::PseudoElement, context: &mut MatchingContext) -> bool; /// Whether this element is a `link`. fn is_link(&self) -> bool; fn has_id(&self, id: &<Self::Impl as SelectorImpl>::Identifier, case_sensitivity: CaseSensitivity) -> bool; fn has_class(&self, name: &<Self::Impl as SelectorImpl>::ClassName, case_sensitivity: CaseSensitivity) -> bool; /// Returns whether this element matches `:empty`. /// /// That is, whether it does not contain any child element or any non-zero-length text node. /// See http://dev.w3.org/csswg/selectors-3/#empty-pseudo fn is_empty(&self) -> bool; /// Returns whether this element matches `:root`, /// i.e. whether it is the root element of a document. /// /// Note: this can be false even if `.parent_element()` is `None` /// if the parent node is a `DocumentFragment`. fn is_root(&self) -> bool; /// Returns whether this element should ignore matching nth child /// selector. fn ignores_nth_child_selectors(&self) -> bool { false } /// Return true if we want to stop lookup ancestor of the current /// element while matching complex selectors with descendant/child /// combinator. fn blocks_ancestor_combinators(&self) -> bool { false
}
}
random_line_split
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity}; use matching::{ElementSelectorFlags, LocalMatchingContext, MatchingContext, RelevantLinkStatus}; use parser::SelectorImpl; use std::fmt::Debug; pub trait Element: Sized + Debug { type Impl: SelectorImpl; fn parent_element(&self) -> Option<Self>; /// The parent of a given pseudo-element, after matching a pseudo-element /// selector. /// /// This is guaranteed to be called in a pseudo-element. fn pseudo_element_originating_element(&self) -> Option<Self> { self.parent_element() } /// Skips non-element nodes fn first_child_element(&self) -> Option<Self>; /// Skips non-element nodes fn last_child_element(&self) -> Option<Self>; /// Skips non-element nodes fn prev_sibling_element(&self) -> Option<Self>; /// Skips non-element nodes fn next_sibling_element(&self) -> Option<Self>; fn is_html_element_in_html_document(&self) -> bool; fn get_local_name(&self) -> &<Self::Impl as SelectorImpl>::BorrowedLocalName; /// Empty string for no namespace fn get_namespace(&self) -> &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl; fn attr_matches(&self, ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>, local_name: &<Self::Impl as SelectorImpl>::LocalName, operation: &AttrSelectorOperation<&<Self::Impl as SelectorImpl>::AttrValue>) -> bool; fn match_non_ts_pseudo_class<F>(&self, pc: &<Self::Impl as SelectorImpl>::NonTSPseudoClass, context: &mut LocalMatchingContext<Self::Impl>, relevant_link: &RelevantLinkStatus, flags_setter: &mut F) -> bool where F: FnMut(&Self, ElementSelectorFlags); fn match_pseudo_element(&self, pe: &<Self::Impl as SelectorImpl>::PseudoElement, context: &mut MatchingContext) -> bool; /// Whether this element is a `link`. fn is_link(&self) -> bool; fn has_id(&self, id: &<Self::Impl as SelectorImpl>::Identifier, case_sensitivity: CaseSensitivity) -> bool; fn has_class(&self, name: &<Self::Impl as SelectorImpl>::ClassName, case_sensitivity: CaseSensitivity) -> bool; /// Returns whether this element matches `:empty`. /// /// That is, whether it does not contain any child element or any non-zero-length text node. /// See http://dev.w3.org/csswg/selectors-3/#empty-pseudo fn is_empty(&self) -> bool; /// Returns whether this element matches `:root`, /// i.e. whether it is the root element of a document. /// /// Note: this can be false even if `.parent_element()` is `None` /// if the parent node is a `DocumentFragment`. fn is_root(&self) -> bool; /// Returns whether this element should ignore matching nth child /// selector. fn
(&self) -> bool { false } /// Return true if we want to stop lookup ancestor of the current /// element while matching complex selectors with descendant/child /// combinator. fn blocks_ancestor_combinators(&self) -> bool { false } }
ignores_nth_child_selectors
identifier_name
mod.rs
//! A Collection of Header implementations for common HTTP Headers. //! //! ## Mime //! //! Several header fields use MIME values for their contents. Keeping with the //! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate //! is used, such as `ContentType(pub Mime)`. pub use self::access_control::*; pub use self::accept::Accept; pub use self::accept_encoding::AcceptEncoding; pub use self::allow::Allow; pub use self::authorization::{Authorization, Scheme, Basic}; pub use self::cache_control::{CacheControl, CacheDirective}; pub use self::connection::{Connection, ConnectionOption}; pub use self::content_length::ContentLength; pub use self::content_type::ContentType; pub use self::cookie::Cookie; pub use self::date::Date; pub use self::etag::Etag; pub use self::expires::Expires; pub use self::host::Host; pub use self::if_modified_since::IfModifiedSince; pub use self::if_none_match::IfNoneMatch; pub use self::if_unmodified_since::IfUnmodifiedSince; pub use self::last_modified::LastModified; pub use self::location::Location; pub use self::pragma::Pragma; pub use self::referer::Referer; pub use self::server::Server; pub use self::set_cookie::SetCookie; pub use self::transfer_encoding::TransferEncoding; pub use self::upgrade::{Upgrade, Protocol}; pub use self::user_agent::UserAgent; pub use self::vary::Vary; #[macro_export] macro_rules! bench_header( ($name:ident, $ty:ty, $value:expr) => { #[cfg(test)] mod $name { use test::Bencher; use super::*; use header::{Header, HeaderFormatter}; #[bench] fn bench_parse(b: &mut Bencher) { let val = $value; b.iter(|| { let _: $ty = Header::parse_header(&val[]).unwrap(); }); } #[bench] fn bench_format(b: &mut Bencher) { let val: $ty = Header::parse_header(&$value[]).unwrap(); let fmt = HeaderFormatter(&val); b.iter(|| { format!("{}", fmt); }); } } } ); #[macro_export] macro_rules! deref( ($from:ty => $to:ty) => { impl ::std::ops::Deref for $from { type Target = $to; fn deref<'a>(&'a self) -> &'a $to { &self.0 } } impl ::std::ops::DerefMut for $from { fn deref_mut<'a>(&'a mut self) -> &'a mut $to { &mut self.0 } } } ); #[macro_export] macro_rules! impl_list_header( ($from:ident, $name:expr, $item:ty) => { deref!($from => $item); impl header::Header for $from { fn header_name() -> &'static str { $name } fn parse_header(raw: &[Vec<u8>]) -> Option<$from> { $crate::header::parsing::from_comma_delimited(raw).map($from) } } impl header::HeaderFormat for $from { fn fmt_header(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { $crate::header::parsing::fmt_comma_delimited(fmt, &self[]) } } impl ::std::fmt::Display for $from { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { use header::HeaderFormat; self.fmt_header(f) } } } ); #[macro_export] macro_rules! impl_header( ($from:ident, $name:expr, $item:ty) => { deref!($from => $item); impl header::Header for $from {
fn parse_header(raw: &[Vec<u8>]) -> Option<$from> { $crate::header::parsing::from_one_raw_str(raw).map($from) } } impl header::HeaderFormat for $from { fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&**self, f) } } impl ::std::fmt::Display for $from { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { use header::HeaderFormat; self.fmt_header(f) } } } ); mod access_control; mod accept; mod accept_encoding; mod allow; mod authorization; mod cache_control; mod cookie; mod connection; mod content_length; mod content_type; mod date; mod etag; mod expires; mod host; mod last_modified; mod if_modified_since; mod if_none_match; mod if_unmodified_since; mod location; mod pragma; mod referer; mod server; mod set_cookie; mod transfer_encoding; mod upgrade; mod user_agent; mod vary;
fn header_name() -> &'static str { $name }
random_line_split
mul.rs
use std::ops::Mul; use traits::{Flops, Matrix, UnsafeGet}; impl<A, B> Flops for ::Mul<A, B> where A: Flops + UnsafeGet, B: Flops + UnsafeGet, A::Output: Mul<B::Output>, { #[inline(always)] fn flops() -> usize { A::flops() + B::flops() + 1 } } impl<A, B, C> Matrix for ::Mul<A, B> where A: UnsafeGet, B: Matrix + UnsafeGet, A::Output: Mul<B::Output, Output=C>, { #[inline(always)] fn nrows(&self) -> u32 { B::nrows(&self.1) } #[inline(always)] fn ncols(&self) -> u32 { B::ncols(&self.1) } #[inline(always)] fn nelems(&self) -> usize { B::nelems(&self.1) } #[inline(always)] fn size(&self) -> (u32, u32) { B::size(&self.1) } } impl<A, B, C> UnsafeGet for ::Mul<A, B> where A: UnsafeGet, B: UnsafeGet, A::Output: Mul<B::Output, Output=C>, { type Output = C;
}
#[inline(always)] unsafe fn unsafe_get(&self, i: (u32, u32)) -> C { self.0.unsafe_get(i) * self.1.unsafe_get(i) }
random_line_split
mul.rs
use std::ops::Mul; use traits::{Flops, Matrix, UnsafeGet}; impl<A, B> Flops for ::Mul<A, B> where A: Flops + UnsafeGet, B: Flops + UnsafeGet, A::Output: Mul<B::Output>, { #[inline(always)] fn flops() -> usize { A::flops() + B::flops() + 1 } } impl<A, B, C> Matrix for ::Mul<A, B> where A: UnsafeGet, B: Matrix + UnsafeGet, A::Output: Mul<B::Output, Output=C>, { #[inline(always)] fn nrows(&self) -> u32 { B::nrows(&self.1) } #[inline(always)] fn ncols(&self) -> u32 { B::ncols(&self.1) } #[inline(always)] fn nelems(&self) -> usize { B::nelems(&self.1) } #[inline(always)] fn
(&self) -> (u32, u32) { B::size(&self.1) } } impl<A, B, C> UnsafeGet for ::Mul<A, B> where A: UnsafeGet, B: UnsafeGet, A::Output: Mul<B::Output, Output=C>, { type Output = C; #[inline(always)] unsafe fn unsafe_get(&self, i: (u32, u32)) -> C { self.0.unsafe_get(i) * self.1.unsafe_get(i) } }
size
identifier_name
mul.rs
use std::ops::Mul; use traits::{Flops, Matrix, UnsafeGet}; impl<A, B> Flops for ::Mul<A, B> where A: Flops + UnsafeGet, B: Flops + UnsafeGet, A::Output: Mul<B::Output>, { #[inline(always)] fn flops() -> usize
} impl<A, B, C> Matrix for ::Mul<A, B> where A: UnsafeGet, B: Matrix + UnsafeGet, A::Output: Mul<B::Output, Output=C>, { #[inline(always)] fn nrows(&self) -> u32 { B::nrows(&self.1) } #[inline(always)] fn ncols(&self) -> u32 { B::ncols(&self.1) } #[inline(always)] fn nelems(&self) -> usize { B::nelems(&self.1) } #[inline(always)] fn size(&self) -> (u32, u32) { B::size(&self.1) } } impl<A, B, C> UnsafeGet for ::Mul<A, B> where A: UnsafeGet, B: UnsafeGet, A::Output: Mul<B::Output, Output=C>, { type Output = C; #[inline(always)] unsafe fn unsafe_get(&self, i: (u32, u32)) -> C { self.0.unsafe_get(i) * self.1.unsafe_get(i) } }
{ A::flops() + B::flops() + 1 }
identifier_body
platform.rs
/* Copyright ⓒ 2015 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ /*! This module is for platform-specific stuff. */ pub use self::inner::{current_time, file_last_modified, get_cache_dir_for}; #[cfg(any(unix, windows))] mod inner_unix_or_windows { extern crate time; /** Gets the current system time, in milliseconds since the UNIX epoch. */ pub fn cu
-> u64 { /* This is kinda dicey, since *ideally* both this function and `file_last_modified` would be using the same underlying APIs. They are not, insofar as I know. At least, not when targetting Windows. That said, so long as everything is in the same units and uses the same epoch, it should be fine. */ let now_1970_utc = time::now_utc().to_timespec(); if now_1970_utc.sec < 0 || now_1970_utc.nsec < 0 { // Fuck it. return 0 } let now_ms_1970_utc = (now_1970_utc.sec as u64 * 1000) + (now_1970_utc.nsec as u64 / 1_000_000); now_ms_1970_utc } } #[cfg(unix)] mod inner { pub use super::inner_unix_or_windows::current_time; use std::path::{Path, PathBuf}; use std::{cmp, env, fs}; use std::os::unix::fs::MetadataExt; use error::{MainError, Blame}; /** Gets the last-modified time of a file, in milliseconds since the UNIX epoch. */ pub fn file_last_modified(file: &fs::File) -> u64 { let mtime_s_1970_utc = file.metadata() .map(|md| md.mtime()) .unwrap_or(0); let mtime_s_1970_utc = cmp::max(0, mtime_s_1970_utc); mtime_s_1970_utc as u64 * 1000 } /** Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions. This is chosen to match the location where Cargo places its cache data. */ pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError> where P: AsRef<Path> { // try $CARGO_HOME then fall back to $HOME let home = match env::var_os("CARGO_HOME") { Some(val) => val, None => match env::var_os("HOME") { Some(val) => val, None => return Err((Blame::Human, "neither $CARGO_HOME nor $HOME is defined").into()) } }; match product.as_ref().to_str() { Some(s) => { let folder = format!(".{}", s.to_lowercase()); Ok(Path::new(&home).join(folder)) }, None => Err("product for `get_cache_dir_for` was not utf8".into()) } } } #[cfg(windows)] pub mod inner { #![allow(non_snake_case)] extern crate ole32; extern crate shell32; extern crate winapi; pub use super::inner_unix_or_windows::current_time; use std::ffi::OsString; use std::fmt; use std::fs; use std::path::{Path, PathBuf}; use std::mem; use std::os::windows::ffi::OsStringExt; use error::MainError; // This *is* in `uuid-sys` ≤ 0.1.2, but that's broken at time of writing. Once its fixed, change it back. #[link(name="uuid")] extern { pub static FOLDERID_LocalAppData: winapi::KNOWNFOLDERID; } /** Gets the last-modified time of a file, in milliseconds since the UNIX epoch. */ pub fn file_last_modified(file: &fs::File) -> u64 { use ::std::os::windows::fs::MetadataExt; const MS_BETWEEN_1601_1970: u64 = 11_644_473_600_000; let mtime_100ns_1601_utc = file.metadata() .map(|md| md.last_write_time()) .unwrap_or(0); let mtime_ms_1601_utc = mtime_100ns_1601_utc / (1000*10); // This can obviously underflow... but since files created prior to 1970 are going to be *somewhat rare*, I'm just going to saturate to zero. let mtime_ms_1970_utc = mtime_ms_1601_utc.saturating_sub(MS_BETWEEN_1601_1970); mtime_ms_1970_utc } /** Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions. This is *not* chosen to match the location where Cargo places its cache data, because Cargo is *wrong*. This is at least *less wrong*. On Windows, LocalAppData is where user- and machine- specific data should go, but it *might* be more appropriate to use whatever the official name for "Program Data" is, though. */ pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError> where P: AsRef<Path> { let dir = try!(SHGetKnownFolderPath(&FOLDERID_LocalAppData, 0, ::std::ptr::null_mut()) .map_err(|e| e.to_string())); Ok(Path::new(&dir).to_path_buf().join(product)) } type WinResult<T> = Result<T, WinError>; struct WinError(winapi::HRESULT); impl fmt::Display for WinError { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "HRESULT({})", self.0) } } fn SHGetKnownFolderPath(rfid: &winapi::KNOWNFOLDERID, dwFlags: winapi::DWORD, hToken: winapi::HANDLE) -> WinResult<OsString> { use self::winapi::PWSTR; let mut psz_path: PWSTR = unsafe { mem::uninitialized() }; let hresult = unsafe { shell32::SHGetKnownFolderPath( rfid, dwFlags, hToken, mem::transmute(&mut psz_path as &mut PWSTR as *mut PWSTR) ) }; if hresult == winapi::S_OK { let r = unsafe { pwstr_to_os_string(psz_path) }; unsafe { ole32::CoTaskMemFree(psz_path as *mut _) }; Ok(r) } else { Err(WinError(hresult)) } } unsafe fn pwstr_to_os_string(ptr: winapi::PWSTR) -> OsString { OsStringExt::from_wide(::std::slice::from_raw_parts(ptr, pwstr_len(ptr))) } unsafe fn pwstr_len(mut ptr: winapi::PWSTR) -> usize { let mut len = 0; while *ptr!= 0 { len += 1; ptr = ptr.offset(1); } len } }
rrent_time()
identifier_name
platform.rs
/* Copyright ⓒ 2015 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ /*! This module is for platform-specific stuff. */ pub use self::inner::{current_time, file_last_modified, get_cache_dir_for}; #[cfg(any(unix, windows))] mod inner_unix_or_windows { extern crate time; /** Gets the current system time, in milliseconds since the UNIX epoch. */ pub fn current_time() -> u64 { /* This is kinda dicey, since *ideally* both this function and `file_last_modified` would be using the same underlying APIs. They are not, insofar as I know. At least, not when targetting Windows. That said, so long as everything is in the same units and uses the same epoch, it should be fine. */ let now_1970_utc = time::now_utc().to_timespec(); if now_1970_utc.sec < 0 || now_1970_utc.nsec < 0 { // Fuck it. return 0 } let now_ms_1970_utc = (now_1970_utc.sec as u64 * 1000) + (now_1970_utc.nsec as u64 / 1_000_000); now_ms_1970_utc } } #[cfg(unix)] mod inner { pub use super::inner_unix_or_windows::current_time; use std::path::{Path, PathBuf}; use std::{cmp, env, fs}; use std::os::unix::fs::MetadataExt; use error::{MainError, Blame}; /** Gets the last-modified time of a file, in milliseconds since the UNIX epoch. */ pub fn file_last_modified(file: &fs::File) -> u64 { let mtime_s_1970_utc = file.metadata() .map(|md| md.mtime()) .unwrap_or(0); let mtime_s_1970_utc = cmp::max(0, mtime_s_1970_utc); mtime_s_1970_utc as u64 * 1000 } /** Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions. This is chosen to match the location where Cargo places its cache data. */ pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError> where P: AsRef<Path> { // try $CARGO_HOME then fall back to $HOME let home = match env::var_os("CARGO_HOME") { Some(val) => val, None => match env::var_os("HOME") { Some(val) => val, None => return Err((Blame::Human, "neither $CARGO_HOME nor $HOME is defined").into()) } }; match product.as_ref().to_str() { Some(s) => { let folder = format!(".{}", s.to_lowercase()); Ok(Path::new(&home).join(folder)) }, None => Err("product for `get_cache_dir_for` was not utf8".into()) } } } #[cfg(windows)] pub mod inner { #![allow(non_snake_case)] extern crate ole32; extern crate shell32; extern crate winapi; pub use super::inner_unix_or_windows::current_time; use std::ffi::OsString; use std::fmt; use std::fs; use std::path::{Path, PathBuf}; use std::mem; use std::os::windows::ffi::OsStringExt; use error::MainError; // This *is* in `uuid-sys` ≤ 0.1.2, but that's broken at time of writing. Once its fixed, change it back. #[link(name="uuid")] extern { pub static FOLDERID_LocalAppData: winapi::KNOWNFOLDERID; } /** Gets the last-modified time of a file, in milliseconds since the UNIX epoch. */ pub fn file_last_modified(file: &fs::File) -> u64 { use ::std::os::windows::fs::MetadataExt; const MS_BETWEEN_1601_1970: u64 = 11_644_473_600_000; let mtime_100ns_1601_utc = file.metadata() .map(|md| md.last_write_time()) .unwrap_or(0); let mtime_ms_1601_utc = mtime_100ns_1601_utc / (1000*10); // This can obviously underflow... but since files created prior to 1970 are going to be *somewhat rare*, I'm just going to saturate to zero. let mtime_ms_1970_utc = mtime_ms_1601_utc.saturating_sub(MS_BETWEEN_1601_1970); mtime_ms_1970_utc } /** Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions. This is *not* chosen to match the location where Cargo places its cache data, because Cargo is *wrong*. This is at least *less wrong*. On Windows, LocalAppData is where user- and machine- specific data should go, but it *might* be more appropriate to use whatever the official name for "Program Data" is, though. */ pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError> where P: AsRef<Path> { let dir = try!(SHGetKnownFolderPath(&FOLDERID_LocalAppData, 0, ::std::ptr::null_mut()) .map_err(|e| e.to_string())); Ok(Path::new(&dir).to_path_buf().join(product)) } type WinResult<T> = Result<T, WinError>; struct WinError(winapi::HRESULT); impl fmt::Display for WinError { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
} fn SHGetKnownFolderPath(rfid: &winapi::KNOWNFOLDERID, dwFlags: winapi::DWORD, hToken: winapi::HANDLE) -> WinResult<OsString> { use self::winapi::PWSTR; let mut psz_path: PWSTR = unsafe { mem::uninitialized() }; let hresult = unsafe { shell32::SHGetKnownFolderPath( rfid, dwFlags, hToken, mem::transmute(&mut psz_path as &mut PWSTR as *mut PWSTR) ) }; if hresult == winapi::S_OK { let r = unsafe { pwstr_to_os_string(psz_path) }; unsafe { ole32::CoTaskMemFree(psz_path as *mut _) }; Ok(r) } else { Err(WinError(hresult)) } } unsafe fn pwstr_to_os_string(ptr: winapi::PWSTR) -> OsString { OsStringExt::from_wide(::std::slice::from_raw_parts(ptr, pwstr_len(ptr))) } unsafe fn pwstr_len(mut ptr: winapi::PWSTR) -> usize { let mut len = 0; while *ptr!= 0 { len += 1; ptr = ptr.offset(1); } len } }
write!(fmt, "HRESULT({})", self.0) }
identifier_body
platform.rs
/* Copyright ⓒ 2015 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ /*! This module is for platform-specific stuff. */ pub use self::inner::{current_time, file_last_modified, get_cache_dir_for}; #[cfg(any(unix, windows))] mod inner_unix_or_windows { extern crate time; /** Gets the current system time, in milliseconds since the UNIX epoch. */ pub fn current_time() -> u64 { /* This is kinda dicey, since *ideally* both this function and `file_last_modified` would be using the same underlying APIs. They are not, insofar as I know. At least, not when targetting Windows. That said, so long as everything is in the same units and uses the same epoch, it should be fine. */ let now_1970_utc = time::now_utc().to_timespec(); if now_1970_utc.sec < 0 || now_1970_utc.nsec < 0 { // Fuck it.
+ (now_1970_utc.nsec as u64 / 1_000_000); now_ms_1970_utc } } #[cfg(unix)] mod inner { pub use super::inner_unix_or_windows::current_time; use std::path::{Path, PathBuf}; use std::{cmp, env, fs}; use std::os::unix::fs::MetadataExt; use error::{MainError, Blame}; /** Gets the last-modified time of a file, in milliseconds since the UNIX epoch. */ pub fn file_last_modified(file: &fs::File) -> u64 { let mtime_s_1970_utc = file.metadata() .map(|md| md.mtime()) .unwrap_or(0); let mtime_s_1970_utc = cmp::max(0, mtime_s_1970_utc); mtime_s_1970_utc as u64 * 1000 } /** Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions. This is chosen to match the location where Cargo places its cache data. */ pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError> where P: AsRef<Path> { // try $CARGO_HOME then fall back to $HOME let home = match env::var_os("CARGO_HOME") { Some(val) => val, None => match env::var_os("HOME") { Some(val) => val, None => return Err((Blame::Human, "neither $CARGO_HOME nor $HOME is defined").into()) } }; match product.as_ref().to_str() { Some(s) => { let folder = format!(".{}", s.to_lowercase()); Ok(Path::new(&home).join(folder)) }, None => Err("product for `get_cache_dir_for` was not utf8".into()) } } } #[cfg(windows)] pub mod inner { #![allow(non_snake_case)] extern crate ole32; extern crate shell32; extern crate winapi; pub use super::inner_unix_or_windows::current_time; use std::ffi::OsString; use std::fmt; use std::fs; use std::path::{Path, PathBuf}; use std::mem; use std::os::windows::ffi::OsStringExt; use error::MainError; // This *is* in `uuid-sys` ≤ 0.1.2, but that's broken at time of writing. Once its fixed, change it back. #[link(name="uuid")] extern { pub static FOLDERID_LocalAppData: winapi::KNOWNFOLDERID; } /** Gets the last-modified time of a file, in milliseconds since the UNIX epoch. */ pub fn file_last_modified(file: &fs::File) -> u64 { use ::std::os::windows::fs::MetadataExt; const MS_BETWEEN_1601_1970: u64 = 11_644_473_600_000; let mtime_100ns_1601_utc = file.metadata() .map(|md| md.last_write_time()) .unwrap_or(0); let mtime_ms_1601_utc = mtime_100ns_1601_utc / (1000*10); // This can obviously underflow... but since files created prior to 1970 are going to be *somewhat rare*, I'm just going to saturate to zero. let mtime_ms_1970_utc = mtime_ms_1601_utc.saturating_sub(MS_BETWEEN_1601_1970); mtime_ms_1970_utc } /** Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions. This is *not* chosen to match the location where Cargo places its cache data, because Cargo is *wrong*. This is at least *less wrong*. On Windows, LocalAppData is where user- and machine- specific data should go, but it *might* be more appropriate to use whatever the official name for "Program Data" is, though. */ pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError> where P: AsRef<Path> { let dir = try!(SHGetKnownFolderPath(&FOLDERID_LocalAppData, 0, ::std::ptr::null_mut()) .map_err(|e| e.to_string())); Ok(Path::new(&dir).to_path_buf().join(product)) } type WinResult<T> = Result<T, WinError>; struct WinError(winapi::HRESULT); impl fmt::Display for WinError { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "HRESULT({})", self.0) } } fn SHGetKnownFolderPath(rfid: &winapi::KNOWNFOLDERID, dwFlags: winapi::DWORD, hToken: winapi::HANDLE) -> WinResult<OsString> { use self::winapi::PWSTR; let mut psz_path: PWSTR = unsafe { mem::uninitialized() }; let hresult = unsafe { shell32::SHGetKnownFolderPath( rfid, dwFlags, hToken, mem::transmute(&mut psz_path as &mut PWSTR as *mut PWSTR) ) }; if hresult == winapi::S_OK { let r = unsafe { pwstr_to_os_string(psz_path) }; unsafe { ole32::CoTaskMemFree(psz_path as *mut _) }; Ok(r) } else { Err(WinError(hresult)) } } unsafe fn pwstr_to_os_string(ptr: winapi::PWSTR) -> OsString { OsStringExt::from_wide(::std::slice::from_raw_parts(ptr, pwstr_len(ptr))) } unsafe fn pwstr_len(mut ptr: winapi::PWSTR) -> usize { let mut len = 0; while *ptr!= 0 { len += 1; ptr = ptr.offset(1); } len } }
return 0 } let now_ms_1970_utc = (now_1970_utc.sec as u64 * 1000)
random_line_split
tag-align-u64.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. // ignore-linux #7340 fails on 32-bit linux // ignore-macos #7340 fails on 32-bit macos use std::cast; enum Tag { Tag(u64) } struct Rec { c8: u8, t: Tag }
fn is_8_byte_aligned(u: &Tag) -> bool { let p: uint = unsafe { cast::transmute(u) }; return (p & 7u) == 0u; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t)); }
fn mk_rec() -> Rec { return Rec { c8:0u8, t:Tag(0u64) }; }
random_line_split
tag-align-u64.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. // ignore-linux #7340 fails on 32-bit linux // ignore-macos #7340 fails on 32-bit macos use std::cast; enum Tag { Tag(u64) } struct Rec { c8: u8, t: Tag } fn mk_rec() -> Rec
fn is_8_byte_aligned(u: &Tag) -> bool { let p: uint = unsafe { cast::transmute(u) }; return (p & 7u) == 0u; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t)); }
{ return Rec { c8:0u8, t:Tag(0u64) }; }
identifier_body
tag-align-u64.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. // ignore-linux #7340 fails on 32-bit linux // ignore-macos #7340 fails on 32-bit macos use std::cast; enum Tag { Tag(u64) } struct
{ c8: u8, t: Tag } fn mk_rec() -> Rec { return Rec { c8:0u8, t:Tag(0u64) }; } fn is_8_byte_aligned(u: &Tag) -> bool { let p: uint = unsafe { cast::transmute(u) }; return (p & 7u) == 0u; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t)); }
Rec
identifier_name
leaf_set.rs
// Copyright 2021 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The Grin leaf_set implementation. //! Compact (roaring) bitmap representing the set of leaf positions //! that exist and are not currently pruned in the MMR. use std::path::{Path, PathBuf}; use croaring::Bitmap; use crate::core::core::hash::Hashed; use crate::core::core::pmmr; use crate::core::core::BlockHeader; use crate::prune_list::PruneList; use crate::{read_bitmap, save_via_temp_file}; use std::fs::File; use std::io::{self, BufWriter, Write}; /// Compact (roaring) bitmap representing the set of positions of /// leaves that are currently unpruned in the MMR. pub struct LeafSet { path: PathBuf, bitmap: Bitmap, bitmap_bak: Bitmap, } impl LeafSet { /// Open the remove log file. /// The content of the file will be read in memory for fast checking. pub fn open<P: AsRef<Path>>(path: P) -> io::Result<LeafSet> { let file_path = path.as_ref(); let bitmap = if file_path.exists() { read_bitmap(&file_path)? } else { Bitmap::create() }; if!bitmap.is_empty() { debug!( "bitmap {} pos ({} bytes)", bitmap.cardinality(), bitmap.get_serialized_size_in_bytes(), ); } Ok(LeafSet { path: file_path.to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }) } /// Copies a snapshot of the utxo file into the primary utxo file. pub fn copy_snapshot<P: AsRef<Path>>(path: P, cp_path: P) -> io::Result<()> { let cp_file_path = cp_path.as_ref(); if!cp_file_path.exists() { debug!( "leaf_set: rewound leaf file not found: {}", cp_file_path.display() ); return Ok(()); } let bitmap = read_bitmap(&cp_file_path)?; debug!( "leaf_set: copying rewound file {} to {}", cp_file_path.display(), path.as_ref().display() ); let mut leaf_set = LeafSet { path: path.as_ref().to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }; leaf_set.flush()?; Ok(()) } /// Calculate the set of unpruned leaves /// up to and including the cutoff_pos. /// Only applicable for the output MMR. fn unpruned_pre_cutoff(&self, cutoff_pos: u64, prune_list: &PruneList) -> Bitmap { (1..=cutoff_pos) .filter(|&x| pmmr::is_leaf(x - 1) &&!prune_list.is_pruned(x - 1)) .map(|x| x as u32) .collect() } /// Calculate the set of pruned positions /// up to and including the cutoff_pos. /// Uses both the leaf_set and the prune_list to determine prunedness. pub fn
( &self, cutoff_pos: u64, rewind_rm_pos: &Bitmap, prune_list: &PruneList, ) -> Bitmap { let mut bitmap = self.bitmap.clone(); // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..bitmap.maximum().unwrap_or(0); bitmap.remove_range_closed(to_remove); // Then add back output pos to the leaf_set // that were removed. bitmap.or_inplace(&rewind_rm_pos); // Invert bitmap for the leaf pos and return the resulting bitmap. bitmap .flip(1..(cutoff_pos + 1)) .and(&self.unpruned_pre_cutoff(cutoff_pos, prune_list)) } /// Rewinds the leaf_set back to a previous state. /// Removes all pos after the cutoff. /// Adds back all pos in rewind_rm_pos. pub fn rewind(&mut self, cutoff_pos: u64, rewind_rm_pos: &Bitmap) { // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..self.bitmap.maximum().unwrap_or(0); self.bitmap.remove_range_closed(to_remove); // Then add back output pos to the leaf_set // that were removed. self.bitmap.or_inplace(&rewind_rm_pos); } /// Append a new position to the leaf_set. pub fn add(&mut self, pos0: u64) { self.bitmap.add(1 + pos0 as u32); } /// Remove the provided position from the leaf_set. pub fn remove(&mut self, pos0: u64) { self.bitmap.remove(1 + pos0 as u32); } /// Saves the utxo file tagged with block hash as filename suffix. /// Needed during fast-sync as the receiving node cannot rewind /// after receiving the txhashset zip file. pub fn snapshot(&self, header: &BlockHeader) -> io::Result<()> { let mut cp_bitmap = self.bitmap.clone(); cp_bitmap.run_optimize(); let cp_path = format!("{}.{}", self.path.to_str().unwrap(), header.hash()); let mut file = BufWriter::new(File::create(cp_path)?); file.write_all(&cp_bitmap.serialize())?; file.flush()?; Ok(()) } /// Flush the leaf_set to file. pub fn flush(&mut self) -> io::Result<()> { // First run the optimization step on the bitmap. self.bitmap.run_optimize(); // Write the updated bitmap file to disk. save_via_temp_file(&self.path, ".tmp", |file| { file.write_all(&self.bitmap.serialize()) })?; // Make sure our backup in memory is up to date. self.bitmap_bak = self.bitmap.clone(); Ok(()) } /// Discard any pending changes. pub fn discard(&mut self) { self.bitmap = self.bitmap_bak.clone(); } /// Whether the leaf_set includes the provided position. pub fn includes(&self, pos0: u64) -> bool { self.bitmap.contains(1 + pos0 as u32) } /// Number of positions stored in the leaf_set. pub fn len(&self) -> usize { self.bitmap.cardinality() as usize } /// Is the leaf_set empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Iterator over positionns in the leaf_set (all leaf positions). pub fn iter(&self) -> impl Iterator<Item = u64> + '_ { self.bitmap.iter().map(|x| x as u64) } }
removed_pre_cutoff
identifier_name
leaf_set.rs
// Copyright 2021 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The Grin leaf_set implementation. //! Compact (roaring) bitmap representing the set of leaf positions //! that exist and are not currently pruned in the MMR. use std::path::{Path, PathBuf}; use croaring::Bitmap; use crate::core::core::hash::Hashed; use crate::core::core::pmmr; use crate::core::core::BlockHeader; use crate::prune_list::PruneList; use crate::{read_bitmap, save_via_temp_file}; use std::fs::File; use std::io::{self, BufWriter, Write}; /// Compact (roaring) bitmap representing the set of positions of /// leaves that are currently unpruned in the MMR. pub struct LeafSet { path: PathBuf, bitmap: Bitmap, bitmap_bak: Bitmap, } impl LeafSet { /// Open the remove log file. /// The content of the file will be read in memory for fast checking. pub fn open<P: AsRef<Path>>(path: P) -> io::Result<LeafSet> { let file_path = path.as_ref(); let bitmap = if file_path.exists() { read_bitmap(&file_path)?
if!bitmap.is_empty() { debug!( "bitmap {} pos ({} bytes)", bitmap.cardinality(), bitmap.get_serialized_size_in_bytes(), ); } Ok(LeafSet { path: file_path.to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }) } /// Copies a snapshot of the utxo file into the primary utxo file. pub fn copy_snapshot<P: AsRef<Path>>(path: P, cp_path: P) -> io::Result<()> { let cp_file_path = cp_path.as_ref(); if!cp_file_path.exists() { debug!( "leaf_set: rewound leaf file not found: {}", cp_file_path.display() ); return Ok(()); } let bitmap = read_bitmap(&cp_file_path)?; debug!( "leaf_set: copying rewound file {} to {}", cp_file_path.display(), path.as_ref().display() ); let mut leaf_set = LeafSet { path: path.as_ref().to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }; leaf_set.flush()?; Ok(()) } /// Calculate the set of unpruned leaves /// up to and including the cutoff_pos. /// Only applicable for the output MMR. fn unpruned_pre_cutoff(&self, cutoff_pos: u64, prune_list: &PruneList) -> Bitmap { (1..=cutoff_pos) .filter(|&x| pmmr::is_leaf(x - 1) &&!prune_list.is_pruned(x - 1)) .map(|x| x as u32) .collect() } /// Calculate the set of pruned positions /// up to and including the cutoff_pos. /// Uses both the leaf_set and the prune_list to determine prunedness. pub fn removed_pre_cutoff( &self, cutoff_pos: u64, rewind_rm_pos: &Bitmap, prune_list: &PruneList, ) -> Bitmap { let mut bitmap = self.bitmap.clone(); // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..bitmap.maximum().unwrap_or(0); bitmap.remove_range_closed(to_remove); // Then add back output pos to the leaf_set // that were removed. bitmap.or_inplace(&rewind_rm_pos); // Invert bitmap for the leaf pos and return the resulting bitmap. bitmap .flip(1..(cutoff_pos + 1)) .and(&self.unpruned_pre_cutoff(cutoff_pos, prune_list)) } /// Rewinds the leaf_set back to a previous state. /// Removes all pos after the cutoff. /// Adds back all pos in rewind_rm_pos. pub fn rewind(&mut self, cutoff_pos: u64, rewind_rm_pos: &Bitmap) { // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..self.bitmap.maximum().unwrap_or(0); self.bitmap.remove_range_closed(to_remove); // Then add back output pos to the leaf_set // that were removed. self.bitmap.or_inplace(&rewind_rm_pos); } /// Append a new position to the leaf_set. pub fn add(&mut self, pos0: u64) { self.bitmap.add(1 + pos0 as u32); } /// Remove the provided position from the leaf_set. pub fn remove(&mut self, pos0: u64) { self.bitmap.remove(1 + pos0 as u32); } /// Saves the utxo file tagged with block hash as filename suffix. /// Needed during fast-sync as the receiving node cannot rewind /// after receiving the txhashset zip file. pub fn snapshot(&self, header: &BlockHeader) -> io::Result<()> { let mut cp_bitmap = self.bitmap.clone(); cp_bitmap.run_optimize(); let cp_path = format!("{}.{}", self.path.to_str().unwrap(), header.hash()); let mut file = BufWriter::new(File::create(cp_path)?); file.write_all(&cp_bitmap.serialize())?; file.flush()?; Ok(()) } /// Flush the leaf_set to file. pub fn flush(&mut self) -> io::Result<()> { // First run the optimization step on the bitmap. self.bitmap.run_optimize(); // Write the updated bitmap file to disk. save_via_temp_file(&self.path, ".tmp", |file| { file.write_all(&self.bitmap.serialize()) })?; // Make sure our backup in memory is up to date. self.bitmap_bak = self.bitmap.clone(); Ok(()) } /// Discard any pending changes. pub fn discard(&mut self) { self.bitmap = self.bitmap_bak.clone(); } /// Whether the leaf_set includes the provided position. pub fn includes(&self, pos0: u64) -> bool { self.bitmap.contains(1 + pos0 as u32) } /// Number of positions stored in the leaf_set. pub fn len(&self) -> usize { self.bitmap.cardinality() as usize } /// Is the leaf_set empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Iterator over positionns in the leaf_set (all leaf positions). pub fn iter(&self) -> impl Iterator<Item = u64> + '_ { self.bitmap.iter().map(|x| x as u64) } }
} else { Bitmap::create() };
random_line_split
leaf_set.rs
// Copyright 2021 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The Grin leaf_set implementation. //! Compact (roaring) bitmap representing the set of leaf positions //! that exist and are not currently pruned in the MMR. use std::path::{Path, PathBuf}; use croaring::Bitmap; use crate::core::core::hash::Hashed; use crate::core::core::pmmr; use crate::core::core::BlockHeader; use crate::prune_list::PruneList; use crate::{read_bitmap, save_via_temp_file}; use std::fs::File; use std::io::{self, BufWriter, Write}; /// Compact (roaring) bitmap representing the set of positions of /// leaves that are currently unpruned in the MMR. pub struct LeafSet { path: PathBuf, bitmap: Bitmap, bitmap_bak: Bitmap, } impl LeafSet { /// Open the remove log file. /// The content of the file will be read in memory for fast checking. pub fn open<P: AsRef<Path>>(path: P) -> io::Result<LeafSet> { let file_path = path.as_ref(); let bitmap = if file_path.exists() { read_bitmap(&file_path)? } else { Bitmap::create() }; if!bitmap.is_empty() { debug!( "bitmap {} pos ({} bytes)", bitmap.cardinality(), bitmap.get_serialized_size_in_bytes(), ); } Ok(LeafSet { path: file_path.to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }) } /// Copies a snapshot of the utxo file into the primary utxo file. pub fn copy_snapshot<P: AsRef<Path>>(path: P, cp_path: P) -> io::Result<()> { let cp_file_path = cp_path.as_ref(); if!cp_file_path.exists() { debug!( "leaf_set: rewound leaf file not found: {}", cp_file_path.display() ); return Ok(()); } let bitmap = read_bitmap(&cp_file_path)?; debug!( "leaf_set: copying rewound file {} to {}", cp_file_path.display(), path.as_ref().display() ); let mut leaf_set = LeafSet { path: path.as_ref().to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }; leaf_set.flush()?; Ok(()) } /// Calculate the set of unpruned leaves /// up to and including the cutoff_pos. /// Only applicable for the output MMR. fn unpruned_pre_cutoff(&self, cutoff_pos: u64, prune_list: &PruneList) -> Bitmap { (1..=cutoff_pos) .filter(|&x| pmmr::is_leaf(x - 1) &&!prune_list.is_pruned(x - 1)) .map(|x| x as u32) .collect() } /// Calculate the set of pruned positions /// up to and including the cutoff_pos. /// Uses both the leaf_set and the prune_list to determine prunedness. pub fn removed_pre_cutoff( &self, cutoff_pos: u64, rewind_rm_pos: &Bitmap, prune_list: &PruneList, ) -> Bitmap { let mut bitmap = self.bitmap.clone(); // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..bitmap.maximum().unwrap_or(0); bitmap.remove_range_closed(to_remove); // Then add back output pos to the leaf_set // that were removed. bitmap.or_inplace(&rewind_rm_pos); // Invert bitmap for the leaf pos and return the resulting bitmap. bitmap .flip(1..(cutoff_pos + 1)) .and(&self.unpruned_pre_cutoff(cutoff_pos, prune_list)) } /// Rewinds the leaf_set back to a previous state. /// Removes all pos after the cutoff. /// Adds back all pos in rewind_rm_pos. pub fn rewind(&mut self, cutoff_pos: u64, rewind_rm_pos: &Bitmap) { // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..self.bitmap.maximum().unwrap_or(0); self.bitmap.remove_range_closed(to_remove); // Then add back output pos to the leaf_set // that were removed. self.bitmap.or_inplace(&rewind_rm_pos); } /// Append a new position to the leaf_set. pub fn add(&mut self, pos0: u64)
/// Remove the provided position from the leaf_set. pub fn remove(&mut self, pos0: u64) { self.bitmap.remove(1 + pos0 as u32); } /// Saves the utxo file tagged with block hash as filename suffix. /// Needed during fast-sync as the receiving node cannot rewind /// after receiving the txhashset zip file. pub fn snapshot(&self, header: &BlockHeader) -> io::Result<()> { let mut cp_bitmap = self.bitmap.clone(); cp_bitmap.run_optimize(); let cp_path = format!("{}.{}", self.path.to_str().unwrap(), header.hash()); let mut file = BufWriter::new(File::create(cp_path)?); file.write_all(&cp_bitmap.serialize())?; file.flush()?; Ok(()) } /// Flush the leaf_set to file. pub fn flush(&mut self) -> io::Result<()> { // First run the optimization step on the bitmap. self.bitmap.run_optimize(); // Write the updated bitmap file to disk. save_via_temp_file(&self.path, ".tmp", |file| { file.write_all(&self.bitmap.serialize()) })?; // Make sure our backup in memory is up to date. self.bitmap_bak = self.bitmap.clone(); Ok(()) } /// Discard any pending changes. pub fn discard(&mut self) { self.bitmap = self.bitmap_bak.clone(); } /// Whether the leaf_set includes the provided position. pub fn includes(&self, pos0: u64) -> bool { self.bitmap.contains(1 + pos0 as u32) } /// Number of positions stored in the leaf_set. pub fn len(&self) -> usize { self.bitmap.cardinality() as usize } /// Is the leaf_set empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Iterator over positionns in the leaf_set (all leaf positions). pub fn iter(&self) -> impl Iterator<Item = u64> + '_ { self.bitmap.iter().map(|x| x as u64) } }
{ self.bitmap.add(1 + pos0 as u32); }
identifier_body
leaf_set.rs
// Copyright 2021 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The Grin leaf_set implementation. //! Compact (roaring) bitmap representing the set of leaf positions //! that exist and are not currently pruned in the MMR. use std::path::{Path, PathBuf}; use croaring::Bitmap; use crate::core::core::hash::Hashed; use crate::core::core::pmmr; use crate::core::core::BlockHeader; use crate::prune_list::PruneList; use crate::{read_bitmap, save_via_temp_file}; use std::fs::File; use std::io::{self, BufWriter, Write}; /// Compact (roaring) bitmap representing the set of positions of /// leaves that are currently unpruned in the MMR. pub struct LeafSet { path: PathBuf, bitmap: Bitmap, bitmap_bak: Bitmap, } impl LeafSet { /// Open the remove log file. /// The content of the file will be read in memory for fast checking. pub fn open<P: AsRef<Path>>(path: P) -> io::Result<LeafSet> { let file_path = path.as_ref(); let bitmap = if file_path.exists() { read_bitmap(&file_path)? } else { Bitmap::create() }; if!bitmap.is_empty() { debug!( "bitmap {} pos ({} bytes)", bitmap.cardinality(), bitmap.get_serialized_size_in_bytes(), ); } Ok(LeafSet { path: file_path.to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }) } /// Copies a snapshot of the utxo file into the primary utxo file. pub fn copy_snapshot<P: AsRef<Path>>(path: P, cp_path: P) -> io::Result<()> { let cp_file_path = cp_path.as_ref(); if!cp_file_path.exists()
let bitmap = read_bitmap(&cp_file_path)?; debug!( "leaf_set: copying rewound file {} to {}", cp_file_path.display(), path.as_ref().display() ); let mut leaf_set = LeafSet { path: path.as_ref().to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }; leaf_set.flush()?; Ok(()) } /// Calculate the set of unpruned leaves /// up to and including the cutoff_pos. /// Only applicable for the output MMR. fn unpruned_pre_cutoff(&self, cutoff_pos: u64, prune_list: &PruneList) -> Bitmap { (1..=cutoff_pos) .filter(|&x| pmmr::is_leaf(x - 1) &&!prune_list.is_pruned(x - 1)) .map(|x| x as u32) .collect() } /// Calculate the set of pruned positions /// up to and including the cutoff_pos. /// Uses both the leaf_set and the prune_list to determine prunedness. pub fn removed_pre_cutoff( &self, cutoff_pos: u64, rewind_rm_pos: &Bitmap, prune_list: &PruneList, ) -> Bitmap { let mut bitmap = self.bitmap.clone(); // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..bitmap.maximum().unwrap_or(0); bitmap.remove_range_closed(to_remove); // Then add back output pos to the leaf_set // that were removed. bitmap.or_inplace(&rewind_rm_pos); // Invert bitmap for the leaf pos and return the resulting bitmap. bitmap .flip(1..(cutoff_pos + 1)) .and(&self.unpruned_pre_cutoff(cutoff_pos, prune_list)) } /// Rewinds the leaf_set back to a previous state. /// Removes all pos after the cutoff. /// Adds back all pos in rewind_rm_pos. pub fn rewind(&mut self, cutoff_pos: u64, rewind_rm_pos: &Bitmap) { // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..self.bitmap.maximum().unwrap_or(0); self.bitmap.remove_range_closed(to_remove); // Then add back output pos to the leaf_set // that were removed. self.bitmap.or_inplace(&rewind_rm_pos); } /// Append a new position to the leaf_set. pub fn add(&mut self, pos0: u64) { self.bitmap.add(1 + pos0 as u32); } /// Remove the provided position from the leaf_set. pub fn remove(&mut self, pos0: u64) { self.bitmap.remove(1 + pos0 as u32); } /// Saves the utxo file tagged with block hash as filename suffix. /// Needed during fast-sync as the receiving node cannot rewind /// after receiving the txhashset zip file. pub fn snapshot(&self, header: &BlockHeader) -> io::Result<()> { let mut cp_bitmap = self.bitmap.clone(); cp_bitmap.run_optimize(); let cp_path = format!("{}.{}", self.path.to_str().unwrap(), header.hash()); let mut file = BufWriter::new(File::create(cp_path)?); file.write_all(&cp_bitmap.serialize())?; file.flush()?; Ok(()) } /// Flush the leaf_set to file. pub fn flush(&mut self) -> io::Result<()> { // First run the optimization step on the bitmap. self.bitmap.run_optimize(); // Write the updated bitmap file to disk. save_via_temp_file(&self.path, ".tmp", |file| { file.write_all(&self.bitmap.serialize()) })?; // Make sure our backup in memory is up to date. self.bitmap_bak = self.bitmap.clone(); Ok(()) } /// Discard any pending changes. pub fn discard(&mut self) { self.bitmap = self.bitmap_bak.clone(); } /// Whether the leaf_set includes the provided position. pub fn includes(&self, pos0: u64) -> bool { self.bitmap.contains(1 + pos0 as u32) } /// Number of positions stored in the leaf_set. pub fn len(&self) -> usize { self.bitmap.cardinality() as usize } /// Is the leaf_set empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Iterator over positionns in the leaf_set (all leaf positions). pub fn iter(&self) -> impl Iterator<Item = u64> + '_ { self.bitmap.iter().map(|x| x as u64) } }
{ debug!( "leaf_set: rewound leaf file not found: {}", cp_file_path.display() ); return Ok(()); }
conditional_block
usage.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io; pub fn general() { io::println("Usage: rustpkg [options] <cmd> [args..] Where <cmd> is one of: build, clean, do, info, install, list, prefer, test, uninstall, unprefer Options: -h, --help Display this message <cmd> -h, <cmd> --help Display help for <cmd>"); } pub fn build() { io::println("rustpkg [options..] build Build all targets described in the package script in the current directory. Options: -c, --cfg Pass a cfg flag to the package script"); } pub fn clean() { io::println("rustpkg clean Remove all build files in the work cache for the package in the current directory."); } pub fn do_cmd() { io::println("rustpkg do <cmd> Runs a command in the package script. You can listen to a command by tagging a function with the attribute `#[pkg_do(cmd)]`."); } pub fn info() { io::println("rustpkg [options..] info Probe the package script in the current directory for information. Options: -j, --json Output the result as JSON"); } pub fn list() { io::println("rustpkg list List all installed packages."); }
Install a package from a URL by Git or cURL (FTP, HTTP, etc.). If target is provided, Git will checkout the branch or tag before continuing. If the URL is a TAR file (with or without compression), extract it before installing. If a URL isn't provided, the package will be built and installed from the current directory (which is functionally the same as `rustpkg build` and installing the result). Examples: rustpkg install rustpkg install git://github.com/mozilla/servo.git rustpkg install git://github.com/mozilla/servo.git v0.1.2 rustpkg install http://rust-lang.org/servo-0.1.2.tar.gz Options: -c, --cfg Pass a cfg flag to the package script"); } pub fn uninstall() { io::println("rustpkg uninstall <id|name>[@version] Remove a package by id or name and optionally version. If the package(s) is/are depended on by another package then they cannot be removed."); } pub fn prefer() { io::println("rustpkg [options..] prefer <id|name>[@version] By default all binaries are given a unique name so that multiple versions can coexist. The prefer command will symlink the uniquely named binary to the binary directory under its bare name. If version is not supplied, the latest version of the package will be preferred. Example: export PATH=$PATH:/home/user/.rustpkg/bin rustpkg prefer [email protected] machine -v ==> v1.2.4 rustpkg prefer [email protected] machine -v ==> v0.4.6"); } pub fn unprefer() { io::println("rustpkg [options..] unprefer <id|name>[@version] Remove all symlinks from the store to the binary directory for a package name and optionally version. If version is not supplied, the latest version of the package will be unpreferred. See `rustpkg prefer -h` for more information."); } pub fn test() { io::println("rustpkg [options..] test Build all targets described in the package script in the current directory with the test flag. The test bootstraps will be run afterwards and the output and exit code will be redirected. Options: -c, --cfg Pass a cfg flag to the package script"); }
pub fn install() { io::println("rustpkg [options..] install [url] [target]
random_line_split
usage.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io; pub fn general() { io::println("Usage: rustpkg [options] <cmd> [args..] Where <cmd> is one of: build, clean, do, info, install, list, prefer, test, uninstall, unprefer Options: -h, --help Display this message <cmd> -h, <cmd> --help Display help for <cmd>"); } pub fn
() { io::println("rustpkg [options..] build Build all targets described in the package script in the current directory. Options: -c, --cfg Pass a cfg flag to the package script"); } pub fn clean() { io::println("rustpkg clean Remove all build files in the work cache for the package in the current directory."); } pub fn do_cmd() { io::println("rustpkg do <cmd> Runs a command in the package script. You can listen to a command by tagging a function with the attribute `#[pkg_do(cmd)]`."); } pub fn info() { io::println("rustpkg [options..] info Probe the package script in the current directory for information. Options: -j, --json Output the result as JSON"); } pub fn list() { io::println("rustpkg list List all installed packages."); } pub fn install() { io::println("rustpkg [options..] install [url] [target] Install a package from a URL by Git or cURL (FTP, HTTP, etc.). If target is provided, Git will checkout the branch or tag before continuing. If the URL is a TAR file (with or without compression), extract it before installing. If a URL isn't provided, the package will be built and installed from the current directory (which is functionally the same as `rustpkg build` and installing the result). Examples: rustpkg install rustpkg install git://github.com/mozilla/servo.git rustpkg install git://github.com/mozilla/servo.git v0.1.2 rustpkg install http://rust-lang.org/servo-0.1.2.tar.gz Options: -c, --cfg Pass a cfg flag to the package script"); } pub fn uninstall() { io::println("rustpkg uninstall <id|name>[@version] Remove a package by id or name and optionally version. If the package(s) is/are depended on by another package then they cannot be removed."); } pub fn prefer() { io::println("rustpkg [options..] prefer <id|name>[@version] By default all binaries are given a unique name so that multiple versions can coexist. The prefer command will symlink the uniquely named binary to the binary directory under its bare name. If version is not supplied, the latest version of the package will be preferred. Example: export PATH=$PATH:/home/user/.rustpkg/bin rustpkg prefer [email protected] machine -v ==> v1.2.4 rustpkg prefer [email protected] machine -v ==> v0.4.6"); } pub fn unprefer() { io::println("rustpkg [options..] unprefer <id|name>[@version] Remove all symlinks from the store to the binary directory for a package name and optionally version. If version is not supplied, the latest version of the package will be unpreferred. See `rustpkg prefer -h` for more information."); } pub fn test() { io::println("rustpkg [options..] test Build all targets described in the package script in the current directory with the test flag. The test bootstraps will be run afterwards and the output and exit code will be redirected. Options: -c, --cfg Pass a cfg flag to the package script"); }
build
identifier_name
usage.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io; pub fn general() { io::println("Usage: rustpkg [options] <cmd> [args..] Where <cmd> is one of: build, clean, do, info, install, list, prefer, test, uninstall, unprefer Options: -h, --help Display this message <cmd> -h, <cmd> --help Display help for <cmd>"); } pub fn build() { io::println("rustpkg [options..] build Build all targets described in the package script in the current directory. Options: -c, --cfg Pass a cfg flag to the package script"); } pub fn clean() { io::println("rustpkg clean Remove all build files in the work cache for the package in the current directory."); } pub fn do_cmd() { io::println("rustpkg do <cmd> Runs a command in the package script. You can listen to a command by tagging a function with the attribute `#[pkg_do(cmd)]`."); } pub fn info() { io::println("rustpkg [options..] info Probe the package script in the current directory for information. Options: -j, --json Output the result as JSON"); } pub fn list() { io::println("rustpkg list List all installed packages."); } pub fn install() { io::println("rustpkg [options..] install [url] [target] Install a package from a URL by Git or cURL (FTP, HTTP, etc.). If target is provided, Git will checkout the branch or tag before continuing. If the URL is a TAR file (with or without compression), extract it before installing. If a URL isn't provided, the package will be built and installed from the current directory (which is functionally the same as `rustpkg build` and installing the result). Examples: rustpkg install rustpkg install git://github.com/mozilla/servo.git rustpkg install git://github.com/mozilla/servo.git v0.1.2 rustpkg install http://rust-lang.org/servo-0.1.2.tar.gz Options: -c, --cfg Pass a cfg flag to the package script"); } pub fn uninstall() { io::println("rustpkg uninstall <id|name>[@version] Remove a package by id or name and optionally version. If the package(s) is/are depended on by another package then they cannot be removed."); } pub fn prefer()
pub fn unprefer() { io::println("rustpkg [options..] unprefer <id|name>[@version] Remove all symlinks from the store to the binary directory for a package name and optionally version. If version is not supplied, the latest version of the package will be unpreferred. See `rustpkg prefer -h` for more information."); } pub fn test() { io::println("rustpkg [options..] test Build all targets described in the package script in the current directory with the test flag. The test bootstraps will be run afterwards and the output and exit code will be redirected. Options: -c, --cfg Pass a cfg flag to the package script"); }
{ io::println("rustpkg [options..] prefer <id|name>[@version] By default all binaries are given a unique name so that multiple versions can coexist. The prefer command will symlink the uniquely named binary to the binary directory under its bare name. If version is not supplied, the latest version of the package will be preferred. Example: export PATH=$PATH:/home/user/.rustpkg/bin rustpkg prefer [email protected] machine -v ==> v1.2.4 rustpkg prefer [email protected] machine -v ==> v0.4.6"); }
identifier_body
shellscalingapi.rs
// except according to those terms. ENUM!{enum PROCESS_DPI_AWARENESS { Process_DPI_Unaware = 0, Process_System_DPI_Aware = 1, Process_Per_Monitor_DPI_Aware = 2, }} ENUM!{enum MONITOR_DPI_TYPE { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI, }} ENUM!{enum SHELL_UI_COMPONENT { SHELL_UI_COMPONENT_TASKBARS = 0, SHELL_UI_COMPONENT_NOTIFICATIONAREA = 1, SHELL_UI_COMPONENT_DESKBAND = 2, }}
// Copyright © 2015-2017 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed
random_line_split
system_allocator.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use base::pagesize; use crate::address_allocator::{AddressAllocator, AddressAllocatorSet}; use crate::{Alloc, Error, Result}; /// Manages allocating system resources such as address space and interrupt numbers. /// MMIO address Type /// Low: address allocated from low_address_space /// High: address allocated from high_address_space #[derive(Copy, Clone)] pub enum MmioType { Low, High, } /// Region of memory. pub struct MemRegion { pub base: u64, pub size: u64, } pub struct SystemAllocatorConfig { /// IO ports. Only for x86_64. pub io: Option<MemRegion>, /// Low (<=4GB) MMIO region. pub low_mmio: MemRegion, /// High (>4GB) MMIO region. pub high_mmio: MemRegion, /// Platform MMIO space. Only for ARM. pub platform_mmio: Option<MemRegion>, /// The first IRQ number to give out. pub first_irq: u32, } #[derive(Debug)] pub struct SystemAllocator { io_address_space: Option<AddressAllocator>, // Indexed by MmioType::Low and MmioType::High. mmio_address_spaces: [AddressAllocator; 2], mmio_platform_address_spaces: Option<AddressAllocator>, // Each bus number has a AddressAllocator pci_allocator: BTreeMap<u8, AddressAllocator>, irq_allocator: AddressAllocator, next_anon_id: usize, } impl SystemAllocator { /// Creates a new `SystemAllocator` for managing addresses and irq numbers. /// Will return an error if `base` + `size` overflows u64 (or allowed /// maximum for the specific type), or if alignment isn't a power of two. /// pub fn new(config: SystemAllocatorConfig) -> Result<Self> { let page_size = pagesize() as u64; Ok(SystemAllocator { io_address_space: if let Some(io) = config.io { // TODO make sure we don't overlap with existing well known // ports such as 0xcf8 (serial ports). if io.base > 0x1_0000 || io.size + io.base > 0x1_0000 { return Err(Error::IOPortOutOfRange(io.base, io.size)); } Some(AddressAllocator::new(io.base, io.size, Some(0x400), None)?) } else { None }, mmio_address_spaces: [ // MmioType::Low AddressAllocator::new( config.low_mmio.base, config.low_mmio.size, Some(page_size), None, )?, // MmioType::High AddressAllocator::new( config.high_mmio.base, config.high_mmio.size, Some(page_size), None, )?, ], pci_allocator: BTreeMap::new(), mmio_platform_address_spaces: if let Some(platform) = config.platform_mmio { Some(AddressAllocator::new( platform.base, platform.size, Some(page_size), None, )?) } else { None }, irq_allocator: AddressAllocator::new( config.first_irq as u64, 1024 - config.first_irq as u64, Some(1), None, )?, next_anon_id: 0, }) } /// Reserves the next available system irq number. pub fn allocate_irq(&mut self) -> Option<u32> { let id = self.get_anon_alloc(); self.irq_allocator .allocate(1, id, "irq-auto".to_string()) .map(|v| v as u32) .ok() } /// release irq to system irq number pool pub fn release_irq(&mut self, irq: u32) { let _ = self.irq_allocator.release_containing(irq.into()); } /// Reserves the next available system irq number. pub fn reserve_irq(&mut self, irq: u32) -> bool { let id = self.get_anon_alloc(); self.irq_allocator .allocate_at(irq as u64, 1, id, "irq-fixed".to_string()) .is_ok() } fn get_pci_allocator_mut(&mut self, bus: u8) -> Option<&mut AddressAllocator> { // pci root is 00:00.0, Bus 0 next device is 00:01.0 with mandatory function // number zero. if self.pci_allocator.get(&bus).is_none() { let base = if bus == 0 { 8 } else { 0 }; // Each bus supports up to 32 (devices) x 8 (functions). // Prefer allocating at device granularity (preferred_align = 8), but fall back to // allocating individual functions (min_align = 1) when we run out of devices. match AddressAllocator::new(base, (32 * 8) - base, Some(1), Some(8)) { Ok(v) => self.pci_allocator.insert(bus, v), Err(_) => return None, }; } self.pci_allocator.get_mut(&bus) } // Check whether devices exist or not on the specified bus pub fn pci_bus_empty(&self, bus: u8) -> bool
/// Allocate PCI slot location. pub fn allocate_pci(&mut self, bus: u8, tag: String) -> Option<Alloc> { let id = self.get_anon_alloc(); let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return None, }; allocator .allocate(1, id, tag) .map(|v| Alloc::PciBar { bus, dev: (v >> 3) as u8, func: (v & 7) as u8, bar: 0, }) .ok() } /// Reserve PCI slot location. pub fn reserve_pci(&mut self, alloc: Alloc, tag: String) -> bool { let id = self.get_anon_alloc(); match alloc { Alloc::PciBar { bus, dev, func, bar: _, } => { let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return false, }; let df = ((dev as u64) << 3) | (func as u64); allocator.allocate_at(df, 1, id, tag).is_ok() } _ => false, } } /// release PCI slot location. pub fn release_pci(&mut self, bus: u8, dev: u8, func: u8) -> bool { let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return false, }; let df = ((dev as u64) << 3) | (func as u64); allocator.release_containing(df).is_ok() } /// Gets an allocator to be used for platform device MMIO allocation. pub fn mmio_platform_allocator(&mut self) -> Option<&mut AddressAllocator> { self.mmio_platform_address_spaces.as_mut() } /// Gets an allocator to be used for IO memory. pub fn io_allocator(&mut self) -> Option<&mut AddressAllocator> { self.io_address_space.as_mut() } /// Gets an allocator to be used for MMIO allocation. /// MmioType::Low: low mmio allocator /// MmioType::High: high mmio allocator pub fn mmio_allocator(&mut self, mmio_type: MmioType) -> &mut AddressAllocator { &mut self.mmio_address_spaces[mmio_type as usize] } /// Gets a set of allocators to be used for MMIO allocation. /// The set of allocators will try the low and high MMIO allocators, in that order. pub fn mmio_allocator_any(&mut self) -> AddressAllocatorSet { AddressAllocatorSet::new(&mut self.mmio_address_spaces) } /// Gets a unique anonymous allocation pub fn get_anon_alloc(&mut self) -> Alloc { self.next_anon_id += 1; Alloc::Anon(self.next_anon_id) } } #[cfg(test)] mod tests { use super::*; #[test] fn example() { let mut a = SystemAllocator::new(SystemAllocatorConfig { io: Some(MemRegion { base: 0x1000, size: 0xf000, }), low_mmio: MemRegion { base: 0x3000_0000, size: 0x1_0000, }, high_mmio: MemRegion { base: 0x1000_0000, size: 0x1000_0000, }, platform_mmio: None, first_irq: 5, }) .unwrap(); assert_eq!(a.allocate_irq(), Some(5)); assert_eq!(a.allocate_irq(), Some(6)); assert_eq!( a.mmio_allocator(MmioType::High).allocate( 0x100, Alloc::PciBar { bus: 0, dev: 0, func: 0, bar: 0 }, "bar0".to_string() ), Ok(0x10000000) ); assert_eq!( a.mmio_allocator(MmioType::High).get(&Alloc::PciBar { bus: 0, dev: 0, func: 0, bar: 0 }), Some(&(0x10000000, 0x100, "bar0".to_string())) ); } }
{ if self.pci_allocator.get(&bus).is_none() { true } else { false } }
identifier_body
system_allocator.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use base::pagesize; use crate::address_allocator::{AddressAllocator, AddressAllocatorSet}; use crate::{Alloc, Error, Result}; /// Manages allocating system resources such as address space and interrupt numbers. /// MMIO address Type /// Low: address allocated from low_address_space /// High: address allocated from high_address_space #[derive(Copy, Clone)] pub enum MmioType { Low, High, } /// Region of memory. pub struct MemRegion { pub base: u64, pub size: u64, } pub struct SystemAllocatorConfig { /// IO ports. Only for x86_64. pub io: Option<MemRegion>, /// Low (<=4GB) MMIO region. pub low_mmio: MemRegion, /// High (>4GB) MMIO region. pub high_mmio: MemRegion, /// Platform MMIO space. Only for ARM. pub platform_mmio: Option<MemRegion>, /// The first IRQ number to give out. pub first_irq: u32, } #[derive(Debug)] pub struct SystemAllocator { io_address_space: Option<AddressAllocator>, // Indexed by MmioType::Low and MmioType::High. mmio_address_spaces: [AddressAllocator; 2], mmio_platform_address_spaces: Option<AddressAllocator>, // Each bus number has a AddressAllocator pci_allocator: BTreeMap<u8, AddressAllocator>, irq_allocator: AddressAllocator, next_anon_id: usize, } impl SystemAllocator { /// Creates a new `SystemAllocator` for managing addresses and irq numbers. /// Will return an error if `base` + `size` overflows u64 (or allowed /// maximum for the specific type), or if alignment isn't a power of two. /// pub fn new(config: SystemAllocatorConfig) -> Result<Self> { let page_size = pagesize() as u64; Ok(SystemAllocator { io_address_space: if let Some(io) = config.io { // TODO make sure we don't overlap with existing well known // ports such as 0xcf8 (serial ports). if io.base > 0x1_0000 || io.size + io.base > 0x1_0000 { return Err(Error::IOPortOutOfRange(io.base, io.size)); } Some(AddressAllocator::new(io.base, io.size, Some(0x400), None)?) } else { None }, mmio_address_spaces: [ // MmioType::Low AddressAllocator::new( config.low_mmio.base, config.low_mmio.size, Some(page_size), None, )?, // MmioType::High AddressAllocator::new( config.high_mmio.base, config.high_mmio.size, Some(page_size), None, )?, ], pci_allocator: BTreeMap::new(), mmio_platform_address_spaces: if let Some(platform) = config.platform_mmio { Some(AddressAllocator::new( platform.base, platform.size, Some(page_size), None, )?) } else { None }, irq_allocator: AddressAllocator::new( config.first_irq as u64, 1024 - config.first_irq as u64, Some(1), None, )?, next_anon_id: 0, }) } /// Reserves the next available system irq number. pub fn allocate_irq(&mut self) -> Option<u32> { let id = self.get_anon_alloc(); self.irq_allocator .allocate(1, id, "irq-auto".to_string()) .map(|v| v as u32) .ok() } /// release irq to system irq number pool pub fn release_irq(&mut self, irq: u32) { let _ = self.irq_allocator.release_containing(irq.into()); } /// Reserves the next available system irq number. pub fn reserve_irq(&mut self, irq: u32) -> bool { let id = self.get_anon_alloc(); self.irq_allocator .allocate_at(irq as u64, 1, id, "irq-fixed".to_string()) .is_ok() } fn
(&mut self, bus: u8) -> Option<&mut AddressAllocator> { // pci root is 00:00.0, Bus 0 next device is 00:01.0 with mandatory function // number zero. if self.pci_allocator.get(&bus).is_none() { let base = if bus == 0 { 8 } else { 0 }; // Each bus supports up to 32 (devices) x 8 (functions). // Prefer allocating at device granularity (preferred_align = 8), but fall back to // allocating individual functions (min_align = 1) when we run out of devices. match AddressAllocator::new(base, (32 * 8) - base, Some(1), Some(8)) { Ok(v) => self.pci_allocator.insert(bus, v), Err(_) => return None, }; } self.pci_allocator.get_mut(&bus) } // Check whether devices exist or not on the specified bus pub fn pci_bus_empty(&self, bus: u8) -> bool { if self.pci_allocator.get(&bus).is_none() { true } else { false } } /// Allocate PCI slot location. pub fn allocate_pci(&mut self, bus: u8, tag: String) -> Option<Alloc> { let id = self.get_anon_alloc(); let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return None, }; allocator .allocate(1, id, tag) .map(|v| Alloc::PciBar { bus, dev: (v >> 3) as u8, func: (v & 7) as u8, bar: 0, }) .ok() } /// Reserve PCI slot location. pub fn reserve_pci(&mut self, alloc: Alloc, tag: String) -> bool { let id = self.get_anon_alloc(); match alloc { Alloc::PciBar { bus, dev, func, bar: _, } => { let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return false, }; let df = ((dev as u64) << 3) | (func as u64); allocator.allocate_at(df, 1, id, tag).is_ok() } _ => false, } } /// release PCI slot location. pub fn release_pci(&mut self, bus: u8, dev: u8, func: u8) -> bool { let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return false, }; let df = ((dev as u64) << 3) | (func as u64); allocator.release_containing(df).is_ok() } /// Gets an allocator to be used for platform device MMIO allocation. pub fn mmio_platform_allocator(&mut self) -> Option<&mut AddressAllocator> { self.mmio_platform_address_spaces.as_mut() } /// Gets an allocator to be used for IO memory. pub fn io_allocator(&mut self) -> Option<&mut AddressAllocator> { self.io_address_space.as_mut() } /// Gets an allocator to be used for MMIO allocation. /// MmioType::Low: low mmio allocator /// MmioType::High: high mmio allocator pub fn mmio_allocator(&mut self, mmio_type: MmioType) -> &mut AddressAllocator { &mut self.mmio_address_spaces[mmio_type as usize] } /// Gets a set of allocators to be used for MMIO allocation. /// The set of allocators will try the low and high MMIO allocators, in that order. pub fn mmio_allocator_any(&mut self) -> AddressAllocatorSet { AddressAllocatorSet::new(&mut self.mmio_address_spaces) } /// Gets a unique anonymous allocation pub fn get_anon_alloc(&mut self) -> Alloc { self.next_anon_id += 1; Alloc::Anon(self.next_anon_id) } } #[cfg(test)] mod tests { use super::*; #[test] fn example() { let mut a = SystemAllocator::new(SystemAllocatorConfig { io: Some(MemRegion { base: 0x1000, size: 0xf000, }), low_mmio: MemRegion { base: 0x3000_0000, size: 0x1_0000, }, high_mmio: MemRegion { base: 0x1000_0000, size: 0x1000_0000, }, platform_mmio: None, first_irq: 5, }) .unwrap(); assert_eq!(a.allocate_irq(), Some(5)); assert_eq!(a.allocate_irq(), Some(6)); assert_eq!( a.mmio_allocator(MmioType::High).allocate( 0x100, Alloc::PciBar { bus: 0, dev: 0, func: 0, bar: 0 }, "bar0".to_string() ), Ok(0x10000000) ); assert_eq!( a.mmio_allocator(MmioType::High).get(&Alloc::PciBar { bus: 0, dev: 0, func: 0, bar: 0 }), Some(&(0x10000000, 0x100, "bar0".to_string())) ); } }
get_pci_allocator_mut
identifier_name
system_allocator.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use base::pagesize; use crate::address_allocator::{AddressAllocator, AddressAllocatorSet}; use crate::{Alloc, Error, Result}; /// Manages allocating system resources such as address space and interrupt numbers. /// MMIO address Type /// Low: address allocated from low_address_space /// High: address allocated from high_address_space #[derive(Copy, Clone)] pub enum MmioType { Low, High, } /// Region of memory. pub struct MemRegion { pub base: u64, pub size: u64, } pub struct SystemAllocatorConfig { /// IO ports. Only for x86_64. pub io: Option<MemRegion>, /// Low (<=4GB) MMIO region. pub low_mmio: MemRegion, /// High (>4GB) MMIO region. pub high_mmio: MemRegion, /// Platform MMIO space. Only for ARM. pub platform_mmio: Option<MemRegion>, /// The first IRQ number to give out. pub first_irq: u32, } #[derive(Debug)] pub struct SystemAllocator { io_address_space: Option<AddressAllocator>, // Indexed by MmioType::Low and MmioType::High. mmio_address_spaces: [AddressAllocator; 2], mmio_platform_address_spaces: Option<AddressAllocator>, // Each bus number has a AddressAllocator pci_allocator: BTreeMap<u8, AddressAllocator>, irq_allocator: AddressAllocator, next_anon_id: usize, } impl SystemAllocator { /// Creates a new `SystemAllocator` for managing addresses and irq numbers. /// Will return an error if `base` + `size` overflows u64 (or allowed /// maximum for the specific type), or if alignment isn't a power of two. /// pub fn new(config: SystemAllocatorConfig) -> Result<Self> { let page_size = pagesize() as u64; Ok(SystemAllocator { io_address_space: if let Some(io) = config.io { // TODO make sure we don't overlap with existing well known // ports such as 0xcf8 (serial ports). if io.base > 0x1_0000 || io.size + io.base > 0x1_0000 { return Err(Error::IOPortOutOfRange(io.base, io.size)); } Some(AddressAllocator::new(io.base, io.size, Some(0x400), None)?) } else { None }, mmio_address_spaces: [ // MmioType::Low AddressAllocator::new( config.low_mmio.base, config.low_mmio.size, Some(page_size), None, )?, // MmioType::High AddressAllocator::new( config.high_mmio.base, config.high_mmio.size, Some(page_size), None, )?, ], pci_allocator: BTreeMap::new(), mmio_platform_address_spaces: if let Some(platform) = config.platform_mmio { Some(AddressAllocator::new( platform.base, platform.size, Some(page_size), None, )?) } else { None }, irq_allocator: AddressAllocator::new( config.first_irq as u64, 1024 - config.first_irq as u64, Some(1), None, )?, next_anon_id: 0, }) } /// Reserves the next available system irq number. pub fn allocate_irq(&mut self) -> Option<u32> { let id = self.get_anon_alloc(); self.irq_allocator .allocate(1, id, "irq-auto".to_string()) .map(|v| v as u32) .ok() } /// release irq to system irq number pool pub fn release_irq(&mut self, irq: u32) { let _ = self.irq_allocator.release_containing(irq.into());
} /// Reserves the next available system irq number. pub fn reserve_irq(&mut self, irq: u32) -> bool { let id = self.get_anon_alloc(); self.irq_allocator .allocate_at(irq as u64, 1, id, "irq-fixed".to_string()) .is_ok() } fn get_pci_allocator_mut(&mut self, bus: u8) -> Option<&mut AddressAllocator> { // pci root is 00:00.0, Bus 0 next device is 00:01.0 with mandatory function // number zero. if self.pci_allocator.get(&bus).is_none() { let base = if bus == 0 { 8 } else { 0 }; // Each bus supports up to 32 (devices) x 8 (functions). // Prefer allocating at device granularity (preferred_align = 8), but fall back to // allocating individual functions (min_align = 1) when we run out of devices. match AddressAllocator::new(base, (32 * 8) - base, Some(1), Some(8)) { Ok(v) => self.pci_allocator.insert(bus, v), Err(_) => return None, }; } self.pci_allocator.get_mut(&bus) } // Check whether devices exist or not on the specified bus pub fn pci_bus_empty(&self, bus: u8) -> bool { if self.pci_allocator.get(&bus).is_none() { true } else { false } } /// Allocate PCI slot location. pub fn allocate_pci(&mut self, bus: u8, tag: String) -> Option<Alloc> { let id = self.get_anon_alloc(); let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return None, }; allocator .allocate(1, id, tag) .map(|v| Alloc::PciBar { bus, dev: (v >> 3) as u8, func: (v & 7) as u8, bar: 0, }) .ok() } /// Reserve PCI slot location. pub fn reserve_pci(&mut self, alloc: Alloc, tag: String) -> bool { let id = self.get_anon_alloc(); match alloc { Alloc::PciBar { bus, dev, func, bar: _, } => { let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return false, }; let df = ((dev as u64) << 3) | (func as u64); allocator.allocate_at(df, 1, id, tag).is_ok() } _ => false, } } /// release PCI slot location. pub fn release_pci(&mut self, bus: u8, dev: u8, func: u8) -> bool { let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return false, }; let df = ((dev as u64) << 3) | (func as u64); allocator.release_containing(df).is_ok() } /// Gets an allocator to be used for platform device MMIO allocation. pub fn mmio_platform_allocator(&mut self) -> Option<&mut AddressAllocator> { self.mmio_platform_address_spaces.as_mut() } /// Gets an allocator to be used for IO memory. pub fn io_allocator(&mut self) -> Option<&mut AddressAllocator> { self.io_address_space.as_mut() } /// Gets an allocator to be used for MMIO allocation. /// MmioType::Low: low mmio allocator /// MmioType::High: high mmio allocator pub fn mmio_allocator(&mut self, mmio_type: MmioType) -> &mut AddressAllocator { &mut self.mmio_address_spaces[mmio_type as usize] } /// Gets a set of allocators to be used for MMIO allocation. /// The set of allocators will try the low and high MMIO allocators, in that order. pub fn mmio_allocator_any(&mut self) -> AddressAllocatorSet { AddressAllocatorSet::new(&mut self.mmio_address_spaces) } /// Gets a unique anonymous allocation pub fn get_anon_alloc(&mut self) -> Alloc { self.next_anon_id += 1; Alloc::Anon(self.next_anon_id) } } #[cfg(test)] mod tests { use super::*; #[test] fn example() { let mut a = SystemAllocator::new(SystemAllocatorConfig { io: Some(MemRegion { base: 0x1000, size: 0xf000, }), low_mmio: MemRegion { base: 0x3000_0000, size: 0x1_0000, }, high_mmio: MemRegion { base: 0x1000_0000, size: 0x1000_0000, }, platform_mmio: None, first_irq: 5, }) .unwrap(); assert_eq!(a.allocate_irq(), Some(5)); assert_eq!(a.allocate_irq(), Some(6)); assert_eq!( a.mmio_allocator(MmioType::High).allocate( 0x100, Alloc::PciBar { bus: 0, dev: 0, func: 0, bar: 0 }, "bar0".to_string() ), Ok(0x10000000) ); assert_eq!( a.mmio_allocator(MmioType::High).get(&Alloc::PciBar { bus: 0, dev: 0, func: 0, bar: 0 }), Some(&(0x10000000, 0x100, "bar0".to_string())) ); } }
random_line_split
ping.rs
// This file is generated by rust-protobuf 2.6.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #![allow(unused_results)] use protobuf::Message as Message_imported_for_functions; use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions; #[derive(PartialEq,Clone,Default)] pub struct PING_MESSAGE { // message fields pub current_utc: u32, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a PING_MESSAGE { fn default() -> &'a PING_MESSAGE { <PING_MESSAGE as ::protobuf::Message>::default_instance() } } impl PING_MESSAGE { pub fn new() -> PING_MESSAGE { ::std::default::Default::default() } // uint32 current_utc = 1; pub fn get_current_utc(&self) -> u32 { self.current_utc } pub fn clear_current_utc(&mut self) { self.current_utc = 0; } // Param is passed by value, moved pub fn set_current_utc(&mut self, v: u32) { self.current_utc = v; } } impl ::protobuf::Message for PING_MESSAGE { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> { while!is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type!= ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_uint32()?; self.current_utc = tmp; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.current_utc!= 0 { my_size += ::protobuf::rt::value_size(1, self.current_utc, ::protobuf::wire_format::WireTypeVarint); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> { if self.current_utc!= 0
os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> PING_MESSAGE { PING_MESSAGE::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::MessageDescriptor, }; unsafe { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( "current_utc", |m: &PING_MESSAGE| { &m.current_utc }, |m: &mut PING_MESSAGE| { &mut m.current_utc }, )); ::protobuf::reflect::MessageDescriptor::new::<PING_MESSAGE>( "PING_MESSAGE", fields, file_descriptor_proto() ) }) } } fn default_instance() -> &'static PING_MESSAGE { static mut instance: ::protobuf::lazy::Lazy<PING_MESSAGE> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const PING_MESSAGE, }; unsafe { instance.get(PING_MESSAGE::new) } } } impl ::protobuf::Clear for PING_MESSAGE { fn clear(&mut self) { self.current_utc = 0; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for PING_MESSAGE { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for PING_MESSAGE { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n\nping.proto\"/\n\x0cPING_MESSAGE\x12\x1f\n\x0bcurrent_utc\x18\x01\x20\ \x01(\rR\ncurrentUtcb\x06proto3\ "; static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto, }; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { unsafe { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) } }
{ os.write_uint32(1, self.current_utc)?; }
conditional_block
ping.rs
// This file is generated by rust-protobuf 2.6.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #![allow(unused_results)] use protobuf::Message as Message_imported_for_functions; use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions; #[derive(PartialEq,Clone,Default)] pub struct PING_MESSAGE { // message fields pub current_utc: u32, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a PING_MESSAGE { fn default() -> &'a PING_MESSAGE { <PING_MESSAGE as ::protobuf::Message>::default_instance() } } impl PING_MESSAGE { pub fn new() -> PING_MESSAGE { ::std::default::Default::default() } // uint32 current_utc = 1; pub fn get_current_utc(&self) -> u32 { self.current_utc } pub fn clear_current_utc(&mut self) { self.current_utc = 0; } // Param is passed by value, moved pub fn set_current_utc(&mut self, v: u32) { self.current_utc = v; } } impl ::protobuf::Message for PING_MESSAGE { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> { while!is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type!= ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_uint32()?; self.current_utc = tmp; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.current_utc!= 0 { my_size += ::protobuf::rt::value_size(1, self.current_utc, ::protobuf::wire_format::WireTypeVarint); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> { if self.current_utc!= 0 { os.write_uint32(1, self.current_utc)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> PING_MESSAGE { PING_MESSAGE::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::MessageDescriptor, }; unsafe { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( "current_utc", |m: &PING_MESSAGE| { &m.current_utc }, |m: &mut PING_MESSAGE| { &mut m.current_utc }, )); ::protobuf::reflect::MessageDescriptor::new::<PING_MESSAGE>( "PING_MESSAGE", fields, file_descriptor_proto() ) }) } } fn default_instance() -> &'static PING_MESSAGE { static mut instance: ::protobuf::lazy::Lazy<PING_MESSAGE> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const PING_MESSAGE, }; unsafe { instance.get(PING_MESSAGE::new) } } } impl ::protobuf::Clear for PING_MESSAGE { fn clear(&mut self) { self.current_utc = 0; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for PING_MESSAGE { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for PING_MESSAGE { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n\nping.proto\"/\n\x0cPING_MESSAGE\x12\x1f\n\x0bcurrent_utc\x18\x01\x20\ \x01(\rR\ncurrentUtcb\x06proto3\ "; static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto, }; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { unsafe { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) } }
{ &self.unknown_fields }
identifier_body
ping.rs
// This file is generated by rust-protobuf 2.6.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #![allow(unused_results)] use protobuf::Message as Message_imported_for_functions; use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions; #[derive(PartialEq,Clone,Default)] pub struct PING_MESSAGE { // message fields pub current_utc: u32, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a PING_MESSAGE { fn default() -> &'a PING_MESSAGE { <PING_MESSAGE as ::protobuf::Message>::default_instance() } } impl PING_MESSAGE { pub fn new() -> PING_MESSAGE { ::std::default::Default::default() } // uint32 current_utc = 1; pub fn get_current_utc(&self) -> u32 { self.current_utc } pub fn clear_current_utc(&mut self) { self.current_utc = 0; } // Param is passed by value, moved pub fn set_current_utc(&mut self, v: u32) { self.current_utc = v; } } impl ::protobuf::Message for PING_MESSAGE { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> { while!is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type!= ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_uint32()?; self.current_utc = tmp; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.current_utc!= 0 { my_size += ::protobuf::rt::value_size(1, self.current_utc, ::protobuf::wire_format::WireTypeVarint); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> { if self.current_utc!= 0 { os.write_uint32(1, self.current_utc)?; }
::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> PING_MESSAGE { PING_MESSAGE::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::MessageDescriptor, }; unsafe { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( "current_utc", |m: &PING_MESSAGE| { &m.current_utc }, |m: &mut PING_MESSAGE| { &mut m.current_utc }, )); ::protobuf::reflect::MessageDescriptor::new::<PING_MESSAGE>( "PING_MESSAGE", fields, file_descriptor_proto() ) }) } } fn default_instance() -> &'static PING_MESSAGE { static mut instance: ::protobuf::lazy::Lazy<PING_MESSAGE> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const PING_MESSAGE, }; unsafe { instance.get(PING_MESSAGE::new) } } } impl ::protobuf::Clear for PING_MESSAGE { fn clear(&mut self) { self.current_utc = 0; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for PING_MESSAGE { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for PING_MESSAGE { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n\nping.proto\"/\n\x0cPING_MESSAGE\x12\x1f\n\x0bcurrent_utc\x18\x01\x20\ \x01(\rR\ncurrentUtcb\x06proto3\ "; static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto, }; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { unsafe { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) } }
os.write_unknown_fields(self.get_unknown_fields())?;
random_line_split
ping.rs
// This file is generated by rust-protobuf 2.6.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #![allow(unused_results)] use protobuf::Message as Message_imported_for_functions; use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions; #[derive(PartialEq,Clone,Default)] pub struct PING_MESSAGE { // message fields pub current_utc: u32, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a PING_MESSAGE { fn default() -> &'a PING_MESSAGE { <PING_MESSAGE as ::protobuf::Message>::default_instance() } } impl PING_MESSAGE { pub fn new() -> PING_MESSAGE { ::std::default::Default::default() } // uint32 current_utc = 1; pub fn
(&self) -> u32 { self.current_utc } pub fn clear_current_utc(&mut self) { self.current_utc = 0; } // Param is passed by value, moved pub fn set_current_utc(&mut self, v: u32) { self.current_utc = v; } } impl ::protobuf::Message for PING_MESSAGE { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> { while!is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type!= ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_uint32()?; self.current_utc = tmp; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.current_utc!= 0 { my_size += ::protobuf::rt::value_size(1, self.current_utc, ::protobuf::wire_format::WireTypeVarint); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> { if self.current_utc!= 0 { os.write_uint32(1, self.current_utc)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> PING_MESSAGE { PING_MESSAGE::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::MessageDescriptor, }; unsafe { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( "current_utc", |m: &PING_MESSAGE| { &m.current_utc }, |m: &mut PING_MESSAGE| { &mut m.current_utc }, )); ::protobuf::reflect::MessageDescriptor::new::<PING_MESSAGE>( "PING_MESSAGE", fields, file_descriptor_proto() ) }) } } fn default_instance() -> &'static PING_MESSAGE { static mut instance: ::protobuf::lazy::Lazy<PING_MESSAGE> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const PING_MESSAGE, }; unsafe { instance.get(PING_MESSAGE::new) } } } impl ::protobuf::Clear for PING_MESSAGE { fn clear(&mut self) { self.current_utc = 0; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for PING_MESSAGE { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for PING_MESSAGE { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n\nping.proto\"/\n\x0cPING_MESSAGE\x12\x1f\n\x0bcurrent_utc\x18\x01\x20\ \x01(\rR\ncurrentUtcb\x06proto3\ "; static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto, }; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { unsafe { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) } }
get_current_utc
identifier_name
directory.rs
use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use hex::ToHex; use serde_json; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use sources::PathSource; use util::{Config, Sha256}; use util::errors::{CargoResult, CargoResultExt}; use util::paths; pub struct DirectorySource<'cfg> { source_id: SourceId, root: PathBuf, packages: HashMap<PackageId, (Package, Checksum)>, config: &'cfg Config, } #[derive(Deserialize)] struct
{ package: String, files: HashMap<String, String>, } impl<'cfg> DirectorySource<'cfg> { pub fn new(path: &Path, id: &SourceId, config: &'cfg Config) -> DirectorySource<'cfg> { DirectorySource { source_id: id.clone(), root: path.to_path_buf(), config: config, packages: HashMap::new(), } } } impl<'cfg> Debug for DirectorySource<'cfg> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "DirectorySource {{ root: {:?} }}", self.root) } } impl<'cfg> Registry for DirectorySource<'cfg> { fn query(&mut self, dep: &Dependency, f: &mut FnMut(Summary)) -> CargoResult<()> { let packages = self.packages.values().map(|p| &p.0); let matches = packages.filter(|pkg| dep.matches(pkg.summary())); for summary in matches.map(|pkg| pkg.summary().clone()) { f(summary); } Ok(()) } fn supports_checksums(&self) -> bool { true } } impl<'cfg> Source for DirectorySource<'cfg> { fn source_id(&self) -> &SourceId { &self.source_id } fn update(&mut self) -> CargoResult<()> { self.packages.clear(); let entries = self.root.read_dir().chain_err(|| { format!("failed to read root of directory source: {}", self.root.display()) })?; for entry in entries { let entry = entry?; let path = entry.path(); // Ignore hidden/dot directories as they typically don't contain // crates and otherwise may conflict with a VCS // (rust-lang/cargo#3414). if let Some(s) = path.file_name().and_then(|s| s.to_str()) { if s.starts_with('.') { continue } } // Vendor directories are often checked into a VCS, but throughout // the lifetime of a vendor dir crates are often added and deleted. // Some VCS implementations don't always fully delete the directory // when a dir is removed from a different checkout. Sometimes a // mostly-empty dir is left behind. // // To help work Cargo work by default in more cases we try to // handle this case by default. If the directory looks like it only // has dotfiles in it (or no files at all) then we skip it. // // In general we don't want to skip completely malformed directories // to help with debugging, so we don't just ignore errors in // `update` below. let mut only_dotfile = true; for entry in path.read_dir()?.filter_map(|e| e.ok()) { if let Some(s) = entry.file_name().to_str() { if s.starts_with(".") { continue } } only_dotfile = false; } if only_dotfile { continue } let mut src = PathSource::new(&path, &self.source_id, self.config); src.update()?; let pkg = src.root_package()?; let cksum_file = path.join(".cargo-checksum.json"); let cksum = paths::read(&path.join(cksum_file)).chain_err(|| { format!("failed to load checksum `.cargo-checksum.json` \ of {} v{}", pkg.package_id().name(), pkg.package_id().version()) })?; let cksum: Checksum = serde_json::from_str(&cksum).chain_err(|| { format!("failed to decode `.cargo-checksum.json` of \ {} v{}", pkg.package_id().name(), pkg.package_id().version()) })?; let mut manifest = pkg.manifest().clone(); let summary = manifest.summary().clone(); manifest.set_summary(summary.set_checksum(cksum.package.clone())); let pkg = Package::new(manifest, pkg.manifest_path()); self.packages.insert(pkg.package_id().clone(), (pkg, cksum)); } Ok(()) } fn download(&mut self, id: &PackageId) -> CargoResult<Package> { self.packages.get(id).map(|p| &p.0).cloned().ok_or_else(|| { format!("failed to find package with id: {}", id).into() }) } fn fingerprint(&self, pkg: &Package) -> CargoResult<String> { Ok(pkg.package_id().version().to_string()) } fn verify(&self, id: &PackageId) -> CargoResult<()> { let (pkg, cksum) = match self.packages.get(id) { Some(&(ref pkg, ref cksum)) => (pkg, cksum), None => bail!("failed to find entry for `{}` in directory source", id), }; let mut buf = [0; 16 * 1024]; for (file, cksum) in cksum.files.iter() { let mut h = Sha256::new(); let file = pkg.root().join(file); (|| -> CargoResult<()> { let mut f = File::open(&file)?; loop { match f.read(&mut buf)? { 0 => return Ok(()), n => h.update(&buf[..n]), } } })().chain_err(|| { format!("failed to calculate checksum of: {}", file.display()) })?; let actual = h.finish().to_hex(); if &*actual!= cksum { bail!("\ the listed checksum of `{}` has changed:\n\ expected: {}\n\ actual: {}\n\ \n\ directory sources are not intended to be edited, if \ modifications are required then it is recommended \ that [replace] is used with a forked copy of the \ source\ ", file.display(), cksum, actual); } } Ok(()) } }
Checksum
identifier_name
directory.rs
use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use hex::ToHex; use serde_json; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use sources::PathSource; use util::{Config, Sha256}; use util::errors::{CargoResult, CargoResultExt}; use util::paths; pub struct DirectorySource<'cfg> { source_id: SourceId, root: PathBuf, packages: HashMap<PackageId, (Package, Checksum)>, config: &'cfg Config, } #[derive(Deserialize)] struct Checksum { package: String, files: HashMap<String, String>, } impl<'cfg> DirectorySource<'cfg> { pub fn new(path: &Path, id: &SourceId, config: &'cfg Config) -> DirectorySource<'cfg> { DirectorySource { source_id: id.clone(), root: path.to_path_buf(), config: config, packages: HashMap::new(), } } } impl<'cfg> Debug for DirectorySource<'cfg> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "DirectorySource {{ root: {:?} }}", self.root) } } impl<'cfg> Registry for DirectorySource<'cfg> { fn query(&mut self, dep: &Dependency, f: &mut FnMut(Summary)) -> CargoResult<()> { let packages = self.packages.values().map(|p| &p.0); let matches = packages.filter(|pkg| dep.matches(pkg.summary())); for summary in matches.map(|pkg| pkg.summary().clone()) { f(summary); } Ok(()) } fn supports_checksums(&self) -> bool { true } } impl<'cfg> Source for DirectorySource<'cfg> { fn source_id(&self) -> &SourceId { &self.source_id } fn update(&mut self) -> CargoResult<()> { self.packages.clear(); let entries = self.root.read_dir().chain_err(|| { format!("failed to read root of directory source: {}", self.root.display()) })?; for entry in entries { let entry = entry?; let path = entry.path(); // Ignore hidden/dot directories as they typically don't contain // crates and otherwise may conflict with a VCS // (rust-lang/cargo#3414). if let Some(s) = path.file_name().and_then(|s| s.to_str()) { if s.starts_with('.') { continue } } // Vendor directories are often checked into a VCS, but throughout // the lifetime of a vendor dir crates are often added and deleted. // Some VCS implementations don't always fully delete the directory // when a dir is removed from a different checkout. Sometimes a // mostly-empty dir is left behind. // // To help work Cargo work by default in more cases we try to // handle this case by default. If the directory looks like it only // has dotfiles in it (or no files at all) then we skip it. // // In general we don't want to skip completely malformed directories // to help with debugging, so we don't just ignore errors in // `update` below. let mut only_dotfile = true; for entry in path.read_dir()?.filter_map(|e| e.ok()) { if let Some(s) = entry.file_name().to_str() { if s.starts_with(".") { continue }
only_dotfile = false; } if only_dotfile { continue } let mut src = PathSource::new(&path, &self.source_id, self.config); src.update()?; let pkg = src.root_package()?; let cksum_file = path.join(".cargo-checksum.json"); let cksum = paths::read(&path.join(cksum_file)).chain_err(|| { format!("failed to load checksum `.cargo-checksum.json` \ of {} v{}", pkg.package_id().name(), pkg.package_id().version()) })?; let cksum: Checksum = serde_json::from_str(&cksum).chain_err(|| { format!("failed to decode `.cargo-checksum.json` of \ {} v{}", pkg.package_id().name(), pkg.package_id().version()) })?; let mut manifest = pkg.manifest().clone(); let summary = manifest.summary().clone(); manifest.set_summary(summary.set_checksum(cksum.package.clone())); let pkg = Package::new(manifest, pkg.manifest_path()); self.packages.insert(pkg.package_id().clone(), (pkg, cksum)); } Ok(()) } fn download(&mut self, id: &PackageId) -> CargoResult<Package> { self.packages.get(id).map(|p| &p.0).cloned().ok_or_else(|| { format!("failed to find package with id: {}", id).into() }) } fn fingerprint(&self, pkg: &Package) -> CargoResult<String> { Ok(pkg.package_id().version().to_string()) } fn verify(&self, id: &PackageId) -> CargoResult<()> { let (pkg, cksum) = match self.packages.get(id) { Some(&(ref pkg, ref cksum)) => (pkg, cksum), None => bail!("failed to find entry for `{}` in directory source", id), }; let mut buf = [0; 16 * 1024]; for (file, cksum) in cksum.files.iter() { let mut h = Sha256::new(); let file = pkg.root().join(file); (|| -> CargoResult<()> { let mut f = File::open(&file)?; loop { match f.read(&mut buf)? { 0 => return Ok(()), n => h.update(&buf[..n]), } } })().chain_err(|| { format!("failed to calculate checksum of: {}", file.display()) })?; let actual = h.finish().to_hex(); if &*actual!= cksum { bail!("\ the listed checksum of `{}` has changed:\n\ expected: {}\n\ actual: {}\n\ \n\ directory sources are not intended to be edited, if \ modifications are required then it is recommended \ that [replace] is used with a forked copy of the \ source\ ", file.display(), cksum, actual); } } Ok(()) } }
}
random_line_split
directory.rs
use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use hex::ToHex; use serde_json; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use sources::PathSource; use util::{Config, Sha256}; use util::errors::{CargoResult, CargoResultExt}; use util::paths; pub struct DirectorySource<'cfg> { source_id: SourceId, root: PathBuf, packages: HashMap<PackageId, (Package, Checksum)>, config: &'cfg Config, } #[derive(Deserialize)] struct Checksum { package: String, files: HashMap<String, String>, } impl<'cfg> DirectorySource<'cfg> { pub fn new(path: &Path, id: &SourceId, config: &'cfg Config) -> DirectorySource<'cfg>
} impl<'cfg> Debug for DirectorySource<'cfg> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "DirectorySource {{ root: {:?} }}", self.root) } } impl<'cfg> Registry for DirectorySource<'cfg> { fn query(&mut self, dep: &Dependency, f: &mut FnMut(Summary)) -> CargoResult<()> { let packages = self.packages.values().map(|p| &p.0); let matches = packages.filter(|pkg| dep.matches(pkg.summary())); for summary in matches.map(|pkg| pkg.summary().clone()) { f(summary); } Ok(()) } fn supports_checksums(&self) -> bool { true } } impl<'cfg> Source for DirectorySource<'cfg> { fn source_id(&self) -> &SourceId { &self.source_id } fn update(&mut self) -> CargoResult<()> { self.packages.clear(); let entries = self.root.read_dir().chain_err(|| { format!("failed to read root of directory source: {}", self.root.display()) })?; for entry in entries { let entry = entry?; let path = entry.path(); // Ignore hidden/dot directories as they typically don't contain // crates and otherwise may conflict with a VCS // (rust-lang/cargo#3414). if let Some(s) = path.file_name().and_then(|s| s.to_str()) { if s.starts_with('.') { continue } } // Vendor directories are often checked into a VCS, but throughout // the lifetime of a vendor dir crates are often added and deleted. // Some VCS implementations don't always fully delete the directory // when a dir is removed from a different checkout. Sometimes a // mostly-empty dir is left behind. // // To help work Cargo work by default in more cases we try to // handle this case by default. If the directory looks like it only // has dotfiles in it (or no files at all) then we skip it. // // In general we don't want to skip completely malformed directories // to help with debugging, so we don't just ignore errors in // `update` below. let mut only_dotfile = true; for entry in path.read_dir()?.filter_map(|e| e.ok()) { if let Some(s) = entry.file_name().to_str() { if s.starts_with(".") { continue } } only_dotfile = false; } if only_dotfile { continue } let mut src = PathSource::new(&path, &self.source_id, self.config); src.update()?; let pkg = src.root_package()?; let cksum_file = path.join(".cargo-checksum.json"); let cksum = paths::read(&path.join(cksum_file)).chain_err(|| { format!("failed to load checksum `.cargo-checksum.json` \ of {} v{}", pkg.package_id().name(), pkg.package_id().version()) })?; let cksum: Checksum = serde_json::from_str(&cksum).chain_err(|| { format!("failed to decode `.cargo-checksum.json` of \ {} v{}", pkg.package_id().name(), pkg.package_id().version()) })?; let mut manifest = pkg.manifest().clone(); let summary = manifest.summary().clone(); manifest.set_summary(summary.set_checksum(cksum.package.clone())); let pkg = Package::new(manifest, pkg.manifest_path()); self.packages.insert(pkg.package_id().clone(), (pkg, cksum)); } Ok(()) } fn download(&mut self, id: &PackageId) -> CargoResult<Package> { self.packages.get(id).map(|p| &p.0).cloned().ok_or_else(|| { format!("failed to find package with id: {}", id).into() }) } fn fingerprint(&self, pkg: &Package) -> CargoResult<String> { Ok(pkg.package_id().version().to_string()) } fn verify(&self, id: &PackageId) -> CargoResult<()> { let (pkg, cksum) = match self.packages.get(id) { Some(&(ref pkg, ref cksum)) => (pkg, cksum), None => bail!("failed to find entry for `{}` in directory source", id), }; let mut buf = [0; 16 * 1024]; for (file, cksum) in cksum.files.iter() { let mut h = Sha256::new(); let file = pkg.root().join(file); (|| -> CargoResult<()> { let mut f = File::open(&file)?; loop { match f.read(&mut buf)? { 0 => return Ok(()), n => h.update(&buf[..n]), } } })().chain_err(|| { format!("failed to calculate checksum of: {}", file.display()) })?; let actual = h.finish().to_hex(); if &*actual!= cksum { bail!("\ the listed checksum of `{}` has changed:\n\ expected: {}\n\ actual: {}\n\ \n\ directory sources are not intended to be edited, if \ modifications are required then it is recommended \ that [replace] is used with a forked copy of the \ source\ ", file.display(), cksum, actual); } } Ok(()) } }
{ DirectorySource { source_id: id.clone(), root: path.to_path_buf(), config: config, packages: HashMap::new(), } }
identifier_body
texttrackcue.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 crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{self, TextTrackCueMethods}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::eventtarget::EventTarget; use crate::dom::texttrack::TextTrack; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; #[dom_struct] pub struct TextTrackCue { eventtarget: EventTarget, id: DomRefCell<DOMString>, track: Option<Dom<TextTrack>>, start_time: Cell<f64>, end_time: Cell<f64>, pause_on_exit: Cell<bool>, } impl TextTrackCue { // FIXME(#22314, dlrobertson) implement VTTCue. #[allow(dead_code)] pub fn new_inherited(id: DOMString, track: Option<&TextTrack>) -> TextTrackCue { TextTrackCue { eventtarget: EventTarget::new_inherited(), id: DomRefCell::new(id), track: track.map(Dom::from_ref), start_time: Cell::new(0.), end_time: Cell::new(0.), pause_on_exit: Cell::new(false), } } // FIXME(#22314, dlrobertson) implement VTTCue. #[allow(dead_code)] pub fn new(window: &Window, id: DOMString, track: Option<&TextTrack>) -> DomRoot<TextTrackCue> { reflect_dom_object( Box::new(TextTrackCue::new_inherited(id, track)), window, TextTrackCueBinding::Wrap, ) } pub fn id(&self) -> DOMString { self.id.borrow().clone() } pub fn get_track(&self) -> Option<DomRoot<TextTrack>> { self.track.as_ref().map(|t| DomRoot::from_ref(&**t)) } } impl TextTrackCueMethods for TextTrackCue { // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-id fn Id(&self) -> DOMString { self.id() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-id fn
(&self, value: DOMString) { *self.id.borrow_mut() = value; } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-track fn GetTrack(&self) -> Option<DomRoot<TextTrack>> { self.get_track() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-starttime fn StartTime(&self) -> Finite<f64> { Finite::wrap(self.start_time.get()) } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-starttime fn SetStartTime(&self, value: Finite<f64>) { self.start_time.set(*value); } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-endtime fn EndTime(&self) -> Finite<f64> { Finite::wrap(self.end_time.get()) } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-endtime fn SetEndTime(&self, value: Finite<f64>) { self.end_time.set(*value); } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-pauseonexit fn PauseOnExit(&self) -> bool { self.pause_on_exit.get() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-pauseonexit fn SetPauseOnExit(&self, value: bool) { self.pause_on_exit.set(value); } // https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onenter event_handler!(enter, GetOnenter, SetOnenter); // https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onexit event_handler!(exit, GetOnexit, SetOnexit); }
SetId
identifier_name
texttrackcue.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 crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{self, TextTrackCueMethods}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::eventtarget::EventTarget; use crate::dom::texttrack::TextTrack; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; #[dom_struct] pub struct TextTrackCue { eventtarget: EventTarget, id: DomRefCell<DOMString>, track: Option<Dom<TextTrack>>, start_time: Cell<f64>, end_time: Cell<f64>, pause_on_exit: Cell<bool>, } impl TextTrackCue { // FIXME(#22314, dlrobertson) implement VTTCue. #[allow(dead_code)] pub fn new_inherited(id: DOMString, track: Option<&TextTrack>) -> TextTrackCue { TextTrackCue { eventtarget: EventTarget::new_inherited(), id: DomRefCell::new(id), track: track.map(Dom::from_ref), start_time: Cell::new(0.), end_time: Cell::new(0.), pause_on_exit: Cell::new(false), } } // FIXME(#22314, dlrobertson) implement VTTCue. #[allow(dead_code)] pub fn new(window: &Window, id: DOMString, track: Option<&TextTrack>) -> DomRoot<TextTrackCue> { reflect_dom_object( Box::new(TextTrackCue::new_inherited(id, track)), window, TextTrackCueBinding::Wrap, ) } pub fn id(&self) -> DOMString { self.id.borrow().clone() } pub fn get_track(&self) -> Option<DomRoot<TextTrack>> { self.track.as_ref().map(|t| DomRoot::from_ref(&**t)) } } impl TextTrackCueMethods for TextTrackCue { // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-id fn Id(&self) -> DOMString { self.id() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-id fn SetId(&self, value: DOMString) { *self.id.borrow_mut() = value; } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-track fn GetTrack(&self) -> Option<DomRoot<TextTrack>> { self.get_track() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-starttime fn StartTime(&self) -> Finite<f64> { Finite::wrap(self.start_time.get()) } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-starttime fn SetStartTime(&self, value: Finite<f64>) { self.start_time.set(*value); } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-endtime fn EndTime(&self) -> Finite<f64> { Finite::wrap(self.end_time.get()) } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-endtime fn SetEndTime(&self, value: Finite<f64>) { self.end_time.set(*value); } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-pauseonexit fn PauseOnExit(&self) -> bool { self.pause_on_exit.get() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-pauseonexit fn SetPauseOnExit(&self, value: bool) { self.pause_on_exit.set(value);
// https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onenter event_handler!(enter, GetOnenter, SetOnenter); // https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onexit event_handler!(exit, GetOnexit, SetOnexit); }
}
random_line_split
texttrackcue.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 crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{self, TextTrackCueMethods}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::eventtarget::EventTarget; use crate::dom::texttrack::TextTrack; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; #[dom_struct] pub struct TextTrackCue { eventtarget: EventTarget, id: DomRefCell<DOMString>, track: Option<Dom<TextTrack>>, start_time: Cell<f64>, end_time: Cell<f64>, pause_on_exit: Cell<bool>, } impl TextTrackCue { // FIXME(#22314, dlrobertson) implement VTTCue. #[allow(dead_code)] pub fn new_inherited(id: DOMString, track: Option<&TextTrack>) -> TextTrackCue { TextTrackCue { eventtarget: EventTarget::new_inherited(), id: DomRefCell::new(id), track: track.map(Dom::from_ref), start_time: Cell::new(0.), end_time: Cell::new(0.), pause_on_exit: Cell::new(false), } } // FIXME(#22314, dlrobertson) implement VTTCue. #[allow(dead_code)] pub fn new(window: &Window, id: DOMString, track: Option<&TextTrack>) -> DomRoot<TextTrackCue> { reflect_dom_object( Box::new(TextTrackCue::new_inherited(id, track)), window, TextTrackCueBinding::Wrap, ) } pub fn id(&self) -> DOMString
pub fn get_track(&self) -> Option<DomRoot<TextTrack>> { self.track.as_ref().map(|t| DomRoot::from_ref(&**t)) } } impl TextTrackCueMethods for TextTrackCue { // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-id fn Id(&self) -> DOMString { self.id() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-id fn SetId(&self, value: DOMString) { *self.id.borrow_mut() = value; } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-track fn GetTrack(&self) -> Option<DomRoot<TextTrack>> { self.get_track() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-starttime fn StartTime(&self) -> Finite<f64> { Finite::wrap(self.start_time.get()) } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-starttime fn SetStartTime(&self, value: Finite<f64>) { self.start_time.set(*value); } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-endtime fn EndTime(&self) -> Finite<f64> { Finite::wrap(self.end_time.get()) } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-endtime fn SetEndTime(&self, value: Finite<f64>) { self.end_time.set(*value); } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-pauseonexit fn PauseOnExit(&self) -> bool { self.pause_on_exit.get() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-pauseonexit fn SetPauseOnExit(&self, value: bool) { self.pause_on_exit.set(value); } // https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onenter event_handler!(enter, GetOnenter, SetOnenter); // https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onexit event_handler!(exit, GetOnexit, SetOnexit); }
{ self.id.borrow().clone() }
identifier_body
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn
<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uint) -> HashMap<N, uint> { assert!(goals.len() > 0); let mut ret = HashMap::new(); // Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k in goals.iter() { for n in neighbors(k).iter() { // XXX: Extra clone op here, should just shuffle references until // things get cloned for the ret structure. if!ret.contains_key(n) { edge.insert(n.clone()); } } } for dist in range(1, limit) { for k in edge.iter() { ret.insert(k.clone(), dist); } let mut new_edge = ~HashSet::new(); for k in edge.iter() { for n in neighbors(k).iter() { if!ret.contains_key(n) { new_edge.insert(n.clone()); } } } edge = new_edge; } ret }
build_map
identifier_name
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uint) -> HashMap<N, uint> { assert!(goals.len() > 0); let mut ret = HashMap::new(); // Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k in goals.iter() { for n in neighbors(k).iter() { // XXX: Extra clone op here, should just shuffle references until // things get cloned for the ret structure. if!ret.contains_key(n) { edge.insert(n.clone()); } } } for dist in range(1, limit) { for k in edge.iter() { ret.insert(k.clone(), dist); } let mut new_edge = ~HashSet::new(); for k in edge.iter() { for n in neighbors(k).iter() { if!ret.contains_key(n)
} } edge = new_edge; } ret }
{ new_edge.insert(n.clone()); }
conditional_block