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
chip8.rs
extern crate sdl2; use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[cfg(feature="debugger")] use std::process::Command; use chip8::MEMORY_SIZE; use chip8::ROM_START_ADDRESS; use chip8::keyboard::Keyboard; use chip8::display::Display; #[cfg(feature="interpreter")] use chip8::interpreter::Interpreter; #[cfg(not(feature="interpreter"))] use chip8::recompiler::Recompiler; const STACK_SIZE: usize = 16; const V_REGISTERS_COUNT: usize = 16; pub struct Chip8 { pub memory: [u8; MEMORY_SIZE], pub stack: [u16; STACK_SIZE], pub register_v: [u8; V_REGISTERS_COUNT], pub register_i: u16, pub register_dt: u8, pub register_st: u8, pub register_pc: u16, pub register_sp: u8, pub keyboard: Keyboard, pub display: Display, time_last_frame: Instant } impl Chip8 { pub fn new() -> Chip8 { let sdl_context = sdl2::init().unwrap(); let mut chip8 = Chip8 { memory: [0; MEMORY_SIZE], stack: [0; STACK_SIZE], register_v: [0; V_REGISTERS_COUNT], register_i: 0, register_dt: 0, register_st: 0, register_pc: ROM_START_ADDRESS, register_sp: 0xFF, keyboard: Keyboard::new(&sdl_context), display: Display::new(&sdl_context), time_last_frame: Instant::now() }; chip8.memory[0x00] = 0xF0; chip8.memory[0x01] = 0x90; chip8.memory[0x02] = 0x90; chip8.memory[0x03] = 0x90; chip8.memory[0x04] = 0xF0; chip8.memory[0x05] = 0x20; chip8.memory[0x06] = 0x60; chip8.memory[0x07] = 0x20; chip8.memory[0x08] = 0x20; chip8.memory[0x09] = 0x70; chip8.memory[0x0A] = 0xF0; chip8.memory[0x0B] = 0x10; chip8.memory[0x0C] = 0xF0; chip8.memory[0x0D] = 0x80; chip8.memory[0x0E] = 0xF0; chip8.memory[0x0F] = 0xF0; chip8.memory[0x10] = 0x10; chip8.memory[0x11] = 0xF0; chip8.memory[0x12] = 0x10; chip8.memory[0x13] = 0xF0; chip8.memory[0x14] = 0x90; chip8.memory[0x15] = 0x90; chip8.memory[0x16] = 0xF0; chip8.memory[0x17] = 0x10; chip8.memory[0x18] = 0x10; chip8.memory[0x19] = 0xF0; chip8.memory[0x1A] = 0x80; chip8.memory[0x1B] = 0xF0; chip8.memory[0x1C] = 0x10; chip8.memory[0x1D] = 0xF0; chip8.memory[0x1E] = 0xF0; chip8.memory[0x1F] = 0x80; chip8.memory[0x20] = 0xF0; chip8.memory[0x21] = 0x90; chip8.memory[0x22] = 0xF0; chip8.memory[0x23] = 0xF0; chip8.memory[0x24] = 0x10; chip8.memory[0x25] = 0x20; chip8.memory[0x26] = 0x40; chip8.memory[0x27] = 0x40; chip8.memory[0x28] = 0xF0; chip8.memory[0x29] = 0x90; chip8.memory[0x2A] = 0xF0; chip8.memory[0x2B] = 0x90; chip8.memory[0x2C] = 0xF0; chip8.memory[0x2D] = 0xF0; chip8.memory[0x2E] = 0x90; chip8.memory[0x2F] = 0xF0; chip8.memory[0x30] = 0x10; chip8.memory[0x31] = 0xF0; chip8.memory[0x32] = 0xF0; chip8.memory[0x33] = 0x90; chip8.memory[0x34] = 0xF0; chip8.memory[0x35] = 0x90; chip8.memory[0x36] = 0x90; chip8.memory[0x37] = 0xE0; chip8.memory[0x38] = 0x90; chip8.memory[0x39] = 0xE0; chip8.memory[0x3A] = 0x90; chip8.memory[0x3B] = 0xE0; chip8.memory[0x3C] = 0xF0; chip8.memory[0x3D] = 0x80; chip8.memory[0x3E] = 0x80; chip8.memory[0x3F] = 0x80; chip8.memory[0x40] = 0xF0; chip8.memory[0x41] = 0xE0; chip8.memory[0x42] = 0x90; chip8.memory[0x43] = 0x90; chip8.memory[0x44] = 0x90; chip8.memory[0x45] = 0xE0; chip8.memory[0x46] = 0xF0; chip8.memory[0x47] = 0x80; chip8.memory[0x48] = 0xF0; chip8.memory[0x49] = 0x80; chip8.memory[0x4A] = 0xF0; chip8.memory[0x4B] = 0xF0; chip8.memory[0x4C] = 0x80; chip8.memory[0x4D] = 0xF0; chip8.memory[0x4E] = 0x80; chip8.memory[0x4F] = 0x80; chip8 } fn load_rom(&mut self, filename: String) { let mut file = File::open(filename).expect("file not found"); let mut buffer: Vec<u8> = Vec::new(); file.read_to_end(&mut buffer).expect("something went wrong reading the file"); self.memory[ROM_START_ADDRESS as usize..ROM_START_ADDRESS as usize + buffer.len()].copy_from_slice(&buffer); } #[cfg(feature="debugger")] fn
(&self) { println!("PC= {:x}", self.register_pc); println!("I= {:x}", self.register_i); println!("DT= {:x}", self.register_dt); println!("ST= {:x}", self.register_st); println!("SP= {:x}", self.register_sp); for i in 0..16 as usize { println!("V{}= {:x}", i, self.register_v[i]); } let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } pub extern "stdcall" fn refresh(&mut self) { // ~60Hz if self.time_last_frame.elapsed() >= Duration::from_millis(1000 / 60) { self.time_last_frame = Instant::now(); self.keyboard.update_key_states(); self.display.refresh(); if self.register_dt > 0 { self.register_dt -= 1 } if self.register_st > 0 { self.register_st -= 1; // TODO: beep } } } pub fn run(&mut self, filename: String) { self.load_rom(filename); #[cfg(not(feature="interpreter"))] let mut recompiler = Recompiler::new(&self.register_pc); loop { #[cfg(feature="debugger")] self.print_registers(); #[cfg(feature="interpreter")] Interpreter::execute_next_instruction(self); #[cfg(feature="interpreter")] self.refresh(); #[cfg(not(feature="interpreter"))] recompiler.execute_next_code_block(self); } } }
print_registers
identifier_name
chip8.rs
extern crate sdl2; use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[cfg(feature="debugger")] use std::process::Command; use chip8::MEMORY_SIZE; use chip8::ROM_START_ADDRESS; use chip8::keyboard::Keyboard; use chip8::display::Display; #[cfg(feature="interpreter")] use chip8::interpreter::Interpreter; #[cfg(not(feature="interpreter"))] use chip8::recompiler::Recompiler; const STACK_SIZE: usize = 16; const V_REGISTERS_COUNT: usize = 16; pub struct Chip8 { pub memory: [u8; MEMORY_SIZE], pub stack: [u16; STACK_SIZE], pub register_v: [u8; V_REGISTERS_COUNT], pub register_i: u16, pub register_dt: u8, pub register_st: u8, pub register_pc: u16, pub register_sp: u8, pub keyboard: Keyboard, pub display: Display, time_last_frame: Instant } impl Chip8 { pub fn new() -> Chip8 { let sdl_context = sdl2::init().unwrap(); let mut chip8 = Chip8 { memory: [0; MEMORY_SIZE], stack: [0; STACK_SIZE], register_v: [0; V_REGISTERS_COUNT], register_i: 0, register_dt: 0, register_st: 0, register_pc: ROM_START_ADDRESS, register_sp: 0xFF, keyboard: Keyboard::new(&sdl_context), display: Display::new(&sdl_context), time_last_frame: Instant::now() }; chip8.memory[0x00] = 0xF0; chip8.memory[0x01] = 0x90; chip8.memory[0x02] = 0x90; chip8.memory[0x03] = 0x90; chip8.memory[0x04] = 0xF0; chip8.memory[0x05] = 0x20; chip8.memory[0x06] = 0x60; chip8.memory[0x07] = 0x20; chip8.memory[0x08] = 0x20; chip8.memory[0x09] = 0x70; chip8.memory[0x0A] = 0xF0; chip8.memory[0x0B] = 0x10; chip8.memory[0x0C] = 0xF0; chip8.memory[0x0D] = 0x80; chip8.memory[0x0E] = 0xF0; chip8.memory[0x0F] = 0xF0; chip8.memory[0x10] = 0x10; chip8.memory[0x11] = 0xF0; chip8.memory[0x12] = 0x10; chip8.memory[0x13] = 0xF0; chip8.memory[0x14] = 0x90; chip8.memory[0x15] = 0x90; chip8.memory[0x16] = 0xF0; chip8.memory[0x17] = 0x10; chip8.memory[0x18] = 0x10; chip8.memory[0x19] = 0xF0; chip8.memory[0x1A] = 0x80; chip8.memory[0x1B] = 0xF0; chip8.memory[0x1C] = 0x10; chip8.memory[0x1D] = 0xF0; chip8.memory[0x1E] = 0xF0; chip8.memory[0x1F] = 0x80; chip8.memory[0x20] = 0xF0; chip8.memory[0x21] = 0x90; chip8.memory[0x22] = 0xF0; chip8.memory[0x23] = 0xF0; chip8.memory[0x24] = 0x10; chip8.memory[0x25] = 0x20; chip8.memory[0x26] = 0x40; chip8.memory[0x27] = 0x40; chip8.memory[0x28] = 0xF0; chip8.memory[0x29] = 0x90; chip8.memory[0x2A] = 0xF0; chip8.memory[0x2B] = 0x90; chip8.memory[0x2C] = 0xF0; chip8.memory[0x2D] = 0xF0; chip8.memory[0x2E] = 0x90; chip8.memory[0x2F] = 0xF0; chip8.memory[0x30] = 0x10; chip8.memory[0x31] = 0xF0; chip8.memory[0x32] = 0xF0; chip8.memory[0x33] = 0x90; chip8.memory[0x34] = 0xF0; chip8.memory[0x35] = 0x90; chip8.memory[0x36] = 0x90; chip8.memory[0x37] = 0xE0; chip8.memory[0x38] = 0x90; chip8.memory[0x39] = 0xE0; chip8.memory[0x3A] = 0x90; chip8.memory[0x3B] = 0xE0; chip8.memory[0x3C] = 0xF0; chip8.memory[0x3D] = 0x80; chip8.memory[0x3E] = 0x80; chip8.memory[0x3F] = 0x80; chip8.memory[0x40] = 0xF0; chip8.memory[0x41] = 0xE0; chip8.memory[0x42] = 0x90; chip8.memory[0x43] = 0x90; chip8.memory[0x44] = 0x90; chip8.memory[0x45] = 0xE0; chip8.memory[0x46] = 0xF0; chip8.memory[0x47] = 0x80; chip8.memory[0x48] = 0xF0; chip8.memory[0x49] = 0x80; chip8.memory[0x4A] = 0xF0; chip8.memory[0x4B] = 0xF0; chip8.memory[0x4C] = 0x80; chip8.memory[0x4D] = 0xF0; chip8.memory[0x4E] = 0x80; chip8.memory[0x4F] = 0x80; chip8 } fn load_rom(&mut self, filename: String) { let mut file = File::open(filename).expect("file not found"); let mut buffer: Vec<u8> = Vec::new(); file.read_to_end(&mut buffer).expect("something went wrong reading the file"); self.memory[ROM_START_ADDRESS as usize..ROM_START_ADDRESS as usize + buffer.len()].copy_from_slice(&buffer); } #[cfg(feature="debugger")] fn print_registers(&self) { println!("PC= {:x}", self.register_pc); println!("I= {:x}", self.register_i); println!("DT= {:x}", self.register_dt); println!("ST= {:x}", self.register_st); println!("SP= {:x}", self.register_sp); for i in 0..16 as usize { println!("V{}= {:x}", i, self.register_v[i]); } let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } pub extern "stdcall" fn refresh(&mut self) { // ~60Hz if self.time_last_frame.elapsed() >= Duration::from_millis(1000 / 60)
} pub fn run(&mut self, filename: String) { self.load_rom(filename); #[cfg(not(feature="interpreter"))] let mut recompiler = Recompiler::new(&self.register_pc); loop { #[cfg(feature="debugger")] self.print_registers(); #[cfg(feature="interpreter")] Interpreter::execute_next_instruction(self); #[cfg(feature="interpreter")] self.refresh(); #[cfg(not(feature="interpreter"))] recompiler.execute_next_code_block(self); } } }
{ self.time_last_frame = Instant::now(); self.keyboard.update_key_states(); self.display.refresh(); if self.register_dt > 0 { self.register_dt -= 1 } if self.register_st > 0 { self.register_st -= 1; // TODO: beep } }
conditional_block
chip8.rs
extern crate sdl2; use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[cfg(feature="debugger")] use std::process::Command; use chip8::MEMORY_SIZE; use chip8::ROM_START_ADDRESS; use chip8::keyboard::Keyboard; use chip8::display::Display; #[cfg(feature="interpreter")] use chip8::interpreter::Interpreter; #[cfg(not(feature="interpreter"))] use chip8::recompiler::Recompiler; const STACK_SIZE: usize = 16; const V_REGISTERS_COUNT: usize = 16; pub struct Chip8 { pub memory: [u8; MEMORY_SIZE], pub stack: [u16; STACK_SIZE], pub register_v: [u8; V_REGISTERS_COUNT], pub register_i: u16, pub register_dt: u8, pub register_st: u8, pub register_pc: u16, pub register_sp: u8, pub keyboard: Keyboard, pub display: Display, time_last_frame: Instant } impl Chip8 { pub fn new() -> Chip8 { let sdl_context = sdl2::init().unwrap(); let mut chip8 = Chip8 { memory: [0; MEMORY_SIZE], stack: [0; STACK_SIZE], register_v: [0; V_REGISTERS_COUNT], register_i: 0, register_dt: 0, register_st: 0, register_pc: ROM_START_ADDRESS, register_sp: 0xFF, keyboard: Keyboard::new(&sdl_context), display: Display::new(&sdl_context), time_last_frame: Instant::now() }; chip8.memory[0x00] = 0xF0; chip8.memory[0x01] = 0x90; chip8.memory[0x02] = 0x90; chip8.memory[0x03] = 0x90; chip8.memory[0x04] = 0xF0; chip8.memory[0x05] = 0x20; chip8.memory[0x06] = 0x60; chip8.memory[0x07] = 0x20; chip8.memory[0x08] = 0x20; chip8.memory[0x09] = 0x70; chip8.memory[0x0A] = 0xF0; chip8.memory[0x0B] = 0x10; chip8.memory[0x0C] = 0xF0; chip8.memory[0x0D] = 0x80; chip8.memory[0x0E] = 0xF0; chip8.memory[0x0F] = 0xF0; chip8.memory[0x10] = 0x10; chip8.memory[0x11] = 0xF0; chip8.memory[0x12] = 0x10; chip8.memory[0x13] = 0xF0; chip8.memory[0x14] = 0x90; chip8.memory[0x15] = 0x90; chip8.memory[0x16] = 0xF0; chip8.memory[0x17] = 0x10; chip8.memory[0x18] = 0x10; chip8.memory[0x19] = 0xF0; chip8.memory[0x1A] = 0x80; chip8.memory[0x1B] = 0xF0; chip8.memory[0x1C] = 0x10; chip8.memory[0x1D] = 0xF0; chip8.memory[0x1E] = 0xF0; chip8.memory[0x1F] = 0x80; chip8.memory[0x20] = 0xF0; chip8.memory[0x21] = 0x90; chip8.memory[0x22] = 0xF0; chip8.memory[0x23] = 0xF0; chip8.memory[0x24] = 0x10; chip8.memory[0x25] = 0x20; chip8.memory[0x26] = 0x40; chip8.memory[0x27] = 0x40; chip8.memory[0x28] = 0xF0; chip8.memory[0x29] = 0x90; chip8.memory[0x2A] = 0xF0; chip8.memory[0x2B] = 0x90; chip8.memory[0x2C] = 0xF0; chip8.memory[0x2D] = 0xF0; chip8.memory[0x2E] = 0x90; chip8.memory[0x2F] = 0xF0; chip8.memory[0x30] = 0x10; chip8.memory[0x31] = 0xF0; chip8.memory[0x32] = 0xF0; chip8.memory[0x33] = 0x90; chip8.memory[0x34] = 0xF0; chip8.memory[0x35] = 0x90; chip8.memory[0x36] = 0x90; chip8.memory[0x37] = 0xE0; chip8.memory[0x38] = 0x90; chip8.memory[0x39] = 0xE0; chip8.memory[0x3A] = 0x90; chip8.memory[0x3B] = 0xE0; chip8.memory[0x3C] = 0xF0; chip8.memory[0x3D] = 0x80; chip8.memory[0x3E] = 0x80; chip8.memory[0x3F] = 0x80; chip8.memory[0x40] = 0xF0; chip8.memory[0x41] = 0xE0; chip8.memory[0x42] = 0x90; chip8.memory[0x43] = 0x90; chip8.memory[0x44] = 0x90; chip8.memory[0x45] = 0xE0; chip8.memory[0x46] = 0xF0; chip8.memory[0x47] = 0x80; chip8.memory[0x48] = 0xF0; chip8.memory[0x49] = 0x80; chip8.memory[0x4A] = 0xF0; chip8.memory[0x4B] = 0xF0; chip8.memory[0x4C] = 0x80; chip8.memory[0x4D] = 0xF0; chip8.memory[0x4E] = 0x80; chip8.memory[0x4F] = 0x80; chip8 } fn load_rom(&mut self, filename: String) { let mut file = File::open(filename).expect("file not found"); let mut buffer: Vec<u8> = Vec::new(); file.read_to_end(&mut buffer).expect("something went wrong reading the file"); self.memory[ROM_START_ADDRESS as usize..ROM_START_ADDRESS as usize + buffer.len()].copy_from_slice(&buffer); } #[cfg(feature="debugger")] fn print_registers(&self) { println!("PC= {:x}", self.register_pc); println!("I= {:x}", self.register_i); println!("DT= {:x}", self.register_dt); println!("ST= {:x}", self.register_st); println!("SP= {:x}", self.register_sp); for i in 0..16 as usize { println!("V{}= {:x}", i, self.register_v[i]); } let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } pub extern "stdcall" fn refresh(&mut self) { // ~60Hz if self.time_last_frame.elapsed() >= Duration::from_millis(1000 / 60) { self.time_last_frame = Instant::now(); self.keyboard.update_key_states(); self.display.refresh(); if self.register_dt > 0 { self.register_dt -= 1 } if self.register_st > 0 { self.register_st -= 1; // TODO: beep } } } pub fn run(&mut self, filename: String) { self.load_rom(filename); #[cfg(not(feature="interpreter"))] let mut recompiler = Recompiler::new(&self.register_pc); loop { #[cfg(feature="debugger")] self.print_registers();
#[cfg(not(feature="interpreter"))] recompiler.execute_next_code_block(self); } } }
#[cfg(feature="interpreter")] Interpreter::execute_next_instruction(self); #[cfg(feature="interpreter")] self.refresh();
random_line_split
parse.rs
use crate::{Error, Result}; use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree}; use quote::ToTokens; use std::iter::Peekable; pub(crate) fn parse_input( input: TokenStream, ) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> { let mut input = input.into_iter().peekable(); let mut attrs = Vec::new(); while let Some(attr) = parse_next_attr(&mut input)? { attrs.push(attr); } let sig = parse_signature(&mut input); let body = input.next().ok_or_else(|| { Error::new( Span::call_site(), "`#[proc_macro_error]` can be applied only to functions".to_string(), ) })?; Ok((attrs, sig, body)) } fn parse_next_attr( input: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Option<Attribute>> { let shebang = match input.peek() { Some(TokenTree::Punct(ref punct)) if punct.as_char() == '#' => input.next().unwrap(), _ => return Ok(None), }; let group = match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Bracket => { let res = group.clone(); input.next(); res } other => { let span = other.map_or(Span::call_site(), |tt| tt.span()); return Err(Error::new(span, "expected `[`".to_string())); } }; let path = match group.stream().into_iter().next() { Some(TokenTree::Ident(ident)) => Some(ident), _ => None, }; Ok(Some(Attribute { shebang, group: TokenTree::Group(group), path, })) } fn parse_signature(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Vec<TokenTree>
pub(crate) struct Attribute { pub(crate) shebang: TokenTree, pub(crate) group: TokenTree, pub(crate) path: Option<Ident>, } impl Attribute { pub(crate) fn path_is_ident(&self, ident: &str) -> bool { self.path.as_ref().map_or(false, |p| *p == ident) } } impl ToTokens for Attribute { fn to_tokens(&self, ts: &mut TokenStream) { self.shebang.to_tokens(ts); self.group.to_tokens(ts); } }
{ let mut sig = Vec::new(); loop { match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Brace => { return sig; } None => return sig, _ => sig.push(input.next().unwrap()), } } }
identifier_body
parse.rs
use crate::{Error, Result}; use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree}; use quote::ToTokens; use std::iter::Peekable; pub(crate) fn parse_input( input: TokenStream, ) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> { let mut input = input.into_iter().peekable(); let mut attrs = Vec::new(); while let Some(attr) = parse_next_attr(&mut input)? { attrs.push(attr); } let sig = parse_signature(&mut input); let body = input.next().ok_or_else(|| { Error::new( Span::call_site(), "`#[proc_macro_error]` can be applied only to functions".to_string(), ) })?; Ok((attrs, sig, body)) } fn parse_next_attr( input: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Option<Attribute>> { let shebang = match input.peek() { Some(TokenTree::Punct(ref punct)) if punct.as_char() == '#' => input.next().unwrap(), _ => return Ok(None), }; let group = match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Bracket => { let res = group.clone(); input.next(); res } other => { let span = other.map_or(Span::call_site(), |tt| tt.span()); return Err(Error::new(span, "expected `[`".to_string())); } }; let path = match group.stream().into_iter().next() { Some(TokenTree::Ident(ident)) => Some(ident), _ => None, };
shebang, group: TokenTree::Group(group), path, })) } fn parse_signature(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Vec<TokenTree> { let mut sig = Vec::new(); loop { match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Brace => { return sig; } None => return sig, _ => sig.push(input.next().unwrap()), } } } pub(crate) struct Attribute { pub(crate) shebang: TokenTree, pub(crate) group: TokenTree, pub(crate) path: Option<Ident>, } impl Attribute { pub(crate) fn path_is_ident(&self, ident: &str) -> bool { self.path.as_ref().map_or(false, |p| *p == ident) } } impl ToTokens for Attribute { fn to_tokens(&self, ts: &mut TokenStream) { self.shebang.to_tokens(ts); self.group.to_tokens(ts); } }
Ok(Some(Attribute {
random_line_split
parse.rs
use crate::{Error, Result}; use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree}; use quote::ToTokens; use std::iter::Peekable; pub(crate) fn parse_input( input: TokenStream, ) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> { let mut input = input.into_iter().peekable(); let mut attrs = Vec::new(); while let Some(attr) = parse_next_attr(&mut input)? { attrs.push(attr); } let sig = parse_signature(&mut input); let body = input.next().ok_or_else(|| { Error::new( Span::call_site(), "`#[proc_macro_error]` can be applied only to functions".to_string(), ) })?; Ok((attrs, sig, body)) } fn
( input: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Option<Attribute>> { let shebang = match input.peek() { Some(TokenTree::Punct(ref punct)) if punct.as_char() == '#' => input.next().unwrap(), _ => return Ok(None), }; let group = match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Bracket => { let res = group.clone(); input.next(); res } other => { let span = other.map_or(Span::call_site(), |tt| tt.span()); return Err(Error::new(span, "expected `[`".to_string())); } }; let path = match group.stream().into_iter().next() { Some(TokenTree::Ident(ident)) => Some(ident), _ => None, }; Ok(Some(Attribute { shebang, group: TokenTree::Group(group), path, })) } fn parse_signature(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Vec<TokenTree> { let mut sig = Vec::new(); loop { match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Brace => { return sig; } None => return sig, _ => sig.push(input.next().unwrap()), } } } pub(crate) struct Attribute { pub(crate) shebang: TokenTree, pub(crate) group: TokenTree, pub(crate) path: Option<Ident>, } impl Attribute { pub(crate) fn path_is_ident(&self, ident: &str) -> bool { self.path.as_ref().map_or(false, |p| *p == ident) } } impl ToTokens for Attribute { fn to_tokens(&self, ts: &mut TokenStream) { self.shebang.to_tokens(ts); self.group.to_tokens(ts); } }
parse_next_attr
identifier_name
browsing_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Liberally derived from the [Firefox JS implementation] //! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webbrowser.js). //! Connection point for remote devtools that wish to investigate a particular Browsing Context's contents. //! Supports dynamic attaching and detaching which control notifications of navigation, etc. use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::actors::console::ConsoleActor; use crate::protocol::JsonPacketStream; use devtools_traits::DevtoolScriptControlMsg::{self, WantsLiveNotifications}; use serde_json::{Map, Value}; use std::net::TcpStream; #[derive(Serialize)] struct BrowsingContextTraits; #[derive(Serialize)] struct BrowsingContextAttachedReply { from: String, #[serde(rename = "type")] type_: String, threadActor: String, cacheDisabled: bool, javascriptEnabled: bool, traits: BrowsingContextTraits, } #[derive(Serialize)] struct BrowsingContextDetachedReply { from: String, #[serde(rename = "type")] type_: String, } #[derive(Serialize)] struct ReconfigureReply { from: String, } #[derive(Serialize)] struct ListFramesReply { from: String, frames: Vec<FrameMsg>, } #[derive(Serialize)] struct FrameMsg { id: u32, url: String, title: String, parentID: u32, } #[derive(Serialize)] struct ListWorkersReply { from: String, workers: Vec<WorkerMsg>, } #[derive(Serialize)] struct WorkerMsg { id: u32, } #[derive(Serialize)] pub struct BrowsingContextActorMsg { actor: String, title: String, url: String, outerWindowID: u32, consoleActor: String, emulationActor: String, inspectorActor: String, timelineActor: String, profilerActor: String, performanceActor: String, styleSheetsActor: String, } pub struct
{ pub name: String, pub title: String, pub url: String, pub console: String, pub emulation: String, pub inspector: String, pub timeline: String, pub profiler: String, pub performance: String, pub styleSheets: String, pub thread: String, } impl Actor for BrowsingContextActor { fn name(&self) -> String { self.name.clone() } fn handle_message( &self, registry: &ActorRegistry, msg_type: &str, msg: &Map<String, Value>, stream: &mut TcpStream, ) -> Result<ActorMessageStatus, ()> { Ok(match msg_type { "reconfigure" => { if let Some(options) = msg.get("options").and_then(|o| o.as_object()) { if let Some(val) = options.get("performReload") { if val.as_bool().unwrap_or(false) { let console_actor = registry.find::<ConsoleActor>(&self.console); let _ = console_actor .script_chan .send(DevtoolScriptControlMsg::Reload(console_actor.pipeline)); } } } stream.write_json_packet(&ReconfigureReply { from: self.name() }); ActorMessageStatus::Processed }, // https://docs.firefox-dev.tools/backend/protocol.html#listing-browser-tabs // (see "To attach to a _targetActor_") "attach" => { let msg = BrowsingContextAttachedReply { from: self.name(), type_: "targetAttached".to_owned(), threadActor: self.thread.clone(), cacheDisabled: false, javascriptEnabled: true, traits: BrowsingContextTraits, }; let console_actor = registry.find::<ConsoleActor>(&self.console); console_actor .streams .borrow_mut() .push(stream.try_clone().unwrap()); stream.write_json_packet(&msg); console_actor .script_chan .send(WantsLiveNotifications(console_actor.pipeline, true)) .unwrap(); ActorMessageStatus::Processed }, //FIXME: The current implementation won't work for multiple connections. Need to ensure 105 // that the correct stream is removed. "detach" => { let msg = BrowsingContextDetachedReply { from: self.name(), type_: "detached".to_owned(), }; let console_actor = registry.find::<ConsoleActor>(&self.console); console_actor.streams.borrow_mut().pop(); stream.write_json_packet(&msg); console_actor .script_chan .send(WantsLiveNotifications(console_actor.pipeline, false)) .unwrap(); ActorMessageStatus::Processed }, "listFrames" => { let msg = ListFramesReply { from: self.name(), frames: vec![], }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "listWorkers" => { let msg = ListWorkersReply { from: self.name(), workers: vec![], }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, _ => ActorMessageStatus::Ignored, }) } } impl BrowsingContextActor { pub fn encodable(&self) -> BrowsingContextActorMsg { BrowsingContextActorMsg { actor: self.name(), title: self.title.clone(), url: self.url.clone(), outerWindowID: 0, //FIXME: this should probably be the pipeline id consoleActor: self.console.clone(), emulationActor: self.emulation.clone(), inspectorActor: self.inspector.clone(), timelineActor: self.timeline.clone(), profilerActor: self.profiler.clone(), performanceActor: self.performance.clone(), styleSheetsActor: self.styleSheets.clone(), } } }
BrowsingContextActor
identifier_name
browsing_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Liberally derived from the [Firefox JS implementation] //! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webbrowser.js). //! Connection point for remote devtools that wish to investigate a particular Browsing Context's contents. //! Supports dynamic attaching and detaching which control notifications of navigation, etc. use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::actors::console::ConsoleActor; use crate::protocol::JsonPacketStream; use devtools_traits::DevtoolScriptControlMsg::{self, WantsLiveNotifications}; use serde_json::{Map, Value}; use std::net::TcpStream; #[derive(Serialize)] struct BrowsingContextTraits; #[derive(Serialize)] struct BrowsingContextAttachedReply { from: String, #[serde(rename = "type")] type_: String, threadActor: String, cacheDisabled: bool, javascriptEnabled: bool, traits: BrowsingContextTraits, } #[derive(Serialize)] struct BrowsingContextDetachedReply { from: String, #[serde(rename = "type")] type_: String, } #[derive(Serialize)] struct ReconfigureReply { from: String, } #[derive(Serialize)] struct ListFramesReply { from: String, frames: Vec<FrameMsg>, } #[derive(Serialize)] struct FrameMsg { id: u32, url: String, title: String, parentID: u32, } #[derive(Serialize)] struct ListWorkersReply { from: String, workers: Vec<WorkerMsg>, } #[derive(Serialize)] struct WorkerMsg { id: u32, } #[derive(Serialize)] pub struct BrowsingContextActorMsg {
consoleActor: String, emulationActor: String, inspectorActor: String, timelineActor: String, profilerActor: String, performanceActor: String, styleSheetsActor: String, } pub struct BrowsingContextActor { pub name: String, pub title: String, pub url: String, pub console: String, pub emulation: String, pub inspector: String, pub timeline: String, pub profiler: String, pub performance: String, pub styleSheets: String, pub thread: String, } impl Actor for BrowsingContextActor { fn name(&self) -> String { self.name.clone() } fn handle_message( &self, registry: &ActorRegistry, msg_type: &str, msg: &Map<String, Value>, stream: &mut TcpStream, ) -> Result<ActorMessageStatus, ()> { Ok(match msg_type { "reconfigure" => { if let Some(options) = msg.get("options").and_then(|o| o.as_object()) { if let Some(val) = options.get("performReload") { if val.as_bool().unwrap_or(false) { let console_actor = registry.find::<ConsoleActor>(&self.console); let _ = console_actor .script_chan .send(DevtoolScriptControlMsg::Reload(console_actor.pipeline)); } } } stream.write_json_packet(&ReconfigureReply { from: self.name() }); ActorMessageStatus::Processed }, // https://docs.firefox-dev.tools/backend/protocol.html#listing-browser-tabs // (see "To attach to a _targetActor_") "attach" => { let msg = BrowsingContextAttachedReply { from: self.name(), type_: "targetAttached".to_owned(), threadActor: self.thread.clone(), cacheDisabled: false, javascriptEnabled: true, traits: BrowsingContextTraits, }; let console_actor = registry.find::<ConsoleActor>(&self.console); console_actor .streams .borrow_mut() .push(stream.try_clone().unwrap()); stream.write_json_packet(&msg); console_actor .script_chan .send(WantsLiveNotifications(console_actor.pipeline, true)) .unwrap(); ActorMessageStatus::Processed }, //FIXME: The current implementation won't work for multiple connections. Need to ensure 105 // that the correct stream is removed. "detach" => { let msg = BrowsingContextDetachedReply { from: self.name(), type_: "detached".to_owned(), }; let console_actor = registry.find::<ConsoleActor>(&self.console); console_actor.streams.borrow_mut().pop(); stream.write_json_packet(&msg); console_actor .script_chan .send(WantsLiveNotifications(console_actor.pipeline, false)) .unwrap(); ActorMessageStatus::Processed }, "listFrames" => { let msg = ListFramesReply { from: self.name(), frames: vec![], }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "listWorkers" => { let msg = ListWorkersReply { from: self.name(), workers: vec![], }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, _ => ActorMessageStatus::Ignored, }) } } impl BrowsingContextActor { pub fn encodable(&self) -> BrowsingContextActorMsg { BrowsingContextActorMsg { actor: self.name(), title: self.title.clone(), url: self.url.clone(), outerWindowID: 0, //FIXME: this should probably be the pipeline id consoleActor: self.console.clone(), emulationActor: self.emulation.clone(), inspectorActor: self.inspector.clone(), timelineActor: self.timeline.clone(), profilerActor: self.profiler.clone(), performanceActor: self.performance.clone(), styleSheetsActor: self.styleSheets.clone(), } } }
actor: String, title: String, url: String, outerWindowID: u32,
random_line_split
mirror.rs
// Copyright 2016 The Gfx-rs 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. // use cocoa::base::{selector, class}; // use cocoa::foundation::{NSUInteger}; use core::{self, shade}; use metal::*; pub fn map_base_type_to_format(ty: shade::BaseType) -> MTLVertexFormat { use core::shade::BaseType::*; match ty { I32 => MTLVertexFormat::Int, U32 => MTLVertexFormat::UInt, F32 => MTLVertexFormat::Float, Bool => MTLVertexFormat::Char2, F64 => { unimplemented!() } } } pub fn populate_vertex_attributes(info: &mut shade::ProgramInfo,
desc: NSArray<MTLVertexAttribute>) { use map::{map_base_type, map_container_type}; for idx in 0..desc.count() { let attr = desc.object_at(idx); info.vertex_attributes.push(shade::AttributeVar { name: attr.name().into(), slot: attr.attribute_index() as core::AttributeSlot, base_type: map_base_type(attr.attribute_type()), container: map_container_type(attr.attribute_type()), }); } } pub fn populate_info(info: &mut shade::ProgramInfo, stage: shade::Stage, args: NSArray<MTLArgument>) { use map::{map_base_type, map_texture_type}; let usage = stage.into(); for idx in 0..args.count() { let arg = args.object_at(idx); let name = arg.name(); match arg.type_() { MTLArgumentType::Buffer => { if name.starts_with("vertexBuffer.") { continue; } info.constant_buffers.push(shade::ConstantBufferVar { name: name.into(), slot: arg.index() as core::ConstantBufferSlot, size: arg.buffer_data_size() as usize, usage: usage, elements: Vec::new(), // TODO! }); } MTLArgumentType::Texture => { info.textures.push(shade::TextureVar { name: name.into(), slot: arg.index() as core::ResourceViewSlot, base_type: map_base_type(arg.texture_data_type()), ty: map_texture_type(arg.texture_type()), usage: usage, }); } MTLArgumentType::Sampler => { let name = name.trim_right_matches('_'); info.samplers.push(shade::SamplerVar { name: name.into(), slot: arg.index() as core::SamplerSlot, ty: shade::SamplerType(shade::IsComparison::NoCompare, shade::IsRect::NoRect), usage: usage, }); } _ => {} } } }
random_line_split
mirror.rs
// Copyright 2016 The Gfx-rs 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. // use cocoa::base::{selector, class}; // use cocoa::foundation::{NSUInteger}; use core::{self, shade}; use metal::*; pub fn map_base_type_to_format(ty: shade::BaseType) -> MTLVertexFormat { use core::shade::BaseType::*; match ty { I32 => MTLVertexFormat::Int, U32 => MTLVertexFormat::UInt, F32 => MTLVertexFormat::Float, Bool => MTLVertexFormat::Char2, F64 => { unimplemented!() } } } pub fn
(info: &mut shade::ProgramInfo, desc: NSArray<MTLVertexAttribute>) { use map::{map_base_type, map_container_type}; for idx in 0..desc.count() { let attr = desc.object_at(idx); info.vertex_attributes.push(shade::AttributeVar { name: attr.name().into(), slot: attr.attribute_index() as core::AttributeSlot, base_type: map_base_type(attr.attribute_type()), container: map_container_type(attr.attribute_type()), }); } } pub fn populate_info(info: &mut shade::ProgramInfo, stage: shade::Stage, args: NSArray<MTLArgument>) { use map::{map_base_type, map_texture_type}; let usage = stage.into(); for idx in 0..args.count() { let arg = args.object_at(idx); let name = arg.name(); match arg.type_() { MTLArgumentType::Buffer => { if name.starts_with("vertexBuffer.") { continue; } info.constant_buffers.push(shade::ConstantBufferVar { name: name.into(), slot: arg.index() as core::ConstantBufferSlot, size: arg.buffer_data_size() as usize, usage: usage, elements: Vec::new(), // TODO! }); } MTLArgumentType::Texture => { info.textures.push(shade::TextureVar { name: name.into(), slot: arg.index() as core::ResourceViewSlot, base_type: map_base_type(arg.texture_data_type()), ty: map_texture_type(arg.texture_type()), usage: usage, }); } MTLArgumentType::Sampler => { let name = name.trim_right_matches('_'); info.samplers.push(shade::SamplerVar { name: name.into(), slot: arg.index() as core::SamplerSlot, ty: shade::SamplerType(shade::IsComparison::NoCompare, shade::IsRect::NoRect), usage: usage, }); } _ => {} } } }
populate_vertex_attributes
identifier_name
mirror.rs
// Copyright 2016 The Gfx-rs 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. // use cocoa::base::{selector, class}; // use cocoa::foundation::{NSUInteger}; use core::{self, shade}; use metal::*; pub fn map_base_type_to_format(ty: shade::BaseType) -> MTLVertexFormat { use core::shade::BaseType::*; match ty { I32 => MTLVertexFormat::Int, U32 => MTLVertexFormat::UInt, F32 => MTLVertexFormat::Float, Bool => MTLVertexFormat::Char2, F64 => { unimplemented!() } } } pub fn populate_vertex_attributes(info: &mut shade::ProgramInfo, desc: NSArray<MTLVertexAttribute>)
pub fn populate_info(info: &mut shade::ProgramInfo, stage: shade::Stage, args: NSArray<MTLArgument>) { use map::{map_base_type, map_texture_type}; let usage = stage.into(); for idx in 0..args.count() { let arg = args.object_at(idx); let name = arg.name(); match arg.type_() { MTLArgumentType::Buffer => { if name.starts_with("vertexBuffer.") { continue; } info.constant_buffers.push(shade::ConstantBufferVar { name: name.into(), slot: arg.index() as core::ConstantBufferSlot, size: arg.buffer_data_size() as usize, usage: usage, elements: Vec::new(), // TODO! }); } MTLArgumentType::Texture => { info.textures.push(shade::TextureVar { name: name.into(), slot: arg.index() as core::ResourceViewSlot, base_type: map_base_type(arg.texture_data_type()), ty: map_texture_type(arg.texture_type()), usage: usage, }); } MTLArgumentType::Sampler => { let name = name.trim_right_matches('_'); info.samplers.push(shade::SamplerVar { name: name.into(), slot: arg.index() as core::SamplerSlot, ty: shade::SamplerType(shade::IsComparison::NoCompare, shade::IsRect::NoRect), usage: usage, }); } _ => {} } } }
{ use map::{map_base_type, map_container_type}; for idx in 0..desc.count() { let attr = desc.object_at(idx); info.vertex_attributes.push(shade::AttributeVar { name: attr.name().into(), slot: attr.attribute_index() as core::AttributeSlot, base_type: map_base_type(attr.attribute_type()), container: map_container_type(attr.attribute_type()), }); } }
identifier_body
mirror.rs
// Copyright 2016 The Gfx-rs 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. // use cocoa::base::{selector, class}; // use cocoa::foundation::{NSUInteger}; use core::{self, shade}; use metal::*; pub fn map_base_type_to_format(ty: shade::BaseType) -> MTLVertexFormat { use core::shade::BaseType::*; match ty { I32 => MTLVertexFormat::Int, U32 => MTLVertexFormat::UInt, F32 => MTLVertexFormat::Float, Bool => MTLVertexFormat::Char2, F64 => { unimplemented!() } } } pub fn populate_vertex_attributes(info: &mut shade::ProgramInfo, desc: NSArray<MTLVertexAttribute>) { use map::{map_base_type, map_container_type}; for idx in 0..desc.count() { let attr = desc.object_at(idx); info.vertex_attributes.push(shade::AttributeVar { name: attr.name().into(), slot: attr.attribute_index() as core::AttributeSlot, base_type: map_base_type(attr.attribute_type()), container: map_container_type(attr.attribute_type()), }); } } pub fn populate_info(info: &mut shade::ProgramInfo, stage: shade::Stage, args: NSArray<MTLArgument>) { use map::{map_base_type, map_texture_type}; let usage = stage.into(); for idx in 0..args.count() { let arg = args.object_at(idx); let name = arg.name(); match arg.type_() { MTLArgumentType::Buffer => { if name.starts_with("vertexBuffer.")
info.constant_buffers.push(shade::ConstantBufferVar { name: name.into(), slot: arg.index() as core::ConstantBufferSlot, size: arg.buffer_data_size() as usize, usage: usage, elements: Vec::new(), // TODO! }); } MTLArgumentType::Texture => { info.textures.push(shade::TextureVar { name: name.into(), slot: arg.index() as core::ResourceViewSlot, base_type: map_base_type(arg.texture_data_type()), ty: map_texture_type(arg.texture_type()), usage: usage, }); } MTLArgumentType::Sampler => { let name = name.trim_right_matches('_'); info.samplers.push(shade::SamplerVar { name: name.into(), slot: arg.index() as core::SamplerSlot, ty: shade::SamplerType(shade::IsComparison::NoCompare, shade::IsRect::NoRect), usage: usage, }); } _ => {} } } }
{ continue; }
conditional_block
leaky_bucket.rs
extern crate ratelimit_meter; #[macro_use] extern crate nonzero_ext; use ratelimit_meter::{ algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket, NegativeMultiDecision, NonConformance, }; use std::thread; use std::time::Duration; #[test] fn accepts_first_cell() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); assert_eq!(Ok(()), lb.check_at(current_moment())); } #[test] fn rejects_too_many() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(2u32)); let now = current_moment(); let ms = Duration::from_millis(1); assert_eq!(Ok(()), lb.check_at(now)); assert_eq!(Ok(()), lb.check_at(now)); assert_ne!(Ok(()), lb.check_at(now + ms * 2)); // should be ok again in 1s: let next = now + Duration::from_millis(1002); assert_eq!(Ok(()), lb.check_at(next)); assert_eq!(Ok(()), lb.check_at(next + ms)); assert_ne!(Ok(()), lb.check_at(next + ms * 2), "{:?}", lb); } #[test] fn never_allows_more_than_capacity() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let now = current_moment(); let ms = Duration::from_millis(1); // Should not allow the first 15 cells on a capacity 5 bucket: assert_ne!(Ok(()), lb.check_n_at(15, now)); // After 3 and 20 seconds, it should not allow 15 on that bucket either: assert_ne!(Ok(()), lb.check_n_at(15, now + (ms * 3 * 1000))); let result = lb.check_n_at(15, now + (ms * 20 * 1000)); match result { Err(NegativeMultiDecision::InsufficientCapacity(n)) => assert_eq!(n, 15), _ => panic!("Did not expect {:?}", result), } } #[test] fn correct_wait_time() { // Bucket adding a new element per 200ms: let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let mut now = current_moment(); let ms = Duration::from_millis(1); let mut conforming = 0; for _i in 0..20 { now += ms; let res = lb.check_at(now); match res { Ok(()) => { conforming += 1; } Err(wait) => { now += wait.wait_time_from(now); assert_eq!(Ok(()), lb.check_at(now)); conforming += 1; } } } assert_eq!(20, conforming); } #[test] fn prevents_time_travel() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let now = current_moment() + Duration::from_secs(1); let ms = Duration::from_millis(1); assert!(lb.check_at(now).is_ok()); assert!(lb.check_at(now - ms).is_ok()); assert!(lb.check_at(now - ms * 500).is_ok()); } #[test] fn
() { let mut lim = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(20u32)); let now = current_moment(); let ms = Duration::from_millis(1); let mut children = vec![]; lim.check_at(now).unwrap(); for _i in 0..20 { let mut lim = lim.clone(); children.push(thread::spawn(move || lim.check_at(now).is_ok())); } for child in children { child.join().unwrap(); } assert!(!lim.check_at(now + ms * 2).is_ok()); assert_eq!(Ok(()), lim.check_at(now + ms * 1000)); } #[test] fn tooearly_wait_time_from() { let lim = LeakyBucket::construct(nonzero!(1u32), nonzero!(1u32), Duration::from_secs(1)).unwrap(); let state = <LeakyBucket as Algorithm>::BucketState::default(); let now = current_moment(); let ms = Duration::from_millis(1); lim.test_and_update(&state, now).unwrap(); if let Err(failure) = lim.test_and_update(&state, now) { assert_eq!(ms * 1000, failure.wait_time_from(now)); assert_eq!(Duration::new(0, 0), failure.wait_time_from(now + ms * 1000)); assert_eq!(Duration::new(0, 0), failure.wait_time_from(now + ms * 2001)); } else { assert!(false, "Second attempt should fail"); } }
actual_threadsafety
identifier_name
leaky_bucket.rs
extern crate ratelimit_meter; #[macro_use] extern crate nonzero_ext; use ratelimit_meter::{ algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket, NegativeMultiDecision, NonConformance, }; use std::thread; use std::time::Duration; #[test] fn accepts_first_cell() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); assert_eq!(Ok(()), lb.check_at(current_moment())); } #[test] fn rejects_too_many()
#[test] fn never_allows_more_than_capacity() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let now = current_moment(); let ms = Duration::from_millis(1); // Should not allow the first 15 cells on a capacity 5 bucket: assert_ne!(Ok(()), lb.check_n_at(15, now)); // After 3 and 20 seconds, it should not allow 15 on that bucket either: assert_ne!(Ok(()), lb.check_n_at(15, now + (ms * 3 * 1000))); let result = lb.check_n_at(15, now + (ms * 20 * 1000)); match result { Err(NegativeMultiDecision::InsufficientCapacity(n)) => assert_eq!(n, 15), _ => panic!("Did not expect {:?}", result), } } #[test] fn correct_wait_time() { // Bucket adding a new element per 200ms: let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let mut now = current_moment(); let ms = Duration::from_millis(1); let mut conforming = 0; for _i in 0..20 { now += ms; let res = lb.check_at(now); match res { Ok(()) => { conforming += 1; } Err(wait) => { now += wait.wait_time_from(now); assert_eq!(Ok(()), lb.check_at(now)); conforming += 1; } } } assert_eq!(20, conforming); } #[test] fn prevents_time_travel() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let now = current_moment() + Duration::from_secs(1); let ms = Duration::from_millis(1); assert!(lb.check_at(now).is_ok()); assert!(lb.check_at(now - ms).is_ok()); assert!(lb.check_at(now - ms * 500).is_ok()); } #[test] fn actual_threadsafety() { let mut lim = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(20u32)); let now = current_moment(); let ms = Duration::from_millis(1); let mut children = vec![]; lim.check_at(now).unwrap(); for _i in 0..20 { let mut lim = lim.clone(); children.push(thread::spawn(move || lim.check_at(now).is_ok())); } for child in children { child.join().unwrap(); } assert!(!lim.check_at(now + ms * 2).is_ok()); assert_eq!(Ok(()), lim.check_at(now + ms * 1000)); } #[test] fn tooearly_wait_time_from() { let lim = LeakyBucket::construct(nonzero!(1u32), nonzero!(1u32), Duration::from_secs(1)).unwrap(); let state = <LeakyBucket as Algorithm>::BucketState::default(); let now = current_moment(); let ms = Duration::from_millis(1); lim.test_and_update(&state, now).unwrap(); if let Err(failure) = lim.test_and_update(&state, now) { assert_eq!(ms * 1000, failure.wait_time_from(now)); assert_eq!(Duration::new(0, 0), failure.wait_time_from(now + ms * 1000)); assert_eq!(Duration::new(0, 0), failure.wait_time_from(now + ms * 2001)); } else { assert!(false, "Second attempt should fail"); } }
{ let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(2u32)); let now = current_moment(); let ms = Duration::from_millis(1); assert_eq!(Ok(()), lb.check_at(now)); assert_eq!(Ok(()), lb.check_at(now)); assert_ne!(Ok(()), lb.check_at(now + ms * 2)); // should be ok again in 1s: let next = now + Duration::from_millis(1002); assert_eq!(Ok(()), lb.check_at(next)); assert_eq!(Ok(()), lb.check_at(next + ms)); assert_ne!(Ok(()), lb.check_at(next + ms * 2), "{:?}", lb); }
identifier_body
leaky_bucket.rs
extern crate ratelimit_meter; #[macro_use] extern crate nonzero_ext; use ratelimit_meter::{ algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket, NegativeMultiDecision, NonConformance, }; use std::thread; use std::time::Duration; #[test] fn accepts_first_cell() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); assert_eq!(Ok(()), lb.check_at(current_moment())); } #[test] fn rejects_too_many() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(2u32)); let now = current_moment(); let ms = Duration::from_millis(1); assert_eq!(Ok(()), lb.check_at(now)); assert_eq!(Ok(()), lb.check_at(now)); assert_ne!(Ok(()), lb.check_at(now + ms * 2)); // should be ok again in 1s: let next = now + Duration::from_millis(1002); assert_eq!(Ok(()), lb.check_at(next)); assert_eq!(Ok(()), lb.check_at(next + ms)); assert_ne!(Ok(()), lb.check_at(next + ms * 2), "{:?}", lb);
let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let now = current_moment(); let ms = Duration::from_millis(1); // Should not allow the first 15 cells on a capacity 5 bucket: assert_ne!(Ok(()), lb.check_n_at(15, now)); // After 3 and 20 seconds, it should not allow 15 on that bucket either: assert_ne!(Ok(()), lb.check_n_at(15, now + (ms * 3 * 1000))); let result = lb.check_n_at(15, now + (ms * 20 * 1000)); match result { Err(NegativeMultiDecision::InsufficientCapacity(n)) => assert_eq!(n, 15), _ => panic!("Did not expect {:?}", result), } } #[test] fn correct_wait_time() { // Bucket adding a new element per 200ms: let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let mut now = current_moment(); let ms = Duration::from_millis(1); let mut conforming = 0; for _i in 0..20 { now += ms; let res = lb.check_at(now); match res { Ok(()) => { conforming += 1; } Err(wait) => { now += wait.wait_time_from(now); assert_eq!(Ok(()), lb.check_at(now)); conforming += 1; } } } assert_eq!(20, conforming); } #[test] fn prevents_time_travel() { let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32)); let now = current_moment() + Duration::from_secs(1); let ms = Duration::from_millis(1); assert!(lb.check_at(now).is_ok()); assert!(lb.check_at(now - ms).is_ok()); assert!(lb.check_at(now - ms * 500).is_ok()); } #[test] fn actual_threadsafety() { let mut lim = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(20u32)); let now = current_moment(); let ms = Duration::from_millis(1); let mut children = vec![]; lim.check_at(now).unwrap(); for _i in 0..20 { let mut lim = lim.clone(); children.push(thread::spawn(move || lim.check_at(now).is_ok())); } for child in children { child.join().unwrap(); } assert!(!lim.check_at(now + ms * 2).is_ok()); assert_eq!(Ok(()), lim.check_at(now + ms * 1000)); } #[test] fn tooearly_wait_time_from() { let lim = LeakyBucket::construct(nonzero!(1u32), nonzero!(1u32), Duration::from_secs(1)).unwrap(); let state = <LeakyBucket as Algorithm>::BucketState::default(); let now = current_moment(); let ms = Duration::from_millis(1); lim.test_and_update(&state, now).unwrap(); if let Err(failure) = lim.test_and_update(&state, now) { assert_eq!(ms * 1000, failure.wait_time_from(now)); assert_eq!(Duration::new(0, 0), failure.wait_time_from(now + ms * 1000)); assert_eq!(Duration::new(0, 0), failure.wait_time_from(now + ms * 2001)); } else { assert!(false, "Second attempt should fail"); } }
} #[test] fn never_allows_more_than_capacity() {
random_line_split
map-types.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. extern crate collections; use std::collections::HashMap; // Test that trait types printed in error msgs include the type arguments. fn
() { let x: Box<HashMap<int, int>> = box HashMap::new(); let x: Box<Map<int, int>> = x; let y: Box<Map<uint, int>> = box x; //~^ ERROR the trait `collections::Map<uint,int>` is not implemented }
main
identifier_name
map-types.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. extern crate collections; use std::collections::HashMap; // Test that trait types printed in error msgs include the type arguments. fn main()
{ let x: Box<HashMap<int, int>> = box HashMap::new(); let x: Box<Map<int, int>> = x; let y: Box<Map<uint, int>> = box x; //~^ ERROR the trait `collections::Map<uint,int>` is not implemented }
identifier_body
map-types.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. extern crate collections;
fn main() { let x: Box<HashMap<int, int>> = box HashMap::new(); let x: Box<Map<int, int>> = x; let y: Box<Map<uint, int>> = box x; //~^ ERROR the trait `collections::Map<uint,int>` is not implemented }
use std::collections::HashMap; // Test that trait types printed in error msgs include the type arguments.
random_line_split
add.rs
use std::cmp::Ordering; use cmp; use denormalize; use normalize; use valid; pub fn add(num_l: &str, num_r: &str) -> Result<String, String> { if!valid(num_l) { Err(format!("Invalid numeral {}", num_l)) } else if!valid(num_r) { Err(format!("Invalid numeral {}", num_r)) } else { let sum = merge(denormalize(num_l), denormalize(num_r)); normalize(&sum) } } fn merge(num_l: String, num_r: String) -> String { let mut digits_l = num_l.chars(); let mut digits_r = num_r.chars(); let mut sum = String::new(); let mut next_l = digits_l.next(); let mut next_r = digits_r.next(); loop { match (next_l, next_r) { (Some(l), Some(r)) => { if cmp(l, r) == Ordering::Greater
else { sum.push(r); next_r = digits_r.next(); } }, (Some(l), None) => { sum.push(l); next_l = digits_l.next(); }, (None, Some(r)) => { sum.push(r); next_r = digits_r.next(); }, (None, None) => { break } } } sum } #[cfg(test)] mod tests { use super::add; #[test] fn add_i_i() { assert_eq!("II", add("I", "I").unwrap()); } #[test] fn add_i_ii() { assert_eq!("III", add("I", "II").unwrap()); } #[test] fn add_ii_iii_requires_normalization_to_v() { assert_eq!("V", add("II", "III").unwrap()); } #[test] fn add_v_i() { assert_eq!("VI", add("V", "I").unwrap()); } #[test] fn add_i_v_understands_the_relative_order_of_v_and_i() { assert_eq!("VI", add("I", "V").unwrap()); } #[test] fn add_i_iv_denormalizes_before_adding() { assert_eq!("V", add("I", "IV").unwrap()); } #[test] fn add_l_i_supports_l() { assert_eq!("LI", add("L", "I").unwrap()); } #[test] fn add_l_xi_understands_l_x_sort_order() { assert_eq!("LXI", add("L", "XI").unwrap()); } #[test] fn add_fails_when_result_is_too_big_to_be_represented() { assert!(add("MCMXCIX", "MMCMXCIX").is_err()); } #[test] fn add_fails_when_lhs_is_invalid() { assert!(add("J", "I").is_err()); } #[test] fn add_fails_when_rhs_is_invalid() { assert!(add("I", "").is_err()); } }
{ sum.push(l); next_l = digits_l.next(); }
conditional_block
add.rs
use std::cmp::Ordering; use cmp; use denormalize; use normalize; use valid; pub fn add(num_l: &str, num_r: &str) -> Result<String, String> { if!valid(num_l) { Err(format!("Invalid numeral {}", num_l)) } else if!valid(num_r) { Err(format!("Invalid numeral {}", num_r)) } else { let sum = merge(denormalize(num_l), denormalize(num_r)); normalize(&sum) } } fn merge(num_l: String, num_r: String) -> String { let mut digits_l = num_l.chars(); let mut digits_r = num_r.chars(); let mut sum = String::new(); let mut next_l = digits_l.next(); let mut next_r = digits_r.next(); loop { match (next_l, next_r) { (Some(l), Some(r)) => { if cmp(l, r) == Ordering::Greater { sum.push(l); next_l = digits_l.next(); } else { sum.push(r); next_r = digits_r.next(); } }, (Some(l), None) => { sum.push(l); next_l = digits_l.next(); }, (None, Some(r)) => { sum.push(r); next_r = digits_r.next(); }, (None, None) => { break } } } sum } #[cfg(test)] mod tests { use super::add; #[test] fn add_i_i() { assert_eq!("II", add("I", "I").unwrap()); } #[test] fn add_i_ii() { assert_eq!("III", add("I", "II").unwrap()); } #[test] fn add_ii_iii_requires_normalization_to_v() { assert_eq!("V", add("II", "III").unwrap()); } #[test] fn add_v_i() { assert_eq!("VI", add("V", "I").unwrap()); } #[test] fn add_i_v_understands_the_relative_order_of_v_and_i() { assert_eq!("VI", add("I", "V").unwrap()); } #[test] fn add_i_iv_denormalizes_before_adding() { assert_eq!("V", add("I", "IV").unwrap()); } #[test]
assert_eq!("LI", add("L", "I").unwrap()); } #[test] fn add_l_xi_understands_l_x_sort_order() { assert_eq!("LXI", add("L", "XI").unwrap()); } #[test] fn add_fails_when_result_is_too_big_to_be_represented() { assert!(add("MCMXCIX", "MMCMXCIX").is_err()); } #[test] fn add_fails_when_lhs_is_invalid() { assert!(add("J", "I").is_err()); } #[test] fn add_fails_when_rhs_is_invalid() { assert!(add("I", "").is_err()); } }
fn add_l_i_supports_l() {
random_line_split
add.rs
use std::cmp::Ordering; use cmp; use denormalize; use normalize; use valid; pub fn add(num_l: &str, num_r: &str) -> Result<String, String> { if!valid(num_l) { Err(format!("Invalid numeral {}", num_l)) } else if!valid(num_r) { Err(format!("Invalid numeral {}", num_r)) } else { let sum = merge(denormalize(num_l), denormalize(num_r)); normalize(&sum) } } fn merge(num_l: String, num_r: String) -> String { let mut digits_l = num_l.chars(); let mut digits_r = num_r.chars(); let mut sum = String::new(); let mut next_l = digits_l.next(); let mut next_r = digits_r.next(); loop { match (next_l, next_r) { (Some(l), Some(r)) => { if cmp(l, r) == Ordering::Greater { sum.push(l); next_l = digits_l.next(); } else { sum.push(r); next_r = digits_r.next(); } }, (Some(l), None) => { sum.push(l); next_l = digits_l.next(); }, (None, Some(r)) => { sum.push(r); next_r = digits_r.next(); }, (None, None) => { break } } } sum } #[cfg(test)] mod tests { use super::add; #[test] fn add_i_i() { assert_eq!("II", add("I", "I").unwrap()); } #[test] fn add_i_ii() { assert_eq!("III", add("I", "II").unwrap()); } #[test] fn add_ii_iii_requires_normalization_to_v() { assert_eq!("V", add("II", "III").unwrap()); } #[test] fn add_v_i() { assert_eq!("VI", add("V", "I").unwrap()); } #[test] fn add_i_v_understands_the_relative_order_of_v_and_i() { assert_eq!("VI", add("I", "V").unwrap()); } #[test] fn add_i_iv_denormalizes_before_adding() { assert_eq!("V", add("I", "IV").unwrap()); } #[test] fn add_l_i_supports_l()
#[test] fn add_l_xi_understands_l_x_sort_order() { assert_eq!("LXI", add("L", "XI").unwrap()); } #[test] fn add_fails_when_result_is_too_big_to_be_represented() { assert!(add("MCMXCIX", "MMCMXCIX").is_err()); } #[test] fn add_fails_when_lhs_is_invalid() { assert!(add("J", "I").is_err()); } #[test] fn add_fails_when_rhs_is_invalid() { assert!(add("I", "").is_err()); } }
{ assert_eq!("LI", add("L", "I").unwrap()); }
identifier_body
add.rs
use std::cmp::Ordering; use cmp; use denormalize; use normalize; use valid; pub fn add(num_l: &str, num_r: &str) -> Result<String, String> { if!valid(num_l) { Err(format!("Invalid numeral {}", num_l)) } else if!valid(num_r) { Err(format!("Invalid numeral {}", num_r)) } else { let sum = merge(denormalize(num_l), denormalize(num_r)); normalize(&sum) } } fn merge(num_l: String, num_r: String) -> String { let mut digits_l = num_l.chars(); let mut digits_r = num_r.chars(); let mut sum = String::new(); let mut next_l = digits_l.next(); let mut next_r = digits_r.next(); loop { match (next_l, next_r) { (Some(l), Some(r)) => { if cmp(l, r) == Ordering::Greater { sum.push(l); next_l = digits_l.next(); } else { sum.push(r); next_r = digits_r.next(); } }, (Some(l), None) => { sum.push(l); next_l = digits_l.next(); }, (None, Some(r)) => { sum.push(r); next_r = digits_r.next(); }, (None, None) => { break } } } sum } #[cfg(test)] mod tests { use super::add; #[test] fn add_i_i() { assert_eq!("II", add("I", "I").unwrap()); } #[test] fn add_i_ii() { assert_eq!("III", add("I", "II").unwrap()); } #[test] fn add_ii_iii_requires_normalization_to_v() { assert_eq!("V", add("II", "III").unwrap()); } #[test] fn add_v_i() { assert_eq!("VI", add("V", "I").unwrap()); } #[test] fn add_i_v_understands_the_relative_order_of_v_and_i() { assert_eq!("VI", add("I", "V").unwrap()); } #[test] fn add_i_iv_denormalizes_before_adding() { assert_eq!("V", add("I", "IV").unwrap()); } #[test] fn add_l_i_supports_l() { assert_eq!("LI", add("L", "I").unwrap()); } #[test] fn
() { assert_eq!("LXI", add("L", "XI").unwrap()); } #[test] fn add_fails_when_result_is_too_big_to_be_represented() { assert!(add("MCMXCIX", "MMCMXCIX").is_err()); } #[test] fn add_fails_when_lhs_is_invalid() { assert!(add("J", "I").is_err()); } #[test] fn add_fails_when_rhs_is_invalid() { assert!(add("I", "").is_err()); } }
add_l_xi_understands_l_x_sort_order
identifier_name
bounds.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{MetaItem, MetaWord, Item}; use codemap::Span; use ext::base::ExtCtxt; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use ptr::P; pub fn
(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: |P<Item>|) { let name = match mitem.node { MetaWord(ref tname) => { match tname.get() { "Copy" => "Copy", "Send" => "Send", "Sync" => "Sync", ref tname => { cx.span_bug(span, format!("expected built-in trait name but \ found {}", *tname).as_slice()) } } }, _ => { return cx.span_err(span, "unexpected value in deriving, expected \ a trait") } }; let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new(vec!("std", "kinds", name)), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!() }; trait_def.expand(cx, mitem, item, push) }
expand_deriving_bound
identifier_name
bounds.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{MetaItem, MetaWord, Item}; use codemap::Span; use ext::base::ExtCtxt; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use ptr::P; pub fn expand_deriving_bound(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: |P<Item>|) { let name = match mitem.node { MetaWord(ref tname) =>
, _ => { return cx.span_err(span, "unexpected value in deriving, expected \ a trait") } }; let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new(vec!("std", "kinds", name)), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!() }; trait_def.expand(cx, mitem, item, push) }
{ match tname.get() { "Copy" => "Copy", "Send" => "Send", "Sync" => "Sync", ref tname => { cx.span_bug(span, format!("expected built-in trait name but \ found {}", *tname).as_slice()) } } }
conditional_block
bounds.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{MetaItem, MetaWord, Item}; use codemap::Span; use ext::base::ExtCtxt; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use ptr::P; pub fn expand_deriving_bound(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: |P<Item>|)
}; let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new(vec!("std", "kinds", name)), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!() }; trait_def.expand(cx, mitem, item, push) }
{ let name = match mitem.node { MetaWord(ref tname) => { match tname.get() { "Copy" => "Copy", "Send" => "Send", "Sync" => "Sync", ref tname => { cx.span_bug(span, format!("expected built-in trait name but \ found {}", *tname).as_slice()) } } }, _ => { return cx.span_err(span, "unexpected value in deriving, expected \ a trait") }
identifier_body
bounds.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{MetaItem, MetaWord, Item}; use codemap::Span; use ext::base::ExtCtxt; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use ptr::P; pub fn expand_deriving_bound(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: |P<Item>|) { let name = match mitem.node { MetaWord(ref tname) => { match tname.get() { "Copy" => "Copy", "Send" => "Send", "Sync" => "Sync", ref tname => {
} } }, _ => { return cx.span_err(span, "unexpected value in deriving, expected \ a trait") } }; let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new(vec!("std", "kinds", name)), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!() }; trait_def.expand(cx, mitem, item, push) }
cx.span_bug(span, format!("expected built-in trait name but \ found {}", *tname).as_slice())
random_line_split
login.rs
use std::io::prelude::*; use std::io; use cargo::ops; use cargo::core::{SourceId, Source}; use cargo::sources::RegistrySource; use cargo::util::{CliResult, CliError, Config}; #[derive(RustcDecodable)] struct
{ flag_host: Option<String>, arg_token: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Save an api token from the registry locally Usage: cargo login [options] [<token>] Options: -h, --help Print this message --host HOST Host to set the token for -v, --verbose Use verbose output "; pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> { config.shell().set_verbose(options.flag_verbose); let token = match options.arg_token.clone() { Some(token) => token, None => { let err = (|| { let src = try!(SourceId::for_central(config)); let mut src = RegistrySource::new(&src, config); try!(src.update()); let config = try!(src.config()); let host = options.flag_host.clone().unwrap_or(config.api); println!("please visit {}me and paste the API Token below", host); let mut line = String::new(); let input = io::stdin(); try!(input.lock().read_line(&mut line)); Ok(line) })(); try!(err.map_err(|e| CliError::from_boxed(e, 101))) } }; let token = token.trim().to_string(); try!(ops::registry_login(config, token).map_err(|e| { CliError::from_boxed(e, 101) })); Ok(None) }
Options
identifier_name
login.rs
use std::io::prelude::*; use std::io; use cargo::ops; use cargo::core::{SourceId, Source}; use cargo::sources::RegistrySource; use cargo::util::{CliResult, CliError, Config}; #[derive(RustcDecodable)] struct Options { flag_host: Option<String>, arg_token: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Save an api token from the registry locally
cargo login [options] [<token>] Options: -h, --help Print this message --host HOST Host to set the token for -v, --verbose Use verbose output "; pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> { config.shell().set_verbose(options.flag_verbose); let token = match options.arg_token.clone() { Some(token) => token, None => { let err = (|| { let src = try!(SourceId::for_central(config)); let mut src = RegistrySource::new(&src, config); try!(src.update()); let config = try!(src.config()); let host = options.flag_host.clone().unwrap_or(config.api); println!("please visit {}me and paste the API Token below", host); let mut line = String::new(); let input = io::stdin(); try!(input.lock().read_line(&mut line)); Ok(line) })(); try!(err.map_err(|e| CliError::from_boxed(e, 101))) } }; let token = token.trim().to_string(); try!(ops::registry_login(config, token).map_err(|e| { CliError::from_boxed(e, 101) })); Ok(None) }
Usage:
random_line_split
text_expression_methods.rs
use crate::dsl; use crate::expression::grouped::Grouped; use crate::expression::operators::{Concat, Like, NotLike}; use crate::expression::{AsExpression, Expression}; use crate::sql_types::{Nullable, SqlType, Text}; /// Methods present on text expressions pub trait TextExpressionMethods: Expression + Sized { /// Concatenates two strings using the `||` operator. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # table! { /// # users { /// # id -> Integer, /// # name -> VarChar, /// # hair_color -> Nullable<Text>, /// # } /// # } /// # /// # fn main() { /// # use self::users::dsl::*; /// # use diesel::insert_into; /// # /// # let connection = connection_no_data(); /// # connection.execute("CREATE TABLE users ( /// # id INTEGER PRIMARY KEY, /// # name VARCHAR(255) NOT NULL, /// # hair_color VARCHAR(255) /// # )").unwrap(); /// # /// # insert_into(users) /// # .values(&vec![ /// # (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))), /// # (id.eq(2), name.eq("Tess"), hair_color.eq(None)), /// # ]) /// # .execute(&connection) /// # .unwrap(); /// # /// let names = users.select(name.concat(" the Greatest")).load(&connection); /// let expected_names = vec![ /// "Sean the Greatest".to_string(), /// "Tess the Greatest".to_string(), /// ]; /// assert_eq!(Ok(expected_names), names); /// /// // If the value is nullable, the output will be nullable /// let names = users.select(hair_color.concat("ish")).load(&connection); /// let expected_names = vec![ /// Some("Greenish".to_string()), /// None, /// ]; /// assert_eq!(Ok(expected_names), names); /// # } /// ``` fn concat<T>(self, other: T) -> dsl::Concat<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>, { Grouped(Concat::new(self, other.as_expression())) } /// Returns a SQL `LIKE` expression /// /// This method is case insensitive for SQLite and MySQL. /// On PostgreSQL, `LIKE` is case sensitive. You may use /// [`ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.ilike) /// for case insensitive comparison on PostgreSQL. /// /// # Examples /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let connection = establish_connection(); /// # /// let starts_with_s = users /// .select(name) /// .filter(name.like("S%")) /// .load::<String>(&connection)?; /// assert_eq!(vec!["Sean"], starts_with_s); /// # Ok(()) /// # } /// ``` fn like<T>(self, other: T) -> dsl::Like<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>,
/// Returns a SQL `NOT LIKE` expression /// /// This method is case insensitive for SQLite and MySQL. /// On PostgreSQL `NOT LIKE` is case sensitive. You may use /// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike) /// for case insensitive comparison on PostgreSQL. /// /// # Examples /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let connection = establish_connection(); /// # /// let doesnt_start_with_s = users /// .select(name) /// .filter(name.not_like("S%")) /// .load::<String>(&connection)?; /// assert_eq!(vec!["Tess"], doesnt_start_with_s); /// # Ok(()) /// # } /// ``` fn not_like<T>(self, other: T) -> dsl::NotLike<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>, { Grouped(NotLike::new(self, other.as_expression())) } } #[doc(hidden)] /// Marker trait used to implement `TextExpressionMethods` on the appropriate /// types. Once coherence takes associated types into account, we can remove /// this trait. pub trait TextOrNullableText {} impl TextOrNullableText for Text {} impl TextOrNullableText for Nullable<Text> {} impl<T> TextExpressionMethods for T where T: Expression, T::SqlType: TextOrNullableText, { }
{ Grouped(Like::new(self, other.as_expression())) }
identifier_body
text_expression_methods.rs
use crate::dsl; use crate::expression::grouped::Grouped; use crate::expression::operators::{Concat, Like, NotLike}; use crate::expression::{AsExpression, Expression}; use crate::sql_types::{Nullable, SqlType, Text}; /// Methods present on text expressions pub trait TextExpressionMethods: Expression + Sized { /// Concatenates two strings using the `||` operator. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # table! { /// # users { /// # id -> Integer, /// # name -> VarChar, /// # hair_color -> Nullable<Text>, /// # } /// # } /// # /// # fn main() { /// # use self::users::dsl::*; /// # use diesel::insert_into; /// # /// # let connection = connection_no_data(); /// # connection.execute("CREATE TABLE users ( /// # id INTEGER PRIMARY KEY, /// # name VARCHAR(255) NOT NULL, /// # hair_color VARCHAR(255)
/// # /// # insert_into(users) /// # .values(&vec![ /// # (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))), /// # (id.eq(2), name.eq("Tess"), hair_color.eq(None)), /// # ]) /// # .execute(&connection) /// # .unwrap(); /// # /// let names = users.select(name.concat(" the Greatest")).load(&connection); /// let expected_names = vec![ /// "Sean the Greatest".to_string(), /// "Tess the Greatest".to_string(), /// ]; /// assert_eq!(Ok(expected_names), names); /// /// // If the value is nullable, the output will be nullable /// let names = users.select(hair_color.concat("ish")).load(&connection); /// let expected_names = vec![ /// Some("Greenish".to_string()), /// None, /// ]; /// assert_eq!(Ok(expected_names), names); /// # } /// ``` fn concat<T>(self, other: T) -> dsl::Concat<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>, { Grouped(Concat::new(self, other.as_expression())) } /// Returns a SQL `LIKE` expression /// /// This method is case insensitive for SQLite and MySQL. /// On PostgreSQL, `LIKE` is case sensitive. You may use /// [`ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.ilike) /// for case insensitive comparison on PostgreSQL. /// /// # Examples /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let connection = establish_connection(); /// # /// let starts_with_s = users /// .select(name) /// .filter(name.like("S%")) /// .load::<String>(&connection)?; /// assert_eq!(vec!["Sean"], starts_with_s); /// # Ok(()) /// # } /// ``` fn like<T>(self, other: T) -> dsl::Like<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>, { Grouped(Like::new(self, other.as_expression())) } /// Returns a SQL `NOT LIKE` expression /// /// This method is case insensitive for SQLite and MySQL. /// On PostgreSQL `NOT LIKE` is case sensitive. You may use /// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike) /// for case insensitive comparison on PostgreSQL. /// /// # Examples /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let connection = establish_connection(); /// # /// let doesnt_start_with_s = users /// .select(name) /// .filter(name.not_like("S%")) /// .load::<String>(&connection)?; /// assert_eq!(vec!["Tess"], doesnt_start_with_s); /// # Ok(()) /// # } /// ``` fn not_like<T>(self, other: T) -> dsl::NotLike<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>, { Grouped(NotLike::new(self, other.as_expression())) } } #[doc(hidden)] /// Marker trait used to implement `TextExpressionMethods` on the appropriate /// types. Once coherence takes associated types into account, we can remove /// this trait. pub trait TextOrNullableText {} impl TextOrNullableText for Text {} impl TextOrNullableText for Nullable<Text> {} impl<T> TextExpressionMethods for T where T: Expression, T::SqlType: TextOrNullableText, { }
/// # )").unwrap();
random_line_split
text_expression_methods.rs
use crate::dsl; use crate::expression::grouped::Grouped; use crate::expression::operators::{Concat, Like, NotLike}; use crate::expression::{AsExpression, Expression}; use crate::sql_types::{Nullable, SqlType, Text}; /// Methods present on text expressions pub trait TextExpressionMethods: Expression + Sized { /// Concatenates two strings using the `||` operator. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # table! { /// # users { /// # id -> Integer, /// # name -> VarChar, /// # hair_color -> Nullable<Text>, /// # } /// # } /// # /// # fn main() { /// # use self::users::dsl::*; /// # use diesel::insert_into; /// # /// # let connection = connection_no_data(); /// # connection.execute("CREATE TABLE users ( /// # id INTEGER PRIMARY KEY, /// # name VARCHAR(255) NOT NULL, /// # hair_color VARCHAR(255) /// # )").unwrap(); /// # /// # insert_into(users) /// # .values(&vec![ /// # (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))), /// # (id.eq(2), name.eq("Tess"), hair_color.eq(None)), /// # ]) /// # .execute(&connection) /// # .unwrap(); /// # /// let names = users.select(name.concat(" the Greatest")).load(&connection); /// let expected_names = vec![ /// "Sean the Greatest".to_string(), /// "Tess the Greatest".to_string(), /// ]; /// assert_eq!(Ok(expected_names), names); /// /// // If the value is nullable, the output will be nullable /// let names = users.select(hair_color.concat("ish")).load(&connection); /// let expected_names = vec![ /// Some("Greenish".to_string()), /// None, /// ]; /// assert_eq!(Ok(expected_names), names); /// # } /// ``` fn concat<T>(self, other: T) -> dsl::Concat<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>, { Grouped(Concat::new(self, other.as_expression())) } /// Returns a SQL `LIKE` expression /// /// This method is case insensitive for SQLite and MySQL. /// On PostgreSQL, `LIKE` is case sensitive. You may use /// [`ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.ilike) /// for case insensitive comparison on PostgreSQL. /// /// # Examples /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let connection = establish_connection(); /// # /// let starts_with_s = users /// .select(name) /// .filter(name.like("S%")) /// .load::<String>(&connection)?; /// assert_eq!(vec!["Sean"], starts_with_s); /// # Ok(()) /// # } /// ``` fn
<T>(self, other: T) -> dsl::Like<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>, { Grouped(Like::new(self, other.as_expression())) } /// Returns a SQL `NOT LIKE` expression /// /// This method is case insensitive for SQLite and MySQL. /// On PostgreSQL `NOT LIKE` is case sensitive. You may use /// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike) /// for case insensitive comparison on PostgreSQL. /// /// # Examples /// /// ```rust /// # include!("../doctest_setup.rs"); /// # /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let connection = establish_connection(); /// # /// let doesnt_start_with_s = users /// .select(name) /// .filter(name.not_like("S%")) /// .load::<String>(&connection)?; /// assert_eq!(vec!["Tess"], doesnt_start_with_s); /// # Ok(()) /// # } /// ``` fn not_like<T>(self, other: T) -> dsl::NotLike<Self, T> where Self::SqlType: SqlType, T: AsExpression<Self::SqlType>, { Grouped(NotLike::new(self, other.as_expression())) } } #[doc(hidden)] /// Marker trait used to implement `TextExpressionMethods` on the appropriate /// types. Once coherence takes associated types into account, we can remove /// this trait. pub trait TextOrNullableText {} impl TextOrNullableText for Text {} impl TextOrNullableText for Nullable<Text> {} impl<T> TextExpressionMethods for T where T: Expression, T::SqlType: TextOrNullableText, { }
like
identifier_name
response.rs
use std::borrow::Cow; use std::sync::RwLock; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::path::Path; use serialize::Encodable; use hyper::status::StatusCode; use hyper::server::Response as HyperResponse; use hyper::header::{ Headers, Date, HttpDate, Server, ContentType, ContentLength, Header, HeaderFormat }; use hyper::net::{Fresh, Streaming}; use time; use mimes::MediaType; use mustache; use mustache::Template; use std::io::{self, Read, Write, copy}; use std::fs::File; use std::any::Any; use {NickelError, Halt, MiddlewareResult, Responder}; use modifier::Modifier; pub type TemplateCache = RwLock<HashMap<String, Template>>; ///A container for the response pub struct Response<'a, T:'static + Any = Fresh> { ///the original `hyper::server::Response` origin: HyperResponse<'a, T>, templates: &'a TemplateCache } impl<'a> Response<'a, Fresh> { pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>, templates: &'c TemplateCache) -> Response<'c, Fresh> { Response { origin: response, templates: templates } } /// Get a mutable reference to the status. pub fn status_mut(&mut self) -> &mut StatusCode { self.origin.status_mut() } /// Get a mutable reference to the Headers. pub fn headers_mut(&mut self) -> &mut Headers { self.origin.headers_mut() } /// Modify the response with the provided data. /// /// # Examples /// ```{rust} /// extern crate hyper; /// #[macro_use] extern crate nickel; /// /// use nickel::{Nickel, HttpRouter, MediaType}; /// use nickel::status::StatusCode; /// use hyper::header::Location; /// /// fn main() { /// let mut server = Nickel::new(); /// server.get("/a", middleware! { |_, mut res| /// // set the Status /// res.set(StatusCode::PermanentRedirect) /// // update a Header value /// .set(Location("http://nickel.rs".into())); /// /// "" /// }); /// /// server.get("/b", middleware! { |_, mut res| /// // setting the content type /// res.set(MediaType::Json); /// /// "{'foo': 'bar'}" /// }); /// /// //... /// } /// ``` pub fn set<T: Modifier<Response<'a>>>(&mut self, attribute: T) -> &mut Response<'a> { attribute.modify(self); self } /// Writes a response /// /// # Examples /// ```{rust} /// use nickel::{Request, Response, MiddlewareResult}; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// res.send("hello world") /// } /// ``` #[inline] pub fn send<T: Responder>(self, data: T) -> MiddlewareResult<'a> { data.respond(self) } /// Writes a file to the output. /// /// # Examples /// ```{rust} /// use nickel::{Request, Response, MiddlewareResult}; /// use std::path::Path; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// let favicon = Path::new("/assets/favicon.ico"); /// res.send_file(favicon) /// } /// ``` pub fn send_file(mut self, path: &Path) -> MiddlewareResult<'a> { // Chunk the response self.origin.headers_mut().remove::<ContentLength>(); // Determine content type by file extension or default to binary let mime = mime_from_filename(path).unwrap_or(MediaType::Bin); self.set(mime);
File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}", path, e)) }); let mut stream = try!(self.start()); match copy(&mut file, &mut stream) { Ok(_) => Ok(Halt(stream)), Err(e) => stream.bail(format!("Failed to send file: {}", e)) } } // TODO: This needs to be more sophisticated to return the correct headers // not just "some headers" :) // // Also, it should only set them if not already set. fn set_fallback_headers(&mut self) { self.set_header_fallback(|| Date(HttpDate(time::now_utc()))); self.set_header_fallback(|| Server("Nickel".to_string())); self.set_header_fallback(|| ContentType(MediaType::Html.into())); } /// Return an error with the appropriate status code for error handlers to /// provide output for. pub fn error<T>(self, status: StatusCode, message: T) -> MiddlewareResult<'a> where T: Into<Cow<'static, str>> { Err(NickelError::new(self, message, status)) } /// Sets the header if not already set. /// /// If the header is not set then `f` will be called. /// Renders the given template bound with the given data. /// /// # Examples /// ```{rust} /// #[macro_use] extern crate nickel; /// extern crate hyper; /// /// use nickel::{Nickel, HttpRouter, MediaType}; /// use hyper::header::ContentType; /// /// # #[allow(unreachable_code)] /// fn main() { /// let mut server = Nickel::new(); /// server.get("/", middleware! { |_, mut res| /// res.set(MediaType::Html); /// res.set_header_fallback(|| { /// panic!("Should not get called"); /// ContentType(MediaType::Txt.into()) /// }); /// /// "<h1>Hello World</h1>" /// }); /// /// //... /// } /// ``` pub fn set_header_fallback<F, H>(&mut self, f: F) where H: Header + HeaderFormat, F: FnOnce() -> H { let headers = self.origin.headers_mut(); if!headers.has::<H>() { headers.set(f()) } } /// Renders the given template bound with the given data. /// /// # Examples /// ```{rust} /// use std::collections::HashMap; /// use nickel::{Request, Response, MiddlewareResult}; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// let mut data = HashMap::new(); /// data.insert("name", "user"); /// res.render("examples/assets/template.tpl", &data) /// } /// ``` pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a> where T: Encodable, P: AsRef<str> + Into<String> { fn render<'a, T>(res: Response<'a>, template: &Template, data: &T) -> MiddlewareResult<'a> where T: Encodable { let mut stream = try!(res.start()); match template.render(&mut stream, data) { Ok(()) => Ok(Halt(stream)), Err(e) => stream.bail(format!("Problem rendering template: {:?}", e)) } } // Fast path doesn't need writer lock if let Some(t) = self.templates.read().unwrap().get(path.as_ref()) { return render(self, t, data); } // We didn't find the template, get writers lock let mut templates = self.templates.write().unwrap(); // Additional clone required for now as the entry api doesn't give us a key ref let path = path.into(); // Search again incase there was a race to compile the template let template = match templates.entry(path.clone()) { Vacant(entry) => { let template = try_with!(self, { mustache::compile_path(&path) .map_err(|e| format!("Failed to compile template '{}': {:?}", path, e)) }); entry.insert(template) }, Occupied(entry) => entry.into_mut() }; render(self, template, data) } pub fn start(mut self) -> Result<Response<'a, Streaming>, NickelError<'a>> { self.set_fallback_headers(); let Response { origin, templates } = self; match origin.start() { Ok(origin) => Ok(Response { origin: origin, templates: templates }), Err(e) => unsafe { Err(NickelError::without_response(format!("Failed to start response: {}", e))) } } } } impl<'a, 'b> Write for Response<'a, Streaming> { #[inline(always)] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.origin.write(buf) } #[inline(always)] fn flush(&mut self) -> io::Result<()> { self.origin.flush() } } impl<'a, 'b> Response<'a, Streaming> { /// In the case of an unrecoverable error while a stream is already in /// progress, there is no standard way to signal to the client that an /// error has occurred. `bail` will drop the connection and log an error /// message. pub fn bail<T>(self, message: T) -> MiddlewareResult<'a> where T: Into<Cow<'static, str>> { let _ = self.end(); unsafe { Err(NickelError::without_response(message)) } } /// Flushes all writing of a response to the client. pub fn end(self) -> io::Result<()> { self.origin.end() } } impl <'a, T:'static + Any> Response<'a, T> { /// The status of this response. pub fn status(&self) -> StatusCode { self.origin.status() } /// The headers of this response. pub fn headers(&self) -> &Headers { self.origin.headers() } } fn mime_from_filename<P: AsRef<Path>>(path: P) -> Option<MediaType> { path.as_ref() .extension() .and_then(|os| os.to_str()) // Lookup mime from file extension .and_then(|s| s.parse().ok()) } #[test] fn matches_content_type () { assert_eq!(Some(MediaType::Txt), mime_from_filename("test.txt")); assert_eq!(Some(MediaType::Json), mime_from_filename("test.json")); assert_eq!(Some(MediaType::Bin), mime_from_filename("test.bin")); } mod modifier_impls { use hyper::header::*; use hyper::status::StatusCode; use modifier::Modifier; use {Response, MediaType}; impl<'a> Modifier<Response<'a>> for StatusCode { fn modify(self, res: &mut Response<'a>) { *res.status_mut() = self } } impl<'a> Modifier<Response<'a>> for MediaType { fn modify(self, res: &mut Response<'a>) { ContentType(self.into()).modify(res) } } macro_rules! header_modifiers { ($($t:ty),+) => ( $( impl<'a> Modifier<Response<'a>> for $t { fn modify(self, res: &mut Response<'a>) { res.headers_mut().set(self) } } )+ ) } header_modifiers! { Accept, AccessControlAllowHeaders, AccessControlAllowMethods, AccessControlAllowOrigin, AccessControlMaxAge, AccessControlRequestHeaders, AccessControlRequestMethod, AcceptCharset, AcceptEncoding, AcceptLanguage, AcceptRanges, Allow, Authorization<Basic>, Authorization<String>, CacheControl, Cookie, Connection, ContentEncoding, ContentLanguage, ContentLength, ContentType, Date, ETag, Expect, Expires, From, Host, IfMatch, IfModifiedSince, IfNoneMatch, IfRange, IfUnmodifiedSince, LastModified, Location, Pragma, Referer, Server, SetCookie, TransferEncoding, Upgrade, UserAgent, Vary } }
let mut file = try_with!(self, {
random_line_split
response.rs
use std::borrow::Cow; use std::sync::RwLock; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::path::Path; use serialize::Encodable; use hyper::status::StatusCode; use hyper::server::Response as HyperResponse; use hyper::header::{ Headers, Date, HttpDate, Server, ContentType, ContentLength, Header, HeaderFormat }; use hyper::net::{Fresh, Streaming}; use time; use mimes::MediaType; use mustache; use mustache::Template; use std::io::{self, Read, Write, copy}; use std::fs::File; use std::any::Any; use {NickelError, Halt, MiddlewareResult, Responder}; use modifier::Modifier; pub type TemplateCache = RwLock<HashMap<String, Template>>; ///A container for the response pub struct
<'a, T:'static + Any = Fresh> { ///the original `hyper::server::Response` origin: HyperResponse<'a, T>, templates: &'a TemplateCache } impl<'a> Response<'a, Fresh> { pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>, templates: &'c TemplateCache) -> Response<'c, Fresh> { Response { origin: response, templates: templates } } /// Get a mutable reference to the status. pub fn status_mut(&mut self) -> &mut StatusCode { self.origin.status_mut() } /// Get a mutable reference to the Headers. pub fn headers_mut(&mut self) -> &mut Headers { self.origin.headers_mut() } /// Modify the response with the provided data. /// /// # Examples /// ```{rust} /// extern crate hyper; /// #[macro_use] extern crate nickel; /// /// use nickel::{Nickel, HttpRouter, MediaType}; /// use nickel::status::StatusCode; /// use hyper::header::Location; /// /// fn main() { /// let mut server = Nickel::new(); /// server.get("/a", middleware! { |_, mut res| /// // set the Status /// res.set(StatusCode::PermanentRedirect) /// // update a Header value /// .set(Location("http://nickel.rs".into())); /// /// "" /// }); /// /// server.get("/b", middleware! { |_, mut res| /// // setting the content type /// res.set(MediaType::Json); /// /// "{'foo': 'bar'}" /// }); /// /// //... /// } /// ``` pub fn set<T: Modifier<Response<'a>>>(&mut self, attribute: T) -> &mut Response<'a> { attribute.modify(self); self } /// Writes a response /// /// # Examples /// ```{rust} /// use nickel::{Request, Response, MiddlewareResult}; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// res.send("hello world") /// } /// ``` #[inline] pub fn send<T: Responder>(self, data: T) -> MiddlewareResult<'a> { data.respond(self) } /// Writes a file to the output. /// /// # Examples /// ```{rust} /// use nickel::{Request, Response, MiddlewareResult}; /// use std::path::Path; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// let favicon = Path::new("/assets/favicon.ico"); /// res.send_file(favicon) /// } /// ``` pub fn send_file(mut self, path: &Path) -> MiddlewareResult<'a> { // Chunk the response self.origin.headers_mut().remove::<ContentLength>(); // Determine content type by file extension or default to binary let mime = mime_from_filename(path).unwrap_or(MediaType::Bin); self.set(mime); let mut file = try_with!(self, { File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}", path, e)) }); let mut stream = try!(self.start()); match copy(&mut file, &mut stream) { Ok(_) => Ok(Halt(stream)), Err(e) => stream.bail(format!("Failed to send file: {}", e)) } } // TODO: This needs to be more sophisticated to return the correct headers // not just "some headers" :) // // Also, it should only set them if not already set. fn set_fallback_headers(&mut self) { self.set_header_fallback(|| Date(HttpDate(time::now_utc()))); self.set_header_fallback(|| Server("Nickel".to_string())); self.set_header_fallback(|| ContentType(MediaType::Html.into())); } /// Return an error with the appropriate status code for error handlers to /// provide output for. pub fn error<T>(self, status: StatusCode, message: T) -> MiddlewareResult<'a> where T: Into<Cow<'static, str>> { Err(NickelError::new(self, message, status)) } /// Sets the header if not already set. /// /// If the header is not set then `f` will be called. /// Renders the given template bound with the given data. /// /// # Examples /// ```{rust} /// #[macro_use] extern crate nickel; /// extern crate hyper; /// /// use nickel::{Nickel, HttpRouter, MediaType}; /// use hyper::header::ContentType; /// /// # #[allow(unreachable_code)] /// fn main() { /// let mut server = Nickel::new(); /// server.get("/", middleware! { |_, mut res| /// res.set(MediaType::Html); /// res.set_header_fallback(|| { /// panic!("Should not get called"); /// ContentType(MediaType::Txt.into()) /// }); /// /// "<h1>Hello World</h1>" /// }); /// /// //... /// } /// ``` pub fn set_header_fallback<F, H>(&mut self, f: F) where H: Header + HeaderFormat, F: FnOnce() -> H { let headers = self.origin.headers_mut(); if!headers.has::<H>() { headers.set(f()) } } /// Renders the given template bound with the given data. /// /// # Examples /// ```{rust} /// use std::collections::HashMap; /// use nickel::{Request, Response, MiddlewareResult}; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// let mut data = HashMap::new(); /// data.insert("name", "user"); /// res.render("examples/assets/template.tpl", &data) /// } /// ``` pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a> where T: Encodable, P: AsRef<str> + Into<String> { fn render<'a, T>(res: Response<'a>, template: &Template, data: &T) -> MiddlewareResult<'a> where T: Encodable { let mut stream = try!(res.start()); match template.render(&mut stream, data) { Ok(()) => Ok(Halt(stream)), Err(e) => stream.bail(format!("Problem rendering template: {:?}", e)) } } // Fast path doesn't need writer lock if let Some(t) = self.templates.read().unwrap().get(path.as_ref()) { return render(self, t, data); } // We didn't find the template, get writers lock let mut templates = self.templates.write().unwrap(); // Additional clone required for now as the entry api doesn't give us a key ref let path = path.into(); // Search again incase there was a race to compile the template let template = match templates.entry(path.clone()) { Vacant(entry) => { let template = try_with!(self, { mustache::compile_path(&path) .map_err(|e| format!("Failed to compile template '{}': {:?}", path, e)) }); entry.insert(template) }, Occupied(entry) => entry.into_mut() }; render(self, template, data) } pub fn start(mut self) -> Result<Response<'a, Streaming>, NickelError<'a>> { self.set_fallback_headers(); let Response { origin, templates } = self; match origin.start() { Ok(origin) => Ok(Response { origin: origin, templates: templates }), Err(e) => unsafe { Err(NickelError::without_response(format!("Failed to start response: {}", e))) } } } } impl<'a, 'b> Write for Response<'a, Streaming> { #[inline(always)] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.origin.write(buf) } #[inline(always)] fn flush(&mut self) -> io::Result<()> { self.origin.flush() } } impl<'a, 'b> Response<'a, Streaming> { /// In the case of an unrecoverable error while a stream is already in /// progress, there is no standard way to signal to the client that an /// error has occurred. `bail` will drop the connection and log an error /// message. pub fn bail<T>(self, message: T) -> MiddlewareResult<'a> where T: Into<Cow<'static, str>> { let _ = self.end(); unsafe { Err(NickelError::without_response(message)) } } /// Flushes all writing of a response to the client. pub fn end(self) -> io::Result<()> { self.origin.end() } } impl <'a, T:'static + Any> Response<'a, T> { /// The status of this response. pub fn status(&self) -> StatusCode { self.origin.status() } /// The headers of this response. pub fn headers(&self) -> &Headers { self.origin.headers() } } fn mime_from_filename<P: AsRef<Path>>(path: P) -> Option<MediaType> { path.as_ref() .extension() .and_then(|os| os.to_str()) // Lookup mime from file extension .and_then(|s| s.parse().ok()) } #[test] fn matches_content_type () { assert_eq!(Some(MediaType::Txt), mime_from_filename("test.txt")); assert_eq!(Some(MediaType::Json), mime_from_filename("test.json")); assert_eq!(Some(MediaType::Bin), mime_from_filename("test.bin")); } mod modifier_impls { use hyper::header::*; use hyper::status::StatusCode; use modifier::Modifier; use {Response, MediaType}; impl<'a> Modifier<Response<'a>> for StatusCode { fn modify(self, res: &mut Response<'a>) { *res.status_mut() = self } } impl<'a> Modifier<Response<'a>> for MediaType { fn modify(self, res: &mut Response<'a>) { ContentType(self.into()).modify(res) } } macro_rules! header_modifiers { ($($t:ty),+) => ( $( impl<'a> Modifier<Response<'a>> for $t { fn modify(self, res: &mut Response<'a>) { res.headers_mut().set(self) } } )+ ) } header_modifiers! { Accept, AccessControlAllowHeaders, AccessControlAllowMethods, AccessControlAllowOrigin, AccessControlMaxAge, AccessControlRequestHeaders, AccessControlRequestMethod, AcceptCharset, AcceptEncoding, AcceptLanguage, AcceptRanges, Allow, Authorization<Basic>, Authorization<String>, CacheControl, Cookie, Connection, ContentEncoding, ContentLanguage, ContentLength, ContentType, Date, ETag, Expect, Expires, From, Host, IfMatch, IfModifiedSince, IfNoneMatch, IfRange, IfUnmodifiedSince, LastModified, Location, Pragma, Referer, Server, SetCookie, TransferEncoding, Upgrade, UserAgent, Vary } }
Response
identifier_name
response.rs
use std::borrow::Cow; use std::sync::RwLock; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::path::Path; use serialize::Encodable; use hyper::status::StatusCode; use hyper::server::Response as HyperResponse; use hyper::header::{ Headers, Date, HttpDate, Server, ContentType, ContentLength, Header, HeaderFormat }; use hyper::net::{Fresh, Streaming}; use time; use mimes::MediaType; use mustache; use mustache::Template; use std::io::{self, Read, Write, copy}; use std::fs::File; use std::any::Any; use {NickelError, Halt, MiddlewareResult, Responder}; use modifier::Modifier; pub type TemplateCache = RwLock<HashMap<String, Template>>; ///A container for the response pub struct Response<'a, T:'static + Any = Fresh> { ///the original `hyper::server::Response` origin: HyperResponse<'a, T>, templates: &'a TemplateCache } impl<'a> Response<'a, Fresh> { pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>, templates: &'c TemplateCache) -> Response<'c, Fresh> { Response { origin: response, templates: templates } } /// Get a mutable reference to the status. pub fn status_mut(&mut self) -> &mut StatusCode { self.origin.status_mut() } /// Get a mutable reference to the Headers. pub fn headers_mut(&mut self) -> &mut Headers { self.origin.headers_mut() } /// Modify the response with the provided data. /// /// # Examples /// ```{rust} /// extern crate hyper; /// #[macro_use] extern crate nickel; /// /// use nickel::{Nickel, HttpRouter, MediaType}; /// use nickel::status::StatusCode; /// use hyper::header::Location; /// /// fn main() { /// let mut server = Nickel::new(); /// server.get("/a", middleware! { |_, mut res| /// // set the Status /// res.set(StatusCode::PermanentRedirect) /// // update a Header value /// .set(Location("http://nickel.rs".into())); /// /// "" /// }); /// /// server.get("/b", middleware! { |_, mut res| /// // setting the content type /// res.set(MediaType::Json); /// /// "{'foo': 'bar'}" /// }); /// /// //... /// } /// ``` pub fn set<T: Modifier<Response<'a>>>(&mut self, attribute: T) -> &mut Response<'a> { attribute.modify(self); self } /// Writes a response /// /// # Examples /// ```{rust} /// use nickel::{Request, Response, MiddlewareResult}; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// res.send("hello world") /// } /// ``` #[inline] pub fn send<T: Responder>(self, data: T) -> MiddlewareResult<'a> { data.respond(self) } /// Writes a file to the output. /// /// # Examples /// ```{rust} /// use nickel::{Request, Response, MiddlewareResult}; /// use std::path::Path; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// let favicon = Path::new("/assets/favicon.ico"); /// res.send_file(favicon) /// } /// ``` pub fn send_file(mut self, path: &Path) -> MiddlewareResult<'a> { // Chunk the response self.origin.headers_mut().remove::<ContentLength>(); // Determine content type by file extension or default to binary let mime = mime_from_filename(path).unwrap_or(MediaType::Bin); self.set(mime); let mut file = try_with!(self, { File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}", path, e)) }); let mut stream = try!(self.start()); match copy(&mut file, &mut stream) { Ok(_) => Ok(Halt(stream)), Err(e) => stream.bail(format!("Failed to send file: {}", e)) } } // TODO: This needs to be more sophisticated to return the correct headers // not just "some headers" :) // // Also, it should only set them if not already set. fn set_fallback_headers(&mut self) { self.set_header_fallback(|| Date(HttpDate(time::now_utc()))); self.set_header_fallback(|| Server("Nickel".to_string())); self.set_header_fallback(|| ContentType(MediaType::Html.into())); } /// Return an error with the appropriate status code for error handlers to /// provide output for. pub fn error<T>(self, status: StatusCode, message: T) -> MiddlewareResult<'a> where T: Into<Cow<'static, str>> { Err(NickelError::new(self, message, status)) } /// Sets the header if not already set. /// /// If the header is not set then `f` will be called. /// Renders the given template bound with the given data. /// /// # Examples /// ```{rust} /// #[macro_use] extern crate nickel; /// extern crate hyper; /// /// use nickel::{Nickel, HttpRouter, MediaType}; /// use hyper::header::ContentType; /// /// # #[allow(unreachable_code)] /// fn main() { /// let mut server = Nickel::new(); /// server.get("/", middleware! { |_, mut res| /// res.set(MediaType::Html); /// res.set_header_fallback(|| { /// panic!("Should not get called"); /// ContentType(MediaType::Txt.into()) /// }); /// /// "<h1>Hello World</h1>" /// }); /// /// //... /// } /// ``` pub fn set_header_fallback<F, H>(&mut self, f: F) where H: Header + HeaderFormat, F: FnOnce() -> H { let headers = self.origin.headers_mut(); if!headers.has::<H>() { headers.set(f()) } } /// Renders the given template bound with the given data. /// /// # Examples /// ```{rust} /// use std::collections::HashMap; /// use nickel::{Request, Response, MiddlewareResult}; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// let mut data = HashMap::new(); /// data.insert("name", "user"); /// res.render("examples/assets/template.tpl", &data) /// } /// ``` pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a> where T: Encodable, P: AsRef<str> + Into<String> { fn render<'a, T>(res: Response<'a>, template: &Template, data: &T) -> MiddlewareResult<'a> where T: Encodable { let mut stream = try!(res.start()); match template.render(&mut stream, data) { Ok(()) => Ok(Halt(stream)), Err(e) => stream.bail(format!("Problem rendering template: {:?}", e)) } } // Fast path doesn't need writer lock if let Some(t) = self.templates.read().unwrap().get(path.as_ref()) { return render(self, t, data); } // We didn't find the template, get writers lock let mut templates = self.templates.write().unwrap(); // Additional clone required for now as the entry api doesn't give us a key ref let path = path.into(); // Search again incase there was a race to compile the template let template = match templates.entry(path.clone()) { Vacant(entry) => { let template = try_with!(self, { mustache::compile_path(&path) .map_err(|e| format!("Failed to compile template '{}': {:?}", path, e)) }); entry.insert(template) }, Occupied(entry) => entry.into_mut() }; render(self, template, data) } pub fn start(mut self) -> Result<Response<'a, Streaming>, NickelError<'a>> { self.set_fallback_headers(); let Response { origin, templates } = self; match origin.start() { Ok(origin) => Ok(Response { origin: origin, templates: templates }), Err(e) => unsafe { Err(NickelError::without_response(format!("Failed to start response: {}", e))) } } } } impl<'a, 'b> Write for Response<'a, Streaming> { #[inline(always)] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.origin.write(buf) } #[inline(always)] fn flush(&mut self) -> io::Result<()> { self.origin.flush() } } impl<'a, 'b> Response<'a, Streaming> { /// In the case of an unrecoverable error while a stream is already in /// progress, there is no standard way to signal to the client that an /// error has occurred. `bail` will drop the connection and log an error /// message. pub fn bail<T>(self, message: T) -> MiddlewareResult<'a> where T: Into<Cow<'static, str>> { let _ = self.end(); unsafe { Err(NickelError::without_response(message)) } } /// Flushes all writing of a response to the client. pub fn end(self) -> io::Result<()>
} impl <'a, T:'static + Any> Response<'a, T> { /// The status of this response. pub fn status(&self) -> StatusCode { self.origin.status() } /// The headers of this response. pub fn headers(&self) -> &Headers { self.origin.headers() } } fn mime_from_filename<P: AsRef<Path>>(path: P) -> Option<MediaType> { path.as_ref() .extension() .and_then(|os| os.to_str()) // Lookup mime from file extension .and_then(|s| s.parse().ok()) } #[test] fn matches_content_type () { assert_eq!(Some(MediaType::Txt), mime_from_filename("test.txt")); assert_eq!(Some(MediaType::Json), mime_from_filename("test.json")); assert_eq!(Some(MediaType::Bin), mime_from_filename("test.bin")); } mod modifier_impls { use hyper::header::*; use hyper::status::StatusCode; use modifier::Modifier; use {Response, MediaType}; impl<'a> Modifier<Response<'a>> for StatusCode { fn modify(self, res: &mut Response<'a>) { *res.status_mut() = self } } impl<'a> Modifier<Response<'a>> for MediaType { fn modify(self, res: &mut Response<'a>) { ContentType(self.into()).modify(res) } } macro_rules! header_modifiers { ($($t:ty),+) => ( $( impl<'a> Modifier<Response<'a>> for $t { fn modify(self, res: &mut Response<'a>) { res.headers_mut().set(self) } } )+ ) } header_modifiers! { Accept, AccessControlAllowHeaders, AccessControlAllowMethods, AccessControlAllowOrigin, AccessControlMaxAge, AccessControlRequestHeaders, AccessControlRequestMethod, AcceptCharset, AcceptEncoding, AcceptLanguage, AcceptRanges, Allow, Authorization<Basic>, Authorization<String>, CacheControl, Cookie, Connection, ContentEncoding, ContentLanguage, ContentLength, ContentType, Date, ETag, Expect, Expires, From, Host, IfMatch, IfModifiedSince, IfNoneMatch, IfRange, IfUnmodifiedSince, LastModified, Location, Pragma, Referer, Server, SetCookie, TransferEncoding, Upgrade, UserAgent, Vary } }
{ self.origin.end() }
identifier_body
response.rs
use std::borrow::Cow; use std::sync::RwLock; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::path::Path; use serialize::Encodable; use hyper::status::StatusCode; use hyper::server::Response as HyperResponse; use hyper::header::{ Headers, Date, HttpDate, Server, ContentType, ContentLength, Header, HeaderFormat }; use hyper::net::{Fresh, Streaming}; use time; use mimes::MediaType; use mustache; use mustache::Template; use std::io::{self, Read, Write, copy}; use std::fs::File; use std::any::Any; use {NickelError, Halt, MiddlewareResult, Responder}; use modifier::Modifier; pub type TemplateCache = RwLock<HashMap<String, Template>>; ///A container for the response pub struct Response<'a, T:'static + Any = Fresh> { ///the original `hyper::server::Response` origin: HyperResponse<'a, T>, templates: &'a TemplateCache } impl<'a> Response<'a, Fresh> { pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>, templates: &'c TemplateCache) -> Response<'c, Fresh> { Response { origin: response, templates: templates } } /// Get a mutable reference to the status. pub fn status_mut(&mut self) -> &mut StatusCode { self.origin.status_mut() } /// Get a mutable reference to the Headers. pub fn headers_mut(&mut self) -> &mut Headers { self.origin.headers_mut() } /// Modify the response with the provided data. /// /// # Examples /// ```{rust} /// extern crate hyper; /// #[macro_use] extern crate nickel; /// /// use nickel::{Nickel, HttpRouter, MediaType}; /// use nickel::status::StatusCode; /// use hyper::header::Location; /// /// fn main() { /// let mut server = Nickel::new(); /// server.get("/a", middleware! { |_, mut res| /// // set the Status /// res.set(StatusCode::PermanentRedirect) /// // update a Header value /// .set(Location("http://nickel.rs".into())); /// /// "" /// }); /// /// server.get("/b", middleware! { |_, mut res| /// // setting the content type /// res.set(MediaType::Json); /// /// "{'foo': 'bar'}" /// }); /// /// //... /// } /// ``` pub fn set<T: Modifier<Response<'a>>>(&mut self, attribute: T) -> &mut Response<'a> { attribute.modify(self); self } /// Writes a response /// /// # Examples /// ```{rust} /// use nickel::{Request, Response, MiddlewareResult}; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// res.send("hello world") /// } /// ``` #[inline] pub fn send<T: Responder>(self, data: T) -> MiddlewareResult<'a> { data.respond(self) } /// Writes a file to the output. /// /// # Examples /// ```{rust} /// use nickel::{Request, Response, MiddlewareResult}; /// use std::path::Path; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// let favicon = Path::new("/assets/favicon.ico"); /// res.send_file(favicon) /// } /// ``` pub fn send_file(mut self, path: &Path) -> MiddlewareResult<'a> { // Chunk the response self.origin.headers_mut().remove::<ContentLength>(); // Determine content type by file extension or default to binary let mime = mime_from_filename(path).unwrap_or(MediaType::Bin); self.set(mime); let mut file = try_with!(self, { File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}", path, e)) }); let mut stream = try!(self.start()); match copy(&mut file, &mut stream) { Ok(_) => Ok(Halt(stream)), Err(e) => stream.bail(format!("Failed to send file: {}", e)) } } // TODO: This needs to be more sophisticated to return the correct headers // not just "some headers" :) // // Also, it should only set them if not already set. fn set_fallback_headers(&mut self) { self.set_header_fallback(|| Date(HttpDate(time::now_utc()))); self.set_header_fallback(|| Server("Nickel".to_string())); self.set_header_fallback(|| ContentType(MediaType::Html.into())); } /// Return an error with the appropriate status code for error handlers to /// provide output for. pub fn error<T>(self, status: StatusCode, message: T) -> MiddlewareResult<'a> where T: Into<Cow<'static, str>> { Err(NickelError::new(self, message, status)) } /// Sets the header if not already set. /// /// If the header is not set then `f` will be called. /// Renders the given template bound with the given data. /// /// # Examples /// ```{rust} /// #[macro_use] extern crate nickel; /// extern crate hyper; /// /// use nickel::{Nickel, HttpRouter, MediaType}; /// use hyper::header::ContentType; /// /// # #[allow(unreachable_code)] /// fn main() { /// let mut server = Nickel::new(); /// server.get("/", middleware! { |_, mut res| /// res.set(MediaType::Html); /// res.set_header_fallback(|| { /// panic!("Should not get called"); /// ContentType(MediaType::Txt.into()) /// }); /// /// "<h1>Hello World</h1>" /// }); /// /// //... /// } /// ``` pub fn set_header_fallback<F, H>(&mut self, f: F) where H: Header + HeaderFormat, F: FnOnce() -> H { let headers = self.origin.headers_mut(); if!headers.has::<H>()
} /// Renders the given template bound with the given data. /// /// # Examples /// ```{rust} /// use std::collections::HashMap; /// use nickel::{Request, Response, MiddlewareResult}; /// /// # #[allow(dead_code)] /// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> { /// let mut data = HashMap::new(); /// data.insert("name", "user"); /// res.render("examples/assets/template.tpl", &data) /// } /// ``` pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a> where T: Encodable, P: AsRef<str> + Into<String> { fn render<'a, T>(res: Response<'a>, template: &Template, data: &T) -> MiddlewareResult<'a> where T: Encodable { let mut stream = try!(res.start()); match template.render(&mut stream, data) { Ok(()) => Ok(Halt(stream)), Err(e) => stream.bail(format!("Problem rendering template: {:?}", e)) } } // Fast path doesn't need writer lock if let Some(t) = self.templates.read().unwrap().get(path.as_ref()) { return render(self, t, data); } // We didn't find the template, get writers lock let mut templates = self.templates.write().unwrap(); // Additional clone required for now as the entry api doesn't give us a key ref let path = path.into(); // Search again incase there was a race to compile the template let template = match templates.entry(path.clone()) { Vacant(entry) => { let template = try_with!(self, { mustache::compile_path(&path) .map_err(|e| format!("Failed to compile template '{}': {:?}", path, e)) }); entry.insert(template) }, Occupied(entry) => entry.into_mut() }; render(self, template, data) } pub fn start(mut self) -> Result<Response<'a, Streaming>, NickelError<'a>> { self.set_fallback_headers(); let Response { origin, templates } = self; match origin.start() { Ok(origin) => Ok(Response { origin: origin, templates: templates }), Err(e) => unsafe { Err(NickelError::without_response(format!("Failed to start response: {}", e))) } } } } impl<'a, 'b> Write for Response<'a, Streaming> { #[inline(always)] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.origin.write(buf) } #[inline(always)] fn flush(&mut self) -> io::Result<()> { self.origin.flush() } } impl<'a, 'b> Response<'a, Streaming> { /// In the case of an unrecoverable error while a stream is already in /// progress, there is no standard way to signal to the client that an /// error has occurred. `bail` will drop the connection and log an error /// message. pub fn bail<T>(self, message: T) -> MiddlewareResult<'a> where T: Into<Cow<'static, str>> { let _ = self.end(); unsafe { Err(NickelError::without_response(message)) } } /// Flushes all writing of a response to the client. pub fn end(self) -> io::Result<()> { self.origin.end() } } impl <'a, T:'static + Any> Response<'a, T> { /// The status of this response. pub fn status(&self) -> StatusCode { self.origin.status() } /// The headers of this response. pub fn headers(&self) -> &Headers { self.origin.headers() } } fn mime_from_filename<P: AsRef<Path>>(path: P) -> Option<MediaType> { path.as_ref() .extension() .and_then(|os| os.to_str()) // Lookup mime from file extension .and_then(|s| s.parse().ok()) } #[test] fn matches_content_type () { assert_eq!(Some(MediaType::Txt), mime_from_filename("test.txt")); assert_eq!(Some(MediaType::Json), mime_from_filename("test.json")); assert_eq!(Some(MediaType::Bin), mime_from_filename("test.bin")); } mod modifier_impls { use hyper::header::*; use hyper::status::StatusCode; use modifier::Modifier; use {Response, MediaType}; impl<'a> Modifier<Response<'a>> for StatusCode { fn modify(self, res: &mut Response<'a>) { *res.status_mut() = self } } impl<'a> Modifier<Response<'a>> for MediaType { fn modify(self, res: &mut Response<'a>) { ContentType(self.into()).modify(res) } } macro_rules! header_modifiers { ($($t:ty),+) => ( $( impl<'a> Modifier<Response<'a>> for $t { fn modify(self, res: &mut Response<'a>) { res.headers_mut().set(self) } } )+ ) } header_modifiers! { Accept, AccessControlAllowHeaders, AccessControlAllowMethods, AccessControlAllowOrigin, AccessControlMaxAge, AccessControlRequestHeaders, AccessControlRequestMethod, AcceptCharset, AcceptEncoding, AcceptLanguage, AcceptRanges, Allow, Authorization<Basic>, Authorization<String>, CacheControl, Cookie, Connection, ContentEncoding, ContentLanguage, ContentLength, ContentType, Date, ETag, Expect, Expires, From, Host, IfMatch, IfModifiedSince, IfNoneMatch, IfRange, IfUnmodifiedSince, LastModified, Location, Pragma, Referer, Server, SetCookie, TransferEncoding, Upgrade, UserAgent, Vary } }
{ headers.set(f()) }
conditional_block
typeclasses-eq-example-static.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. // Example from lkuper's intern talk, August 2012 -- now with static // methods! trait Equal { fn isEq(a: Self, b: Self) -> bool; } enum Color { cyan, magenta, yellow, black } impl Equal for Color { fn isEq(a: Color, b: Color) -> bool { match (a, b) { (cyan, cyan) => { true } (magenta, magenta) => { true } (yellow, yellow) => { true } (black, black) => { true } _ => { false } } } } enum
{ leaf(Color), branch(@ColorTree, @ColorTree) } impl Equal for ColorTree { fn isEq(a: ColorTree, b: ColorTree) -> bool { match (a, b) { (leaf(x), leaf(y)) => { Equal::isEq(x, y) } (branch(l1, r1), branch(l2, r2)) => { Equal::isEq(*l1, *l2) && Equal::isEq(*r1, *r2) } _ => { false } } } } pub fn main() { assert!(Equal::isEq(cyan, cyan)); assert!(Equal::isEq(magenta, magenta)); assert!(!Equal::isEq(cyan, yellow)); assert!(!Equal::isEq(magenta, cyan)); assert!(Equal::isEq(leaf(cyan), leaf(cyan))); assert!(!Equal::isEq(leaf(cyan), leaf(yellow))); assert!(Equal::isEq(branch(@leaf(magenta), @leaf(cyan)), branch(@leaf(magenta), @leaf(cyan)))); assert!(!Equal::isEq(branch(@leaf(magenta), @leaf(cyan)), branch(@leaf(magenta), @leaf(magenta)))); error2!("Assertions all succeeded!"); }
ColorTree
identifier_name
typeclasses-eq-example-static.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. // Example from lkuper's intern talk, August 2012 -- now with static // methods! trait Equal { fn isEq(a: Self, b: Self) -> bool; } enum Color { cyan, magenta, yellow, black } impl Equal for Color { fn isEq(a: Color, b: Color) -> bool { match (a, b) { (cyan, cyan) => { true } (magenta, magenta) => { true } (yellow, yellow) => { true } (black, black) => { true } _ => { false } } } }
branch(@ColorTree, @ColorTree) } impl Equal for ColorTree { fn isEq(a: ColorTree, b: ColorTree) -> bool { match (a, b) { (leaf(x), leaf(y)) => { Equal::isEq(x, y) } (branch(l1, r1), branch(l2, r2)) => { Equal::isEq(*l1, *l2) && Equal::isEq(*r1, *r2) } _ => { false } } } } pub fn main() { assert!(Equal::isEq(cyan, cyan)); assert!(Equal::isEq(magenta, magenta)); assert!(!Equal::isEq(cyan, yellow)); assert!(!Equal::isEq(magenta, cyan)); assert!(Equal::isEq(leaf(cyan), leaf(cyan))); assert!(!Equal::isEq(leaf(cyan), leaf(yellow))); assert!(Equal::isEq(branch(@leaf(magenta), @leaf(cyan)), branch(@leaf(magenta), @leaf(cyan)))); assert!(!Equal::isEq(branch(@leaf(magenta), @leaf(cyan)), branch(@leaf(magenta), @leaf(magenta)))); error2!("Assertions all succeeded!"); }
enum ColorTree { leaf(Color),
random_line_split
typeclasses-eq-example-static.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. // Example from lkuper's intern talk, August 2012 -- now with static // methods! trait Equal { fn isEq(a: Self, b: Self) -> bool; } enum Color { cyan, magenta, yellow, black } impl Equal for Color { fn isEq(a: Color, b: Color) -> bool { match (a, b) { (cyan, cyan) => { true } (magenta, magenta) =>
(yellow, yellow) => { true } (black, black) => { true } _ => { false } } } } enum ColorTree { leaf(Color), branch(@ColorTree, @ColorTree) } impl Equal for ColorTree { fn isEq(a: ColorTree, b: ColorTree) -> bool { match (a, b) { (leaf(x), leaf(y)) => { Equal::isEq(x, y) } (branch(l1, r1), branch(l2, r2)) => { Equal::isEq(*l1, *l2) && Equal::isEq(*r1, *r2) } _ => { false } } } } pub fn main() { assert!(Equal::isEq(cyan, cyan)); assert!(Equal::isEq(magenta, magenta)); assert!(!Equal::isEq(cyan, yellow)); assert!(!Equal::isEq(magenta, cyan)); assert!(Equal::isEq(leaf(cyan), leaf(cyan))); assert!(!Equal::isEq(leaf(cyan), leaf(yellow))); assert!(Equal::isEq(branch(@leaf(magenta), @leaf(cyan)), branch(@leaf(magenta), @leaf(cyan)))); assert!(!Equal::isEq(branch(@leaf(magenta), @leaf(cyan)), branch(@leaf(magenta), @leaf(magenta)))); error2!("Assertions all succeeded!"); }
{ true }
conditional_block
backend.rs
use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite}; use crate::fair_queue::QueueInner; use crate::util::PeerIdentity; use crate::{ MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult, }; use async_trait::async_trait; use crossbeam::queue::SegQueue; use dashmap::DashMap; use futures::channel::mpsc; use futures::SinkExt; use parking_lot::Mutex; use std::sync::Arc; pub(crate) struct Peer { pub(crate) send_queue: ZmqFramedWrite, } pub(crate) struct GenericSocketBackend { pub(crate) peers: DashMap<PeerIdentity, Peer>, fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>, pub(crate) round_robin: SegQueue<PeerIdentity>, socket_type: SocketType, socket_options: SocketOptions, pub(crate) socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>, } impl GenericSocketBackend { pub(crate) fn with_options( fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>, socket_type: SocketType, options: SocketOptions, ) -> Self { Self { peers: DashMap::new(), fair_queue_inner, round_robin: SegQueue::new(), socket_type, socket_options: options, socket_monitor: Mutex::new(None), } } pub(crate) async fn send_round_robin(&self, message: Message) -> ZmqResult<PeerIdentity> { // In normal scenario this will always be only 1 iteration // There can be special case when peer has disconnected and his id is still in // RR queue This happens because SegQueue don't have an api to delete // items from queue. So in such case we'll just pop item and skip it if // we don't have a matching peer in peers map loop { let next_peer_id = match self.round_robin.pop() { Ok(peer) => peer, Err(_) => match message { Message::Greeting(_) => panic!("Sending greeting is not supported"), Message::Command(_) => panic!("Sending commands is not supported"), Message::Message(m) => { return Err(ZmqError::ReturnToSender { reason: "Not connected to peers. Unable to send messages", message: m, }) } }, }; let send_result = match self.peers.get_mut(&next_peer_id) { Some(mut peer) => peer.send_queue.send(message).await, None => continue, }; return match send_result { Ok(()) => { self.round_robin.push(next_peer_id.clone()); Ok(next_peer_id)
self.peer_disconnected(&next_peer_id); Err(e.into()) } }; } } } impl SocketBackend for GenericSocketBackend { fn socket_type(&self) -> SocketType { self.socket_type } fn socket_options(&self) -> &SocketOptions { &self.socket_options } fn shutdown(&self) { self.peers.clear(); } fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> { &self.socket_monitor } } #[async_trait] impl MultiPeerBackend for GenericSocketBackend { async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) { let (recv_queue, send_queue) = io.into_parts(); self.peers.insert(peer_id.clone(), Peer { send_queue }); self.round_robin.push(peer_id.clone()); match &self.fair_queue_inner { None => {} Some(inner) => { inner.lock().insert(peer_id.clone(), recv_queue); } }; } fn peer_disconnected(&self, peer_id: &PeerIdentity) { self.peers.remove(peer_id); match &self.fair_queue_inner { None => {} Some(inner) => { inner.lock().remove(peer_id); } }; } }
} Err(e) => {
random_line_split
backend.rs
use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite}; use crate::fair_queue::QueueInner; use crate::util::PeerIdentity; use crate::{ MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult, }; use async_trait::async_trait; use crossbeam::queue::SegQueue; use dashmap::DashMap; use futures::channel::mpsc; use futures::SinkExt; use parking_lot::Mutex; use std::sync::Arc; pub(crate) struct Peer { pub(crate) send_queue: ZmqFramedWrite, } pub(crate) struct GenericSocketBackend { pub(crate) peers: DashMap<PeerIdentity, Peer>, fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>, pub(crate) round_robin: SegQueue<PeerIdentity>, socket_type: SocketType, socket_options: SocketOptions, pub(crate) socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>, } impl GenericSocketBackend { pub(crate) fn with_options( fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>, socket_type: SocketType, options: SocketOptions, ) -> Self { Self { peers: DashMap::new(), fair_queue_inner, round_robin: SegQueue::new(), socket_type, socket_options: options, socket_monitor: Mutex::new(None), } } pub(crate) async fn send_round_robin(&self, message: Message) -> ZmqResult<PeerIdentity> { // In normal scenario this will always be only 1 iteration // There can be special case when peer has disconnected and his id is still in // RR queue This happens because SegQueue don't have an api to delete // items from queue. So in such case we'll just pop item and skip it if // we don't have a matching peer in peers map loop { let next_peer_id = match self.round_robin.pop() { Ok(peer) => peer, Err(_) => match message { Message::Greeting(_) => panic!("Sending greeting is not supported"), Message::Command(_) => panic!("Sending commands is not supported"), Message::Message(m) => { return Err(ZmqError::ReturnToSender { reason: "Not connected to peers. Unable to send messages", message: m, }) } }, }; let send_result = match self.peers.get_mut(&next_peer_id) { Some(mut peer) => peer.send_queue.send(message).await, None => continue, }; return match send_result { Ok(()) => { self.round_robin.push(next_peer_id.clone()); Ok(next_peer_id) } Err(e) => { self.peer_disconnected(&next_peer_id); Err(e.into()) } }; } } } impl SocketBackend for GenericSocketBackend { fn socket_type(&self) -> SocketType { self.socket_type } fn socket_options(&self) -> &SocketOptions { &self.socket_options } fn shutdown(&self) { self.peers.clear(); } fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> { &self.socket_monitor } } #[async_trait] impl MultiPeerBackend for GenericSocketBackend { async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) { let (recv_queue, send_queue) = io.into_parts(); self.peers.insert(peer_id.clone(), Peer { send_queue }); self.round_robin.push(peer_id.clone()); match &self.fair_queue_inner { None => {} Some(inner) => { inner.lock().insert(peer_id.clone(), recv_queue); } }; } fn
(&self, peer_id: &PeerIdentity) { self.peers.remove(peer_id); match &self.fair_queue_inner { None => {} Some(inner) => { inner.lock().remove(peer_id); } }; } }
peer_disconnected
identifier_name
backend.rs
use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite}; use crate::fair_queue::QueueInner; use crate::util::PeerIdentity; use crate::{ MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult, }; use async_trait::async_trait; use crossbeam::queue::SegQueue; use dashmap::DashMap; use futures::channel::mpsc; use futures::SinkExt; use parking_lot::Mutex; use std::sync::Arc; pub(crate) struct Peer { pub(crate) send_queue: ZmqFramedWrite, } pub(crate) struct GenericSocketBackend { pub(crate) peers: DashMap<PeerIdentity, Peer>, fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>, pub(crate) round_robin: SegQueue<PeerIdentity>, socket_type: SocketType, socket_options: SocketOptions, pub(crate) socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>, } impl GenericSocketBackend { pub(crate) fn with_options( fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>, socket_type: SocketType, options: SocketOptions, ) -> Self { Self { peers: DashMap::new(), fair_queue_inner, round_robin: SegQueue::new(), socket_type, socket_options: options, socket_monitor: Mutex::new(None), } } pub(crate) async fn send_round_robin(&self, message: Message) -> ZmqResult<PeerIdentity> { // In normal scenario this will always be only 1 iteration // There can be special case when peer has disconnected and his id is still in // RR queue This happens because SegQueue don't have an api to delete // items from queue. So in such case we'll just pop item and skip it if // we don't have a matching peer in peers map loop { let next_peer_id = match self.round_robin.pop() { Ok(peer) => peer, Err(_) => match message { Message::Greeting(_) => panic!("Sending greeting is not supported"), Message::Command(_) => panic!("Sending commands is not supported"), Message::Message(m) => { return Err(ZmqError::ReturnToSender { reason: "Not connected to peers. Unable to send messages", message: m, }) } }, }; let send_result = match self.peers.get_mut(&next_peer_id) { Some(mut peer) => peer.send_queue.send(message).await, None => continue, }; return match send_result { Ok(()) => { self.round_robin.push(next_peer_id.clone()); Ok(next_peer_id) } Err(e) => { self.peer_disconnected(&next_peer_id); Err(e.into()) } }; } } } impl SocketBackend for GenericSocketBackend { fn socket_type(&self) -> SocketType { self.socket_type } fn socket_options(&self) -> &SocketOptions { &self.socket_options } fn shutdown(&self) { self.peers.clear(); } fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>>
} #[async_trait] impl MultiPeerBackend for GenericSocketBackend { async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) { let (recv_queue, send_queue) = io.into_parts(); self.peers.insert(peer_id.clone(), Peer { send_queue }); self.round_robin.push(peer_id.clone()); match &self.fair_queue_inner { None => {} Some(inner) => { inner.lock().insert(peer_id.clone(), recv_queue); } }; } fn peer_disconnected(&self, peer_id: &PeerIdentity) { self.peers.remove(peer_id); match &self.fair_queue_inner { None => {} Some(inner) => { inner.lock().remove(peer_id); } }; } }
{ &self.socket_monitor }
identifier_body
builder.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> #![cfg_attr(not(feature = "v3_10"), allow(unused_imports))] use libc::{c_char, ssize_t}; use glib::Object; use glib::object::{Downcast, IsA}; use glib::translate::*; use ffi; use std::path::Path; use Error; glib_wrapper! { pub struct Builder(Object<ffi::GtkBuilder>); match fn { get_type => || ffi::gtk_builder_get_type(), } } impl Builder { pub fn new() -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new()) } } #[cfg(feature = "v3_10")] pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) } } #[cfg(feature = "v3_10")] pub fn new_from_resource(resource_path: &str) -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new_from_resource(resource_path.to_glib_none().0)) } } #[cfg(feature = "v3_10")] pub fn new_from_string(string: &str) -> Builder { assert_initialized_main_thread!(); unsafe { // Don't need a null-terminated string here from_glib_full( ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char, string.len() as ssize_t)) } } pub fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T> { unsafe { Option::<Object>::from_glib_none( ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0)) .and_then(|obj| obj.downcast().ok()) } } pub fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_file(self.to_glib_none().0, file_path.as_ref().to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn add_from_resource(&self, resource_path: &str) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_resource(self.to_glib_none().0, resource_path.to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else
} } pub fn add_from_string(&self, string: &str) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_string(self.to_glib_none().0, string.as_ptr() as *const c_char, string.len(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn set_translation_domain(&self, domain: Option<&str>) { unsafe { ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0); } } pub fn get_translation_domain(&self) -> Option<String> { unsafe { from_glib_none(ffi::gtk_builder_get_translation_domain(self.to_glib_none().0)) } } }
{ Err(from_glib_full(error)) }
conditional_block
builder.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> #![cfg_attr(not(feature = "v3_10"), allow(unused_imports))] use libc::{c_char, ssize_t}; use glib::Object; use glib::object::{Downcast, IsA}; use glib::translate::*; use ffi; use std::path::Path; use Error; glib_wrapper! { pub struct Builder(Object<ffi::GtkBuilder>); match fn { get_type => || ffi::gtk_builder_get_type(), } } impl Builder { pub fn new() -> Builder
#[cfg(feature = "v3_10")] pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) } } #[cfg(feature = "v3_10")] pub fn new_from_resource(resource_path: &str) -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new_from_resource(resource_path.to_glib_none().0)) } } #[cfg(feature = "v3_10")] pub fn new_from_string(string: &str) -> Builder { assert_initialized_main_thread!(); unsafe { // Don't need a null-terminated string here from_glib_full( ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char, string.len() as ssize_t)) } } pub fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T> { unsafe { Option::<Object>::from_glib_none( ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0)) .and_then(|obj| obj.downcast().ok()) } } pub fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_file(self.to_glib_none().0, file_path.as_ref().to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn add_from_resource(&self, resource_path: &str) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_resource(self.to_glib_none().0, resource_path.to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn add_from_string(&self, string: &str) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_string(self.to_glib_none().0, string.as_ptr() as *const c_char, string.len(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn set_translation_domain(&self, domain: Option<&str>) { unsafe { ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0); } } pub fn get_translation_domain(&self) -> Option<String> { unsafe { from_glib_none(ffi::gtk_builder_get_translation_domain(self.to_glib_none().0)) } } }
{ assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new()) } }
identifier_body
builder.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> #![cfg_attr(not(feature = "v3_10"), allow(unused_imports))] use libc::{c_char, ssize_t}; use glib::Object; use glib::object::{Downcast, IsA}; use glib::translate::*; use ffi; use std::path::Path; use Error; glib_wrapper! { pub struct Builder(Object<ffi::GtkBuilder>); match fn { get_type => || ffi::gtk_builder_get_type(), } } impl Builder { pub fn new() -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new()) } } #[cfg(feature = "v3_10")] pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) } } #[cfg(feature = "v3_10")] pub fn new_from_resource(resource_path: &str) -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new_from_resource(resource_path.to_glib_none().0)) } } #[cfg(feature = "v3_10")] pub fn new_from_string(string: &str) -> Builder { assert_initialized_main_thread!(); unsafe { // Don't need a null-terminated string here from_glib_full( ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char, string.len() as ssize_t)) } } pub fn
<T: IsA<Object>>(&self, name: &str) -> Option<T> { unsafe { Option::<Object>::from_glib_none( ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0)) .and_then(|obj| obj.downcast().ok()) } } pub fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_file(self.to_glib_none().0, file_path.as_ref().to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn add_from_resource(&self, resource_path: &str) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_resource(self.to_glib_none().0, resource_path.to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn add_from_string(&self, string: &str) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_string(self.to_glib_none().0, string.as_ptr() as *const c_char, string.len(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn set_translation_domain(&self, domain: Option<&str>) { unsafe { ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0); } } pub fn get_translation_domain(&self) -> Option<String> { unsafe { from_glib_none(ffi::gtk_builder_get_translation_domain(self.to_glib_none().0)) } } }
get_object
identifier_name
builder.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> #![cfg_attr(not(feature = "v3_10"), allow(unused_imports))] use libc::{c_char, ssize_t}; use glib::Object; use glib::object::{Downcast, IsA}; use glib::translate::*; use ffi; use std::path::Path; use Error; glib_wrapper! { pub struct Builder(Object<ffi::GtkBuilder>); match fn { get_type => || ffi::gtk_builder_get_type(), } } impl Builder { pub fn new() -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new()) } } #[cfg(feature = "v3_10")] pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) } } #[cfg(feature = "v3_10")] pub fn new_from_resource(resource_path: &str) -> Builder { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_builder_new_from_resource(resource_path.to_glib_none().0)) } }
from_glib_full( ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char, string.len() as ssize_t)) } } pub fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T> { unsafe { Option::<Object>::from_glib_none( ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0)) .and_then(|obj| obj.downcast().ok()) } } pub fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_file(self.to_glib_none().0, file_path.as_ref().to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn add_from_resource(&self, resource_path: &str) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_resource(self.to_glib_none().0, resource_path.to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn add_from_string(&self, string: &str) -> Result<(), Error> { unsafe { let mut error = ::std::ptr::null_mut(); ffi::gtk_builder_add_from_string(self.to_glib_none().0, string.as_ptr() as *const c_char, string.len(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn set_translation_domain(&self, domain: Option<&str>) { unsafe { ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0); } } pub fn get_translation_domain(&self) -> Option<String> { unsafe { from_glib_none(ffi::gtk_builder_get_translation_domain(self.to_glib_none().0)) } } }
#[cfg(feature = "v3_10")] pub fn new_from_string(string: &str) -> Builder { assert_initialized_main_thread!(); unsafe { // Don't need a null-terminated string here
random_line_split
hello.rs
/* * 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; either * version 2.1 of the License, or (at your option) any later version. * * 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, see * <http://www.gnu.org/licenses/>. * * Sahid Orentino Ferdjaoui <[email protected]> */ //! This file contains trivial example code to connect to the running //! hypervisor and gather a few bits of information about domains. //! Similar API's exist for storage pools, networks, and interfaces. //! //! Largely inspired by hellolibvirt.c extern crate virt; use std::env; use virt::connect::Connect; use virt::error::Error; fn show_hypervisor_info(conn: &Connect) -> Result<(), Error> { if let Ok(hv_type) = conn.get_type() { if let Ok(mut hv_ver) = conn.get_hyp_version() { let major = hv_ver / 1000000; hv_ver %= 1000000; let minor = hv_ver / 1000; let release = hv_ver % 1000; println!("Hypervisor: '{}' version: {}.{}.{}", hv_type, major, minor, release); return Ok(()); } } Err(Error::new()) } fn show_domains(conn: &Connect) -> Result<(), Error>
println!("Domain info:"); println!(" State: {}", dinfo.state); println!(" Max Memory: {}", dinfo.max_mem); println!(" Memory: {}", dinfo.memory); println!(" CPUs: {}", dinfo.nr_virt_cpu); println!(" CPU Time: {}", dinfo.cpu_time); } if let Ok(memtune) = dom.get_memory_parameters(0) { println!("Memory tune:"); println!(" Hard Limit: {}", memtune.hard_limit.unwrap_or(0)); println!(" Soft Limit: {}", memtune.soft_limit.unwrap_or(0)); println!(" Min Guarantee: {}", memtune.min_guarantee.unwrap_or(0)); println!(" Swap Hard Limit: {}", memtune.swap_hard_limit.unwrap_or(0)); } if let Ok(numa) = dom.get_numa_parameters(0) { println!("NUMA:"); println!(" Node Set: {}", numa.node_set.unwrap_or(String::from(""))); println!(" Mode: {}", numa.mode.unwrap_or(0)); } } } return Ok(()); } } Err(Error::new()) } fn main() { let uri = match env::args().nth(1) { Some(u) => u, None => String::from(""), }; println!("Attempting to connect to hypervisor: '{}'", uri); let conn = match Connect::open(&uri) { Ok(c) => c, Err(e) => { panic!("No connection to hypervisor: code {}, message: {}", e.code, e.message) } }; match conn.get_uri() { Ok(u) => println!("Connected to hypervisor at '{}'", u), Err(e) => { disconnect(conn); panic!("Failed to get URI for hypervisor connection: code {}, message: {}", e.code, e.message); } }; if let Err(e) = show_hypervisor_info(&conn) { disconnect(conn); panic!("Failed to show hypervisor info: code {}, message: {}", e.code, e.message); } if let Err(e) = show_domains(&conn) { disconnect(conn); panic!("Failed to show domains info: code {}, message: {}", e.code, e.message); } fn disconnect(mut conn: Connect) { if let Err(e) = conn.close() { panic!("Failed to disconnect from hypervisor: code {}, message: {}", e.code, e.message); } println!("Disconnected from hypervisor"); } }
{ let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE | virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE; if let Ok(num_active_domains) = conn.num_of_domains() { if let Ok(num_inactive_domains) = conn.num_of_defined_domains() { println!("There are {} active and {} inactive domains", num_active_domains, num_inactive_domains); /* Return a list of all active and inactive domains. Using this API * instead of virConnectListDomains() and virConnectListDefinedDomains() * is preferred since it "solves" an inherit race between separated API * calls if domains are started or stopped between calls */ if let Ok(doms) = conn.list_all_domains(flags) { for dom in doms { let id = dom.get_id().unwrap_or(0); let name = dom.get_name().unwrap_or(String::from("no-name")); let active = dom.is_active().unwrap_or(false); println!("ID: {}, Name: {}, Active: {}", id, name, active); if let Ok(dinfo) = dom.get_info() {
identifier_body
hello.rs
/* * 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; either * version 2.1 of the License, or (at your option) any later version. * * 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, see * <http://www.gnu.org/licenses/>. * * Sahid Orentino Ferdjaoui <[email protected]> */ //! This file contains trivial example code to connect to the running //! hypervisor and gather a few bits of information about domains. //! Similar API's exist for storage pools, networks, and interfaces. //! //! Largely inspired by hellolibvirt.c extern crate virt; use std::env; use virt::connect::Connect; use virt::error::Error; fn show_hypervisor_info(conn: &Connect) -> Result<(), Error> { if let Ok(hv_type) = conn.get_type() { if let Ok(mut hv_ver) = conn.get_hyp_version() { let major = hv_ver / 1000000; hv_ver %= 1000000; let minor = hv_ver / 1000; let release = hv_ver % 1000; println!("Hypervisor: '{}' version: {}.{}.{}", hv_type, major, minor, release); return Ok(()); } } Err(Error::new()) } fn
(conn: &Connect) -> Result<(), Error> { let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE | virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE; if let Ok(num_active_domains) = conn.num_of_domains() { if let Ok(num_inactive_domains) = conn.num_of_defined_domains() { println!("There are {} active and {} inactive domains", num_active_domains, num_inactive_domains); /* Return a list of all active and inactive domains. Using this API * instead of virConnectListDomains() and virConnectListDefinedDomains() * is preferred since it "solves" an inherit race between separated API * calls if domains are started or stopped between calls */ if let Ok(doms) = conn.list_all_domains(flags) { for dom in doms { let id = dom.get_id().unwrap_or(0); let name = dom.get_name().unwrap_or(String::from("no-name")); let active = dom.is_active().unwrap_or(false); println!("ID: {}, Name: {}, Active: {}", id, name, active); if let Ok(dinfo) = dom.get_info() { println!("Domain info:"); println!(" State: {}", dinfo.state); println!(" Max Memory: {}", dinfo.max_mem); println!(" Memory: {}", dinfo.memory); println!(" CPUs: {}", dinfo.nr_virt_cpu); println!(" CPU Time: {}", dinfo.cpu_time); } if let Ok(memtune) = dom.get_memory_parameters(0) { println!("Memory tune:"); println!(" Hard Limit: {}", memtune.hard_limit.unwrap_or(0)); println!(" Soft Limit: {}", memtune.soft_limit.unwrap_or(0)); println!(" Min Guarantee: {}", memtune.min_guarantee.unwrap_or(0)); println!(" Swap Hard Limit: {}", memtune.swap_hard_limit.unwrap_or(0)); } if let Ok(numa) = dom.get_numa_parameters(0) { println!("NUMA:"); println!(" Node Set: {}", numa.node_set.unwrap_or(String::from(""))); println!(" Mode: {}", numa.mode.unwrap_or(0)); } } } return Ok(()); } } Err(Error::new()) } fn main() { let uri = match env::args().nth(1) { Some(u) => u, None => String::from(""), }; println!("Attempting to connect to hypervisor: '{}'", uri); let conn = match Connect::open(&uri) { Ok(c) => c, Err(e) => { panic!("No connection to hypervisor: code {}, message: {}", e.code, e.message) } }; match conn.get_uri() { Ok(u) => println!("Connected to hypervisor at '{}'", u), Err(e) => { disconnect(conn); panic!("Failed to get URI for hypervisor connection: code {}, message: {}", e.code, e.message); } }; if let Err(e) = show_hypervisor_info(&conn) { disconnect(conn); panic!("Failed to show hypervisor info: code {}, message: {}", e.code, e.message); } if let Err(e) = show_domains(&conn) { disconnect(conn); panic!("Failed to show domains info: code {}, message: {}", e.code, e.message); } fn disconnect(mut conn: Connect) { if let Err(e) = conn.close() { panic!("Failed to disconnect from hypervisor: code {}, message: {}", e.code, e.message); } println!("Disconnected from hypervisor"); } }
show_domains
identifier_name
hello.rs
/* * 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; either * version 2.1 of the License, or (at your option) any later version. * * 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, see * <http://www.gnu.org/licenses/>. * * Sahid Orentino Ferdjaoui <[email protected]> */ //! This file contains trivial example code to connect to the running //! hypervisor and gather a few bits of information about domains. //! Similar API's exist for storage pools, networks, and interfaces. //! //! Largely inspired by hellolibvirt.c extern crate virt; use std::env; use virt::connect::Connect; use virt::error::Error; fn show_hypervisor_info(conn: &Connect) -> Result<(), Error> { if let Ok(hv_type) = conn.get_type() { if let Ok(mut hv_ver) = conn.get_hyp_version() { let major = hv_ver / 1000000; hv_ver %= 1000000; let minor = hv_ver / 1000; let release = hv_ver % 1000; println!("Hypervisor: '{}' version: {}.{}.{}", hv_type, major, minor, release); return Ok(()); } } Err(Error::new()) } fn show_domains(conn: &Connect) -> Result<(), Error> { let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE | virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE; if let Ok(num_active_domains) = conn.num_of_domains() { if let Ok(num_inactive_domains) = conn.num_of_defined_domains() { println!("There are {} active and {} inactive domains", num_active_domains, num_inactive_domains); /* Return a list of all active and inactive domains. Using this API * instead of virConnectListDomains() and virConnectListDefinedDomains() * is preferred since it "solves" an inherit race between separated API * calls if domains are started or stopped between calls */ if let Ok(doms) = conn.list_all_domains(flags) { for dom in doms { let id = dom.get_id().unwrap_or(0); let name = dom.get_name().unwrap_or(String::from("no-name")); let active = dom.is_active().unwrap_or(false); println!("ID: {}, Name: {}, Active: {}", id, name, active); if let Ok(dinfo) = dom.get_info() { println!("Domain info:"); println!(" State: {}", dinfo.state); println!(" Max Memory: {}", dinfo.max_mem); println!(" Memory: {}", dinfo.memory); println!(" CPUs: {}", dinfo.nr_virt_cpu); println!(" CPU Time: {}", dinfo.cpu_time); } if let Ok(memtune) = dom.get_memory_parameters(0) { println!("Memory tune:"); println!(" Hard Limit: {}", memtune.hard_limit.unwrap_or(0)); println!(" Soft Limit: {}", memtune.soft_limit.unwrap_or(0)); println!(" Min Guarantee: {}", memtune.min_guarantee.unwrap_or(0)); println!(" Swap Hard Limit: {}", memtune.swap_hard_limit.unwrap_or(0)); } if let Ok(numa) = dom.get_numa_parameters(0) { println!("NUMA:"); println!(" Node Set: {}", numa.node_set.unwrap_or(String::from(""))); println!(" Mode: {}", numa.mode.unwrap_or(0));
return Ok(()); } } Err(Error::new()) } fn main() { let uri = match env::args().nth(1) { Some(u) => u, None => String::from(""), }; println!("Attempting to connect to hypervisor: '{}'", uri); let conn = match Connect::open(&uri) { Ok(c) => c, Err(e) => { panic!("No connection to hypervisor: code {}, message: {}", e.code, e.message) } }; match conn.get_uri() { Ok(u) => println!("Connected to hypervisor at '{}'", u), Err(e) => { disconnect(conn); panic!("Failed to get URI for hypervisor connection: code {}, message: {}", e.code, e.message); } }; if let Err(e) = show_hypervisor_info(&conn) { disconnect(conn); panic!("Failed to show hypervisor info: code {}, message: {}", e.code, e.message); } if let Err(e) = show_domains(&conn) { disconnect(conn); panic!("Failed to show domains info: code {}, message: {}", e.code, e.message); } fn disconnect(mut conn: Connect) { if let Err(e) = conn.close() { panic!("Failed to disconnect from hypervisor: code {}, message: {}", e.code, e.message); } println!("Disconnected from hypervisor"); } }
} } }
random_line_split
hello.rs
/* * 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; either * version 2.1 of the License, or (at your option) any later version. * * 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, see * <http://www.gnu.org/licenses/>. * * Sahid Orentino Ferdjaoui <[email protected]> */ //! This file contains trivial example code to connect to the running //! hypervisor and gather a few bits of information about domains. //! Similar API's exist for storage pools, networks, and interfaces. //! //! Largely inspired by hellolibvirt.c extern crate virt; use std::env; use virt::connect::Connect; use virt::error::Error; fn show_hypervisor_info(conn: &Connect) -> Result<(), Error> { if let Ok(hv_type) = conn.get_type() { if let Ok(mut hv_ver) = conn.get_hyp_version() { let major = hv_ver / 1000000; hv_ver %= 1000000; let minor = hv_ver / 1000; let release = hv_ver % 1000; println!("Hypervisor: '{}' version: {}.{}.{}", hv_type, major, minor, release); return Ok(()); } } Err(Error::new()) } fn show_domains(conn: &Connect) -> Result<(), Error> { let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE | virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE; if let Ok(num_active_domains) = conn.num_of_domains() { if let Ok(num_inactive_domains) = conn.num_of_defined_domains() { println!("There are {} active and {} inactive domains", num_active_domains, num_inactive_domains); /* Return a list of all active and inactive domains. Using this API * instead of virConnectListDomains() and virConnectListDefinedDomains() * is preferred since it "solves" an inherit race between separated API * calls if domains are started or stopped between calls */ if let Ok(doms) = conn.list_all_domains(flags) { for dom in doms { let id = dom.get_id().unwrap_or(0); let name = dom.get_name().unwrap_or(String::from("no-name")); let active = dom.is_active().unwrap_or(false); println!("ID: {}, Name: {}, Active: {}", id, name, active); if let Ok(dinfo) = dom.get_info() { println!("Domain info:"); println!(" State: {}", dinfo.state); println!(" Max Memory: {}", dinfo.max_mem); println!(" Memory: {}", dinfo.memory); println!(" CPUs: {}", dinfo.nr_virt_cpu); println!(" CPU Time: {}", dinfo.cpu_time); } if let Ok(memtune) = dom.get_memory_parameters(0) { println!("Memory tune:"); println!(" Hard Limit: {}", memtune.hard_limit.unwrap_or(0)); println!(" Soft Limit: {}", memtune.soft_limit.unwrap_or(0)); println!(" Min Guarantee: {}", memtune.min_guarantee.unwrap_or(0)); println!(" Swap Hard Limit: {}", memtune.swap_hard_limit.unwrap_or(0)); } if let Ok(numa) = dom.get_numa_parameters(0) { println!("NUMA:"); println!(" Node Set: {}", numa.node_set.unwrap_or(String::from(""))); println!(" Mode: {}", numa.mode.unwrap_or(0)); } } } return Ok(()); } } Err(Error::new()) } fn main() { let uri = match env::args().nth(1) { Some(u) => u, None => String::from(""), }; println!("Attempting to connect to hypervisor: '{}'", uri); let conn = match Connect::open(&uri) { Ok(c) => c, Err(e) => { panic!("No connection to hypervisor: code {}, message: {}", e.code, e.message) } }; match conn.get_uri() { Ok(u) => println!("Connected to hypervisor at '{}'", u), Err(e) => { disconnect(conn); panic!("Failed to get URI for hypervisor connection: code {}, message: {}", e.code, e.message); } }; if let Err(e) = show_hypervisor_info(&conn)
if let Err(e) = show_domains(&conn) { disconnect(conn); panic!("Failed to show domains info: code {}, message: {}", e.code, e.message); } fn disconnect(mut conn: Connect) { if let Err(e) = conn.close() { panic!("Failed to disconnect from hypervisor: code {}, message: {}", e.code, e.message); } println!("Disconnected from hypervisor"); } }
{ disconnect(conn); panic!("Failed to show hypervisor info: code {}, message: {}", e.code, e.message); }
conditional_block
kay_auto.rs
//! This is all auto-generated. Do not touch. #![rustfmt::skip] #[allow(unused_imports)] use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait}; #[allow(unused_imports)] use super::*; #[derive(Serialize, Deserialize)] #[serde(transparent)] pub struct TimeUIID { _raw_id: RawID } impl Copy for TimeUIID {} impl Clone for TimeUIID { fn clone(&self) -> Self { *self } } impl ::std::fmt::Debug for TimeUIID { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "TimeUIID({:?})", self._raw_id) } } impl ::std::hash::Hash for TimeUIID { fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) { self._raw_id.hash(state); } } impl PartialEq for TimeUIID { fn eq(&self, other: &TimeUIID) -> bool { self._raw_id == other._raw_id } } impl Eq for TimeUIID {} pub struct TimeUIRepresentative; impl ActorOrActorTrait for TimeUIRepresentative { type ID = TimeUIID; } impl TypedID for TimeUIID { type Target = TimeUIRepresentative; fn from_raw(id: RawID) -> Self { TimeUIID { _raw_id: id } } fn as_raw(&self) -> RawID { self._raw_id } } impl<Act: Actor + TimeUI> TraitIDFrom<Act> for TimeUIID {} impl TimeUIID { pub fn on_time_info(self, current_instant: :: units :: Instant, speed: u16, world: &mut World)
pub fn register_trait(system: &mut ActorSystem) { system.register_trait::<TimeUIRepresentative>(); system.register_trait_message::<MSG_TimeUI_on_time_info>(); } pub fn register_implementor<Act: Actor + TimeUI>(system: &mut ActorSystem) { system.register_implementor::<Act, TimeUIRepresentative>(); system.add_handler::<Act, _, _>( |&MSG_TimeUI_on_time_info(current_instant, speed), instance, world| { instance.on_time_info(current_instant, speed, world); Fate::Live }, false ); } } #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_TimeUI_on_time_info(pub :: units :: Instant, pub u16); impl TimeID { pub fn get_info(self, requester: TimeUIID, world: &mut World) { world.send(self.as_raw(), MSG_Time_get_info(requester)); } pub fn set_speed(self, speed: u16, world: &mut World) { world.send(self.as_raw(), MSG_Time_set_speed(speed)); } } #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_Time_get_info(pub TimeUIID); #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_Time_set_speed(pub u16); #[allow(unused_variables)] #[allow(unused_mut)] pub fn auto_setup(system: &mut ActorSystem) { TimeUIID::register_trait(system); system.add_handler::<Time, _, _>( |&MSG_Time_get_info(requester), instance, world| { instance.get_info(requester, world); Fate::Live }, false ); system.add_handler::<Time, _, _>( |&MSG_Time_set_speed(speed), instance, world| { instance.set_speed(speed, world); Fate::Live }, false ); }
{ world.send(self.as_raw(), MSG_TimeUI_on_time_info(current_instant, speed)); }
identifier_body
kay_auto.rs
//! This is all auto-generated. Do not touch. #![rustfmt::skip] #[allow(unused_imports)] use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait}; #[allow(unused_imports)] use super::*; #[derive(Serialize, Deserialize)] #[serde(transparent)] pub struct TimeUIID { _raw_id: RawID } impl Copy for TimeUIID {} impl Clone for TimeUIID { fn clone(&self) -> Self { *self } } impl ::std::fmt::Debug for TimeUIID { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "TimeUIID({:?})", self._raw_id) } } impl ::std::hash::Hash for TimeUIID { fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) { self._raw_id.hash(state); } } impl PartialEq for TimeUIID { fn eq(&self, other: &TimeUIID) -> bool { self._raw_id == other._raw_id } } impl Eq for TimeUIID {} pub struct TimeUIRepresentative; impl ActorOrActorTrait for TimeUIRepresentative { type ID = TimeUIID; } impl TypedID for TimeUIID { type Target = TimeUIRepresentative; fn from_raw(id: RawID) -> Self { TimeUIID { _raw_id: id } } fn as_raw(&self) -> RawID { self._raw_id } } impl<Act: Actor + TimeUI> TraitIDFrom<Act> for TimeUIID {} impl TimeUIID { pub fn
(self, current_instant: :: units :: Instant, speed: u16, world: &mut World) { world.send(self.as_raw(), MSG_TimeUI_on_time_info(current_instant, speed)); } pub fn register_trait(system: &mut ActorSystem) { system.register_trait::<TimeUIRepresentative>(); system.register_trait_message::<MSG_TimeUI_on_time_info>(); } pub fn register_implementor<Act: Actor + TimeUI>(system: &mut ActorSystem) { system.register_implementor::<Act, TimeUIRepresentative>(); system.add_handler::<Act, _, _>( |&MSG_TimeUI_on_time_info(current_instant, speed), instance, world| { instance.on_time_info(current_instant, speed, world); Fate::Live }, false ); } } #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_TimeUI_on_time_info(pub :: units :: Instant, pub u16); impl TimeID { pub fn get_info(self, requester: TimeUIID, world: &mut World) { world.send(self.as_raw(), MSG_Time_get_info(requester)); } pub fn set_speed(self, speed: u16, world: &mut World) { world.send(self.as_raw(), MSG_Time_set_speed(speed)); } } #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_Time_get_info(pub TimeUIID); #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_Time_set_speed(pub u16); #[allow(unused_variables)] #[allow(unused_mut)] pub fn auto_setup(system: &mut ActorSystem) { TimeUIID::register_trait(system); system.add_handler::<Time, _, _>( |&MSG_Time_get_info(requester), instance, world| { instance.get_info(requester, world); Fate::Live }, false ); system.add_handler::<Time, _, _>( |&MSG_Time_set_speed(speed), instance, world| { instance.set_speed(speed, world); Fate::Live }, false ); }
on_time_info
identifier_name
kay_auto.rs
//! This is all auto-generated. Do not touch. #![rustfmt::skip] #[allow(unused_imports)] use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait}; #[allow(unused_imports)] use super::*; #[derive(Serialize, Deserialize)] #[serde(transparent)] pub struct TimeUIID { _raw_id: RawID }
} } impl ::std::hash::Hash for TimeUIID { fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) { self._raw_id.hash(state); } } impl PartialEq for TimeUIID { fn eq(&self, other: &TimeUIID) -> bool { self._raw_id == other._raw_id } } impl Eq for TimeUIID {} pub struct TimeUIRepresentative; impl ActorOrActorTrait for TimeUIRepresentative { type ID = TimeUIID; } impl TypedID for TimeUIID { type Target = TimeUIRepresentative; fn from_raw(id: RawID) -> Self { TimeUIID { _raw_id: id } } fn as_raw(&self) -> RawID { self._raw_id } } impl<Act: Actor + TimeUI> TraitIDFrom<Act> for TimeUIID {} impl TimeUIID { pub fn on_time_info(self, current_instant: :: units :: Instant, speed: u16, world: &mut World) { world.send(self.as_raw(), MSG_TimeUI_on_time_info(current_instant, speed)); } pub fn register_trait(system: &mut ActorSystem) { system.register_trait::<TimeUIRepresentative>(); system.register_trait_message::<MSG_TimeUI_on_time_info>(); } pub fn register_implementor<Act: Actor + TimeUI>(system: &mut ActorSystem) { system.register_implementor::<Act, TimeUIRepresentative>(); system.add_handler::<Act, _, _>( |&MSG_TimeUI_on_time_info(current_instant, speed), instance, world| { instance.on_time_info(current_instant, speed, world); Fate::Live }, false ); } } #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_TimeUI_on_time_info(pub :: units :: Instant, pub u16); impl TimeID { pub fn get_info(self, requester: TimeUIID, world: &mut World) { world.send(self.as_raw(), MSG_Time_get_info(requester)); } pub fn set_speed(self, speed: u16, world: &mut World) { world.send(self.as_raw(), MSG_Time_set_speed(speed)); } } #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_Time_get_info(pub TimeUIID); #[derive(Compact, Clone)] #[allow(non_camel_case_types)] struct MSG_Time_set_speed(pub u16); #[allow(unused_variables)] #[allow(unused_mut)] pub fn auto_setup(system: &mut ActorSystem) { TimeUIID::register_trait(system); system.add_handler::<Time, _, _>( |&MSG_Time_get_info(requester), instance, world| { instance.get_info(requester, world); Fate::Live }, false ); system.add_handler::<Time, _, _>( |&MSG_Time_set_speed(speed), instance, world| { instance.set_speed(speed, world); Fate::Live }, false ); }
impl Copy for TimeUIID {} impl Clone for TimeUIID { fn clone(&self) -> Self { *self } } impl ::std::fmt::Debug for TimeUIID { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "TimeUIID({:?})", self._raw_id)
random_line_split
mod.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Ethereum virtual machine. pub mod ext; pub mod evm; pub mod interpreter; #[macro_use] pub mod factory; pub mod schedule; mod vmtype; mod instructions; #[cfg(feature = "jit" )] mod jit; #[cfg(test)] mod tests; #[cfg(all(feature="benches", test))] mod benches; pub use self::evm::{Evm, Error, Finalize, FinalizationResult, GasLeft, Result, CostType, ReturnData}; pub use self::ext::{Ext, ContractCreateResult, MessageCallResult, CreateContractAddress}; pub use self::instructions::{InstructionInfo, INSTRUCTIONS, push_bytes}; pub use self::vmtype::VMType;
pub use self::schedule::{Schedule, CleanDustMode}; pub use types::executed::CallType;
pub use self::factory::Factory;
random_line_split
parity_signing.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use jsonrpc_core::Error; use futures::BoxFuture; use v1::types::{U256, H160, Bytes, ConfirmationResponse, TransactionRequest, Either}; build_rpc_trait! { /// Signing methods implementation. pub trait ParitySigning { type Metadata; /// Posts sign request asynchronously. /// Will return a confirmation ID for later use with check_transaction. #[rpc(meta, name = "parity_postSign")] fn post_sign(&self, Self::Metadata, H160, Bytes) -> BoxFuture<Either<U256, ConfirmationResponse>, Error>; /// Posts transaction asynchronously. /// Will return a transaction ID for later use with check_transaction. #[rpc(meta, name = "parity_postTransaction")] fn post_transaction(&self, Self::Metadata, TransactionRequest) -> BoxFuture<Either<U256, ConfirmationResponse>, Error>; /// Checks the progress of a previously posted request (transaction/sign). /// Should be given a valid send_transaction ID. #[rpc(name = "parity_checkRequest")] fn check_request(&self, U256) -> Result<Option<ConfirmationResponse>, Error>; /// Decrypt some ECIES-encrypted message. /// First parameter is the address with which it is encrypted, second is the ciphertext. #[rpc(meta, name = "parity_decryptMessage")] fn decrypt_message(&self, Self::Metadata, H160, Bytes) -> BoxFuture<Bytes, Error>; } }
//! ParitySigning rpc interface.
random_line_split
u_char.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. //! Unicode-intensive `char` methods along with the `core` methods. //! //! These methods implement functionality for `char` that requires knowledge of //! Unicode definitions, including normalization, categorization, and display information. use core::char; use core::char::CharExt as C; use core::option::Option; use tables::{derived_property, property, general_category, conversions, charwidth}; /// Functionality for manipulating `char`. #[stable] pub trait CharExt { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool; /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint>; /// Returns an iterator that yields the hexadecimal Unicode escape /// of a character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. #[stable] fn escape_unicode(self) -> char::EscapeUnicode; /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. #[stable] fn escape_default(self) -> char::EscapeDefault; /// Returns the amount of bytes this character would need if encoded in /// UTF-8. #[stable] fn len_utf8(self) -> uint; /// Returns the amount of bytes this character would need if encoded in /// UTF-16. #[stable] fn len_utf16(self) -> uint; /// Encodes this character as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>; /// Encodes this character as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>; /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable] fn is_alphabetic(self) -> bool; /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool; /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool; /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable] fn is_lowercase(self) -> bool; /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable] fn is_uppercase(self) -> bool; /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable] fn is_whitespace(self) -> bool; /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable] fn is_alphanumeric(self) -> bool; /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable] fn is_control(self) -> bool; /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable] fn is_numeric(self) -> bool; /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns the lowercase equivalent of the character, or the character /// itself if no conversion is possible. #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char; /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint (one character in Rust) to its uppercase /// equivalent according to the Unicode database [1]. The additional /// [`SpecialCasing.txt`] is not considered here, as it expands to multiple /// codepoints in some cases. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns the uppercase equivalent of the character, or the character /// itself if no conversion was made. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char; /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint>; } #[stable] impl CharExt for char { #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool { C::is_digit(self, radix) } #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint> { C::to_digit(self, radix) } #[stable] fn escape_unicode(self) -> char::EscapeUnicode { C::escape_unicode(self) } #[stable] fn escape_default(self) -> char::EscapeDefault { C::escape_default(self) } #[stable] fn len_utf8(self) -> uint { C::len_utf8(self) } #[stable] fn len_utf16(self) -> uint { C::len_utf16(self) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint> { C::encode_utf8(self, dst) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint> { C::encode_utf16(self, dst) } #[stable] fn is_alphabetic(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool
#[stable] fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } #[stable] fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } #[stable] fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } #[stable] fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } #[stable] fn is_control(self) -> bool { general_category::Cc(self) } #[stable] fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char { conversions::to_lower(self) } #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char { conversions::to_upper(self) } #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint> { charwidth::width(self, is_cjk) } }
{ derived_property::XID_Continue(self) }
identifier_body
u_char.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. //! Unicode-intensive `char` methods along with the `core` methods. //! //! These methods implement functionality for `char` that requires knowledge of //! Unicode definitions, including normalization, categorization, and display information. use core::char; use core::char::CharExt as C; use core::option::Option; use tables::{derived_property, property, general_category, conversions, charwidth}; /// Functionality for manipulating `char`. #[stable] pub trait CharExt { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool; /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint>; /// Returns an iterator that yields the hexadecimal Unicode escape /// of a character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. #[stable] fn escape_unicode(self) -> char::EscapeUnicode; /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. #[stable] fn escape_default(self) -> char::EscapeDefault; /// Returns the amount of bytes this character would need if encoded in /// UTF-8. #[stable] fn len_utf8(self) -> uint; /// Returns the amount of bytes this character would need if encoded in /// UTF-16. #[stable] fn len_utf16(self) -> uint; /// Encodes this character as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>; /// Encodes this character as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>; /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable] fn is_alphabetic(self) -> bool; /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool; /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool; /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable] fn is_lowercase(self) -> bool; /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable] fn is_uppercase(self) -> bool; /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable] fn is_whitespace(self) -> bool; /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable] fn is_alphanumeric(self) -> bool; /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable] fn is_control(self) -> bool; /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable] fn is_numeric(self) -> bool; /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns the lowercase equivalent of the character, or the character /// itself if no conversion is possible. #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char; /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint (one character in Rust) to its uppercase /// equivalent according to the Unicode database [1]. The additional /// [`SpecialCasing.txt`] is not considered here, as it expands to multiple /// codepoints in some cases. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns the uppercase equivalent of the character, or the character /// itself if no conversion was made. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char; /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint>; } #[stable] impl CharExt for char { #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool { C::is_digit(self, radix) } #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint> { C::to_digit(self, radix) } #[stable] fn escape_unicode(self) -> char::EscapeUnicode { C::escape_unicode(self) } #[stable] fn escape_default(self) -> char::EscapeDefault { C::escape_default(self) } #[stable] fn len_utf8(self) -> uint { C::len_utf8(self) } #[stable] fn len_utf16(self) -> uint { C::len_utf16(self) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint> { C::encode_utf8(self, dst) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint> { C::encode_utf16(self, dst) } #[stable] fn
(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } #[stable] fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } #[stable] fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } #[stable] fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } #[stable] fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } #[stable] fn is_control(self) -> bool { general_category::Cc(self) } #[stable] fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char { conversions::to_lower(self) } #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char { conversions::to_upper(self) } #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint> { charwidth::width(self, is_cjk) } }
is_alphabetic
identifier_name
u_char.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. //! Unicode-intensive `char` methods along with the `core` methods. //! //! These methods implement functionality for `char` that requires knowledge of //! Unicode definitions, including normalization, categorization, and display information. use core::char; use core::char::CharExt as C; use core::option::Option; use tables::{derived_property, property, general_category, conversions, charwidth}; /// Functionality for manipulating `char`. #[stable] pub trait CharExt { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool; /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint>; /// Returns an iterator that yields the hexadecimal Unicode escape /// of a character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. #[stable] fn escape_unicode(self) -> char::EscapeUnicode; /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. #[stable] fn escape_default(self) -> char::EscapeDefault;
#[stable] fn len_utf8(self) -> uint; /// Returns the amount of bytes this character would need if encoded in /// UTF-16. #[stable] fn len_utf16(self) -> uint; /// Encodes this character as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>; /// Encodes this character as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>; /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable] fn is_alphabetic(self) -> bool; /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool; /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool; /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable] fn is_lowercase(self) -> bool; /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable] fn is_uppercase(self) -> bool; /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable] fn is_whitespace(self) -> bool; /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable] fn is_alphanumeric(self) -> bool; /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable] fn is_control(self) -> bool; /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable] fn is_numeric(self) -> bool; /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns the lowercase equivalent of the character, or the character /// itself if no conversion is possible. #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char; /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint (one character in Rust) to its uppercase /// equivalent according to the Unicode database [1]. The additional /// [`SpecialCasing.txt`] is not considered here, as it expands to multiple /// codepoints in some cases. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns the uppercase equivalent of the character, or the character /// itself if no conversion was made. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char; /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint>; } #[stable] impl CharExt for char { #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool { C::is_digit(self, radix) } #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint> { C::to_digit(self, radix) } #[stable] fn escape_unicode(self) -> char::EscapeUnicode { C::escape_unicode(self) } #[stable] fn escape_default(self) -> char::EscapeDefault { C::escape_default(self) } #[stable] fn len_utf8(self) -> uint { C::len_utf8(self) } #[stable] fn len_utf16(self) -> uint { C::len_utf16(self) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint> { C::encode_utf8(self, dst) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint> { C::encode_utf16(self, dst) } #[stable] fn is_alphabetic(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } #[stable] fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } #[stable] fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } #[stable] fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } #[stable] fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } #[stable] fn is_control(self) -> bool { general_category::Cc(self) } #[stable] fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char { conversions::to_lower(self) } #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char { conversions::to_upper(self) } #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint> { charwidth::width(self, is_cjk) } }
/// Returns the amount of bytes this character would need if encoded in /// UTF-8.
random_line_split
lib.rs
#![feature(globs)] use std::collections::HashMap; use std::fmt::{Show, FormatError, Formatter}; use std::os; use std::str; pub use self::gnu::GnuMakefile; // XXX: no idea why this is necessary #[path = "gnu/mod.rs"] pub mod gnu; pub type TokenResult<T> = Result<T, TokenError>; pub type ParseResult<T> = Result<T, ParseError>; pub trait Makefile<'a> { fn vars(&mut self) -> &mut MutableMap<&'a [u8], Vec<u8>>; fn tokenize<'a>(&mut self, data: &[u8]) -> TokenResult<Vec<Token<'a>>>; fn parse<'a, 'b>(&mut self, tokens: Vec<Token<'b>>) -> ParseResult<MakefileDag<'a>>; fn find_var<'b>(&'b mut self, name: &'a [u8]) -> Option<Vec<u8>> { let vars = self.vars(); match vars.find(&name).and_then(|val| Some(val.clone())) { // get the borrow checker to shut up None => { if let Some(utf8_name) = str::from_utf8(name) { match os::getenv_as_bytes(utf8_name) { Some(val) => { vars.insert(name, val.clone()); Some(val) } None => None } } else { None } } val => val } } } pub enum Token<'a> { Ident(&'a [u8]), Var(&'a [u8]), // NOTE: both Var and FuncCall have the same syntax FuncCall(&'a [u8]), Command(&'a Token<'a>), // i.e. shell commands in a rule (Token should be Other) Colon, Equal, Comma, Dollar, Question, Plus, Tab, IfEq, IfNeq, Other(&'a [u8]) } pub struct
<'a> { rules: HashMap<&'a [u8], MakefileRule<'a>>, funcs: HashMap<&'a [u8], &'a [u8]> } pub struct MakefileRule<'a> { name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8] } pub struct ParseError { pub message: String, pub code: int } pub struct TokenError { pub message: String, pub code: int } impl<'a> MakefileDag<'a> { #[inline] pub fn new() -> MakefileDag<'a> { MakefileDag { rules: HashMap::new(), funcs: HashMap::new(), } } } impl<'a> MakefileRule<'a> { #[inline] pub fn new(name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8]) -> MakefileRule<'a> { MakefileRule { name: name, deps: deps, body: body } } } impl ParseError { #[inline] pub fn new(msg: String, code: int) -> ParseError { ParseError { message: msg, code: code } } } impl Show for ParseError { fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> { formatter.write(self.message.as_bytes()) } } impl TokenError { #[inline] pub fn new(msg: String, code: int) -> TokenError { TokenError { message: msg, code: code } } } impl Show for TokenError { fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> { formatter.write(self.message.as_bytes()) } }
MakefileDag
identifier_name
lib.rs
#![feature(globs)] use std::collections::HashMap; use std::fmt::{Show, FormatError, Formatter}; use std::os; use std::str; pub use self::gnu::GnuMakefile; // XXX: no idea why this is necessary #[path = "gnu/mod.rs"] pub mod gnu; pub type TokenResult<T> = Result<T, TokenError>; pub type ParseResult<T> = Result<T, ParseError>; pub trait Makefile<'a> { fn vars(&mut self) -> &mut MutableMap<&'a [u8], Vec<u8>>; fn tokenize<'a>(&mut self, data: &[u8]) -> TokenResult<Vec<Token<'a>>>; fn parse<'a, 'b>(&mut self, tokens: Vec<Token<'b>>) -> ParseResult<MakefileDag<'a>>; fn find_var<'b>(&'b mut self, name: &'a [u8]) -> Option<Vec<u8>> { let vars = self.vars(); match vars.find(&name).and_then(|val| Some(val.clone())) { // get the borrow checker to shut up None => { if let Some(utf8_name) = str::from_utf8(name) { match os::getenv_as_bytes(utf8_name) { Some(val) => { vars.insert(name, val.clone()); Some(val) } None => None } } else { None } } val => val } } } pub enum Token<'a> { Ident(&'a [u8]), Var(&'a [u8]), // NOTE: both Var and FuncCall have the same syntax FuncCall(&'a [u8]), Command(&'a Token<'a>), // i.e. shell commands in a rule (Token should be Other) Colon, Equal, Comma, Dollar, Question, Plus, Tab, IfEq, IfNeq, Other(&'a [u8]) } pub struct MakefileDag<'a> { rules: HashMap<&'a [u8], MakefileRule<'a>>, funcs: HashMap<&'a [u8], &'a [u8]> } pub struct MakefileRule<'a> { name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8] } pub struct ParseError { pub message: String, pub code: int } pub struct TokenError { pub message: String, pub code: int } impl<'a> MakefileDag<'a> { #[inline] pub fn new() -> MakefileDag<'a> { MakefileDag { rules: HashMap::new(), funcs: HashMap::new(), }
} impl<'a> MakefileRule<'a> { #[inline] pub fn new(name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8]) -> MakefileRule<'a> { MakefileRule { name: name, deps: deps, body: body } } } impl ParseError { #[inline] pub fn new(msg: String, code: int) -> ParseError { ParseError { message: msg, code: code } } } impl Show for ParseError { fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> { formatter.write(self.message.as_bytes()) } } impl TokenError { #[inline] pub fn new(msg: String, code: int) -> TokenError { TokenError { message: msg, code: code } } } impl Show for TokenError { fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> { formatter.write(self.message.as_bytes()) } }
}
random_line_split
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to manage C code initialization and clean-up. #[must_use] pub struct Sdl2TtfContext; // Clean up the context once it goes out of scope impl Drop for Sdl2TtfContext { fn drop(&mut self) {
} } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf,'static>, String> { internal_load_font(path, point_size) } /// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf,'static>, String> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized twice /// Necessary for context management, unless we find a way to have a singleton #[derive(Debug)] pub enum InitError { InitializationError(io::Error), AlreadyInitializedError, } impl error::Error for InitError { fn description(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), } } } impl fmt::Display for InitError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("SDL2_TTF has already been initialized") } } /// Initializes the truetype font API and returns a context manager which will /// clean up the library once it goes out of scope. pub fn init() -> Result<Sdl2TtfContext, InitError> { unsafe { if ttf::TTF_WasInit() == 1 { Err(InitError::AlreadyInitializedError) } else if ttf::TTF_Init() == 0 { Ok(Sdl2TtfContext) } else { Err(InitError::InitializationError(io::Error::last_os_error())) } } } /// Returns whether library has been initialized already. pub fn has_been_initialized() -> bool { unsafe { ttf::TTF_WasInit() == 1 } }
unsafe { ttf::TTF_Quit();
random_line_split
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to manage C code initialization and clean-up. #[must_use] pub struct Sdl2TtfContext; // Clean up the context once it goes out of scope impl Drop for Sdl2TtfContext { fn drop(&mut self) { unsafe { ttf::TTF_Quit(); } } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf,'static>, String>
/// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf,'static>, String> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized twice /// Necessary for context management, unless we find a way to have a singleton #[derive(Debug)] pub enum InitError { InitializationError(io::Error), AlreadyInitializedError, } impl error::Error for InitError { fn description(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), } } } impl fmt::Display for InitError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("SDL2_TTF has already been initialized") } } /// Initializes the truetype font API and returns a context manager which will /// clean up the library once it goes out of scope. pub fn init() -> Result<Sdl2TtfContext, InitError> { unsafe { if ttf::TTF_WasInit() == 1 { Err(InitError::AlreadyInitializedError) } else if ttf::TTF_Init() == 0 { Ok(Sdl2TtfContext) } else { Err(InitError::InitializationError(io::Error::last_os_error())) } } } /// Returns whether library has been initialized already. pub fn has_been_initialized() -> bool { unsafe { ttf::TTF_WasInit() == 1 } }
{ internal_load_font(path, point_size) }
identifier_body
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to manage C code initialization and clean-up. #[must_use] pub struct Sdl2TtfContext; // Clean up the context once it goes out of scope impl Drop for Sdl2TtfContext { fn drop(&mut self) { unsafe { ttf::TTF_Quit(); } } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf,'static>, String> { internal_load_font(path, point_size) } /// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf,'static>, String> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null()
else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized twice /// Necessary for context management, unless we find a way to have a singleton #[derive(Debug)] pub enum InitError { InitializationError(io::Error), AlreadyInitializedError, } impl error::Error for InitError { fn description(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), } } } impl fmt::Display for InitError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("SDL2_TTF has already been initialized") } } /// Initializes the truetype font API and returns a context manager which will /// clean up the library once it goes out of scope. pub fn init() -> Result<Sdl2TtfContext, InitError> { unsafe { if ttf::TTF_WasInit() == 1 { Err(InitError::AlreadyInitializedError) } else if ttf::TTF_Init() == 0 { Ok(Sdl2TtfContext) } else { Err(InitError::InitializationError(io::Error::last_os_error())) } } } /// Returns whether library has been initialized already. pub fn has_been_initialized() -> bool { unsafe { ttf::TTF_WasInit() == 1 } }
{ Err(get_error()) }
conditional_block
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to manage C code initialization and clean-up. #[must_use] pub struct Sdl2TtfContext; // Clean up the context once it goes out of scope impl Drop for Sdl2TtfContext { fn drop(&mut self) { unsafe { ttf::TTF_Quit(); } } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf,'static>, String> { internal_load_font(path, point_size) } /// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf,'static>, String> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized twice /// Necessary for context management, unless we find a way to have a singleton #[derive(Debug)] pub enum InitError { InitializationError(io::Error), AlreadyInitializedError, } impl error::Error for InitError { fn
(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), } } } impl fmt::Display for InitError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("SDL2_TTF has already been initialized") } } /// Initializes the truetype font API and returns a context manager which will /// clean up the library once it goes out of scope. pub fn init() -> Result<Sdl2TtfContext, InitError> { unsafe { if ttf::TTF_WasInit() == 1 { Err(InitError::AlreadyInitializedError) } else if ttf::TTF_Init() == 0 { Ok(Sdl2TtfContext) } else { Err(InitError::InitializationError(io::Error::last_os_error())) } } } /// Returns whether library has been initialized already. pub fn has_been_initialized() -> bool { unsafe { ttf::TTF_WasInit() == 1 } }
description
identifier_name
sched.rs
//! Execution scheduling //! //! See Also //! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html) use crate::{Errno, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::sched_linux_like::*; #[cfg(any(target_os = "android", target_os = "linux"))] mod sched_linux_like { use crate::errno::Errno; use libc::{self, c_int, c_void}; use std::mem; use std::option::Option; use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { /// The calling process and the child process run in the same /// memory space. CLONE_VM; /// The caller and the child process share the same filesystem /// information. CLONE_FS; /// The calling process and the child process share the same file /// descriptor table. CLONE_FILES; /// The calling process and the child process share the same table /// of signal handlers. CLONE_SIGHAND; /// If the calling process is being traced, then trace the child /// also. CLONE_PTRACE; /// The execution of the calling process is suspended until the /// child releases its virtual memory resources via a call to /// execve(2) or _exit(2) (as with vfork(2)). CLONE_VFORK; /// The parent of the new child (as returned by getppid(2)) /// will be the same as that of the calling process. CLONE_PARENT; /// The child is placed in the same thread group as the calling /// process. CLONE_THREAD; /// The cloned child is started in a new mount namespace. CLONE_NEWNS; /// The child and the calling process share a single list of System /// V semaphore adjustment values CLONE_SYSVSEM; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_SETTLS; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_PARENT_SETTID; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_CLEARTID; /// Unused since Linux 2.6.2 #[deprecated(since = "0.23.0", note = "Deprecated by Linux 2.6.2")] CLONE_DETACHED; /// A tracing process cannot force `CLONE_PTRACE` on this child /// process. CLONE_UNTRACED; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_SETTID; /// Create the process in a new cgroup namespace. CLONE_NEWCGROUP; /// Create the process in a new UTS namespace. CLONE_NEWUTS; /// Create the process in a new IPC namespace. CLONE_NEWIPC; /// Create the process in a new user namespace. CLONE_NEWUSER; /// Create the process in a new PID namespace. CLONE_NEWPID; /// Create the process in a new network namespace. CLONE_NEWNET; /// The new process shares an I/O context with the calling process. CLONE_IO; } } /// Type for the function executed by [`clone`]. pub type CloneCb<'a> = Box<dyn FnMut() -> isize + 'a>; /// CpuSet represent a bit-mask of CPUs. /// CpuSets are used by sched_setaffinity and /// sched_getaffinity for example. /// /// This is a wrapper around `libc::cpu_set_t`. #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct CpuSet { cpu_set: libc::cpu_set_t, } impl CpuSet { /// Create a new and empty CpuSet. pub fn new() -> CpuSet { CpuSet { cpu_set: unsafe { mem::zeroed() }, } } /// Test to see if a CPU is in the CpuSet. /// `field` is the CPU id to test pub fn is_set(&self, field: usize) -> Result<bool>
/// Add a CPU to CpuSet. /// `field` is the CPU id to add pub fn set(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_SET(field, &mut self.cpu_set); } Ok(()) } } /// Remove a CPU from CpuSet. /// `field` is the CPU id to remove pub fn unset(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_CLR(field, &mut self.cpu_set);} Ok(()) } } /// Return the maximum number of CPU in CpuSet pub const fn count() -> usize { 8 * mem::size_of::<libc::cpu_set_t>() } } impl Default for CpuSet { fn default() -> Self { Self::new() } } /// `sched_setaffinity` set a thread's CPU affinity mask /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html)) /// /// `pid` is the thread ID to update. /// If pid is zero, then the calling thread is updated. /// /// The `cpuset` argument specifies the set of CPUs on which the thread /// will be eligible to run. /// /// # Example /// /// Binding the current thread to CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::{CpuSet, sched_setaffinity}; /// use nix::unistd::Pid; /// /// let mut cpu_set = CpuSet::new(); /// cpu_set.set(0); /// sched_setaffinity(Pid::from_raw(0), &cpu_set); /// ``` pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> { let res = unsafe { libc::sched_setaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &cpuset.cpu_set, ) }; Errno::result(res).map(drop) } /// `sched_getaffinity` get a thread's CPU affinity mask /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html)) /// /// `pid` is the thread ID to check. /// If pid is zero, then the calling thread is checked. /// /// Returned `cpuset` is the set of CPUs on which the thread /// is eligible to run. /// /// # Example /// /// Checking if the current thread can run on CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::sched_getaffinity; /// use nix::unistd::Pid; /// /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap(); /// if cpu_set.is_set(0).unwrap() { /// println!("Current thread can run on CPU 0"); /// } /// ``` pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> { let mut cpuset = CpuSet::new(); let res = unsafe { libc::sched_getaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &mut cpuset.cpu_set, ) }; Errno::result(res).and(Ok(cpuset)) } /// `clone` create a child process /// ([`clone(2)`](https://man7.org/linux/man-pages/man2/clone.2.html)) /// /// `stack` is a reference to an array which will hold the stack of the new /// process. Unlike when calling `clone(2)` from C, the provided stack /// address need not be the highest address of the region. Nix will take /// care of that requirement. The user only needs to provide a reference to /// a normally allocated buffer. pub fn clone( mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags, signal: Option<c_int>, ) -> Result<Pid> { extern "C" fn callback(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int } let res = unsafe { let combined = flags.bits() | signal.unwrap_or(0); let ptr = stack.as_mut_ptr().add(stack.len()); let ptr_aligned = ptr.sub(ptr as usize % 16); libc::clone( mem::transmute( callback as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32, ), ptr_aligned as *mut c_void, combined, &mut cb as *mut _ as *mut c_void, ) }; Errno::result(res).map(Pid::from_raw) } /// disassociate parts of the process execution context /// /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html) pub fn unshare(flags: CloneFlags) -> Result<()> { let res = unsafe { libc::unshare(flags.bits()) }; Errno::result(res).map(drop) } /// reassociate thread with a namespace /// /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html) pub fn setns(fd: RawFd, nstype: CloneFlags) -> Result<()> { let res = unsafe { libc::setns(fd, nstype.bits()) }; Errno::result(res).map(drop) } } /// Explicitly yield the processor to other threads. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html) pub fn sched_yield() -> Result<()> { let res = unsafe { libc::sched_yield() }; Errno::result(res).map(drop) }
{ if field >= CpuSet::count() { Err(Errno::EINVAL) } else { Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) }) } }
identifier_body
sched.rs
//! Execution scheduling //! //! See Also //! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html) use crate::{Errno, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::sched_linux_like::*; #[cfg(any(target_os = "android", target_os = "linux"))] mod sched_linux_like { use crate::errno::Errno; use libc::{self, c_int, c_void}; use std::mem; use std::option::Option; use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { /// The calling process and the child process run in the same /// memory space. CLONE_VM; /// The caller and the child process share the same filesystem /// information. CLONE_FS; /// The calling process and the child process share the same file /// descriptor table. CLONE_FILES; /// The calling process and the child process share the same table /// of signal handlers. CLONE_SIGHAND; /// If the calling process is being traced, then trace the child /// also. CLONE_PTRACE; /// The execution of the calling process is suspended until the /// child releases its virtual memory resources via a call to /// execve(2) or _exit(2) (as with vfork(2)). CLONE_VFORK; /// The parent of the new child (as returned by getppid(2)) /// will be the same as that of the calling process. CLONE_PARENT; /// The child is placed in the same thread group as the calling /// process. CLONE_THREAD; /// The cloned child is started in a new mount namespace. CLONE_NEWNS; /// The child and the calling process share a single list of System /// V semaphore adjustment values CLONE_SYSVSEM; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_SETTLS; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_PARENT_SETTID; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_CLEARTID; /// Unused since Linux 2.6.2 #[deprecated(since = "0.23.0", note = "Deprecated by Linux 2.6.2")] CLONE_DETACHED; /// A tracing process cannot force `CLONE_PTRACE` on this child /// process. CLONE_UNTRACED; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_SETTID; /// Create the process in a new cgroup namespace. CLONE_NEWCGROUP; /// Create the process in a new UTS namespace. CLONE_NEWUTS; /// Create the process in a new IPC namespace. CLONE_NEWIPC; /// Create the process in a new user namespace. CLONE_NEWUSER; /// Create the process in a new PID namespace. CLONE_NEWPID; /// Create the process in a new network namespace. CLONE_NEWNET; /// The new process shares an I/O context with the calling process. CLONE_IO; } } /// Type for the function executed by [`clone`]. pub type CloneCb<'a> = Box<dyn FnMut() -> isize + 'a>; /// CpuSet represent a bit-mask of CPUs. /// CpuSets are used by sched_setaffinity and /// sched_getaffinity for example. /// /// This is a wrapper around `libc::cpu_set_t`. #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct CpuSet { cpu_set: libc::cpu_set_t, } impl CpuSet { /// Create a new and empty CpuSet. pub fn new() -> CpuSet { CpuSet { cpu_set: unsafe { mem::zeroed() }, } } /// Test to see if a CPU is in the CpuSet. /// `field` is the CPU id to test pub fn is_set(&self, field: usize) -> Result<bool> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) }) } } /// Add a CPU to CpuSet. /// `field` is the CPU id to add pub fn set(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else
} /// Remove a CPU from CpuSet. /// `field` is the CPU id to remove pub fn unset(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_CLR(field, &mut self.cpu_set);} Ok(()) } } /// Return the maximum number of CPU in CpuSet pub const fn count() -> usize { 8 * mem::size_of::<libc::cpu_set_t>() } } impl Default for CpuSet { fn default() -> Self { Self::new() } } /// `sched_setaffinity` set a thread's CPU affinity mask /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html)) /// /// `pid` is the thread ID to update. /// If pid is zero, then the calling thread is updated. /// /// The `cpuset` argument specifies the set of CPUs on which the thread /// will be eligible to run. /// /// # Example /// /// Binding the current thread to CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::{CpuSet, sched_setaffinity}; /// use nix::unistd::Pid; /// /// let mut cpu_set = CpuSet::new(); /// cpu_set.set(0); /// sched_setaffinity(Pid::from_raw(0), &cpu_set); /// ``` pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> { let res = unsafe { libc::sched_setaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &cpuset.cpu_set, ) }; Errno::result(res).map(drop) } /// `sched_getaffinity` get a thread's CPU affinity mask /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html)) /// /// `pid` is the thread ID to check. /// If pid is zero, then the calling thread is checked. /// /// Returned `cpuset` is the set of CPUs on which the thread /// is eligible to run. /// /// # Example /// /// Checking if the current thread can run on CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::sched_getaffinity; /// use nix::unistd::Pid; /// /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap(); /// if cpu_set.is_set(0).unwrap() { /// println!("Current thread can run on CPU 0"); /// } /// ``` pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> { let mut cpuset = CpuSet::new(); let res = unsafe { libc::sched_getaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &mut cpuset.cpu_set, ) }; Errno::result(res).and(Ok(cpuset)) } /// `clone` create a child process /// ([`clone(2)`](https://man7.org/linux/man-pages/man2/clone.2.html)) /// /// `stack` is a reference to an array which will hold the stack of the new /// process. Unlike when calling `clone(2)` from C, the provided stack /// address need not be the highest address of the region. Nix will take /// care of that requirement. The user only needs to provide a reference to /// a normally allocated buffer. pub fn clone( mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags, signal: Option<c_int>, ) -> Result<Pid> { extern "C" fn callback(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int } let res = unsafe { let combined = flags.bits() | signal.unwrap_or(0); let ptr = stack.as_mut_ptr().add(stack.len()); let ptr_aligned = ptr.sub(ptr as usize % 16); libc::clone( mem::transmute( callback as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32, ), ptr_aligned as *mut c_void, combined, &mut cb as *mut _ as *mut c_void, ) }; Errno::result(res).map(Pid::from_raw) } /// disassociate parts of the process execution context /// /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html) pub fn unshare(flags: CloneFlags) -> Result<()> { let res = unsafe { libc::unshare(flags.bits()) }; Errno::result(res).map(drop) } /// reassociate thread with a namespace /// /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html) pub fn setns(fd: RawFd, nstype: CloneFlags) -> Result<()> { let res = unsafe { libc::setns(fd, nstype.bits()) }; Errno::result(res).map(drop) } } /// Explicitly yield the processor to other threads. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html) pub fn sched_yield() -> Result<()> { let res = unsafe { libc::sched_yield() }; Errno::result(res).map(drop) }
{ unsafe { libc::CPU_SET(field, &mut self.cpu_set); } Ok(()) }
conditional_block
sched.rs
//! Execution scheduling //! //! See Also //! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html) use crate::{Errno, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::sched_linux_like::*; #[cfg(any(target_os = "android", target_os = "linux"))] mod sched_linux_like { use crate::errno::Errno; use libc::{self, c_int, c_void}; use std::mem; use std::option::Option; use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { /// The calling process and the child process run in the same /// memory space. CLONE_VM; /// The caller and the child process share the same filesystem /// information. CLONE_FS; /// The calling process and the child process share the same file /// descriptor table. CLONE_FILES; /// The calling process and the child process share the same table /// of signal handlers. CLONE_SIGHAND; /// If the calling process is being traced, then trace the child /// also. CLONE_PTRACE; /// The execution of the calling process is suspended until the /// child releases its virtual memory resources via a call to /// execve(2) or _exit(2) (as with vfork(2)). CLONE_VFORK; /// The parent of the new child (as returned by getppid(2)) /// will be the same as that of the calling process. CLONE_PARENT; /// The child is placed in the same thread group as the calling /// process. CLONE_THREAD; /// The cloned child is started in a new mount namespace. CLONE_NEWNS; /// The child and the calling process share a single list of System /// V semaphore adjustment values CLONE_SYSVSEM; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_SETTLS; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_PARENT_SETTID; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_CLEARTID; /// Unused since Linux 2.6.2 #[deprecated(since = "0.23.0", note = "Deprecated by Linux 2.6.2")] CLONE_DETACHED; /// A tracing process cannot force `CLONE_PTRACE` on this child /// process. CLONE_UNTRACED; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_SETTID; /// Create the process in a new cgroup namespace. CLONE_NEWCGROUP; /// Create the process in a new UTS namespace. CLONE_NEWUTS; /// Create the process in a new IPC namespace. CLONE_NEWIPC; /// Create the process in a new user namespace. CLONE_NEWUSER; /// Create the process in a new PID namespace. CLONE_NEWPID; /// Create the process in a new network namespace. CLONE_NEWNET; /// The new process shares an I/O context with the calling process. CLONE_IO; } } /// Type for the function executed by [`clone`]. pub type CloneCb<'a> = Box<dyn FnMut() -> isize + 'a>; /// CpuSet represent a bit-mask of CPUs. /// CpuSets are used by sched_setaffinity and /// sched_getaffinity for example. /// /// This is a wrapper around `libc::cpu_set_t`. #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct
{ cpu_set: libc::cpu_set_t, } impl CpuSet { /// Create a new and empty CpuSet. pub fn new() -> CpuSet { CpuSet { cpu_set: unsafe { mem::zeroed() }, } } /// Test to see if a CPU is in the CpuSet. /// `field` is the CPU id to test pub fn is_set(&self, field: usize) -> Result<bool> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) }) } } /// Add a CPU to CpuSet. /// `field` is the CPU id to add pub fn set(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_SET(field, &mut self.cpu_set); } Ok(()) } } /// Remove a CPU from CpuSet. /// `field` is the CPU id to remove pub fn unset(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_CLR(field, &mut self.cpu_set);} Ok(()) } } /// Return the maximum number of CPU in CpuSet pub const fn count() -> usize { 8 * mem::size_of::<libc::cpu_set_t>() } } impl Default for CpuSet { fn default() -> Self { Self::new() } } /// `sched_setaffinity` set a thread's CPU affinity mask /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html)) /// /// `pid` is the thread ID to update. /// If pid is zero, then the calling thread is updated. /// /// The `cpuset` argument specifies the set of CPUs on which the thread /// will be eligible to run. /// /// # Example /// /// Binding the current thread to CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::{CpuSet, sched_setaffinity}; /// use nix::unistd::Pid; /// /// let mut cpu_set = CpuSet::new(); /// cpu_set.set(0); /// sched_setaffinity(Pid::from_raw(0), &cpu_set); /// ``` pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> { let res = unsafe { libc::sched_setaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &cpuset.cpu_set, ) }; Errno::result(res).map(drop) } /// `sched_getaffinity` get a thread's CPU affinity mask /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html)) /// /// `pid` is the thread ID to check. /// If pid is zero, then the calling thread is checked. /// /// Returned `cpuset` is the set of CPUs on which the thread /// is eligible to run. /// /// # Example /// /// Checking if the current thread can run on CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::sched_getaffinity; /// use nix::unistd::Pid; /// /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap(); /// if cpu_set.is_set(0).unwrap() { /// println!("Current thread can run on CPU 0"); /// } /// ``` pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> { let mut cpuset = CpuSet::new(); let res = unsafe { libc::sched_getaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &mut cpuset.cpu_set, ) }; Errno::result(res).and(Ok(cpuset)) } /// `clone` create a child process /// ([`clone(2)`](https://man7.org/linux/man-pages/man2/clone.2.html)) /// /// `stack` is a reference to an array which will hold the stack of the new /// process. Unlike when calling `clone(2)` from C, the provided stack /// address need not be the highest address of the region. Nix will take /// care of that requirement. The user only needs to provide a reference to /// a normally allocated buffer. pub fn clone( mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags, signal: Option<c_int>, ) -> Result<Pid> { extern "C" fn callback(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int } let res = unsafe { let combined = flags.bits() | signal.unwrap_or(0); let ptr = stack.as_mut_ptr().add(stack.len()); let ptr_aligned = ptr.sub(ptr as usize % 16); libc::clone( mem::transmute( callback as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32, ), ptr_aligned as *mut c_void, combined, &mut cb as *mut _ as *mut c_void, ) }; Errno::result(res).map(Pid::from_raw) } /// disassociate parts of the process execution context /// /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html) pub fn unshare(flags: CloneFlags) -> Result<()> { let res = unsafe { libc::unshare(flags.bits()) }; Errno::result(res).map(drop) } /// reassociate thread with a namespace /// /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html) pub fn setns(fd: RawFd, nstype: CloneFlags) -> Result<()> { let res = unsafe { libc::setns(fd, nstype.bits()) }; Errno::result(res).map(drop) } } /// Explicitly yield the processor to other threads. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html) pub fn sched_yield() -> Result<()> { let res = unsafe { libc::sched_yield() }; Errno::result(res).map(drop) }
CpuSet
identifier_name
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive 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 Intrusive. If not, see <http://www.gnu.org/licenses/>. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(all(feature="nostd",not(test)))] use core::prelude::*; use std::mem; use std::ptr; #[allow(raw_pointer_derive)] #[derive(Debug)] pub struct Rawlink<T> { p: *mut T } impl<T> Copy for Rawlink<T> {} unsafe impl<T:'static+Send> Send for Rawlink<T> {} unsafe impl<T:Send+Sync> Sync for Rawlink<T> {} /// Rawlink is a type like Option<T> but for holding a raw pointer impl<T> Rawlink<T> { /// Like Option::None for Rawlink pub fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink pub fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n} } /// Convert the `Rawlink` into an Option value pub fn resolve<'a>(&self) -> Option<&'a T>
/// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() { None } else { Some(unsafe { mem::transmute(self.p) }) } } /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Rawlink<T> { #[inline] fn clone(&self) -> Rawlink<T> { Rawlink{p: self.p} } } impl<T> Default for Rawlink<T> { fn default() -> Rawlink<T> { Rawlink::none() } }
{ unsafe { mem::transmute(self.p.as_ref()) } }
identifier_body
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive 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 Intrusive. If not, see <http://www.gnu.org/licenses/>. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(all(feature="nostd",not(test)))] use core::prelude::*; use std::mem; use std::ptr; #[allow(raw_pointer_derive)] #[derive(Debug)] pub struct Rawlink<T> { p: *mut T } impl<T> Copy for Rawlink<T> {} unsafe impl<T:'static+Send> Send for Rawlink<T> {} unsafe impl<T:Send+Sync> Sync for Rawlink<T> {} /// Rawlink is a type like Option<T> but for holding a raw pointer impl<T> Rawlink<T> { /// Like Option::None for Rawlink pub fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink pub fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n} } /// Convert the `Rawlink` into an Option value pub fn resolve<'a>(&self) -> Option<&'a T> { unsafe { mem::transmute(self.p.as_ref()) } } /// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() {
None } else { Some(unsafe { mem::transmute(self.p) }) } } /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Rawlink<T> { #[inline] fn clone(&self) -> Rawlink<T> { Rawlink{p: self.p} } } impl<T> Default for Rawlink<T> { fn default() -> Rawlink<T> { Rawlink::none() } }
random_line_split
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive 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 Intrusive. If not, see <http://www.gnu.org/licenses/>. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(all(feature="nostd",not(test)))] use core::prelude::*; use std::mem; use std::ptr; #[allow(raw_pointer_derive)] #[derive(Debug)] pub struct Rawlink<T> { p: *mut T } impl<T> Copy for Rawlink<T> {} unsafe impl<T:'static+Send> Send for Rawlink<T> {} unsafe impl<T:Send+Sync> Sync for Rawlink<T> {} /// Rawlink is a type like Option<T> but for holding a raw pointer impl<T> Rawlink<T> { /// Like Option::None for Rawlink pub fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink pub fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n} } /// Convert the `Rawlink` into an Option value pub fn resolve<'a>(&self) -> Option<&'a T> { unsafe { mem::transmute(self.p.as_ref()) } } /// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() { None } else { Some(unsafe { mem::transmute(self.p) }) } } /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Rawlink<T> { #[inline] fn clone(&self) -> Rawlink<T> { Rawlink{p: self.p} } } impl<T> Default for Rawlink<T> { fn
() -> Rawlink<T> { Rawlink::none() } }
default
identifier_name
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive 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 Intrusive. If not, see <http://www.gnu.org/licenses/>. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(all(feature="nostd",not(test)))] use core::prelude::*; use std::mem; use std::ptr; #[allow(raw_pointer_derive)] #[derive(Debug)] pub struct Rawlink<T> { p: *mut T } impl<T> Copy for Rawlink<T> {} unsafe impl<T:'static+Send> Send for Rawlink<T> {} unsafe impl<T:Send+Sync> Sync for Rawlink<T> {} /// Rawlink is a type like Option<T> but for holding a raw pointer impl<T> Rawlink<T> { /// Like Option::None for Rawlink pub fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink pub fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n} } /// Convert the `Rawlink` into an Option value pub fn resolve<'a>(&self) -> Option<&'a T> { unsafe { mem::transmute(self.p.as_ref()) } } /// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() { None } else
} /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Rawlink<T> { #[inline] fn clone(&self) -> Rawlink<T> { Rawlink{p: self.p} } } impl<T> Default for Rawlink<T> { fn default() -> Rawlink<T> { Rawlink::none() } }
{ Some(unsafe { mem::transmute(self.p) }) }
conditional_block
match-vec-rvalue.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. // Tests that matching rvalues with drops does not crash. // pretty-expanded FIXME #23616 pub fn
() { match vec!(1, 2, 3) { x => { assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); } } }
main
identifier_name
match-vec-rvalue.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. // Tests that matching rvalues with drops does not crash. // pretty-expanded FIXME #23616 pub fn main() { match vec!(1, 2, 3) { x =>
} }
{ assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); }
conditional_block
match-vec-rvalue.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. // Tests that matching rvalues with drops does not crash. // pretty-expanded FIXME #23616 pub fn main()
{ match vec!(1, 2, 3) { x => { assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); } } }
identifier_body
match-vec-rvalue.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. // Tests that matching rvalues with drops does not crash. // pretty-expanded FIXME #23616 pub fn main() { match vec!(1, 2, 3) { x => { assert_eq!(x.len(), 3);
assert_eq!(x[2], 3); } } }
assert_eq!(x[0], 1); assert_eq!(x[1], 2);
random_line_split
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPlugin } pub fn get_plugin_name() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType>
impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return, } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) => { m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }, None => () } } }
{ match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } }
identifier_body
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPlugin } pub fn
() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } } impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return, } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) => { m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }, None => () } } }
get_plugin_name
identifier_name
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1);
WhoAmIPlugin } pub fn get_plugin_name() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } } impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return, } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) => { m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }, None => () } } }
pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin {
random_line_split
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPlugin } pub fn get_plugin_name() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } } impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return, } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) =>
, None => () } } }
{ m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }
conditional_block
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop { let mut input = String::new(); let result = io::stdin().read_line(&mut input); match result { Ok(byte_count) => if byte_count == 0 { break; }, Err(_) => { println!("error reading from stdin"); break; } } // Parse input let (city1, city2, distance) = scan_fmt!(&input, "{} to {} = {}", String, String, u32); city_table.add_distance(&city1.unwrap(), &city2.unwrap(), distance.unwrap()); } let min = calc_shortest_distance(&city_table); println!("Shortest route: {}", min); let max = calc_longest_distance(&city_table); println!("Longest route: {}", max); } struct CityDistances { cities: Vec<String>, distance_map: std::collections::HashMap<(usize, usize), u32>, } impl CityDistances { fn new() -> CityDistances { CityDistances{cities: Vec::new(), distance_map: std::collections::HashMap::new()} } fn
(&mut self, city: &str) -> usize { match self.cities.iter().position(|x| x == city) { Some(idx) => idx, None => { self.cities.push(String::from(city)); self.cities.len() - 1 } } } fn add_distance(&mut self, city1: &str, city2: &str, distance: u32) { let idx1 = self.find_city_idx(city1); let idx2 = self.find_city_idx(city2); // insert both possible tuples; we won't run out of memory and it makes things simpler self.distance_map.insert((idx1, idx2), distance); self.distance_map.insert((idx2, idx1), distance); } fn find_distance(&self, idx1: usize, idx2: usize) -> u32 { *self.distance_map.get(&(idx1, idx2)).unwrap() } } fn calc_shortest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .min().unwrap() } #[test] fn test_distance_struct() { let mut cities = CityDistances::new(); cities.add_distance("Hoth", "Tatooine", 1000); cities.add_distance("Hoth", "Coruscant", 300); cities.add_distance("Coruscant", "Tatooine", 900); assert_eq!(1000, cities.find_distance(0, 1)); assert_eq!(1000, cities.find_distance(1, 0)); assert_eq!(300, cities.find_distance(0, 2)); assert_eq!(300, cities.find_distance(2, 0)); assert_eq!(900, cities.find_distance(1, 2)); assert_eq!(900, cities.find_distance(2, 1)); } #[test] fn test_calc_shortest_distance() { let mut cities = CityDistances::new(); cities.add_distance("London", "Dublin", 464); cities.add_distance("London", "Belfast", 518); cities.add_distance("Dublin", "Belfast", 141); assert_eq!(605, calc_shortest_distance(&cities)); } // Part 2 fn calc_longest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .max().unwrap() }
find_city_idx
identifier_name
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop { let mut input = String::new(); let result = io::stdin().read_line(&mut input); match result { Ok(byte_count) => if byte_count == 0 { break; }, Err(_) => { println!("error reading from stdin"); break; } } // Parse input let (city1, city2, distance) = scan_fmt!(&input, "{} to {} = {}", String, String, u32); city_table.add_distance(&city1.unwrap(), &city2.unwrap(), distance.unwrap()); } let min = calc_shortest_distance(&city_table); println!("Shortest route: {}", min); let max = calc_longest_distance(&city_table); println!("Longest route: {}", max); } struct CityDistances { cities: Vec<String>, distance_map: std::collections::HashMap<(usize, usize), u32>, } impl CityDistances { fn new() -> CityDistances { CityDistances{cities: Vec::new(), distance_map: std::collections::HashMap::new()} } fn find_city_idx(&mut self, city: &str) -> usize { match self.cities.iter().position(|x| x == city) { Some(idx) => idx, None => { self.cities.push(String::from(city)); self.cities.len() - 1 } } } fn add_distance(&mut self, city1: &str, city2: &str, distance: u32) { let idx1 = self.find_city_idx(city1); let idx2 = self.find_city_idx(city2); // insert both possible tuples; we won't run out of memory and it makes things simpler self.distance_map.insert((idx1, idx2), distance); self.distance_map.insert((idx2, idx1), distance); } fn find_distance(&self, idx1: usize, idx2: usize) -> u32 { *self.distance_map.get(&(idx1, idx2)).unwrap() } } fn calc_shortest_distance(city_table: &CityDistances) -> u32
#[test] fn test_distance_struct() { let mut cities = CityDistances::new(); cities.add_distance("Hoth", "Tatooine", 1000); cities.add_distance("Hoth", "Coruscant", 300); cities.add_distance("Coruscant", "Tatooine", 900); assert_eq!(1000, cities.find_distance(0, 1)); assert_eq!(1000, cities.find_distance(1, 0)); assert_eq!(300, cities.find_distance(0, 2)); assert_eq!(300, cities.find_distance(2, 0)); assert_eq!(900, cities.find_distance(1, 2)); assert_eq!(900, cities.find_distance(2, 1)); } #[test] fn test_calc_shortest_distance() { let mut cities = CityDistances::new(); cities.add_distance("London", "Dublin", 464); cities.add_distance("London", "Belfast", 518); cities.add_distance("Dublin", "Belfast", 141); assert_eq!(605, calc_shortest_distance(&cities)); } // Part 2 fn calc_longest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .max().unwrap() }
{ let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .min().unwrap() }
identifier_body
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop {
match result { Ok(byte_count) => if byte_count == 0 { break; }, Err(_) => { println!("error reading from stdin"); break; } } // Parse input let (city1, city2, distance) = scan_fmt!(&input, "{} to {} = {}", String, String, u32); city_table.add_distance(&city1.unwrap(), &city2.unwrap(), distance.unwrap()); } let min = calc_shortest_distance(&city_table); println!("Shortest route: {}", min); let max = calc_longest_distance(&city_table); println!("Longest route: {}", max); } struct CityDistances { cities: Vec<String>, distance_map: std::collections::HashMap<(usize, usize), u32>, } impl CityDistances { fn new() -> CityDistances { CityDistances{cities: Vec::new(), distance_map: std::collections::HashMap::new()} } fn find_city_idx(&mut self, city: &str) -> usize { match self.cities.iter().position(|x| x == city) { Some(idx) => idx, None => { self.cities.push(String::from(city)); self.cities.len() - 1 } } } fn add_distance(&mut self, city1: &str, city2: &str, distance: u32) { let idx1 = self.find_city_idx(city1); let idx2 = self.find_city_idx(city2); // insert both possible tuples; we won't run out of memory and it makes things simpler self.distance_map.insert((idx1, idx2), distance); self.distance_map.insert((idx2, idx1), distance); } fn find_distance(&self, idx1: usize, idx2: usize) -> u32 { *self.distance_map.get(&(idx1, idx2)).unwrap() } } fn calc_shortest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .min().unwrap() } #[test] fn test_distance_struct() { let mut cities = CityDistances::new(); cities.add_distance("Hoth", "Tatooine", 1000); cities.add_distance("Hoth", "Coruscant", 300); cities.add_distance("Coruscant", "Tatooine", 900); assert_eq!(1000, cities.find_distance(0, 1)); assert_eq!(1000, cities.find_distance(1, 0)); assert_eq!(300, cities.find_distance(0, 2)); assert_eq!(300, cities.find_distance(2, 0)); assert_eq!(900, cities.find_distance(1, 2)); assert_eq!(900, cities.find_distance(2, 1)); } #[test] fn test_calc_shortest_distance() { let mut cities = CityDistances::new(); cities.add_distance("London", "Dublin", 464); cities.add_distance("London", "Belfast", 518); cities.add_distance("Dublin", "Belfast", 141); assert_eq!(605, calc_shortest_distance(&cities)); } // Part 2 fn calc_longest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .max().unwrap() }
let mut input = String::new(); let result = io::stdin().read_line(&mut input);
random_line_split
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cell::UnsafeCell; use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::rwlock::{self, RWLock}; extern "C" { #[thread_local] static __pthread_thread_id: abi::tid; } // Implement Mutex using an RWLock. This doesn't introduce any // performance overhead in this environment, as the operations would be // implemented identically. pub struct Mutex(RWLock); pub unsafe fn raw(m: &Mutex) -> *mut AtomicU32 { rwlock::raw(&m.0) } impl Mutex { pub const fn new() -> Mutex { Mutex(RWLock::new()) } pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } pub unsafe fn lock(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, } impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to acquire the lock. let lock = self.lock.get(); let recursion = self.recursion.get(); if let Err(old) = (*lock).compare_exchange( abi::LOCK_UNLOCKED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, Ordering::Acquire, Ordering::Relaxed, ) { // If we fail to acquire the lock, it may be the case // that we've already acquired it and may need to recurse. if old &!abi::LOCK_KERNEL_MANAGED.0 == __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0 { *recursion += 1; true } else { false } } else { // Success. assert_eq!(*recursion, 0, "Mutex has invalid recursion count"); true } } pub unsafe fn lock(&self) { if!self.try_lock() { // Call into the kernel to acquire a write lock. let lock = self.lock.get(); let subscription = abi::subscription { type_: abi::eventtype::LOCK_WRLOCK, union: abi::subscription_union { lock: abi::subscription_lock { lock: lock as *mut abi::lock, lock_scope: abi::scope::PRIVATE, }, }, ..mem::zeroed() }; let mut event: abi::event = mem::uninitialized(); let mut nevents: usize = mem::uninitialized(); let ret = abi::poll(&subscription, &mut event, 1, &mut nevents); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire mutex"); assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire mutex"); } } pub unsafe fn unlock(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed) &!abi::LOCK_KERNEL_MANAGED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, "This mutex is locked by a different thread" ); if *recursion > 0 { *recursion -= 1; } else if!(*lock) .compare_exchange( __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, abi::LOCK_UNLOCKED.0, Ordering::Release, Ordering::Relaxed, ) .is_ok()
} pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Recursion counter invalid"); } }
{ // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); }
conditional_block
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cell::UnsafeCell; use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::rwlock::{self, RWLock}; extern "C" { #[thread_local] static __pthread_thread_id: abi::tid; } // Implement Mutex using an RWLock. This doesn't introduce any // performance overhead in this environment, as the operations would be // implemented identically. pub struct Mutex(RWLock); pub unsafe fn raw(m: &Mutex) -> *mut AtomicU32 { rwlock::raw(&m.0) } impl Mutex { pub const fn new() -> Mutex { Mutex(RWLock::new()) } pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } pub unsafe fn lock(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, }
pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to acquire the lock. let lock = self.lock.get(); let recursion = self.recursion.get(); if let Err(old) = (*lock).compare_exchange( abi::LOCK_UNLOCKED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, Ordering::Acquire, Ordering::Relaxed, ) { // If we fail to acquire the lock, it may be the case // that we've already acquired it and may need to recurse. if old &!abi::LOCK_KERNEL_MANAGED.0 == __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0 { *recursion += 1; true } else { false } } else { // Success. assert_eq!(*recursion, 0, "Mutex has invalid recursion count"); true } } pub unsafe fn lock(&self) { if!self.try_lock() { // Call into the kernel to acquire a write lock. let lock = self.lock.get(); let subscription = abi::subscription { type_: abi::eventtype::LOCK_WRLOCK, union: abi::subscription_union { lock: abi::subscription_lock { lock: lock as *mut abi::lock, lock_scope: abi::scope::PRIVATE, }, }, ..mem::zeroed() }; let mut event: abi::event = mem::uninitialized(); let mut nevents: usize = mem::uninitialized(); let ret = abi::poll(&subscription, &mut event, 1, &mut nevents); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire mutex"); assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire mutex"); } } pub unsafe fn unlock(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed) &!abi::LOCK_KERNEL_MANAGED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, "This mutex is locked by a different thread" ); if *recursion > 0 { *recursion -= 1; } else if!(*lock) .compare_exchange( __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, abi::LOCK_UNLOCKED.0, Ordering::Release, Ordering::Relaxed, ) .is_ok() { // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); } } pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Recursion counter invalid"); } }
impl ReentrantMutex {
random_line_split
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cell::UnsafeCell; use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::rwlock::{self, RWLock}; extern "C" { #[thread_local] static __pthread_thread_id: abi::tid; } // Implement Mutex using an RWLock. This doesn't introduce any // performance overhead in this environment, as the operations would be // implemented identically. pub struct Mutex(RWLock); pub unsafe fn raw(m: &Mutex) -> *mut AtomicU32 { rwlock::raw(&m.0) } impl Mutex { pub const fn new() -> Mutex { Mutex(RWLock::new()) } pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } pub unsafe fn
(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, } impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to acquire the lock. let lock = self.lock.get(); let recursion = self.recursion.get(); if let Err(old) = (*lock).compare_exchange( abi::LOCK_UNLOCKED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, Ordering::Acquire, Ordering::Relaxed, ) { // If we fail to acquire the lock, it may be the case // that we've already acquired it and may need to recurse. if old &!abi::LOCK_KERNEL_MANAGED.0 == __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0 { *recursion += 1; true } else { false } } else { // Success. assert_eq!(*recursion, 0, "Mutex has invalid recursion count"); true } } pub unsafe fn lock(&self) { if!self.try_lock() { // Call into the kernel to acquire a write lock. let lock = self.lock.get(); let subscription = abi::subscription { type_: abi::eventtype::LOCK_WRLOCK, union: abi::subscription_union { lock: abi::subscription_lock { lock: lock as *mut abi::lock, lock_scope: abi::scope::PRIVATE, }, }, ..mem::zeroed() }; let mut event: abi::event = mem::uninitialized(); let mut nevents: usize = mem::uninitialized(); let ret = abi::poll(&subscription, &mut event, 1, &mut nevents); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire mutex"); assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire mutex"); } } pub unsafe fn unlock(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed) &!abi::LOCK_KERNEL_MANAGED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, "This mutex is locked by a different thread" ); if *recursion > 0 { *recursion -= 1; } else if!(*lock) .compare_exchange( __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, abi::LOCK_UNLOCKED.0, Ordering::Release, Ordering::Relaxed, ) .is_ok() { // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); } } pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Recursion counter invalid"); } }
lock
identifier_name
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cell::UnsafeCell; use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::rwlock::{self, RWLock}; extern "C" { #[thread_local] static __pthread_thread_id: abi::tid; } // Implement Mutex using an RWLock. This doesn't introduce any // performance overhead in this environment, as the operations would be // implemented identically. pub struct Mutex(RWLock); pub unsafe fn raw(m: &Mutex) -> *mut AtomicU32 { rwlock::raw(&m.0) } impl Mutex { pub const fn new() -> Mutex
pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } pub unsafe fn lock(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, } impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to acquire the lock. let lock = self.lock.get(); let recursion = self.recursion.get(); if let Err(old) = (*lock).compare_exchange( abi::LOCK_UNLOCKED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, Ordering::Acquire, Ordering::Relaxed, ) { // If we fail to acquire the lock, it may be the case // that we've already acquired it and may need to recurse. if old &!abi::LOCK_KERNEL_MANAGED.0 == __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0 { *recursion += 1; true } else { false } } else { // Success. assert_eq!(*recursion, 0, "Mutex has invalid recursion count"); true } } pub unsafe fn lock(&self) { if!self.try_lock() { // Call into the kernel to acquire a write lock. let lock = self.lock.get(); let subscription = abi::subscription { type_: abi::eventtype::LOCK_WRLOCK, union: abi::subscription_union { lock: abi::subscription_lock { lock: lock as *mut abi::lock, lock_scope: abi::scope::PRIVATE, }, }, ..mem::zeroed() }; let mut event: abi::event = mem::uninitialized(); let mut nevents: usize = mem::uninitialized(); let ret = abi::poll(&subscription, &mut event, 1, &mut nevents); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire mutex"); assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire mutex"); } } pub unsafe fn unlock(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed) &!abi::LOCK_KERNEL_MANAGED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, "This mutex is locked by a different thread" ); if *recursion > 0 { *recursion -= 1; } else if!(*lock) .compare_exchange( __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, abi::LOCK_UNLOCKED.0, Ordering::Release, Ordering::Relaxed, ) .is_ok() { // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); } } pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Recursion counter invalid"); } }
{ Mutex(RWLock::new()) }
identifier_body
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only full descending stacks are supported. /// Represents the different types of stacks that exist. #[allow(dead_code)] pub enum StackType { /// The value currently pointed to is used and the stack grows downward. FullDescending, /// The value currently pointed to is not used and the stack grows downward. EmptyDescending, /// The value currently pointed to is used and the stack grows upward. FullAscending, /// The value currently pointed to is not used and the stack grows upward. EmptyAscending } /// Determines the type of accesses possible for this stack. #[derive(PartialEq)] pub enum AccessType { /// The stack can be accessed by usermode code. UserAccessible, /// The stack can only be accessed by the kernel. KernelOnly } /// Represents a stack. pub struct Stack { /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: VirtualAddress, /// The access type for this stack. access_type: AccessType } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { /// Pushes the given value to the stack pointed to in the given address /// space. pub fn push_in<T>( address_space: &mut AddressSpace, stack_pointer: &mut VirtualAddress, value: T ) { match arch::Current::STACK_TYPE { StackType::FullDescending => { *stack_pointer -= size_of::<T>(); unsafe { address_space.write_val(value, *stack_pointer); } }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Creates a new stack of size zero with the given start address. pub fn new( initial_size: usize, max_size: usize, start_address: VirtualAddress, access_type: AccessType, mut address_space: Option<&mut AddressSpace> ) -> Stack { let mut stack = match arch::Current::STACK_TYPE { StackType::FullDescending => Stack { top_address: start_address + max_size, bottom_address: start_address + max_size, max_size, base_stack_pointer: start_address + max_size, access_type }, _ => unimplemented!("Currently only Full Descending stacks are implemented") }; if let Some(ref mut address_space) = address_space { let mut flags = READABLE | WRITABLE; if stack.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); stack } /// Grows the stack by the given amount. pub fn grow(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = max( self.top_address - self.max_size, self.bottom_address - amount ); let mut flags = READABLE | WRITABLE; if self.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let first_page_to_map = new_bottom.page_num(); // This should be one less, but the range is exclusive. let last_page_to_map = self.bottom_address.page_num(); // TODO: flags shouldn't be passed, it should be segment checked instead. let mut map_fn = |page_address, flags| match address_space { Some(ref mut address_space) => address_space.map_page(page_address), None => arch::Current::map_page(page_address, flags) }; for page_num in first_page_to_map..last_page_to_map { map_fn(VirtualAddress::from_page_num(page_num), flags); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Shrinks the stack by the given amount. pub fn shrink(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = min(self.top_address, self.bottom_address + amount); let first_page_to_unmap = self.bottom_address.page_num(); // This should be one less, but the range is exclusive. let last_page_to_unmap = new_bottom.page_num(); let mut unmap_fn = |page_address| unsafe { match address_space { Some(ref mut address_space) => address_space.unmap_page(page_address), None => arch::Current::unmap_page(page_address) } }; for page_num in first_page_to_unmap..last_page_to_unmap { unmap_fn(VirtualAddress::from_page_num(page_num)); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Resizes the stack to the given size. pub fn resize(&mut self, new_size: usize, address_space: Option<&mut AddressSpace>)
}
{ let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } }
identifier_body
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only full descending stacks are supported. /// Represents the different types of stacks that exist. #[allow(dead_code)] pub enum StackType { /// The value currently pointed to is used and the stack grows downward. FullDescending, /// The value currently pointed to is not used and the stack grows downward. EmptyDescending, /// The value currently pointed to is used and the stack grows upward. FullAscending, /// The value currently pointed to is not used and the stack grows upward. EmptyAscending } /// Determines the type of accesses possible for this stack. #[derive(PartialEq)] pub enum AccessType { /// The stack can be accessed by usermode code. UserAccessible, /// The stack can only be accessed by the kernel. KernelOnly } /// Represents a stack. pub struct Stack { /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: VirtualAddress, /// The access type for this stack. access_type: AccessType } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { /// Pushes the given value to the stack pointed to in the given address /// space. pub fn push_in<T>( address_space: &mut AddressSpace, stack_pointer: &mut VirtualAddress, value: T ) { match arch::Current::STACK_TYPE { StackType::FullDescending => { *stack_pointer -= size_of::<T>(); unsafe { address_space.write_val(value, *stack_pointer); } }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Creates a new stack of size zero with the given start address. pub fn new( initial_size: usize, max_size: usize, start_address: VirtualAddress, access_type: AccessType, mut address_space: Option<&mut AddressSpace> ) -> Stack { let mut stack = match arch::Current::STACK_TYPE { StackType::FullDescending => Stack { top_address: start_address + max_size, bottom_address: start_address + max_size, max_size, base_stack_pointer: start_address + max_size, access_type }, _ => unimplemented!("Currently only Full Descending stacks are implemented") }; if let Some(ref mut address_space) = address_space { let mut flags = READABLE | WRITABLE; if stack.access_type == AccessType::UserAccessible
let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); stack } /// Grows the stack by the given amount. pub fn grow(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = max( self.top_address - self.max_size, self.bottom_address - amount ); let mut flags = READABLE | WRITABLE; if self.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let first_page_to_map = new_bottom.page_num(); // This should be one less, but the range is exclusive. let last_page_to_map = self.bottom_address.page_num(); // TODO: flags shouldn't be passed, it should be segment checked instead. let mut map_fn = |page_address, flags| match address_space { Some(ref mut address_space) => address_space.map_page(page_address), None => arch::Current::map_page(page_address, flags) }; for page_num in first_page_to_map..last_page_to_map { map_fn(VirtualAddress::from_page_num(page_num), flags); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Shrinks the stack by the given amount. pub fn shrink(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = min(self.top_address, self.bottom_address + amount); let first_page_to_unmap = self.bottom_address.page_num(); // This should be one less, but the range is exclusive. let last_page_to_unmap = new_bottom.page_num(); let mut unmap_fn = |page_address| unsafe { match address_space { Some(ref mut address_space) => address_space.unmap_page(page_address), None => arch::Current::unmap_page(page_address) } }; for page_num in first_page_to_unmap..last_page_to_unmap { unmap_fn(VirtualAddress::from_page_num(page_num)); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Resizes the stack to the given size. pub fn resize(&mut self, new_size: usize, address_space: Option<&mut AddressSpace>) { let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } } }
{ flags |= USER_ACCESSIBLE; }
conditional_block
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only full descending stacks are supported. /// Represents the different types of stacks that exist. #[allow(dead_code)] pub enum StackType { /// The value currently pointed to is used and the stack grows downward. FullDescending, /// The value currently pointed to is not used and the stack grows downward. EmptyDescending, /// The value currently pointed to is used and the stack grows upward. FullAscending, /// The value currently pointed to is not used and the stack grows upward. EmptyAscending } /// Determines the type of accesses possible for this stack. #[derive(PartialEq)] pub enum AccessType { /// The stack can be accessed by usermode code. UserAccessible, /// The stack can only be accessed by the kernel. KernelOnly } /// Represents a stack. pub struct Stack { /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: VirtualAddress, /// The access type for this stack. access_type: AccessType } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f,
"Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { /// Pushes the given value to the stack pointed to in the given address /// space. pub fn push_in<T>( address_space: &mut AddressSpace, stack_pointer: &mut VirtualAddress, value: T ) { match arch::Current::STACK_TYPE { StackType::FullDescending => { *stack_pointer -= size_of::<T>(); unsafe { address_space.write_val(value, *stack_pointer); } }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Creates a new stack of size zero with the given start address. pub fn new( initial_size: usize, max_size: usize, start_address: VirtualAddress, access_type: AccessType, mut address_space: Option<&mut AddressSpace> ) -> Stack { let mut stack = match arch::Current::STACK_TYPE { StackType::FullDescending => Stack { top_address: start_address + max_size, bottom_address: start_address + max_size, max_size, base_stack_pointer: start_address + max_size, access_type }, _ => unimplemented!("Currently only Full Descending stacks are implemented") }; if let Some(ref mut address_space) = address_space { let mut flags = READABLE | WRITABLE; if stack.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); stack } /// Grows the stack by the given amount. pub fn grow(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = max( self.top_address - self.max_size, self.bottom_address - amount ); let mut flags = READABLE | WRITABLE; if self.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let first_page_to_map = new_bottom.page_num(); // This should be one less, but the range is exclusive. let last_page_to_map = self.bottom_address.page_num(); // TODO: flags shouldn't be passed, it should be segment checked instead. let mut map_fn = |page_address, flags| match address_space { Some(ref mut address_space) => address_space.map_page(page_address), None => arch::Current::map_page(page_address, flags) }; for page_num in first_page_to_map..last_page_to_map { map_fn(VirtualAddress::from_page_num(page_num), flags); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Shrinks the stack by the given amount. pub fn shrink(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = min(self.top_address, self.bottom_address + amount); let first_page_to_unmap = self.bottom_address.page_num(); // This should be one less, but the range is exclusive. let last_page_to_unmap = new_bottom.page_num(); let mut unmap_fn = |page_address| unsafe { match address_space { Some(ref mut address_space) => address_space.unmap_page(page_address), None => arch::Current::unmap_page(page_address) } }; for page_num in first_page_to_unmap..last_page_to_unmap { unmap_fn(VirtualAddress::from_page_num(page_num)); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Resizes the stack to the given size. pub fn resize(&mut self, new_size: usize, address_space: Option<&mut AddressSpace>) { let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } } }
random_line_split
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only full descending stacks are supported. /// Represents the different types of stacks that exist. #[allow(dead_code)] pub enum StackType { /// The value currently pointed to is used and the stack grows downward. FullDescending, /// The value currently pointed to is not used and the stack grows downward. EmptyDescending, /// The value currently pointed to is used and the stack grows upward. FullAscending, /// The value currently pointed to is not used and the stack grows upward. EmptyAscending } /// Determines the type of accesses possible for this stack. #[derive(PartialEq)] pub enum AccessType { /// The stack can be accessed by usermode code. UserAccessible, /// The stack can only be accessed by the kernel. KernelOnly } /// Represents a stack. pub struct
{ /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: VirtualAddress, /// The access type for this stack. access_type: AccessType } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { /// Pushes the given value to the stack pointed to in the given address /// space. pub fn push_in<T>( address_space: &mut AddressSpace, stack_pointer: &mut VirtualAddress, value: T ) { match arch::Current::STACK_TYPE { StackType::FullDescending => { *stack_pointer -= size_of::<T>(); unsafe { address_space.write_val(value, *stack_pointer); } }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Creates a new stack of size zero with the given start address. pub fn new( initial_size: usize, max_size: usize, start_address: VirtualAddress, access_type: AccessType, mut address_space: Option<&mut AddressSpace> ) -> Stack { let mut stack = match arch::Current::STACK_TYPE { StackType::FullDescending => Stack { top_address: start_address + max_size, bottom_address: start_address + max_size, max_size, base_stack_pointer: start_address + max_size, access_type }, _ => unimplemented!("Currently only Full Descending stacks are implemented") }; if let Some(ref mut address_space) = address_space { let mut flags = READABLE | WRITABLE; if stack.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); stack } /// Grows the stack by the given amount. pub fn grow(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = max( self.top_address - self.max_size, self.bottom_address - amount ); let mut flags = READABLE | WRITABLE; if self.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let first_page_to_map = new_bottom.page_num(); // This should be one less, but the range is exclusive. let last_page_to_map = self.bottom_address.page_num(); // TODO: flags shouldn't be passed, it should be segment checked instead. let mut map_fn = |page_address, flags| match address_space { Some(ref mut address_space) => address_space.map_page(page_address), None => arch::Current::map_page(page_address, flags) }; for page_num in first_page_to_map..last_page_to_map { map_fn(VirtualAddress::from_page_num(page_num), flags); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Shrinks the stack by the given amount. pub fn shrink(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = min(self.top_address, self.bottom_address + amount); let first_page_to_unmap = self.bottom_address.page_num(); // This should be one less, but the range is exclusive. let last_page_to_unmap = new_bottom.page_num(); let mut unmap_fn = |page_address| unsafe { match address_space { Some(ref mut address_space) => address_space.unmap_page(page_address), None => arch::Current::unmap_page(page_address) } }; for page_num in first_page_to_unmap..last_page_to_unmap { unmap_fn(VirtualAddress::from_page_num(page_num)); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Resizes the stack to the given size. pub fn resize(&mut self, new_size: usize, address_space: Option<&mut AddressSpace>) { let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } } }
Stack
identifier_name
animations.rs
//! Animation effects embedded in the game world. use crate::{location::Location, world::World}; use calx::{ease, project, CellSpace, ProjectVec, Space}; use calx_ecs::Entity; use euclid::{vec2, Vector2D, Vector3D}; use serde::{Deserialize, Serialize}; /// Location with a non-integer offset delta. /// /// Use for tweened animations. #[derive(Copy, Clone, PartialEq, Debug, Default)] pub struct LerpLocation { pub location: Location, pub offset: PhysicsVector, } impl From<Location> for LerpLocation { fn from(location: Location) -> LerpLocation { LerpLocation { location, offset: Default::default(), } } } impl World { pub fn get_anim_tick(&self) -> u64 { self.flags.anim_tick } pub fn anim(&self, e: Entity) -> Option<&Anim> { self.ecs.anim.get(e) } pub(crate) fn anim_mut(&mut self, e: Entity) -> Option<&mut Anim> { self.ecs.anim.get_mut(e) } /// Advance animations without ticking the world logic. /// /// Use this when waiting for player input to finish pending animations. pub fn tick_anims(&mut self) { self.flags.anim_tick += 1; } /// Return whether entity is a transient effect. pub fn is_fx(&self, e: Entity) -> bool { self.anim(e) .map_or(false, |a| a.state.is_transient_anim_state()) } /// Return a location structure that includes the entity's animation displacement pub fn
(&self, e: Entity) -> Option<LerpLocation> { if let Some(location) = self.location(e) { Some(LerpLocation { location, offset: self.lerp_offset(e), }) } else { None } } pub fn lerp_offset(&self, e: Entity) -> PhysicsVector { if let Some(location) = self.location(e) { if let Some(anim) = self.anim(e) { let frame = (self.get_anim_tick() - anim.tween_start) as u32; if frame < anim.tween_duration { if let Some(vec) = location.v2_at(anim.tween_from) { let offset = vec.project::<PhysicsSpace>().to_3d(); let scalar = frame as f32 / anim.tween_duration as f32; let scalar = ease::cubic_in_out(1.0 - scalar); return offset * scalar; } } } } Default::default() } } /// Entity animation state. #[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)] pub struct Anim { pub tween_from: Location, /// Anim_tick when tweening started pub tween_start: u64, /// How many frames does the tweening take pub tween_duration: u32, /// Anim_tick when the animation started pub anim_start: u64, /// World tick when anim should be cleaned up. /// /// NB: Both entity creation and destruction must use world logic and world clock, not the /// undeterministic animation clock. Deleting entities at unspecified time points through /// animation logic can inject indeterminism in world progress. pub anim_done_world_tick: Option<u64>, pub state: AnimState, } #[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)] pub enum AnimState { /// Mob decorator, doing nothing in particular Mob, /// Show mob hurt animation MobHurt, /// Show mob blocking autoexplore animation MobBlocks, /// A death gib Gib, /// Puff of smoke Smoke, /// Single-cell explosion Explosion, /// Pre-exploded fireball Firespell, } impl AnimState { /// This is a state that belongs to an animation that gets removed, not a status marker for a /// permanent entity. pub fn is_transient_anim_state(self) -> bool { use AnimState::*; match self { Mob | MobHurt | MobBlocks => false, Gib | Smoke | Explosion | Firespell => true, } } } impl Default for AnimState { fn default() -> Self { AnimState::Mob } } /// 3D physics space, used for eg. lighting. pub struct PhysicsSpace; impl Space for PhysicsSpace { type T = f32; } // | 1 -1 | // | -1/2 -1/2 | // NB: Produces a 2D PhysicsSpace vector, you need to 3d-ify it manually. impl project::From<CellSpace> for PhysicsSpace { fn vec_from(vec: Vector2D<<CellSpace as Space>::T, CellSpace>) -> Vector2D<Self::T, Self> { let vec = vec.cast::<f32>(); vec2(vec.x - vec.y, -vec.x / 2.0 - vec.y / 2.0) } } // | 1/2 -1 | // | -1/2 -1 | impl project::From32<PhysicsSpace> for CellSpace { fn vec_from( vec: Vector3D<<PhysicsSpace as Space>::T, PhysicsSpace>, ) -> Vector2D<Self::T, Self> { vec2( (vec.x / 2.0 - vec.y).round() as i32, (-vec.x / 2.0 - vec.y).round() as i32, ) } } pub type PhysicsVector = Vector3D<f32, PhysicsSpace>;
lerp_location
identifier_name
animations.rs
use euclid::{vec2, Vector2D, Vector3D}; use serde::{Deserialize, Serialize}; /// Location with a non-integer offset delta. /// /// Use for tweened animations. #[derive(Copy, Clone, PartialEq, Debug, Default)] pub struct LerpLocation { pub location: Location, pub offset: PhysicsVector, } impl From<Location> for LerpLocation { fn from(location: Location) -> LerpLocation { LerpLocation { location, offset: Default::default(), } } } impl World { pub fn get_anim_tick(&self) -> u64 { self.flags.anim_tick } pub fn anim(&self, e: Entity) -> Option<&Anim> { self.ecs.anim.get(e) } pub(crate) fn anim_mut(&mut self, e: Entity) -> Option<&mut Anim> { self.ecs.anim.get_mut(e) } /// Advance animations without ticking the world logic. /// /// Use this when waiting for player input to finish pending animations. pub fn tick_anims(&mut self) { self.flags.anim_tick += 1; } /// Return whether entity is a transient effect. pub fn is_fx(&self, e: Entity) -> bool { self.anim(e) .map_or(false, |a| a.state.is_transient_anim_state()) } /// Return a location structure that includes the entity's animation displacement pub fn lerp_location(&self, e: Entity) -> Option<LerpLocation> { if let Some(location) = self.location(e) { Some(LerpLocation { location, offset: self.lerp_offset(e), }) } else { None } } pub fn lerp_offset(&self, e: Entity) -> PhysicsVector { if let Some(location) = self.location(e) { if let Some(anim) = self.anim(e) { let frame = (self.get_anim_tick() - anim.tween_start) as u32; if frame < anim.tween_duration { if let Some(vec) = location.v2_at(anim.tween_from) { let offset = vec.project::<PhysicsSpace>().to_3d(); let scalar = frame as f32 / anim.tween_duration as f32; let scalar = ease::cubic_in_out(1.0 - scalar); return offset * scalar; } } } } Default::default() } } /// Entity animation state. #[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)] pub struct Anim { pub tween_from: Location, /// Anim_tick when tweening started pub tween_start: u64, /// How many frames does the tweening take pub tween_duration: u32, /// Anim_tick when the animation started pub anim_start: u64, /// World tick when anim should be cleaned up. /// /// NB: Both entity creation and destruction must use world logic and world clock, not the /// undeterministic animation clock. Deleting entities at unspecified time points through /// animation logic can inject indeterminism in world progress. pub anim_done_world_tick: Option<u64>, pub state: AnimState, } #[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)] pub enum AnimState { /// Mob decorator, doing nothing in particular Mob, /// Show mob hurt animation MobHurt, /// Show mob blocking autoexplore animation MobBlocks, /// A death gib Gib, /// Puff of smoke Smoke, /// Single-cell explosion Explosion, /// Pre-exploded fireball Firespell, } impl AnimState { /// This is a state that belongs to an animation that gets removed, not a status marker for a /// permanent entity. pub fn is_transient_anim_state(self) -> bool { use AnimState::*; match self { Mob | MobHurt | MobBlocks => false, Gib | Smoke | Explosion | Firespell => true, } } } impl Default for AnimState { fn default() -> Self { AnimState::Mob } } /// 3D physics space, used for eg. lighting. pub struct PhysicsSpace; impl Space for PhysicsSpace { type T = f32; } // | 1 -1 | // | -1/2 -1/2 | // NB: Produces a 2D PhysicsSpace vector, you need to 3d-ify it manually. impl project::From<CellSpace> for PhysicsSpace { fn vec_from(vec: Vector2D<<CellSpace as Space>::T, CellSpace>) -> Vector2D<Self::T, Self> { let vec = vec.cast::<f32>(); vec2(vec.x - vec.y, -vec.x / 2.0 - vec.y / 2.0) } } // | 1/2 -1 | // | -1/2 -1 | impl project::From32<PhysicsSpace> for CellSpace { fn vec_from( vec: Vector3D<<PhysicsSpace as Space>::T, PhysicsSpace>, ) -> Vector2D<Self::T, Self> { vec2( (vec.x / 2.0 - vec.y).round() as i32, (-vec.x / 2.0 - vec.y).round() as i32, ) } } pub type PhysicsVector = Vector3D<f32, PhysicsSpace>;
//! Animation effects embedded in the game world. use crate::{location::Location, world::World}; use calx::{ease, project, CellSpace, ProjectVec, Space}; use calx_ecs::Entity;
random_line_split
animations.rs
//! Animation effects embedded in the game world. use crate::{location::Location, world::World}; use calx::{ease, project, CellSpace, ProjectVec, Space}; use calx_ecs::Entity; use euclid::{vec2, Vector2D, Vector3D}; use serde::{Deserialize, Serialize}; /// Location with a non-integer offset delta. /// /// Use for tweened animations. #[derive(Copy, Clone, PartialEq, Debug, Default)] pub struct LerpLocation { pub location: Location, pub offset: PhysicsVector, } impl From<Location> for LerpLocation { fn from(location: Location) -> LerpLocation { LerpLocation { location, offset: Default::default(), } } } impl World { pub fn get_anim_tick(&self) -> u64 { self.flags.anim_tick } pub fn anim(&self, e: Entity) -> Option<&Anim> { self.ecs.anim.get(e) } pub(crate) fn anim_mut(&mut self, e: Entity) -> Option<&mut Anim> { self.ecs.anim.get_mut(e) } /// Advance animations without ticking the world logic. /// /// Use this when waiting for player input to finish pending animations. pub fn tick_anims(&mut self) { self.flags.anim_tick += 1; } /// Return whether entity is a transient effect. pub fn is_fx(&self, e: Entity) -> bool { self.anim(e) .map_or(false, |a| a.state.is_transient_anim_state()) } /// Return a location structure that includes the entity's animation displacement pub fn lerp_location(&self, e: Entity) -> Option<LerpLocation> { if let Some(location) = self.location(e) { Some(LerpLocation { location, offset: self.lerp_offset(e), }) } else
} pub fn lerp_offset(&self, e: Entity) -> PhysicsVector { if let Some(location) = self.location(e) { if let Some(anim) = self.anim(e) { let frame = (self.get_anim_tick() - anim.tween_start) as u32; if frame < anim.tween_duration { if let Some(vec) = location.v2_at(anim.tween_from) { let offset = vec.project::<PhysicsSpace>().to_3d(); let scalar = frame as f32 / anim.tween_duration as f32; let scalar = ease::cubic_in_out(1.0 - scalar); return offset * scalar; } } } } Default::default() } } /// Entity animation state. #[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)] pub struct Anim { pub tween_from: Location, /// Anim_tick when tweening started pub tween_start: u64, /// How many frames does the tweening take pub tween_duration: u32, /// Anim_tick when the animation started pub anim_start: u64, /// World tick when anim should be cleaned up. /// /// NB: Both entity creation and destruction must use world logic and world clock, not the /// undeterministic animation clock. Deleting entities at unspecified time points through /// animation logic can inject indeterminism in world progress. pub anim_done_world_tick: Option<u64>, pub state: AnimState, } #[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)] pub enum AnimState { /// Mob decorator, doing nothing in particular Mob, /// Show mob hurt animation MobHurt, /// Show mob blocking autoexplore animation MobBlocks, /// A death gib Gib, /// Puff of smoke Smoke, /// Single-cell explosion Explosion, /// Pre-exploded fireball Firespell, } impl AnimState { /// This is a state that belongs to an animation that gets removed, not a status marker for a /// permanent entity. pub fn is_transient_anim_state(self) -> bool { use AnimState::*; match self { Mob | MobHurt | MobBlocks => false, Gib | Smoke | Explosion | Firespell => true, } } } impl Default for AnimState { fn default() -> Self { AnimState::Mob } } /// 3D physics space, used for eg. lighting. pub struct PhysicsSpace; impl Space for PhysicsSpace { type T = f32; } // | 1 -1 | // | -1/2 -1/2 | // NB: Produces a 2D PhysicsSpace vector, you need to 3d-ify it manually. impl project::From<CellSpace> for PhysicsSpace { fn vec_from(vec: Vector2D<<CellSpace as Space>::T, CellSpace>) -> Vector2D<Self::T, Self> { let vec = vec.cast::<f32>(); vec2(vec.x - vec.y, -vec.x / 2.0 - vec.y / 2.0) } } // | 1/2 -1 | // | -1/2 -1 | impl project::From32<PhysicsSpace> for CellSpace { fn vec_from( vec: Vector3D<<PhysicsSpace as Space>::T, PhysicsSpace>, ) -> Vector2D<Self::T, Self> { vec2( (vec.x / 2.0 - vec.y).round() as i32, (-vec.x / 2.0 - vec.y).round() as i32, ) } } pub type PhysicsVector = Vector3D<f32, PhysicsSpace>;
{ None }
conditional_block
errors.rs
use rstest::*; #[fixture] pub fn fixture() -> u32 { 42 } #[fixture] fn error_inner(fixture: u32) { let a: u32 = ""; } #[fixture] fn error_cannot_resolve_fixture(no_fixture: u32) { } #[fixture] fn error_fixture_wrong_type(fixture: String) { } #[fixture(not_a_fixture(24))] fn error_inject_an_invalid_fixture(fixture: String) { } #[fixture] fn name() -> &'static str { "name" } #[fixture] fn f(name: &str) -> String { name.to_owned() } #[fixture(f("first"), f("second"))] fn error_inject_a_fixture_more_than_once(f: String)
#[fixture] #[once] async fn error_async_once_fixture() { } #[fixture] #[once] fn error_generics_once_fixture<T: std::fmt::Debug>() -> T { 42 } #[fixture] #[once] fn error_generics_once_fixture() -> impl Iterator<Item: u32> { std::iter::once(42) }
{ }
identifier_body
errors.rs
use rstest::*; #[fixture] pub fn fixture() -> u32 { 42 } #[fixture] fn error_inner(fixture: u32) { let a: u32 = ""; } #[fixture] fn error_cannot_resolve_fixture(no_fixture: u32) { } #[fixture] fn error_fixture_wrong_type(fixture: String) { } #[fixture(not_a_fixture(24))] fn error_inject_an_invalid_fixture(fixture: String) { } #[fixture] fn name() -> &'static str { "name" } #[fixture] fn f(name: &str) -> String { name.to_owned() } #[fixture(f("first"), f("second"))] fn error_inject_a_fixture_more_than_once(f: String) { } #[fixture] #[once] async fn error_async_once_fixture() { } #[fixture] #[once] fn error_generics_once_fixture<T: std::fmt::Debug>() -> T { 42
fn error_generics_once_fixture() -> impl Iterator<Item: u32> { std::iter::once(42) }
} #[fixture] #[once]
random_line_split
errors.rs
use rstest::*; #[fixture] pub fn fixture() -> u32 { 42 } #[fixture] fn error_inner(fixture: u32) { let a: u32 = ""; } #[fixture] fn error_cannot_resolve_fixture(no_fixture: u32) { } #[fixture] fn error_fixture_wrong_type(fixture: String) { } #[fixture(not_a_fixture(24))] fn error_inject_an_invalid_fixture(fixture: String) { } #[fixture] fn name() -> &'static str { "name" } #[fixture] fn
(name: &str) -> String { name.to_owned() } #[fixture(f("first"), f("second"))] fn error_inject_a_fixture_more_than_once(f: String) { } #[fixture] #[once] async fn error_async_once_fixture() { } #[fixture] #[once] fn error_generics_once_fixture<T: std::fmt::Debug>() -> T { 42 } #[fixture] #[once] fn error_generics_once_fixture() -> impl Iterator<Item: u32> { std::iter::once(42) }
f
identifier_name
multipart.rs
use std::fmt; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::PathBuf; use mime_guess; use crate::error::Result; use crate::http::plus::random_alphanumeric; const BOUNDARY_LEN: usize = 32; fn gen_boundary() -> String { random_alphanumeric(BOUNDARY_LEN) } use crate::http::mime::{self, Mime}; /// Create a structure to process the multipart/form-data data format for /// the client to initiate the request. /// /// # Examples /// /// ``` /// use sincere::http::plus::client::Multipart; /// /// let mut multipart = Multipart::new(); /// /// multipart.add_text("hello", "world"); /// /// let (boundary, data) = multipart.convert().unwrap(); /// ``` /// #[derive(Debug, Default)] pub struct Multipart<'a> { fields: Vec<Field<'a>>, } impl<'a> Multipart<'a> { /// Returns the empty `Multipart` set. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// ``` #[inline] pub fn new() -> Multipart<'a> { Multipart { fields: Vec::new() } } /// Add text 'key-value' into `Multipart`. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_text("hello", "world"); /// ``` #[inline] pub fn add_text<V>(&mut self, name: V, value: V) -> &mut Self where V: Into<String>, { let filed = Field { name: name.into(), data: Data::Text(value.into()), }; self.fields.push(filed); self } /// Add file into `Multipart`. /// /// # Examples /// /// ```no_test /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_file("hello.rs", "/aaa/bbb"); /// ``` #[inline] pub fn add_file<V, P>(&mut self, name: V, path: P) -> &mut Self where V: Into<String>, P: Into<PathBuf>, { let filed = Field { name: name.into(), data: Data::File(path.into()), }; self.fields.push(filed); self } /// Add reader stream into `Multipart`. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let temp = r#"{"hello": "world"}"#.as_bytes(); /// let reader = ::std::io::Cursor::new(temp); /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_stream("ddd", reader, Some("hello.rs"), Some(sincere::http::mime::APPLICATION_JSON)); /// ``` #[inline] pub fn add_stream<V, R>( &mut self, name: V, stream: R, filename: Option<V>, mime: Option<Mime>, ) -> &mut Self where R: Read + 'a, V: Into<String>, { let filed = Field { name: name.into(), data: Data::Stream(Stream { content_type: mime.unwrap_or(mime::APPLICATION_OCTET_STREAM), filename: filename.map(|f| f.into()), stream: Box::new(stream), }), }; self.fields.push(filed); self } /// Convert `Multipart` to client boundary and body. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_text("hello", "world"); /// /// let (boundary, data) = multipart.convert().unwrap(); /// ``` pub fn convert(&mut self) -> Result<(String, Vec<u8>)>
"{}\r\nContent-Disposition: form-data; name=\"{}\"", boundary, field.name )?; if let Some(filename) = filename { write!(buf, "; filename=\"{}\"", filename)?; } write!(buf, "\r\nContent-Type: {}\r\n\r\n", content_type)?; let mut temp: Vec<u8> = Vec::new(); file.read_to_end(&mut temp)?; buf.extend(temp); } Data::Stream(mut stream) => { write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"", boundary, field.name )?; if let Some(filename) = stream.filename { write!(buf, "; filename=\"{}\"", filename)?; } write!(buf, "\r\nContent-Type: {}\r\n\r\n", stream.content_type)?; let mut temp: Vec<u8> = Vec::new(); stream.stream.read_to_end(&mut temp)?; buf.extend(temp); } } } boundary.push_str("--"); buf.extend(boundary.as_bytes()); Ok((boundary[4..boundary.len() - 2].to_string(), buf)) } } #[derive(Debug)] struct Field<'a> { name: String, data: Data<'a>, } enum Data<'a> { Text(String), File(PathBuf), Stream(Stream<'a>), } impl<'a> fmt::Debug for Data<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Data::Text(ref value) => write!(f, "Data::Text({:?})", value), Data::File(ref path) => write!(f, "Data::File({:?})", path), Data::Stream(_) => f.write_str("Data::Stream(Box<Read>)"), } } } struct Stream<'a> { filename: Option<String>, content_type: Mime, stream: Box<dyn Read + 'a>, } fn mime_filename(path: &PathBuf) -> (Mime, Option<&str>) { let content_type = mime_guess::from_path(path).first_or_octet_stream(); let filename = opt_filename(path); (content_type, filename) } fn opt_filename(path: &PathBuf) -> Option<&str> { path.file_name().and_then(|filename| filename.to_str()) }
{ let mut boundary = format!("\r\n--{}", gen_boundary()); let mut buf: Vec<u8> = Vec::new(); for field in self.fields.drain(..) { match field.data { Data::Text(value) => { write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}", boundary, field.name, value )?; } Data::File(path) => { let (content_type, filename) = mime_filename(&path); let mut file = File::open(&path)?; write!( buf,
identifier_body
multipart.rs
use std::fmt; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::PathBuf; use mime_guess; use crate::error::Result; use crate::http::plus::random_alphanumeric; const BOUNDARY_LEN: usize = 32; fn gen_boundary() -> String { random_alphanumeric(BOUNDARY_LEN) } use crate::http::mime::{self, Mime}; /// Create a structure to process the multipart/form-data data format for /// the client to initiate the request. /// /// # Examples /// /// ``` /// use sincere::http::plus::client::Multipart; /// /// let mut multipart = Multipart::new(); /// /// multipart.add_text("hello", "world"); /// /// let (boundary, data) = multipart.convert().unwrap(); /// ``` /// #[derive(Debug, Default)] pub struct Multipart<'a> { fields: Vec<Field<'a>>, } impl<'a> Multipart<'a> { /// Returns the empty `Multipart` set. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// ``` #[inline] pub fn new() -> Multipart<'a> { Multipart { fields: Vec::new() } } /// Add text 'key-value' into `Multipart`. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_text("hello", "world"); /// ``` #[inline] pub fn add_text<V>(&mut self, name: V, value: V) -> &mut Self where V: Into<String>, { let filed = Field { name: name.into(), data: Data::Text(value.into()), }; self.fields.push(filed); self } /// Add file into `Multipart`. /// /// # Examples /// /// ```no_test /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_file("hello.rs", "/aaa/bbb"); /// ``` #[inline] pub fn add_file<V, P>(&mut self, name: V, path: P) -> &mut Self where V: Into<String>, P: Into<PathBuf>, { let filed = Field { name: name.into(), data: Data::File(path.into()), }; self.fields.push(filed); self } /// Add reader stream into `Multipart`. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let temp = r#"{"hello": "world"}"#.as_bytes(); /// let reader = ::std::io::Cursor::new(temp); /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_stream("ddd", reader, Some("hello.rs"), Some(sincere::http::mime::APPLICATION_JSON)); /// ``` #[inline] pub fn add_stream<V, R>( &mut self, name: V, stream: R, filename: Option<V>, mime: Option<Mime>, ) -> &mut Self where R: Read + 'a, V: Into<String>, { let filed = Field { name: name.into(), data: Data::Stream(Stream { content_type: mime.unwrap_or(mime::APPLICATION_OCTET_STREAM), filename: filename.map(|f| f.into()), stream: Box::new(stream), }), }; self.fields.push(filed); self } /// Convert `Multipart` to client boundary and body. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_text("hello", "world"); /// /// let (boundary, data) = multipart.convert().unwrap(); /// ``` pub fn convert(&mut self) -> Result<(String, Vec<u8>)> { let mut boundary = format!("\r\n--{}", gen_boundary()); let mut buf: Vec<u8> = Vec::new(); for field in self.fields.drain(..) { match field.data { Data::Text(value) => { write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}", boundary, field.name, value )?; } Data::File(path) => { let (content_type, filename) = mime_filename(&path); let mut file = File::open(&path)?; write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"", boundary, field.name )?; if let Some(filename) = filename { write!(buf, "; filename=\"{}\"", filename)?; } write!(buf, "\r\nContent-Type: {}\r\n\r\n", content_type)?; let mut temp: Vec<u8> = Vec::new(); file.read_to_end(&mut temp)?; buf.extend(temp); } Data::Stream(mut stream) => { write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"", boundary, field.name )?; if let Some(filename) = stream.filename { write!(buf, "; filename=\"{}\"", filename)?; } write!(buf, "\r\nContent-Type: {}\r\n\r\n", stream.content_type)?; let mut temp: Vec<u8> = Vec::new(); stream.stream.read_to_end(&mut temp)?; buf.extend(temp); } } } boundary.push_str("--"); buf.extend(boundary.as_bytes()); Ok((boundary[4..boundary.len() - 2].to_string(), buf)) } } #[derive(Debug)] struct Field<'a> { name: String, data: Data<'a>, } enum
<'a> { Text(String), File(PathBuf), Stream(Stream<'a>), } impl<'a> fmt::Debug for Data<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Data::Text(ref value) => write!(f, "Data::Text({:?})", value), Data::File(ref path) => write!(f, "Data::File({:?})", path), Data::Stream(_) => f.write_str("Data::Stream(Box<Read>)"), } } } struct Stream<'a> { filename: Option<String>, content_type: Mime, stream: Box<dyn Read + 'a>, } fn mime_filename(path: &PathBuf) -> (Mime, Option<&str>) { let content_type = mime_guess::from_path(path).first_or_octet_stream(); let filename = opt_filename(path); (content_type, filename) } fn opt_filename(path: &PathBuf) -> Option<&str> { path.file_name().and_then(|filename| filename.to_str()) }
Data
identifier_name
multipart.rs
use std::fmt; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::PathBuf; use mime_guess; use crate::error::Result; use crate::http::plus::random_alphanumeric; const BOUNDARY_LEN: usize = 32; fn gen_boundary() -> String { random_alphanumeric(BOUNDARY_LEN) } use crate::http::mime::{self, Mime}; /// Create a structure to process the multipart/form-data data format for /// the client to initiate the request. /// /// # Examples /// /// ``` /// use sincere::http::plus::client::Multipart; /// /// let mut multipart = Multipart::new(); /// /// multipart.add_text("hello", "world"); /// /// let (boundary, data) = multipart.convert().unwrap(); /// ``` /// #[derive(Debug, Default)] pub struct Multipart<'a> { fields: Vec<Field<'a>>, } impl<'a> Multipart<'a> { /// Returns the empty `Multipart` set. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// ``` #[inline] pub fn new() -> Multipart<'a> { Multipart { fields: Vec::new() } } /// Add text 'key-value' into `Multipart`. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_text("hello", "world"); /// ``` #[inline] pub fn add_text<V>(&mut self, name: V, value: V) -> &mut Self
V: Into<String>, { let filed = Field { name: name.into(), data: Data::Text(value.into()), }; self.fields.push(filed); self } /// Add file into `Multipart`. /// /// # Examples /// /// ```no_test /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_file("hello.rs", "/aaa/bbb"); /// ``` #[inline] pub fn add_file<V, P>(&mut self, name: V, path: P) -> &mut Self where V: Into<String>, P: Into<PathBuf>, { let filed = Field { name: name.into(), data: Data::File(path.into()), }; self.fields.push(filed); self } /// Add reader stream into `Multipart`. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let temp = r#"{"hello": "world"}"#.as_bytes(); /// let reader = ::std::io::Cursor::new(temp); /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_stream("ddd", reader, Some("hello.rs"), Some(sincere::http::mime::APPLICATION_JSON)); /// ``` #[inline] pub fn add_stream<V, R>( &mut self, name: V, stream: R, filename: Option<V>, mime: Option<Mime>, ) -> &mut Self where R: Read + 'a, V: Into<String>, { let filed = Field { name: name.into(), data: Data::Stream(Stream { content_type: mime.unwrap_or(mime::APPLICATION_OCTET_STREAM), filename: filename.map(|f| f.into()), stream: Box::new(stream), }), }; self.fields.push(filed); self } /// Convert `Multipart` to client boundary and body. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_text("hello", "world"); /// /// let (boundary, data) = multipart.convert().unwrap(); /// ``` pub fn convert(&mut self) -> Result<(String, Vec<u8>)> { let mut boundary = format!("\r\n--{}", gen_boundary()); let mut buf: Vec<u8> = Vec::new(); for field in self.fields.drain(..) { match field.data { Data::Text(value) => { write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}", boundary, field.name, value )?; } Data::File(path) => { let (content_type, filename) = mime_filename(&path); let mut file = File::open(&path)?; write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"", boundary, field.name )?; if let Some(filename) = filename { write!(buf, "; filename=\"{}\"", filename)?; } write!(buf, "\r\nContent-Type: {}\r\n\r\n", content_type)?; let mut temp: Vec<u8> = Vec::new(); file.read_to_end(&mut temp)?; buf.extend(temp); } Data::Stream(mut stream) => { write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"", boundary, field.name )?; if let Some(filename) = stream.filename { write!(buf, "; filename=\"{}\"", filename)?; } write!(buf, "\r\nContent-Type: {}\r\n\r\n", stream.content_type)?; let mut temp: Vec<u8> = Vec::new(); stream.stream.read_to_end(&mut temp)?; buf.extend(temp); } } } boundary.push_str("--"); buf.extend(boundary.as_bytes()); Ok((boundary[4..boundary.len() - 2].to_string(), buf)) } } #[derive(Debug)] struct Field<'a> { name: String, data: Data<'a>, } enum Data<'a> { Text(String), File(PathBuf), Stream(Stream<'a>), } impl<'a> fmt::Debug for Data<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Data::Text(ref value) => write!(f, "Data::Text({:?})", value), Data::File(ref path) => write!(f, "Data::File({:?})", path), Data::Stream(_) => f.write_str("Data::Stream(Box<Read>)"), } } } struct Stream<'a> { filename: Option<String>, content_type: Mime, stream: Box<dyn Read + 'a>, } fn mime_filename(path: &PathBuf) -> (Mime, Option<&str>) { let content_type = mime_guess::from_path(path).first_or_octet_stream(); let filename = opt_filename(path); (content_type, filename) } fn opt_filename(path: &PathBuf) -> Option<&str> { path.file_name().and_then(|filename| filename.to_str()) }
where
random_line_split
multipart.rs
use std::fmt; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::PathBuf; use mime_guess; use crate::error::Result; use crate::http::plus::random_alphanumeric; const BOUNDARY_LEN: usize = 32; fn gen_boundary() -> String { random_alphanumeric(BOUNDARY_LEN) } use crate::http::mime::{self, Mime}; /// Create a structure to process the multipart/form-data data format for /// the client to initiate the request. /// /// # Examples /// /// ``` /// use sincere::http::plus::client::Multipart; /// /// let mut multipart = Multipart::new(); /// /// multipart.add_text("hello", "world"); /// /// let (boundary, data) = multipart.convert().unwrap(); /// ``` /// #[derive(Debug, Default)] pub struct Multipart<'a> { fields: Vec<Field<'a>>, } impl<'a> Multipart<'a> { /// Returns the empty `Multipart` set. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// ``` #[inline] pub fn new() -> Multipart<'a> { Multipart { fields: Vec::new() } } /// Add text 'key-value' into `Multipart`. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_text("hello", "world"); /// ``` #[inline] pub fn add_text<V>(&mut self, name: V, value: V) -> &mut Self where V: Into<String>, { let filed = Field { name: name.into(), data: Data::Text(value.into()), }; self.fields.push(filed); self } /// Add file into `Multipart`. /// /// # Examples /// /// ```no_test /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_file("hello.rs", "/aaa/bbb"); /// ``` #[inline] pub fn add_file<V, P>(&mut self, name: V, path: P) -> &mut Self where V: Into<String>, P: Into<PathBuf>, { let filed = Field { name: name.into(), data: Data::File(path.into()), }; self.fields.push(filed); self } /// Add reader stream into `Multipart`. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let temp = r#"{"hello": "world"}"#.as_bytes(); /// let reader = ::std::io::Cursor::new(temp); /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_stream("ddd", reader, Some("hello.rs"), Some(sincere::http::mime::APPLICATION_JSON)); /// ``` #[inline] pub fn add_stream<V, R>( &mut self, name: V, stream: R, filename: Option<V>, mime: Option<Mime>, ) -> &mut Self where R: Read + 'a, V: Into<String>, { let filed = Field { name: name.into(), data: Data::Stream(Stream { content_type: mime.unwrap_or(mime::APPLICATION_OCTET_STREAM), filename: filename.map(|f| f.into()), stream: Box::new(stream), }), }; self.fields.push(filed); self } /// Convert `Multipart` to client boundary and body. /// /// # Examples /// /// ``` /// use sincere::http::plus::client; /// /// let mut multipart = client::Multipart::new(); /// /// multipart.add_text("hello", "world"); /// /// let (boundary, data) = multipart.convert().unwrap(); /// ``` pub fn convert(&mut self) -> Result<(String, Vec<u8>)> { let mut boundary = format!("\r\n--{}", gen_boundary()); let mut buf: Vec<u8> = Vec::new(); for field in self.fields.drain(..) { match field.data { Data::Text(value) =>
Data::File(path) => { let (content_type, filename) = mime_filename(&path); let mut file = File::open(&path)?; write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"", boundary, field.name )?; if let Some(filename) = filename { write!(buf, "; filename=\"{}\"", filename)?; } write!(buf, "\r\nContent-Type: {}\r\n\r\n", content_type)?; let mut temp: Vec<u8> = Vec::new(); file.read_to_end(&mut temp)?; buf.extend(temp); } Data::Stream(mut stream) => { write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"", boundary, field.name )?; if let Some(filename) = stream.filename { write!(buf, "; filename=\"{}\"", filename)?; } write!(buf, "\r\nContent-Type: {}\r\n\r\n", stream.content_type)?; let mut temp: Vec<u8> = Vec::new(); stream.stream.read_to_end(&mut temp)?; buf.extend(temp); } } } boundary.push_str("--"); buf.extend(boundary.as_bytes()); Ok((boundary[4..boundary.len() - 2].to_string(), buf)) } } #[derive(Debug)] struct Field<'a> { name: String, data: Data<'a>, } enum Data<'a> { Text(String), File(PathBuf), Stream(Stream<'a>), } impl<'a> fmt::Debug for Data<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Data::Text(ref value) => write!(f, "Data::Text({:?})", value), Data::File(ref path) => write!(f, "Data::File({:?})", path), Data::Stream(_) => f.write_str("Data::Stream(Box<Read>)"), } } } struct Stream<'a> { filename: Option<String>, content_type: Mime, stream: Box<dyn Read + 'a>, } fn mime_filename(path: &PathBuf) -> (Mime, Option<&str>) { let content_type = mime_guess::from_path(path).first_or_octet_stream(); let filename = opt_filename(path); (content_type, filename) } fn opt_filename(path: &PathBuf) -> Option<&str> { path.file_name().and_then(|filename| filename.to_str()) }
{ write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}", boundary, field.name, value )?; }
conditional_block
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use ptr::P; pub fn expand_deriving_default<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>),
} ), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let default_ident = vec!( cx.ident_of_std("core"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref summary) => { match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); cx.expr_call_ident(trait_span, substr.type_ident, exprs) } } Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } } StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_usize(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`") }; }
{ let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::default::Default), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( MethodDef { name: "default", generics: LifetimeBounds::empty(), explicit_self: None, args: Vec::new(), ret_ty: Self, attributes: attrs, combine_substructure: combine_substructure(box |a, b, c| { default_substructure(a, b, c) })
identifier_body