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
counter.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; /// Naive implementation of a `Counter`. #[derive(Debug)] pub struct StdCounter { /// The counter value. value: AtomicUsize, } /// A snapshot of the current value of a `Counter`. #[derive(Debug)] pub struct CounterSnapshot { /// The snapshot of the counter value. pub value: usize, } /// `Counter` is a `Metric` that represents a single numerical value that can /// increases over time. pub trait Counter: Send + Sync { /// Clear the counter, setting the value to `0`. fn clear(&self); /// Increment the counter by 1. fn inc(&self); /// Increment the counter by the given amount. MUST check that v >= 0. fn add(&self, value: usize); /// Take a snapshot of the current value for use with a `Reporter`. fn snapshot(&self) -> CounterSnapshot; } impl Counter for StdCounter { fn clear(&self) { self.value.store(0, Ordering::Relaxed); } fn inc(&self) { self.value.fetch_add(1, Ordering::Relaxed); } fn add(&self, value: usize) { self.value.fetch_add(value, Ordering::Relaxed); } fn snapshot(&self) -> CounterSnapshot { CounterSnapshot { value: self.value.load(Ordering::Relaxed) } } } impl StdCounter { /// Create a new `StdCounter`. pub fn
() -> Arc<Self> { Arc::new(Self::default()) } } impl Default for StdCounter { fn default() -> Self { StdCounter { value: AtomicUsize::new(0) } } } #[cfg(test)] mod test { use super::*; #[test] fn a_counting_counter() { let c = StdCounter::new(); c.add(1); assert_eq!(c.snapshot().value, 1); let c = StdCounter::new(); c.inc(); assert_eq!(c.snapshot().value, 1); } #[test] fn validate_snapshots() { let c = StdCounter::new(); let snapshot_1 = c.snapshot(); c.add(1); let snapshot_2 = c.snapshot(); assert_eq!(snapshot_1.value, 0); assert_eq!(snapshot_2.value, 1); } }
new
identifier_name
counter.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; /// Naive implementation of a `Counter`. #[derive(Debug)] pub struct StdCounter { /// The counter value. value: AtomicUsize, } /// A snapshot of the current value of a `Counter`. #[derive(Debug)] pub struct CounterSnapshot { /// The snapshot of the counter value. pub value: usize, } /// `Counter` is a `Metric` that represents a single numerical value that can /// increases over time. pub trait Counter: Send + Sync { /// Clear the counter, setting the value to `0`. fn clear(&self); /// Increment the counter by 1. fn inc(&self); /// Increment the counter by the given amount. MUST check that v >= 0. fn add(&self, value: usize); /// Take a snapshot of the current value for use with a `Reporter`. fn snapshot(&self) -> CounterSnapshot; } impl Counter for StdCounter { fn clear(&self)
fn inc(&self) { self.value.fetch_add(1, Ordering::Relaxed); } fn add(&self, value: usize) { self.value.fetch_add(value, Ordering::Relaxed); } fn snapshot(&self) -> CounterSnapshot { CounterSnapshot { value: self.value.load(Ordering::Relaxed) } } } impl StdCounter { /// Create a new `StdCounter`. pub fn new() -> Arc<Self> { Arc::new(Self::default()) } } impl Default for StdCounter { fn default() -> Self { StdCounter { value: AtomicUsize::new(0) } } } #[cfg(test)] mod test { use super::*; #[test] fn a_counting_counter() { let c = StdCounter::new(); c.add(1); assert_eq!(c.snapshot().value, 1); let c = StdCounter::new(); c.inc(); assert_eq!(c.snapshot().value, 1); } #[test] fn validate_snapshots() { let c = StdCounter::new(); let snapshot_1 = c.snapshot(); c.add(1); let snapshot_2 = c.snapshot(); assert_eq!(snapshot_1.value, 0); assert_eq!(snapshot_2.value, 1); } }
{ self.value.store(0, Ordering::Relaxed); }
identifier_body
cpu.rs
use opcode::Opcode; use keypad::Keypad; use display::Display; use util; pub struct Cpu { pub memory: [u8; 4096], pub v: [u8; 16], pub i: usize, pub pc: usize, pub gfx: [u8; 64 * 32], pub delay_timer: u8, pub sound_timer: u8, pub stack: [u16; 16], pub sp: usize,
fn not_implemented(op: usize, pc: usize) { println!("Not implemented:: op: {:x}, pc: {:x}", op, pc); } impl Cpu { pub fn new() -> Cpu { let mut cpu: Cpu = Cpu { v: [0; 16], gfx: [0; 64 * 32], delay_timer: 0, sound_timer: 0, stack: [0; 16], pc: 0x200, // Program counter starts at 0x200 i: 0, // Reset index register sp: 0, // Reset stack pointer memory: [0; 4096], display: Display::new(), keypad: Keypad::new(), }; // load in Util::fontset for i in 0..80 { cpu.memory[i] = util::FONTSET[i]; } return cpu; } pub fn emulate_cycle(&mut self) { // fetch opcode let opcode_bits: u16 = (self.memory[self.pc as usize] as u16) << 8 | self.memory[(self.pc + 1) as usize] as u16; let opcode: Opcode = Opcode::new(opcode_bits); util::debug_cycle(self, &opcode); self.pc += 2; self.execute(&opcode); //?? // self.pc += 2; // update timers if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { if self.sound_timer == 0 { println!("BUZZ"); } self.sound_timer -= 1; } } pub fn execute(&mut self, opcode: &Opcode) { match opcode.code & 0xf000 { 0x0000 => self.execute_clear_return(opcode), // 0nnn - SYS nnn 0x1000 => op_1xxx(self, opcode), 0x2000 => op_2xxx(self, opcode), 0x3000 => op_3xxx(self, opcode), 0x4000 => op_4xxx(self, opcode), 0x5000 => op_5xxx(self, opcode), 0x6000 => op_6xxx(self, opcode), 0x7000 => op_7xxx(self, opcode), 0x8000 => op_8xxx(self, opcode), 0x9000 => op_9xxx(self, opcode), 0xA000 => op_Axxx(self, opcode), 0xB000 => op_Bxxx(self, opcode), 0xC000 => op_Cxxx(self, opcode), 0xD000 => op_Dxxx(self, opcode), 0xE000 => op_Exxx(self, opcode), 0xF000 => op_Fxxx(self, opcode), _ => not_implemented(opcode.code as usize, self.pc), } } pub fn execute_clear_return(&mut self, opcode: &Opcode) { match opcode.code { 0x00E0 => { // CLS // clear screen self.display.clear(); } 0x00EE => self.return_from_subroutine(), _ => not_implemented(opcode.code as usize, self.pc), } } pub fn return_from_subroutine(&mut self) { // 00EE - RTS // Return from subroutine. Pop the current value in the stack pointer // off of the stack, and set the program counter to the value popped. // self.registers['sp'] -= 1 // self.registers['pc'] = self.memory[self.registers['sp']] << 8 // self.registers['sp'] -= 1 // self.registers['pc'] += self.memory[self.registers['sp']] self.sp -= 1; } // 0x0: self.clear_return, # 0nnn - SYS nnn // 0x1: self.jump_to_address, # 1nnn - JUMP nnn // 0x2: self.jump_to_subroutine, # 2nnn - CALL nnn // 0x3: self.skip_if_reg_equal_val, # 3snn - SKE Vs, nn // 0x4: self.skip_if_reg_not_equal_val, # 4snn - SKNE Vs, nn // 0x5: self.skip_if_reg_equal_reg, # 5st0 - SKE Vs, Vt // 0x6: self.move_value_to_reg, # 6snn - LOAD Vs, nn // 0x7: self.add_value_to_reg, # 7snn - ADD Vs, nn // 0x8: self.execute_logical_instruction, # see subfunctions below // 0x9: self.skip_if_reg_not_equal_reg, # 9st0 - SKNE Vs, Vt // 0xA: self.load_index_reg_with_value, # Annn - LOAD I, nnn // 0xB: self.jump_to_index_plus_value, # Bnnn - JUMP [I] + nnn // 0xC: self.generate_random_number, # Ctnn - RAND Vt, nn // 0xD: self.draw_sprite, # Dstn - DRAW Vs, Vy, n // 0xE: self.keyboard_routines, # see subfunctions below // 0xF: self.misc_routines, # see subfunctions below }
pub keypad: Keypad, pub display: Display, }
random_line_split
cpu.rs
use opcode::Opcode; use keypad::Keypad; use display::Display; use util; pub struct Cpu { pub memory: [u8; 4096], pub v: [u8; 16], pub i: usize, pub pc: usize, pub gfx: [u8; 64 * 32], pub delay_timer: u8, pub sound_timer: u8, pub stack: [u16; 16], pub sp: usize, pub keypad: Keypad, pub display: Display, } fn not_implemented(op: usize, pc: usize) { println!("Not implemented:: op: {:x}, pc: {:x}", op, pc); } impl Cpu { pub fn new() -> Cpu { let mut cpu: Cpu = Cpu { v: [0; 16], gfx: [0; 64 * 32], delay_timer: 0, sound_timer: 0, stack: [0; 16], pc: 0x200, // Program counter starts at 0x200 i: 0, // Reset index register sp: 0, // Reset stack pointer memory: [0; 4096], display: Display::new(), keypad: Keypad::new(), }; // load in Util::fontset for i in 0..80 { cpu.memory[i] = util::FONTSET[i]; } return cpu; } pub fn emulate_cycle(&mut self) { // fetch opcode let opcode_bits: u16 = (self.memory[self.pc as usize] as u16) << 8 | self.memory[(self.pc + 1) as usize] as u16; let opcode: Opcode = Opcode::new(opcode_bits); util::debug_cycle(self, &opcode); self.pc += 2; self.execute(&opcode); //?? // self.pc += 2; // update timers if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { if self.sound_timer == 0 { println!("BUZZ"); } self.sound_timer -= 1; } } pub fn execute(&mut self, opcode: &Opcode) { match opcode.code & 0xf000 { 0x0000 => self.execute_clear_return(opcode), // 0nnn - SYS nnn 0x1000 => op_1xxx(self, opcode), 0x2000 => op_2xxx(self, opcode), 0x3000 => op_3xxx(self, opcode), 0x4000 => op_4xxx(self, opcode), 0x5000 => op_5xxx(self, opcode), 0x6000 => op_6xxx(self, opcode), 0x7000 => op_7xxx(self, opcode), 0x8000 => op_8xxx(self, opcode), 0x9000 => op_9xxx(self, opcode), 0xA000 => op_Axxx(self, opcode), 0xB000 => op_Bxxx(self, opcode), 0xC000 => op_Cxxx(self, opcode), 0xD000 => op_Dxxx(self, opcode), 0xE000 => op_Exxx(self, opcode), 0xF000 => op_Fxxx(self, opcode), _ => not_implemented(opcode.code as usize, self.pc), } } pub fn execute_clear_return(&mut self, opcode: &Opcode)
pub fn return_from_subroutine(&mut self) { // 00EE - RTS // Return from subroutine. Pop the current value in the stack pointer // off of the stack, and set the program counter to the value popped. // self.registers['sp'] -= 1 // self.registers['pc'] = self.memory[self.registers['sp']] << 8 // self.registers['sp'] -= 1 // self.registers['pc'] += self.memory[self.registers['sp']] self.sp -= 1; } // 0x0: self.clear_return, # 0nnn - SYS nnn // 0x1: self.jump_to_address, # 1nnn - JUMP nnn // 0x2: self.jump_to_subroutine, # 2nnn - CALL nnn // 0x3: self.skip_if_reg_equal_val, # 3snn - SKE Vs, nn // 0x4: self.skip_if_reg_not_equal_val, # 4snn - SKNE Vs, nn // 0x5: self.skip_if_reg_equal_reg, # 5st0 - SKE Vs, Vt // 0x6: self.move_value_to_reg, # 6snn - LOAD Vs, nn // 0x7: self.add_value_to_reg, # 7snn - ADD Vs, nn // 0x8: self.execute_logical_instruction, # see subfunctions below // 0x9: self.skip_if_reg_not_equal_reg, # 9st0 - SKNE Vs, Vt // 0xA: self.load_index_reg_with_value, # Annn - LOAD I, nnn // 0xB: self.jump_to_index_plus_value, # Bnnn - JUMP [I] + nnn // 0xC: self.generate_random_number, # Ctnn - RAND Vt, nn // 0xD: self.draw_sprite, # Dstn - DRAW Vs, Vy, n // 0xE: self.keyboard_routines, # see subfunctions below // 0xF: self.misc_routines, # see subfunctions below }
{ match opcode.code { 0x00E0 => { // CLS // clear screen self.display.clear(); } 0x00EE => self.return_from_subroutine(), _ => not_implemented(opcode.code as usize, self.pc), } }
identifier_body
cpu.rs
use opcode::Opcode; use keypad::Keypad; use display::Display; use util; pub struct Cpu { pub memory: [u8; 4096], pub v: [u8; 16], pub i: usize, pub pc: usize, pub gfx: [u8; 64 * 32], pub delay_timer: u8, pub sound_timer: u8, pub stack: [u16; 16], pub sp: usize, pub keypad: Keypad, pub display: Display, } fn not_implemented(op: usize, pc: usize) { println!("Not implemented:: op: {:x}, pc: {:x}", op, pc); } impl Cpu { pub fn
() -> Cpu { let mut cpu: Cpu = Cpu { v: [0; 16], gfx: [0; 64 * 32], delay_timer: 0, sound_timer: 0, stack: [0; 16], pc: 0x200, // Program counter starts at 0x200 i: 0, // Reset index register sp: 0, // Reset stack pointer memory: [0; 4096], display: Display::new(), keypad: Keypad::new(), }; // load in Util::fontset for i in 0..80 { cpu.memory[i] = util::FONTSET[i]; } return cpu; } pub fn emulate_cycle(&mut self) { // fetch opcode let opcode_bits: u16 = (self.memory[self.pc as usize] as u16) << 8 | self.memory[(self.pc + 1) as usize] as u16; let opcode: Opcode = Opcode::new(opcode_bits); util::debug_cycle(self, &opcode); self.pc += 2; self.execute(&opcode); //?? // self.pc += 2; // update timers if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { if self.sound_timer == 0 { println!("BUZZ"); } self.sound_timer -= 1; } } pub fn execute(&mut self, opcode: &Opcode) { match opcode.code & 0xf000 { 0x0000 => self.execute_clear_return(opcode), // 0nnn - SYS nnn 0x1000 => op_1xxx(self, opcode), 0x2000 => op_2xxx(self, opcode), 0x3000 => op_3xxx(self, opcode), 0x4000 => op_4xxx(self, opcode), 0x5000 => op_5xxx(self, opcode), 0x6000 => op_6xxx(self, opcode), 0x7000 => op_7xxx(self, opcode), 0x8000 => op_8xxx(self, opcode), 0x9000 => op_9xxx(self, opcode), 0xA000 => op_Axxx(self, opcode), 0xB000 => op_Bxxx(self, opcode), 0xC000 => op_Cxxx(self, opcode), 0xD000 => op_Dxxx(self, opcode), 0xE000 => op_Exxx(self, opcode), 0xF000 => op_Fxxx(self, opcode), _ => not_implemented(opcode.code as usize, self.pc), } } pub fn execute_clear_return(&mut self, opcode: &Opcode) { match opcode.code { 0x00E0 => { // CLS // clear screen self.display.clear(); } 0x00EE => self.return_from_subroutine(), _ => not_implemented(opcode.code as usize, self.pc), } } pub fn return_from_subroutine(&mut self) { // 00EE - RTS // Return from subroutine. Pop the current value in the stack pointer // off of the stack, and set the program counter to the value popped. // self.registers['sp'] -= 1 // self.registers['pc'] = self.memory[self.registers['sp']] << 8 // self.registers['sp'] -= 1 // self.registers['pc'] += self.memory[self.registers['sp']] self.sp -= 1; } // 0x0: self.clear_return, # 0nnn - SYS nnn // 0x1: self.jump_to_address, # 1nnn - JUMP nnn // 0x2: self.jump_to_subroutine, # 2nnn - CALL nnn // 0x3: self.skip_if_reg_equal_val, # 3snn - SKE Vs, nn // 0x4: self.skip_if_reg_not_equal_val, # 4snn - SKNE Vs, nn // 0x5: self.skip_if_reg_equal_reg, # 5st0 - SKE Vs, Vt // 0x6: self.move_value_to_reg, # 6snn - LOAD Vs, nn // 0x7: self.add_value_to_reg, # 7snn - ADD Vs, nn // 0x8: self.execute_logical_instruction, # see subfunctions below // 0x9: self.skip_if_reg_not_equal_reg, # 9st0 - SKNE Vs, Vt // 0xA: self.load_index_reg_with_value, # Annn - LOAD I, nnn // 0xB: self.jump_to_index_plus_value, # Bnnn - JUMP [I] + nnn // 0xC: self.generate_random_number, # Ctnn - RAND Vt, nn // 0xD: self.draw_sprite, # Dstn - DRAW Vs, Vy, n // 0xE: self.keyboard_routines, # see subfunctions below // 0xF: self.misc_routines, # see subfunctions below }
new
identifier_name
h5f.rs
pub use self::H5F_scope_t::*; pub use self::H5F_close_degree_t::*; pub use self::H5F_mem_t::*; pub use self::H5F_libver_t::*; use libc::{c_int, c_uint, c_void, c_char, c_double, size_t, ssize_t}; use h5::{herr_t, hsize_t, htri_t, hssize_t, H5_ih_info_t}; use h5i::hid_t; use h5ac::H5AC_cache_config_t; /* these flags call H5check() in the C library */ pub const H5F_ACC_RDONLY: c_uint = 0x0000; pub const H5F_ACC_RDWR: c_uint = 0x0001; pub const H5F_ACC_TRUNC: c_uint = 0x0002; pub const H5F_ACC_EXCL: c_uint = 0x0004; pub const H5F_ACC_DEBUG: c_uint = 0x0008; pub const H5F_ACC_CREAT: c_uint = 0x0010; pub const H5F_ACC_DEFAULT: c_uint = 0xffff; pub const H5F_OBJ_FILE: c_uint = 0x0001; pub const H5F_OBJ_DATASET: c_uint = 0x0002; pub const H5F_OBJ_GROUP: c_uint = 0x0004; pub const H5F_OBJ_DATATYPE: c_uint = 0x0008; pub const H5F_OBJ_ATTR: c_uint = 0x0010; pub const H5F_OBJ_ALL: c_uint = H5F_OBJ_FILE | H5F_OBJ_DATASET | H5F_OBJ_GROUP | H5F_OBJ_DATATYPE | H5F_OBJ_ATTR; pub const H5F_OBJ_LOCAL: c_uint = 0x0020; pub const H5F_FAMILY_DEFAULT: hsize_t = 0; pub const H5F_MPIO_DEBUG_KEY: &'static str = "H5F_mpio_debug_key"; pub const H5F_UNLIMITED: hsize_t =!0; #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_scope_t { H5F_SCOPE_LOCAL = 0, H5F_SCOPE_GLOBAL = 1, } #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_close_degree_t { H5F_CLOSE_DEFAULT = 0, H5F_CLOSE_WEAK = 1, H5F_CLOSE_SEMI = 2, H5F_CLOSE_STRONG = 3, } #[repr(C)] #[derive(Copy, Clone)] pub struct H5F_info_t { pub super_ext_size: hsize_t, pub sohm: __H5F_info_t__sohm, } impl ::std::default::Default for H5F_info_t { fn default() -> H5F_info_t { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy, Clone)] pub struct __H5F_info_t__sohm { pub hdr_size: hsize_t, pub msgs_info: H5_ih_info_t, } impl ::std::default::Default for __H5F_info_t__sohm { fn default() -> __H5F_info_t__sohm { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_mem_t {
H5FD_MEM_GHEAP = 4, H5FD_MEM_LHEAP = 5, H5FD_MEM_OHDR = 6, H5FD_MEM_NTYPES = 7, } #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_libver_t { H5F_LIBVER_EARLIEST = 0, H5F_LIBVER_LATEST = 1, } pub const H5F_LIBVER_18: H5F_libver_t = H5F_LIBVER_LATEST; extern { pub fn H5Fis_hdf5(filename: *const c_char) -> htri_t; pub fn H5Fcreate(filename: *const c_char, flags: c_uint, create_plist: hid_t, access_plist: hid_t) -> hid_t; pub fn H5Fopen(filename: *const c_char, flags: c_uint, access_plist: hid_t) -> hid_t; pub fn H5Freopen(file_id: hid_t) -> hid_t; pub fn H5Fflush(object_id: hid_t, scope: H5F_scope_t) -> herr_t; pub fn H5Fclose(file_id: hid_t) -> herr_t; pub fn H5Fget_create_plist(file_id: hid_t) -> hid_t; pub fn H5Fget_access_plist(file_id: hid_t) -> hid_t; pub fn H5Fget_intent(file_id: hid_t, intent: *mut c_uint) -> herr_t; pub fn H5Fget_obj_count(file_id: hid_t, types: c_uint) -> ssize_t; pub fn H5Fget_obj_ids(file_id: hid_t, types: c_uint, max_objs: size_t, obj_id_list: *mut hid_t) -> ssize_t; pub fn H5Fget_vfd_handle(file_id: hid_t, fapl: hid_t, file_handle: *mut *mut c_void) -> herr_t; pub fn H5Fmount(loc: hid_t, name: *const c_char, child: hid_t, plist: hid_t) -> herr_t; pub fn H5Funmount(loc: hid_t, name: *const c_char) -> herr_t; pub fn H5Fget_freespace(file_id: hid_t) -> hssize_t; pub fn H5Fget_filesize(file_id: hid_t, size: *mut hsize_t) -> herr_t; pub fn H5Fget_file_image(file_id: hid_t, buf_ptr: *mut c_void, buf_len: size_t) -> ssize_t; pub fn H5Fget_mdc_config(file_id: hid_t, config_ptr: *mut H5AC_cache_config_t) -> herr_t; pub fn H5Fset_mdc_config(file_id: hid_t, config_ptr: *mut H5AC_cache_config_t) -> herr_t; pub fn H5Fget_mdc_hit_rate(file_id: hid_t, hit_rate_ptr: *mut c_double) -> herr_t; pub fn H5Fget_mdc_size(file_id: hid_t, max_size_ptr: *mut size_t, min_clean_size_ptr: *mut size_t, cur_size_ptr: *mut size_t, cur_num_entries_ptr: *mut c_int) -> herr_t; pub fn H5Freset_mdc_hit_rate_stats(file_id: hid_t) -> herr_t; pub fn H5Fget_name(obj_id: hid_t, name: *mut c_char, size: size_t) -> ssize_t; pub fn H5Fget_info(obj_id: hid_t, bh_info: *mut H5F_info_t) -> herr_t; pub fn H5Fclear_elink_file_cache(file_id: hid_t) -> herr_t; }
H5FD_MEM_NOLIST = -1, H5FD_MEM_DEFAULT = 0, H5FD_MEM_SUPER = 1, H5FD_MEM_BTREE = 2, H5FD_MEM_DRAW = 3,
random_line_split
h5f.rs
pub use self::H5F_scope_t::*; pub use self::H5F_close_degree_t::*; pub use self::H5F_mem_t::*; pub use self::H5F_libver_t::*; use libc::{c_int, c_uint, c_void, c_char, c_double, size_t, ssize_t}; use h5::{herr_t, hsize_t, htri_t, hssize_t, H5_ih_info_t}; use h5i::hid_t; use h5ac::H5AC_cache_config_t; /* these flags call H5check() in the C library */ pub const H5F_ACC_RDONLY: c_uint = 0x0000; pub const H5F_ACC_RDWR: c_uint = 0x0001; pub const H5F_ACC_TRUNC: c_uint = 0x0002; pub const H5F_ACC_EXCL: c_uint = 0x0004; pub const H5F_ACC_DEBUG: c_uint = 0x0008; pub const H5F_ACC_CREAT: c_uint = 0x0010; pub const H5F_ACC_DEFAULT: c_uint = 0xffff; pub const H5F_OBJ_FILE: c_uint = 0x0001; pub const H5F_OBJ_DATASET: c_uint = 0x0002; pub const H5F_OBJ_GROUP: c_uint = 0x0004; pub const H5F_OBJ_DATATYPE: c_uint = 0x0008; pub const H5F_OBJ_ATTR: c_uint = 0x0010; pub const H5F_OBJ_ALL: c_uint = H5F_OBJ_FILE | H5F_OBJ_DATASET | H5F_OBJ_GROUP | H5F_OBJ_DATATYPE | H5F_OBJ_ATTR; pub const H5F_OBJ_LOCAL: c_uint = 0x0020; pub const H5F_FAMILY_DEFAULT: hsize_t = 0; pub const H5F_MPIO_DEBUG_KEY: &'static str = "H5F_mpio_debug_key"; pub const H5F_UNLIMITED: hsize_t =!0; #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum
{ H5F_SCOPE_LOCAL = 0, H5F_SCOPE_GLOBAL = 1, } #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_close_degree_t { H5F_CLOSE_DEFAULT = 0, H5F_CLOSE_WEAK = 1, H5F_CLOSE_SEMI = 2, H5F_CLOSE_STRONG = 3, } #[repr(C)] #[derive(Copy, Clone)] pub struct H5F_info_t { pub super_ext_size: hsize_t, pub sohm: __H5F_info_t__sohm, } impl ::std::default::Default for H5F_info_t { fn default() -> H5F_info_t { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy, Clone)] pub struct __H5F_info_t__sohm { pub hdr_size: hsize_t, pub msgs_info: H5_ih_info_t, } impl ::std::default::Default for __H5F_info_t__sohm { fn default() -> __H5F_info_t__sohm { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_mem_t { H5FD_MEM_NOLIST = -1, H5FD_MEM_DEFAULT = 0, H5FD_MEM_SUPER = 1, H5FD_MEM_BTREE = 2, H5FD_MEM_DRAW = 3, H5FD_MEM_GHEAP = 4, H5FD_MEM_LHEAP = 5, H5FD_MEM_OHDR = 6, H5FD_MEM_NTYPES = 7, } #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_libver_t { H5F_LIBVER_EARLIEST = 0, H5F_LIBVER_LATEST = 1, } pub const H5F_LIBVER_18: H5F_libver_t = H5F_LIBVER_LATEST; extern { pub fn H5Fis_hdf5(filename: *const c_char) -> htri_t; pub fn H5Fcreate(filename: *const c_char, flags: c_uint, create_plist: hid_t, access_plist: hid_t) -> hid_t; pub fn H5Fopen(filename: *const c_char, flags: c_uint, access_plist: hid_t) -> hid_t; pub fn H5Freopen(file_id: hid_t) -> hid_t; pub fn H5Fflush(object_id: hid_t, scope: H5F_scope_t) -> herr_t; pub fn H5Fclose(file_id: hid_t) -> herr_t; pub fn H5Fget_create_plist(file_id: hid_t) -> hid_t; pub fn H5Fget_access_plist(file_id: hid_t) -> hid_t; pub fn H5Fget_intent(file_id: hid_t, intent: *mut c_uint) -> herr_t; pub fn H5Fget_obj_count(file_id: hid_t, types: c_uint) -> ssize_t; pub fn H5Fget_obj_ids(file_id: hid_t, types: c_uint, max_objs: size_t, obj_id_list: *mut hid_t) -> ssize_t; pub fn H5Fget_vfd_handle(file_id: hid_t, fapl: hid_t, file_handle: *mut *mut c_void) -> herr_t; pub fn H5Fmount(loc: hid_t, name: *const c_char, child: hid_t, plist: hid_t) -> herr_t; pub fn H5Funmount(loc: hid_t, name: *const c_char) -> herr_t; pub fn H5Fget_freespace(file_id: hid_t) -> hssize_t; pub fn H5Fget_filesize(file_id: hid_t, size: *mut hsize_t) -> herr_t; pub fn H5Fget_file_image(file_id: hid_t, buf_ptr: *mut c_void, buf_len: size_t) -> ssize_t; pub fn H5Fget_mdc_config(file_id: hid_t, config_ptr: *mut H5AC_cache_config_t) -> herr_t; pub fn H5Fset_mdc_config(file_id: hid_t, config_ptr: *mut H5AC_cache_config_t) -> herr_t; pub fn H5Fget_mdc_hit_rate(file_id: hid_t, hit_rate_ptr: *mut c_double) -> herr_t; pub fn H5Fget_mdc_size(file_id: hid_t, max_size_ptr: *mut size_t, min_clean_size_ptr: *mut size_t, cur_size_ptr: *mut size_t, cur_num_entries_ptr: *mut c_int) -> herr_t; pub fn H5Freset_mdc_hit_rate_stats(file_id: hid_t) -> herr_t; pub fn H5Fget_name(obj_id: hid_t, name: *mut c_char, size: size_t) -> ssize_t; pub fn H5Fget_info(obj_id: hid_t, bh_info: *mut H5F_info_t) -> herr_t; pub fn H5Fclear_elink_file_cache(file_id: hid_t) -> herr_t; }
H5F_scope_t
identifier_name
h5f.rs
pub use self::H5F_scope_t::*; pub use self::H5F_close_degree_t::*; pub use self::H5F_mem_t::*; pub use self::H5F_libver_t::*; use libc::{c_int, c_uint, c_void, c_char, c_double, size_t, ssize_t}; use h5::{herr_t, hsize_t, htri_t, hssize_t, H5_ih_info_t}; use h5i::hid_t; use h5ac::H5AC_cache_config_t; /* these flags call H5check() in the C library */ pub const H5F_ACC_RDONLY: c_uint = 0x0000; pub const H5F_ACC_RDWR: c_uint = 0x0001; pub const H5F_ACC_TRUNC: c_uint = 0x0002; pub const H5F_ACC_EXCL: c_uint = 0x0004; pub const H5F_ACC_DEBUG: c_uint = 0x0008; pub const H5F_ACC_CREAT: c_uint = 0x0010; pub const H5F_ACC_DEFAULT: c_uint = 0xffff; pub const H5F_OBJ_FILE: c_uint = 0x0001; pub const H5F_OBJ_DATASET: c_uint = 0x0002; pub const H5F_OBJ_GROUP: c_uint = 0x0004; pub const H5F_OBJ_DATATYPE: c_uint = 0x0008; pub const H5F_OBJ_ATTR: c_uint = 0x0010; pub const H5F_OBJ_ALL: c_uint = H5F_OBJ_FILE | H5F_OBJ_DATASET | H5F_OBJ_GROUP | H5F_OBJ_DATATYPE | H5F_OBJ_ATTR; pub const H5F_OBJ_LOCAL: c_uint = 0x0020; pub const H5F_FAMILY_DEFAULT: hsize_t = 0; pub const H5F_MPIO_DEBUG_KEY: &'static str = "H5F_mpio_debug_key"; pub const H5F_UNLIMITED: hsize_t =!0; #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_scope_t { H5F_SCOPE_LOCAL = 0, H5F_SCOPE_GLOBAL = 1, } #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_close_degree_t { H5F_CLOSE_DEFAULT = 0, H5F_CLOSE_WEAK = 1, H5F_CLOSE_SEMI = 2, H5F_CLOSE_STRONG = 3, } #[repr(C)] #[derive(Copy, Clone)] pub struct H5F_info_t { pub super_ext_size: hsize_t, pub sohm: __H5F_info_t__sohm, } impl ::std::default::Default for H5F_info_t { fn default() -> H5F_info_t { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy, Clone)] pub struct __H5F_info_t__sohm { pub hdr_size: hsize_t, pub msgs_info: H5_ih_info_t, } impl ::std::default::Default for __H5F_info_t__sohm { fn default() -> __H5F_info_t__sohm
} #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_mem_t { H5FD_MEM_NOLIST = -1, H5FD_MEM_DEFAULT = 0, H5FD_MEM_SUPER = 1, H5FD_MEM_BTREE = 2, H5FD_MEM_DRAW = 3, H5FD_MEM_GHEAP = 4, H5FD_MEM_LHEAP = 5, H5FD_MEM_OHDR = 6, H5FD_MEM_NTYPES = 7, } #[repr(C)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub enum H5F_libver_t { H5F_LIBVER_EARLIEST = 0, H5F_LIBVER_LATEST = 1, } pub const H5F_LIBVER_18: H5F_libver_t = H5F_LIBVER_LATEST; extern { pub fn H5Fis_hdf5(filename: *const c_char) -> htri_t; pub fn H5Fcreate(filename: *const c_char, flags: c_uint, create_plist: hid_t, access_plist: hid_t) -> hid_t; pub fn H5Fopen(filename: *const c_char, flags: c_uint, access_plist: hid_t) -> hid_t; pub fn H5Freopen(file_id: hid_t) -> hid_t; pub fn H5Fflush(object_id: hid_t, scope: H5F_scope_t) -> herr_t; pub fn H5Fclose(file_id: hid_t) -> herr_t; pub fn H5Fget_create_plist(file_id: hid_t) -> hid_t; pub fn H5Fget_access_plist(file_id: hid_t) -> hid_t; pub fn H5Fget_intent(file_id: hid_t, intent: *mut c_uint) -> herr_t; pub fn H5Fget_obj_count(file_id: hid_t, types: c_uint) -> ssize_t; pub fn H5Fget_obj_ids(file_id: hid_t, types: c_uint, max_objs: size_t, obj_id_list: *mut hid_t) -> ssize_t; pub fn H5Fget_vfd_handle(file_id: hid_t, fapl: hid_t, file_handle: *mut *mut c_void) -> herr_t; pub fn H5Fmount(loc: hid_t, name: *const c_char, child: hid_t, plist: hid_t) -> herr_t; pub fn H5Funmount(loc: hid_t, name: *const c_char) -> herr_t; pub fn H5Fget_freespace(file_id: hid_t) -> hssize_t; pub fn H5Fget_filesize(file_id: hid_t, size: *mut hsize_t) -> herr_t; pub fn H5Fget_file_image(file_id: hid_t, buf_ptr: *mut c_void, buf_len: size_t) -> ssize_t; pub fn H5Fget_mdc_config(file_id: hid_t, config_ptr: *mut H5AC_cache_config_t) -> herr_t; pub fn H5Fset_mdc_config(file_id: hid_t, config_ptr: *mut H5AC_cache_config_t) -> herr_t; pub fn H5Fget_mdc_hit_rate(file_id: hid_t, hit_rate_ptr: *mut c_double) -> herr_t; pub fn H5Fget_mdc_size(file_id: hid_t, max_size_ptr: *mut size_t, min_clean_size_ptr: *mut size_t, cur_size_ptr: *mut size_t, cur_num_entries_ptr: *mut c_int) -> herr_t; pub fn H5Freset_mdc_hit_rate_stats(file_id: hid_t) -> herr_t; pub fn H5Fget_name(obj_id: hid_t, name: *mut c_char, size: size_t) -> ssize_t; pub fn H5Fget_info(obj_id: hid_t, bh_info: *mut H5F_info_t) -> herr_t; pub fn H5Fclear_elink_file_cache(file_id: hid_t) -> herr_t; }
{ unsafe { ::std::mem::zeroed() } }
identifier_body
main.rs
extern crate capnp; extern crate capnp_rpc; use std::error::Error; use std::io; use capnp_rpc::{RpcSystem,twoparty,rpc_twoparty_capnp}; use capnp_rpc::capability::{InitRequest,LocalClient,WaitForContent}; use gj::{EventLoop,Promise,TaskReaper,TaskSet}; use gj::io::tcp; use freestack::identity3; pub fn accept_loop(listener: tcp::Listener, mut task_set: TaskSet<(), Box<Error>>, client: Client,, ) -> Promise<(), io::Error> { listener.accept().lift().then(move |(listener, stream)| { let (reader, writer) = stream.split(); let mut network = twoparty::VatNetwork::new(reader, writer, rpc_twoparty_capnp::Side::Server, Default::default()); let disconnect_promise = network.on_disconnect(); let rpc_system = RpcSystem::new(Box::new(network), Some(client.clone().client)); task_set.add(disconnect_promise.attach(rpc_system).lift()); accept_loop(listener, task_set, client) }) } struct Reaper; impl TaskReaper<(), Box<Error>> for Reaper { fn task_failed(&mut self, error: Box<Error>) { // FIXME: log instead println!("Task failed: {}", error); } } fn main() {
let store = Rc::new(RefCell::new( kvstore::etcd::Etcd::new(etcd_url) .expect("Error connecting to etcd"))); let identity3_server = identity3::bootstrap_interface(store); EventLoop::top_level(move |wait_scope| { use std::net::ToSocketAddrs; let addr = try!(bind_addr.to_socket_addrs()).next().expect("could ot parse address"); let listener = try!(tcp::Listener::bind(addr)); let task_set = TaskSet::new(Box::new(Reaper)); try!(accept_loop(listener, task_set, identity3_server).wait(wait_scope)); Ok(()) }).expect("top level error"); }
println!("Starting up"); let bind_addr = "localhost:1234"; let etcd_url = "http://localhost:2379";
random_line_split
main.rs
extern crate capnp; extern crate capnp_rpc; use std::error::Error; use std::io; use capnp_rpc::{RpcSystem,twoparty,rpc_twoparty_capnp}; use capnp_rpc::capability::{InitRequest,LocalClient,WaitForContent}; use gj::{EventLoop,Promise,TaskReaper,TaskSet}; use gj::io::tcp; use freestack::identity3; pub fn accept_loop(listener: tcp::Listener, mut task_set: TaskSet<(), Box<Error>>, client: Client,, ) -> Promise<(), io::Error> { listener.accept().lift().then(move |(listener, stream)| { let (reader, writer) = stream.split(); let mut network = twoparty::VatNetwork::new(reader, writer, rpc_twoparty_capnp::Side::Server, Default::default()); let disconnect_promise = network.on_disconnect(); let rpc_system = RpcSystem::new(Box::new(network), Some(client.clone().client)); task_set.add(disconnect_promise.attach(rpc_system).lift()); accept_loop(listener, task_set, client) }) } struct
; impl TaskReaper<(), Box<Error>> for Reaper { fn task_failed(&mut self, error: Box<Error>) { // FIXME: log instead println!("Task failed: {}", error); } } fn main() { println!("Starting up"); let bind_addr = "localhost:1234"; let etcd_url = "http://localhost:2379"; let store = Rc::new(RefCell::new( kvstore::etcd::Etcd::new(etcd_url) .expect("Error connecting to etcd"))); let identity3_server = identity3::bootstrap_interface(store); EventLoop::top_level(move |wait_scope| { use std::net::ToSocketAddrs; let addr = try!(bind_addr.to_socket_addrs()).next().expect("could ot parse address"); let listener = try!(tcp::Listener::bind(addr)); let task_set = TaskSet::new(Box::new(Reaper)); try!(accept_loop(listener, task_set, identity3_server).wait(wait_scope)); Ok(()) }).expect("top level error"); }
Reaper
identifier_name
rectangle.rs
use crate::factory::IFactory; use crate::geometry::IGeometry; use crate::resource::IResource; use std::mem::MaybeUninit; use com_wrapper::ComWrapper; use dcommon::Error; use math2d::Rectf; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::{ID2D1Geometry, ID2D1RectangleGeometry, ID2D1Resource}; use wio::com::ComPtr; #[repr(transparent)] #[derive(ComWrapper, Clone)] #[com(send, sync, debug)] /// Represents a rectangle which can be used anywhere Geometry is needed pub struct RectangleGeometry { ptr: ComPtr<ID2D1RectangleGeometry>,
impl RectangleGeometry { pub fn create(factory: &dyn IFactory, rectangle: &Rectf) -> Result<RectangleGeometry, Error> { unsafe { let mut ptr = std::ptr::null_mut(); let hr = factory .raw_f() .CreateRectangleGeometry(rectangle as *const _ as *const _, &mut ptr); if SUCCEEDED(hr) { Ok(RectangleGeometry::from_raw(ptr)) } else { Err(hr.into()) } } } pub fn rect(&self) -> Rectf { unsafe { let mut rect = MaybeUninit::uninit(); self.ptr.GetRect(rect.as_mut_ptr()); rect.assume_init().into() } } } unsafe impl IResource for RectangleGeometry { unsafe fn raw_resource(&self) -> &ID2D1Resource { &self.ptr } } unsafe impl IGeometry for RectangleGeometry { unsafe fn raw_geom(&self) -> &ID2D1Geometry { &self.ptr } } unsafe impl super::GeometryType for RectangleGeometry {}
}
random_line_split
rectangle.rs
use crate::factory::IFactory; use crate::geometry::IGeometry; use crate::resource::IResource; use std::mem::MaybeUninit; use com_wrapper::ComWrapper; use dcommon::Error; use math2d::Rectf; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::{ID2D1Geometry, ID2D1RectangleGeometry, ID2D1Resource}; use wio::com::ComPtr; #[repr(transparent)] #[derive(ComWrapper, Clone)] #[com(send, sync, debug)] /// Represents a rectangle which can be used anywhere Geometry is needed pub struct
{ ptr: ComPtr<ID2D1RectangleGeometry>, } impl RectangleGeometry { pub fn create(factory: &dyn IFactory, rectangle: &Rectf) -> Result<RectangleGeometry, Error> { unsafe { let mut ptr = std::ptr::null_mut(); let hr = factory .raw_f() .CreateRectangleGeometry(rectangle as *const _ as *const _, &mut ptr); if SUCCEEDED(hr) { Ok(RectangleGeometry::from_raw(ptr)) } else { Err(hr.into()) } } } pub fn rect(&self) -> Rectf { unsafe { let mut rect = MaybeUninit::uninit(); self.ptr.GetRect(rect.as_mut_ptr()); rect.assume_init().into() } } } unsafe impl IResource for RectangleGeometry { unsafe fn raw_resource(&self) -> &ID2D1Resource { &self.ptr } } unsafe impl IGeometry for RectangleGeometry { unsafe fn raw_geom(&self) -> &ID2D1Geometry { &self.ptr } } unsafe impl super::GeometryType for RectangleGeometry {}
RectangleGeometry
identifier_name
rectangle.rs
use crate::factory::IFactory; use crate::geometry::IGeometry; use crate::resource::IResource; use std::mem::MaybeUninit; use com_wrapper::ComWrapper; use dcommon::Error; use math2d::Rectf; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::{ID2D1Geometry, ID2D1RectangleGeometry, ID2D1Resource}; use wio::com::ComPtr; #[repr(transparent)] #[derive(ComWrapper, Clone)] #[com(send, sync, debug)] /// Represents a rectangle which can be used anywhere Geometry is needed pub struct RectangleGeometry { ptr: ComPtr<ID2D1RectangleGeometry>, } impl RectangleGeometry { pub fn create(factory: &dyn IFactory, rectangle: &Rectf) -> Result<RectangleGeometry, Error> { unsafe { let mut ptr = std::ptr::null_mut(); let hr = factory .raw_f() .CreateRectangleGeometry(rectangle as *const _ as *const _, &mut ptr); if SUCCEEDED(hr) { Ok(RectangleGeometry::from_raw(ptr)) } else { Err(hr.into()) } } } pub fn rect(&self) -> Rectf { unsafe { let mut rect = MaybeUninit::uninit(); self.ptr.GetRect(rect.as_mut_ptr()); rect.assume_init().into() } } } unsafe impl IResource for RectangleGeometry { unsafe fn raw_resource(&self) -> &ID2D1Resource { &self.ptr } } unsafe impl IGeometry for RectangleGeometry { unsafe fn raw_geom(&self) -> &ID2D1Geometry
} unsafe impl super::GeometryType for RectangleGeometry {}
{ &self.ptr }
identifier_body
rectangle.rs
use crate::factory::IFactory; use crate::geometry::IGeometry; use crate::resource::IResource; use std::mem::MaybeUninit; use com_wrapper::ComWrapper; use dcommon::Error; use math2d::Rectf; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::{ID2D1Geometry, ID2D1RectangleGeometry, ID2D1Resource}; use wio::com::ComPtr; #[repr(transparent)] #[derive(ComWrapper, Clone)] #[com(send, sync, debug)] /// Represents a rectangle which can be used anywhere Geometry is needed pub struct RectangleGeometry { ptr: ComPtr<ID2D1RectangleGeometry>, } impl RectangleGeometry { pub fn create(factory: &dyn IFactory, rectangle: &Rectf) -> Result<RectangleGeometry, Error> { unsafe { let mut ptr = std::ptr::null_mut(); let hr = factory .raw_f() .CreateRectangleGeometry(rectangle as *const _ as *const _, &mut ptr); if SUCCEEDED(hr) { Ok(RectangleGeometry::from_raw(ptr)) } else
} } pub fn rect(&self) -> Rectf { unsafe { let mut rect = MaybeUninit::uninit(); self.ptr.GetRect(rect.as_mut_ptr()); rect.assume_init().into() } } } unsafe impl IResource for RectangleGeometry { unsafe fn raw_resource(&self) -> &ID2D1Resource { &self.ptr } } unsafe impl IGeometry for RectangleGeometry { unsafe fn raw_geom(&self) -> &ID2D1Geometry { &self.ptr } } unsafe impl super::GeometryType for RectangleGeometry {}
{ Err(hr.into()) }
conditional_block
pipe.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use io; use libc; use sys::cvt; use sys::c; use sys::handle::Handle; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe { inner: Handle, } pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { let mut reader = libc::INVALID_HANDLE_VALUE; let mut writer = libc::INVALID_HANDLE_VALUE; try!(cvt(unsafe { c::CreatePipe(&mut reader, &mut writer, 0 as *mut _, 0) })); let reader = Handle::new(reader); let writer = Handle::new(writer); Ok((AnonPipe { inner: reader }, AnonPipe { inner: writer })) } impl AnonPipe { pub fn handle(&self) -> &Handle { &self.inner } pub fn into_handle(self) -> Handle
pub fn raw(&self) -> libc::HANDLE { self.inner.raw() } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.inner.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.inner.write(buf) } }
{ self.inner }
identifier_body
pipe.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use io; use libc; use sys::cvt; use sys::c; use sys::handle::Handle; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe { inner: Handle, } pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { let mut reader = libc::INVALID_HANDLE_VALUE; let mut writer = libc::INVALID_HANDLE_VALUE; try!(cvt(unsafe { c::CreatePipe(&mut reader, &mut writer, 0 as *mut _, 0) })); let reader = Handle::new(reader); let writer = Handle::new(writer); Ok((AnonPipe { inner: reader }, AnonPipe { inner: writer })) } impl AnonPipe { pub fn handle(&self) -> &Handle { &self.inner } pub fn into_handle(self) -> Handle { self.inner } pub fn raw(&self) -> libc::HANDLE { self.inner.raw() } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.inner.read(buf) } pub fn
(&self, buf: &[u8]) -> io::Result<usize> { self.inner.write(buf) } }
write
identifier_name
pipe.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use io; use libc; use sys::cvt; use sys::c; use sys::handle::Handle; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe { inner: Handle, } pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { let mut reader = libc::INVALID_HANDLE_VALUE; let mut writer = libc::INVALID_HANDLE_VALUE; try!(cvt(unsafe {
})); let reader = Handle::new(reader); let writer = Handle::new(writer); Ok((AnonPipe { inner: reader }, AnonPipe { inner: writer })) } impl AnonPipe { pub fn handle(&self) -> &Handle { &self.inner } pub fn into_handle(self) -> Handle { self.inner } pub fn raw(&self) -> libc::HANDLE { self.inner.raw() } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.inner.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.inner.write(buf) } }
c::CreatePipe(&mut reader, &mut writer, 0 as *mut _, 0)
random_line_split
msgsend-pipes-shared.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. // This version uses pipes with a shared send endpoint. It should have // different scalability characteristics compared to the select // version. extern crate time; extern crate debug; use std::comm; use std::os; use std::task; use std::uint; fn move_out<T>(_x: T)
enum request { get_count, bytes(uint), stop } fn server(requests: &Receiver<request>, responses: &Sender<uint>) { let mut count = 0u; let mut done = false; while!done { match requests.recv_opt() { Ok(get_count) => { responses.send(count.clone()); } Ok(bytes(b)) => { //println!("server: received {:?} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count); //println!("server exiting"); } fn run(args: &[String]) { let (to_parent, from_child) = channel(); let (to_child, from_parent) = channel(); let size = from_str::<uint>(args[1].as_slice()).unwrap(); let workers = from_str::<uint>(args[2].as_slice()).unwrap(); let num_bytes = 100; let start = time::precise_time_s(); let mut worker_results = Vec::new(); for _ in range(0u, workers) { let to_child = to_child.clone(); worker_results.push(task::try_future(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); })); } task::spawn(proc() { server(&from_parent, &to_parent); }); for r in worker_results.move_iter() { r.unwrap(); } //println!("sending stop message"); to_child.send(stop); move_out(to_child); let result = from_child.recv(); let end = time::precise_time_s(); let elapsed = end - start; print!("Count is {:?}\n", result); print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_string(), "1000000".to_string(), "10000".to_string()) } else if args.len() <= 1u { vec!("".to_string(), "10000".to_string(), "4".to_string()) } else { args.move_iter().map(|x| x.to_string()).collect() }; println!("{}", args); run(args.as_slice()); }
{}
identifier_body
msgsend-pipes-shared.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. // This version uses pipes with a shared send endpoint. It should have // different scalability characteristics compared to the select // version. extern crate time; extern crate debug; use std::comm; use std::os; use std::task; use std::uint; fn move_out<T>(_x: T) {} enum request { get_count, bytes(uint), stop } fn server(requests: &Receiver<request>, responses: &Sender<uint>) { let mut count = 0u; let mut done = false; while!done { match requests.recv_opt() { Ok(get_count) => { responses.send(count.clone()); } Ok(bytes(b)) => { //println!("server: received {:?} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count); //println!("server exiting"); } fn run(args: &[String]) { let (to_parent, from_child) = channel(); let (to_child, from_parent) = channel(); let size = from_str::<uint>(args[1].as_slice()).unwrap(); let workers = from_str::<uint>(args[2].as_slice()).unwrap(); let num_bytes = 100; let start = time::precise_time_s(); let mut worker_results = Vec::new(); for _ in range(0u, workers) { let to_child = to_child.clone(); worker_results.push(task::try_future(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); })); } task::spawn(proc() { server(&from_parent, &to_parent); }); for r in worker_results.move_iter() { r.unwrap(); } //println!("sending stop message"); to_child.send(stop); move_out(to_child); let result = from_child.recv(); let end = time::precise_time_s(); let elapsed = end - start; print!("Count is {:?}\n", result); print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some()
else if args.len() <= 1u { vec!("".to_string(), "10000".to_string(), "4".to_string()) } else { args.move_iter().map(|x| x.to_string()).collect() }; println!("{}", args); run(args.as_slice()); }
{ vec!("".to_string(), "1000000".to_string(), "10000".to_string()) }
conditional_block
msgsend-pipes-shared.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. // This version uses pipes with a shared send endpoint. It should have // different scalability characteristics compared to the select // version. extern crate time; extern crate debug; use std::comm; use std::os; use std::task; use std::uint; fn move_out<T>(_x: T) {} enum request { get_count, bytes(uint), stop } fn server(requests: &Receiver<request>, responses: &Sender<uint>) { let mut count = 0u; let mut done = false; while!done { match requests.recv_opt() {
Ok(get_count) => { responses.send(count.clone()); } Ok(bytes(b)) => { //println!("server: received {:?} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count); //println!("server exiting"); } fn run(args: &[String]) { let (to_parent, from_child) = channel(); let (to_child, from_parent) = channel(); let size = from_str::<uint>(args[1].as_slice()).unwrap(); let workers = from_str::<uint>(args[2].as_slice()).unwrap(); let num_bytes = 100; let start = time::precise_time_s(); let mut worker_results = Vec::new(); for _ in range(0u, workers) { let to_child = to_child.clone(); worker_results.push(task::try_future(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); })); } task::spawn(proc() { server(&from_parent, &to_parent); }); for r in worker_results.move_iter() { r.unwrap(); } //println!("sending stop message"); to_child.send(stop); move_out(to_child); let result = from_child.recv(); let end = time::precise_time_s(); let elapsed = end - start; print!("Count is {:?}\n", result); print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_string(), "1000000".to_string(), "10000".to_string()) } else if args.len() <= 1u { vec!("".to_string(), "10000".to_string(), "4".to_string()) } else { args.move_iter().map(|x| x.to_string()).collect() }; println!("{}", args); run(args.as_slice()); }
random_line_split
msgsend-pipes-shared.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. // This version uses pipes with a shared send endpoint. It should have // different scalability characteristics compared to the select // version. extern crate time; extern crate debug; use std::comm; use std::os; use std::task; use std::uint; fn
<T>(_x: T) {} enum request { get_count, bytes(uint), stop } fn server(requests: &Receiver<request>, responses: &Sender<uint>) { let mut count = 0u; let mut done = false; while!done { match requests.recv_opt() { Ok(get_count) => { responses.send(count.clone()); } Ok(bytes(b)) => { //println!("server: received {:?} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count); //println!("server exiting"); } fn run(args: &[String]) { let (to_parent, from_child) = channel(); let (to_child, from_parent) = channel(); let size = from_str::<uint>(args[1].as_slice()).unwrap(); let workers = from_str::<uint>(args[2].as_slice()).unwrap(); let num_bytes = 100; let start = time::precise_time_s(); let mut worker_results = Vec::new(); for _ in range(0u, workers) { let to_child = to_child.clone(); worker_results.push(task::try_future(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); })); } task::spawn(proc() { server(&from_parent, &to_parent); }); for r in worker_results.move_iter() { r.unwrap(); } //println!("sending stop message"); to_child.send(stop); move_out(to_child); let result = from_child.recv(); let end = time::precise_time_s(); let elapsed = end - start; print!("Count is {:?}\n", result); print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_string(), "1000000".to_string(), "10000".to_string()) } else if args.len() <= 1u { vec!("".to_string(), "10000".to_string(), "4".to_string()) } else { args.move_iter().map(|x| x.to_string()).collect() }; println!("{}", args); run(args.as_slice()); }
move_out
identifier_name
contain.rs
use matchers::matcher::Matcher; pub struct Contain<T: PartialEq> { value: T, file_line: (&'static str, u32) } impl <T: PartialEq> Matcher<Vec<T>> for Contain<T> { fn assert_check(&self, expected: Vec<T>) -> bool { expected.contains(&self.value) } #[allow(unused_variables)] fn msg(&self, expected: Vec<T>) -> String { format!("Expected {} to contain {} but it did not.", stringify!(expected), stringify!(self.value)) } #[allow(unused_variables)] fn negated_msg(&self, expected: Vec<T>) -> String { format!("Expected {} NOT to contain {} but it did.", stringify!(expected), stringify!(self.value)) } fn get_file_line(&self) -> (&'static str, u32)
} pub fn contain<T: PartialEq>(value: T, file_line: (&'static str, u32)) -> Box<Contain<T>> { Box::new(Contain { value: value, file_line: file_line }) } #[macro_export] macro_rules! contain( ($value:expr) => ( contain($value.clone(), (file!(), expand_line!())) ); );
{ self.file_line }
identifier_body
contain.rs
use matchers::matcher::Matcher; pub struct Contain<T: PartialEq> {
file_line: (&'static str, u32) } impl <T: PartialEq> Matcher<Vec<T>> for Contain<T> { fn assert_check(&self, expected: Vec<T>) -> bool { expected.contains(&self.value) } #[allow(unused_variables)] fn msg(&self, expected: Vec<T>) -> String { format!("Expected {} to contain {} but it did not.", stringify!(expected), stringify!(self.value)) } #[allow(unused_variables)] fn negated_msg(&self, expected: Vec<T>) -> String { format!("Expected {} NOT to contain {} but it did.", stringify!(expected), stringify!(self.value)) } fn get_file_line(&self) -> (&'static str, u32) { self.file_line } } pub fn contain<T: PartialEq>(value: T, file_line: (&'static str, u32)) -> Box<Contain<T>> { Box::new(Contain { value: value, file_line: file_line }) } #[macro_export] macro_rules! contain( ($value:expr) => ( contain($value.clone(), (file!(), expand_line!())) ); );
value: T,
random_line_split
contain.rs
use matchers::matcher::Matcher; pub struct Contain<T: PartialEq> { value: T, file_line: (&'static str, u32) } impl <T: PartialEq> Matcher<Vec<T>> for Contain<T> { fn assert_check(&self, expected: Vec<T>) -> bool { expected.contains(&self.value) } #[allow(unused_variables)] fn msg(&self, expected: Vec<T>) -> String { format!("Expected {} to contain {} but it did not.", stringify!(expected), stringify!(self.value)) } #[allow(unused_variables)] fn negated_msg(&self, expected: Vec<T>) -> String { format!("Expected {} NOT to contain {} but it did.", stringify!(expected), stringify!(self.value)) } fn
(&self) -> (&'static str, u32) { self.file_line } } pub fn contain<T: PartialEq>(value: T, file_line: (&'static str, u32)) -> Box<Contain<T>> { Box::new(Contain { value: value, file_line: file_line }) } #[macro_export] macro_rules! contain( ($value:expr) => ( contain($value.clone(), (file!(), expand_line!())) ); );
get_file_line
identifier_name
mod.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. //! Trait Resolution. See the Book for more. pub use self::SelectionError::*; pub use self::FulfillmentErrorCode::*; pub use self::Vtable::*; pub use self::ObligationCauseCode::*; use middle::free_region::FreeRegionMap; use middle::subst; use middle::ty::{self, HasTypeFlags, Ty}; use middle::ty_fold::TypeFoldable; use middle::infer::{self, fixup_err_to_string, InferCtxt}; use std::rc::Rc; use syntax::ast; use syntax::codemap::{Span, DUMMY_SP}; pub use self::error_reporting::report_fulfillment_errors; pub use self::error_reporting::report_overflow_error; pub use self::error_reporting::report_selection_error; pub use self::error_reporting::suggest_new_overflow_limit; pub use self::coherence::orphan_check; pub use self::coherence::overlapping_impls; pub use self::coherence::OrphanCheckErr; pub use self::fulfill::{FulfillmentContext, FulfilledPredicates, RegionObligation}; pub use self::project::MismatchedProjectionTypes; pub use self::project::normalize; pub use self::project::Normalized; pub use self::object_safety::is_object_safe; pub use self::object_safety::object_safety_violations; pub use self::object_safety::ObjectSafetyViolation; pub use self::object_safety::MethodViolationCode; pub use self::object_safety::is_vtable_safe_method; pub use self::select::SelectionContext; pub use self::select::SelectionCache; pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch}; pub use self::select::{MethodMatchedData}; // intentionally don't export variants pub use self::util::elaborate_predicates; pub use self::util::get_vtable_index_of_object_method; pub use self::util::trait_ref_for_builtin_bound; pub use self::util::predicate_for_trait_def; pub use self::util::supertraits; pub use self::util::Supertraits; pub use self::util::supertrait_def_ids; pub use self::util::SupertraitDefIds; pub use self::util::transitive_bounds; pub use self::util::upcast; mod coherence; mod error_reporting; mod fulfill; mod project; mod object_safety; mod select; mod util; /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for /// which the vtable must be found. The process of finding a vtable is /// called "resolving" the `Obligation`. This process consists of /// either identifying an `impl` (e.g., `impl Eq for int`) that /// provides the required vtable, or else finding a bound that is in /// scope. The eventual result is usually a `Selection` (defined below). #[derive(Clone, PartialEq, Eq)] pub struct Obligation<'tcx, T> { pub cause: ObligationCause<'tcx>, pub recursion_depth: usize, pub predicate: T, } pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>; pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>; /// Why did we incur this obligation? Used for error reporting. #[derive(Clone, PartialEq, Eq)] pub struct ObligationCause<'tcx> { pub span: Span, // The id of the fn body that triggered this obligation. This is // used for region obligations to determine the precise // environment in which the region obligation should be evaluated // (in particular, closures can add new assumptions). See the // field `region_obligations` of the `FulfillmentContext` for more // information. pub body_id: ast::NodeId, pub code: ObligationCauseCode<'tcx> } #[derive(Clone, PartialEq, Eq)] pub enum ObligationCauseCode<'tcx> { /// Not well classified or should be obvious from span. MiscObligation, /// In an impl of trait X for type Y, type Y must /// also implement all supertraits of X. ItemObligation(ast::DefId), /// Obligation incurred due to an object cast. ObjectCastObligation(/* Object type */ Ty<'tcx>), /// Various cases where expressions must be sized/copy/etc: AssignmentLhsSized, // L = X implies that L is Sized StructInitializerSized, // S {... } must be Sized VariableType(ast::NodeId), // Type of each variable must be Sized ReturnType, // Return type must be Sized RepeatVec, // [T,..n] --> T must be Copy // Captures of variable the given id by a closure (span is the // span of the closure) ClosureCapture(ast::NodeId, Span, ty::BuiltinBound), // Types of fields (other than the last) in a struct must be sized. FieldSized, // static items must have `Sync` type SharedStatic, BuiltinDerivedObligation(DerivedObligationCause<'tcx>), ImplDerivedObligation(DerivedObligationCause<'tcx>), CompareImplMethodObligation, } #[derive(Clone, PartialEq, Eq)] pub struct DerivedObligationCause<'tcx> { /// The trait reference of the parent obligation that led to the /// current obligation. Note that only trait obligations lead to /// derived obligations, so we just store the trait reference here /// directly. parent_trait_ref: ty::PolyTraitRef<'tcx>, /// The parent trait had this cause parent_code: Rc<ObligationCauseCode<'tcx>> } pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>; pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>; pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>; pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>; #[derive(Clone,Debug)] pub enum SelectionError<'tcx> { Unimplemented, OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>, ty::PolyTraitRef<'tcx>, ty::type_err<'tcx>), TraitNotObjectSafe(ast::DefId), } pub struct FulfillmentError<'tcx> { pub obligation: PredicateObligation<'tcx>, pub code: FulfillmentErrorCode<'tcx> } #[derive(Clone)] pub enum FulfillmentErrorCode<'tcx> { CodeSelectionError(SelectionError<'tcx>), CodeProjectionError(MismatchedProjectionTypes<'tcx>), CodeAmbiguity, } /// When performing resolution, it is typically the case that there /// can be one of three outcomes: /// /// - `Ok(Some(r))`: success occurred with result `r` /// - `Ok(None)`: could not definitely determine anything, usually due /// to inconclusive type inference. /// - `Err(e)`: error `e` occurred pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>; /// Given the successful resolution of an obligation, the `Vtable` /// indicates where the vtable comes from. Note that while we call this /// a "vtable", it does not necessarily indicate dynamic dispatch at /// runtime. `Vtable` instances just tell the compiler where to find /// methods, but in generic code those methods are typically statically /// dispatched -- only when an object is constructed is a `Vtable` /// instance reified into an actual vtable. /// /// For example, the vtable may be tied to a specific impl (case A), /// or it may be relative to some bound that is in scope (case B). /// /// /// ``` /// impl<T:Clone> Clone<T> for Option<T> {... } // Impl_1 /// impl<T:Clone> Clone<T> for Box<T> {... } // Impl_2 /// impl Clone for int {... } // Impl_3 /// /// fn foo<T:Clone>(concrete: Option<Box<int>>, /// param: T, /// mixed: Option<T>) { /// /// // Case A: Vtable points at a specific impl. Only possible when /// // type is concretely known. If the impl itself has bounded /// // type parameters, Vtable will carry resolutions for those as well: /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])]) /// /// // Case B: Vtable must be provided by caller. This applies when /// // type is a type parameter. /// param.clone(); // VtableParam /// /// // Case C: A mix of cases A and B. /// mixed.clone(); // Vtable(Impl_1, [VtableParam]) /// } /// ``` /// /// ### The type parameter `N` /// /// See explanation on `VtableImplData`. #[derive(Clone)] pub enum Vtable<'tcx, N> { /// Vtable identifying a particular impl. VtableImpl(VtableImplData<'tcx, N>), /// Vtable for default trait implementations /// This carries the information and nested obligations with regards /// to a default implementation for a trait `Trait`. The nested obligations /// ensure the trait implementation holds for all the constituent types. VtableDefaultImpl(VtableDefaultImplData<N>), /// Successful resolution to an obligation provided by the caller /// for some type parameter. The `Vec<N>` represents the /// obligations incurred from normalizing the where-clause (if /// any). VtableParam(Vec<N>), /// Virtual calls through an object VtableObject(VtableObjectData<'tcx>), /// Successful resolution for a builtin trait. VtableBuiltin(VtableBuiltinData<N>), /// Vtable automatically generated for a closure. The def ID is the ID /// of the closure expression. This is a `VtableImpl` in spirit, but the /// impl is generated by the compiler and does not appear in the source. VtableClosure(VtableClosureData<'tcx, N>), /// Same as above, but for a fn pointer type with the given signature. VtableFnPointer(ty::Ty<'tcx>), } /// Identifies a particular impl in the source, along with a set of /// substitutions from the impl's type/lifetime parameters. The /// `nested` vector corresponds to the nested obligations attached to /// the impl's type parameters. /// /// The type parameter `N` indicates the type used for "nested /// obligations" that are required by the impl. During type check, this /// is `Obligation`, as one might expect. During trans, however, this /// is `()`, because trans only requires a shallow resolution of an /// impl, and nested obligations are satisfied later. #[derive(Clone, PartialEq, Eq)] pub struct VtableImplData<'tcx, N> { pub impl_def_id: ast::DefId, pub substs: subst::Substs<'tcx>, pub nested: Vec<N> } #[derive(Clone, PartialEq, Eq)] pub struct VtableClosureData<'tcx, N> { pub closure_def_id: ast::DefId, pub substs: subst::Substs<'tcx>, /// Nested obligations. This can be non-empty if the closure /// signature contains associated types. pub nested: Vec<N> } #[derive(Clone)] pub struct VtableDefaultImplData<N> { pub trait_def_id: ast::DefId, pub nested: Vec<N> } #[derive(Clone)] pub struct VtableBuiltinData<N> { pub nested: Vec<N> } /// A vtable for some object-safe trait `Foo` automatically derived /// for the object type `Foo`. #[derive(PartialEq,Eq,Clone)] pub struct VtableObjectData<'tcx> { /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`. pub upcast_trait_ref: ty::PolyTraitRef<'tcx>, /// The vtable is formed by concatenating together the method lists of /// the base object trait and all supertraits; this is the start of /// `upcast_trait_ref`'s methods in that vtable. pub vtable_base: usize } /// Creates predicate obligations from the generic bounds. pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>, generic_bounds: &ty::InstantiatedPredicates<'tcx>) -> PredicateObligations<'tcx> { util::predicates_for_generics(cause, 0, generic_bounds) } /// Determines whether the type `ty` is known to meet `bound` and /// returns true if so. Returns false if `ty` either does not meet /// `bound` or is not known to meet bound (note that this is /// conservative towards *no impl*, which is the opposite of the /// `evaluate` methods). pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, ty: Ty<'tcx>, bound: ty::BuiltinBound, span: Span) -> bool { debug!("type_known_to_meet_builtin_bound(ty={:?}, bound={:?})", ty, bound); let mut fulfill_cx = FulfillmentContext::new(false); // We can use a dummy node-id here because we won't pay any mind // to region obligations that arise (there shouldn't really be any // anyhow). let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID); fulfill_cx.register_builtin_bound(infcx, ty, bound, cause); // Note: we only assume something is `Copy` if we can // *definitively* show that it implements `Copy`. Otherwise, // assume it is move; linear is always ok. match fulfill_cx.select_all_or_error(infcx) { Ok(()) => { debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} success", ty, bound); true } Err(e) => { debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} errors={:?}", ty, bound, e); false } } } // FIXME: this is gonna need to be removed... /// Normalizes the parameter environment, reporting errors if they occur. pub fn normalize_param_env_or_error<'a,'tcx>(unnormalized_env: ty::ParameterEnvironment<'a,'tcx>, cause: ObligationCause<'tcx>) -> ty::ParameterEnvironment<'a,'tcx> { // I'm not wild about reporting errors here; I'd prefer to // have the errors get reported at a defined place (e.g., // during typeck). Instead I have all parameter // environments, in effect, going through this function // and hence potentially reporting errors. This ensurse of // course that we never forget to normalize (the // alternative seemed like it would involve a lot of // manual invocations of this fn -- and then we'd have to // deal with the errors at each of those sites). // // In any case, in practice, typeck constructs all the // parameter environments once for every fn as it goes, // and errors will get reported then; so after typeck we // can be sure that no errors should occur. let tcx = unnormalized_env.tcx; let span = cause.span; let body_id = cause.body_id; debug!("normalize_param_env_or_error(unnormalized_env={:?})", unnormalized_env); let predicates: Vec<_> = util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone()) .filter(|p|!p.is_global()) // (*) .collect(); // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't // need to be in the *environment* to be proven, so screen those // out. This is important for the soundness of inter-fn // caching. Note though that we should probably check that these // predicates hold at the point where the environment is // constructed, but I am not currently doing so out of laziness. // -nmatsakis debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates); let elaborated_env = unnormalized_env.with_caller_bounds(predicates); let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(elaborated_env), false); let predicates = match fully_normalize(&infcx, cause, &infcx.parameter_environment.caller_bounds) { Ok(predicates) => predicates, Err(errors) => { report_fulfillment_errors(&infcx, &errors); return infcx.parameter_environment; // an unnormalized env is better than nothing } }; let free_regions = FreeRegionMap::new(); infcx.resolve_regions_and_report_errors(&free_regions, body_id); let predicates = match infcx.fully_resolve(&predicates) { Ok(predicates) => predicates, Err(fixup_err) => { // If we encounter a fixup error, it means that some type // variable wound up unconstrained. I actually don't know // if this can happen, and I certainly don't expect it to // happen often, but if it did happen it probably // represents a legitimate failure due to some kind of // unconstrained variable, and it seems better not to ICE, // all things considered. let err_msg = fixup_err_to_string(fixup_err); tcx.sess.span_err(span, &err_msg); return infcx.parameter_environment; // an unnormalized env is better than nothing } }; infcx.parameter_environment.with_caller_bounds(predicates) } pub fn fully_normalize<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, cause: ObligationCause<'tcx>, value: &T) -> Result<T, Vec<FulfillmentError<'tcx>>> where T : TypeFoldable<'tcx> + HasTypeFlags { debug!("normalize_param_env(value={:?})", value); let mut selcx = &mut SelectionContext::new(infcx); // FIXME (@jroesch) ISSUE 26721 // I'm not sure if this is a bug or not, needs further investigation. // It appears that by reusing the fulfillment_cx here we incur more // obligations and later trip an asssertion on regionck.rs line 337. // // The two possibilities I see is: // - normalization is not actually fully happening and we // have a bug else where // - we are adding a duplicate bound into the list causing // its size to change. // // I think we should probably land this refactor and then come // back to this is a follow-up patch. let mut fulfill_cx = FulfillmentContext::new(false); let Normalized { value: normalized_value, obligations } = project::normalize(selcx, cause, value); debug!("normalize_param_env: normalized_value={:?} obligations={:?}", normalized_value, obligations); for obligation in obligations { fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation); } try!(fulfill_cx.select_all_or_error(infcx)); let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value); debug!("normalize_param_env: resolved_value={:?}", resolved_value); Ok(resolved_value) } impl<'tcx,O> Obligation<'tcx,O> { pub fn new(cause: ObligationCause<'tcx>, trait_ref: O) -> Obligation<'tcx, O> { Obligation { cause: cause, recursion_depth: 0, predicate: trait_ref } } fn with_depth(cause: ObligationCause<'tcx>, recursion_depth: usize, trait_ref: O) -> Obligation<'tcx, O> { Obligation { cause: cause, recursion_depth: recursion_depth, predicate: trait_ref } } pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> { Obligation::new(ObligationCause::misc(span, body_id), trait_ref) } pub fn with<P>(&self, value: P) -> Obligation<'tcx,P>
} impl<'tcx> ObligationCause<'tcx> { pub fn new(span: Span, body_id: ast::NodeId, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> { ObligationCause { span: span, body_id: body_id, code: code } } pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> { ObligationCause { span: span, body_id: body_id, code: MiscObligation } } pub fn dummy() -> ObligationCause<'tcx> { ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation } } } impl<'tcx, N> Vtable<'tcx, N> { pub fn nested_obligations(self) -> Vec<N> { match self { VtableImpl(i) => i.nested, VtableParam(n) => n, VtableBuiltin(i) => i.nested, VtableDefaultImpl(d) => d.nested, VtableClosure(c) => c.nested, VtableObject(_) | VtableFnPointer(..) => vec![] } } pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M { match self { VtableImpl(i) => VtableImpl(VtableImplData { impl_def_id: i.impl_def_id, substs: i.substs, nested: i.nested.into_iter().map(f).collect() }), VtableParam(n) => VtableParam(n.into_iter().map(f).collect()), VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() }), VtableObject(o) => VtableObject(o), VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData { trait_def_id: d.trait_def_id, nested: d.nested.into_iter().map(f).collect() }), VtableFnPointer(f) => VtableFnPointer(f), VtableClosure(c) => VtableClosure(VtableClosureData { closure_def_id: c.closure_def_id, substs: c.substs, nested: c.nested.into_iter().map(f).collect() }) } } } impl<'tcx> FulfillmentError<'tcx> { fn new(obligation: PredicateObligation<'tcx>, code: FulfillmentErrorCode<'tcx>) -> FulfillmentError<'tcx> { FulfillmentError { obligation: obligation, code: code } } } impl<'tcx> TraitObligation<'tcx> { fn self_ty(&self) -> ty::Binder<Ty<'tcx>> { ty::Binder(self.predicate.skip_binder().self_ty()) } }
{ Obligation { cause: self.cause.clone(), recursion_depth: self.recursion_depth, predicate: value } }
identifier_body
mod.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. //! Trait Resolution. See the Book for more. pub use self::SelectionError::*; pub use self::FulfillmentErrorCode::*; pub use self::Vtable::*; pub use self::ObligationCauseCode::*; use middle::free_region::FreeRegionMap; use middle::subst; use middle::ty::{self, HasTypeFlags, Ty}; use middle::ty_fold::TypeFoldable; use middle::infer::{self, fixup_err_to_string, InferCtxt}; use std::rc::Rc; use syntax::ast; use syntax::codemap::{Span, DUMMY_SP}; pub use self::error_reporting::report_fulfillment_errors; pub use self::error_reporting::report_overflow_error; pub use self::error_reporting::report_selection_error; pub use self::error_reporting::suggest_new_overflow_limit; pub use self::coherence::orphan_check; pub use self::coherence::overlapping_impls; pub use self::coherence::OrphanCheckErr; pub use self::fulfill::{FulfillmentContext, FulfilledPredicates, RegionObligation}; pub use self::project::MismatchedProjectionTypes; pub use self::project::normalize; pub use self::project::Normalized; pub use self::object_safety::is_object_safe; pub use self::object_safety::object_safety_violations; pub use self::object_safety::ObjectSafetyViolation; pub use self::object_safety::MethodViolationCode; pub use self::object_safety::is_vtable_safe_method; pub use self::select::SelectionContext; pub use self::select::SelectionCache; pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch}; pub use self::select::{MethodMatchedData}; // intentionally don't export variants
pub use self::util::Supertraits; pub use self::util::supertrait_def_ids; pub use self::util::SupertraitDefIds; pub use self::util::transitive_bounds; pub use self::util::upcast; mod coherence; mod error_reporting; mod fulfill; mod project; mod object_safety; mod select; mod util; /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for /// which the vtable must be found. The process of finding a vtable is /// called "resolving" the `Obligation`. This process consists of /// either identifying an `impl` (e.g., `impl Eq for int`) that /// provides the required vtable, or else finding a bound that is in /// scope. The eventual result is usually a `Selection` (defined below). #[derive(Clone, PartialEq, Eq)] pub struct Obligation<'tcx, T> { pub cause: ObligationCause<'tcx>, pub recursion_depth: usize, pub predicate: T, } pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>; pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>; /// Why did we incur this obligation? Used for error reporting. #[derive(Clone, PartialEq, Eq)] pub struct ObligationCause<'tcx> { pub span: Span, // The id of the fn body that triggered this obligation. This is // used for region obligations to determine the precise // environment in which the region obligation should be evaluated // (in particular, closures can add new assumptions). See the // field `region_obligations` of the `FulfillmentContext` for more // information. pub body_id: ast::NodeId, pub code: ObligationCauseCode<'tcx> } #[derive(Clone, PartialEq, Eq)] pub enum ObligationCauseCode<'tcx> { /// Not well classified or should be obvious from span. MiscObligation, /// In an impl of trait X for type Y, type Y must /// also implement all supertraits of X. ItemObligation(ast::DefId), /// Obligation incurred due to an object cast. ObjectCastObligation(/* Object type */ Ty<'tcx>), /// Various cases where expressions must be sized/copy/etc: AssignmentLhsSized, // L = X implies that L is Sized StructInitializerSized, // S {... } must be Sized VariableType(ast::NodeId), // Type of each variable must be Sized ReturnType, // Return type must be Sized RepeatVec, // [T,..n] --> T must be Copy // Captures of variable the given id by a closure (span is the // span of the closure) ClosureCapture(ast::NodeId, Span, ty::BuiltinBound), // Types of fields (other than the last) in a struct must be sized. FieldSized, // static items must have `Sync` type SharedStatic, BuiltinDerivedObligation(DerivedObligationCause<'tcx>), ImplDerivedObligation(DerivedObligationCause<'tcx>), CompareImplMethodObligation, } #[derive(Clone, PartialEq, Eq)] pub struct DerivedObligationCause<'tcx> { /// The trait reference of the parent obligation that led to the /// current obligation. Note that only trait obligations lead to /// derived obligations, so we just store the trait reference here /// directly. parent_trait_ref: ty::PolyTraitRef<'tcx>, /// The parent trait had this cause parent_code: Rc<ObligationCauseCode<'tcx>> } pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>; pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>; pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>; pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>; #[derive(Clone,Debug)] pub enum SelectionError<'tcx> { Unimplemented, OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>, ty::PolyTraitRef<'tcx>, ty::type_err<'tcx>), TraitNotObjectSafe(ast::DefId), } pub struct FulfillmentError<'tcx> { pub obligation: PredicateObligation<'tcx>, pub code: FulfillmentErrorCode<'tcx> } #[derive(Clone)] pub enum FulfillmentErrorCode<'tcx> { CodeSelectionError(SelectionError<'tcx>), CodeProjectionError(MismatchedProjectionTypes<'tcx>), CodeAmbiguity, } /// When performing resolution, it is typically the case that there /// can be one of three outcomes: /// /// - `Ok(Some(r))`: success occurred with result `r` /// - `Ok(None)`: could not definitely determine anything, usually due /// to inconclusive type inference. /// - `Err(e)`: error `e` occurred pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>; /// Given the successful resolution of an obligation, the `Vtable` /// indicates where the vtable comes from. Note that while we call this /// a "vtable", it does not necessarily indicate dynamic dispatch at /// runtime. `Vtable` instances just tell the compiler where to find /// methods, but in generic code those methods are typically statically /// dispatched -- only when an object is constructed is a `Vtable` /// instance reified into an actual vtable. /// /// For example, the vtable may be tied to a specific impl (case A), /// or it may be relative to some bound that is in scope (case B). /// /// /// ``` /// impl<T:Clone> Clone<T> for Option<T> {... } // Impl_1 /// impl<T:Clone> Clone<T> for Box<T> {... } // Impl_2 /// impl Clone for int {... } // Impl_3 /// /// fn foo<T:Clone>(concrete: Option<Box<int>>, /// param: T, /// mixed: Option<T>) { /// /// // Case A: Vtable points at a specific impl. Only possible when /// // type is concretely known. If the impl itself has bounded /// // type parameters, Vtable will carry resolutions for those as well: /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])]) /// /// // Case B: Vtable must be provided by caller. This applies when /// // type is a type parameter. /// param.clone(); // VtableParam /// /// // Case C: A mix of cases A and B. /// mixed.clone(); // Vtable(Impl_1, [VtableParam]) /// } /// ``` /// /// ### The type parameter `N` /// /// See explanation on `VtableImplData`. #[derive(Clone)] pub enum Vtable<'tcx, N> { /// Vtable identifying a particular impl. VtableImpl(VtableImplData<'tcx, N>), /// Vtable for default trait implementations /// This carries the information and nested obligations with regards /// to a default implementation for a trait `Trait`. The nested obligations /// ensure the trait implementation holds for all the constituent types. VtableDefaultImpl(VtableDefaultImplData<N>), /// Successful resolution to an obligation provided by the caller /// for some type parameter. The `Vec<N>` represents the /// obligations incurred from normalizing the where-clause (if /// any). VtableParam(Vec<N>), /// Virtual calls through an object VtableObject(VtableObjectData<'tcx>), /// Successful resolution for a builtin trait. VtableBuiltin(VtableBuiltinData<N>), /// Vtable automatically generated for a closure. The def ID is the ID /// of the closure expression. This is a `VtableImpl` in spirit, but the /// impl is generated by the compiler and does not appear in the source. VtableClosure(VtableClosureData<'tcx, N>), /// Same as above, but for a fn pointer type with the given signature. VtableFnPointer(ty::Ty<'tcx>), } /// Identifies a particular impl in the source, along with a set of /// substitutions from the impl's type/lifetime parameters. The /// `nested` vector corresponds to the nested obligations attached to /// the impl's type parameters. /// /// The type parameter `N` indicates the type used for "nested /// obligations" that are required by the impl. During type check, this /// is `Obligation`, as one might expect. During trans, however, this /// is `()`, because trans only requires a shallow resolution of an /// impl, and nested obligations are satisfied later. #[derive(Clone, PartialEq, Eq)] pub struct VtableImplData<'tcx, N> { pub impl_def_id: ast::DefId, pub substs: subst::Substs<'tcx>, pub nested: Vec<N> } #[derive(Clone, PartialEq, Eq)] pub struct VtableClosureData<'tcx, N> { pub closure_def_id: ast::DefId, pub substs: subst::Substs<'tcx>, /// Nested obligations. This can be non-empty if the closure /// signature contains associated types. pub nested: Vec<N> } #[derive(Clone)] pub struct VtableDefaultImplData<N> { pub trait_def_id: ast::DefId, pub nested: Vec<N> } #[derive(Clone)] pub struct VtableBuiltinData<N> { pub nested: Vec<N> } /// A vtable for some object-safe trait `Foo` automatically derived /// for the object type `Foo`. #[derive(PartialEq,Eq,Clone)] pub struct VtableObjectData<'tcx> { /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`. pub upcast_trait_ref: ty::PolyTraitRef<'tcx>, /// The vtable is formed by concatenating together the method lists of /// the base object trait and all supertraits; this is the start of /// `upcast_trait_ref`'s methods in that vtable. pub vtable_base: usize } /// Creates predicate obligations from the generic bounds. pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>, generic_bounds: &ty::InstantiatedPredicates<'tcx>) -> PredicateObligations<'tcx> { util::predicates_for_generics(cause, 0, generic_bounds) } /// Determines whether the type `ty` is known to meet `bound` and /// returns true if so. Returns false if `ty` either does not meet /// `bound` or is not known to meet bound (note that this is /// conservative towards *no impl*, which is the opposite of the /// `evaluate` methods). pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, ty: Ty<'tcx>, bound: ty::BuiltinBound, span: Span) -> bool { debug!("type_known_to_meet_builtin_bound(ty={:?}, bound={:?})", ty, bound); let mut fulfill_cx = FulfillmentContext::new(false); // We can use a dummy node-id here because we won't pay any mind // to region obligations that arise (there shouldn't really be any // anyhow). let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID); fulfill_cx.register_builtin_bound(infcx, ty, bound, cause); // Note: we only assume something is `Copy` if we can // *definitively* show that it implements `Copy`. Otherwise, // assume it is move; linear is always ok. match fulfill_cx.select_all_or_error(infcx) { Ok(()) => { debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} success", ty, bound); true } Err(e) => { debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} errors={:?}", ty, bound, e); false } } } // FIXME: this is gonna need to be removed... /// Normalizes the parameter environment, reporting errors if they occur. pub fn normalize_param_env_or_error<'a,'tcx>(unnormalized_env: ty::ParameterEnvironment<'a,'tcx>, cause: ObligationCause<'tcx>) -> ty::ParameterEnvironment<'a,'tcx> { // I'm not wild about reporting errors here; I'd prefer to // have the errors get reported at a defined place (e.g., // during typeck). Instead I have all parameter // environments, in effect, going through this function // and hence potentially reporting errors. This ensurse of // course that we never forget to normalize (the // alternative seemed like it would involve a lot of // manual invocations of this fn -- and then we'd have to // deal with the errors at each of those sites). // // In any case, in practice, typeck constructs all the // parameter environments once for every fn as it goes, // and errors will get reported then; so after typeck we // can be sure that no errors should occur. let tcx = unnormalized_env.tcx; let span = cause.span; let body_id = cause.body_id; debug!("normalize_param_env_or_error(unnormalized_env={:?})", unnormalized_env); let predicates: Vec<_> = util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone()) .filter(|p|!p.is_global()) // (*) .collect(); // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't // need to be in the *environment* to be proven, so screen those // out. This is important for the soundness of inter-fn // caching. Note though that we should probably check that these // predicates hold at the point where the environment is // constructed, but I am not currently doing so out of laziness. // -nmatsakis debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates); let elaborated_env = unnormalized_env.with_caller_bounds(predicates); let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(elaborated_env), false); let predicates = match fully_normalize(&infcx, cause, &infcx.parameter_environment.caller_bounds) { Ok(predicates) => predicates, Err(errors) => { report_fulfillment_errors(&infcx, &errors); return infcx.parameter_environment; // an unnormalized env is better than nothing } }; let free_regions = FreeRegionMap::new(); infcx.resolve_regions_and_report_errors(&free_regions, body_id); let predicates = match infcx.fully_resolve(&predicates) { Ok(predicates) => predicates, Err(fixup_err) => { // If we encounter a fixup error, it means that some type // variable wound up unconstrained. I actually don't know // if this can happen, and I certainly don't expect it to // happen often, but if it did happen it probably // represents a legitimate failure due to some kind of // unconstrained variable, and it seems better not to ICE, // all things considered. let err_msg = fixup_err_to_string(fixup_err); tcx.sess.span_err(span, &err_msg); return infcx.parameter_environment; // an unnormalized env is better than nothing } }; infcx.parameter_environment.with_caller_bounds(predicates) } pub fn fully_normalize<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, cause: ObligationCause<'tcx>, value: &T) -> Result<T, Vec<FulfillmentError<'tcx>>> where T : TypeFoldable<'tcx> + HasTypeFlags { debug!("normalize_param_env(value={:?})", value); let mut selcx = &mut SelectionContext::new(infcx); // FIXME (@jroesch) ISSUE 26721 // I'm not sure if this is a bug or not, needs further investigation. // It appears that by reusing the fulfillment_cx here we incur more // obligations and later trip an asssertion on regionck.rs line 337. // // The two possibilities I see is: // - normalization is not actually fully happening and we // have a bug else where // - we are adding a duplicate bound into the list causing // its size to change. // // I think we should probably land this refactor and then come // back to this is a follow-up patch. let mut fulfill_cx = FulfillmentContext::new(false); let Normalized { value: normalized_value, obligations } = project::normalize(selcx, cause, value); debug!("normalize_param_env: normalized_value={:?} obligations={:?}", normalized_value, obligations); for obligation in obligations { fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation); } try!(fulfill_cx.select_all_or_error(infcx)); let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value); debug!("normalize_param_env: resolved_value={:?}", resolved_value); Ok(resolved_value) } impl<'tcx,O> Obligation<'tcx,O> { pub fn new(cause: ObligationCause<'tcx>, trait_ref: O) -> Obligation<'tcx, O> { Obligation { cause: cause, recursion_depth: 0, predicate: trait_ref } } fn with_depth(cause: ObligationCause<'tcx>, recursion_depth: usize, trait_ref: O) -> Obligation<'tcx, O> { Obligation { cause: cause, recursion_depth: recursion_depth, predicate: trait_ref } } pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> { Obligation::new(ObligationCause::misc(span, body_id), trait_ref) } pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> { Obligation { cause: self.cause.clone(), recursion_depth: self.recursion_depth, predicate: value } } } impl<'tcx> ObligationCause<'tcx> { pub fn new(span: Span, body_id: ast::NodeId, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> { ObligationCause { span: span, body_id: body_id, code: code } } pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> { ObligationCause { span: span, body_id: body_id, code: MiscObligation } } pub fn dummy() -> ObligationCause<'tcx> { ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation } } } impl<'tcx, N> Vtable<'tcx, N> { pub fn nested_obligations(self) -> Vec<N> { match self { VtableImpl(i) => i.nested, VtableParam(n) => n, VtableBuiltin(i) => i.nested, VtableDefaultImpl(d) => d.nested, VtableClosure(c) => c.nested, VtableObject(_) | VtableFnPointer(..) => vec![] } } pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M { match self { VtableImpl(i) => VtableImpl(VtableImplData { impl_def_id: i.impl_def_id, substs: i.substs, nested: i.nested.into_iter().map(f).collect() }), VtableParam(n) => VtableParam(n.into_iter().map(f).collect()), VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() }), VtableObject(o) => VtableObject(o), VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData { trait_def_id: d.trait_def_id, nested: d.nested.into_iter().map(f).collect() }), VtableFnPointer(f) => VtableFnPointer(f), VtableClosure(c) => VtableClosure(VtableClosureData { closure_def_id: c.closure_def_id, substs: c.substs, nested: c.nested.into_iter().map(f).collect() }) } } } impl<'tcx> FulfillmentError<'tcx> { fn new(obligation: PredicateObligation<'tcx>, code: FulfillmentErrorCode<'tcx>) -> FulfillmentError<'tcx> { FulfillmentError { obligation: obligation, code: code } } } impl<'tcx> TraitObligation<'tcx> { fn self_ty(&self) -> ty::Binder<Ty<'tcx>> { ty::Binder(self.predicate.skip_binder().self_ty()) } }
pub use self::util::elaborate_predicates; pub use self::util::get_vtable_index_of_object_method; pub use self::util::trait_ref_for_builtin_bound; pub use self::util::predicate_for_trait_def; pub use self::util::supertraits;
random_line_split
mod.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. //! Trait Resolution. See the Book for more. pub use self::SelectionError::*; pub use self::FulfillmentErrorCode::*; pub use self::Vtable::*; pub use self::ObligationCauseCode::*; use middle::free_region::FreeRegionMap; use middle::subst; use middle::ty::{self, HasTypeFlags, Ty}; use middle::ty_fold::TypeFoldable; use middle::infer::{self, fixup_err_to_string, InferCtxt}; use std::rc::Rc; use syntax::ast; use syntax::codemap::{Span, DUMMY_SP}; pub use self::error_reporting::report_fulfillment_errors; pub use self::error_reporting::report_overflow_error; pub use self::error_reporting::report_selection_error; pub use self::error_reporting::suggest_new_overflow_limit; pub use self::coherence::orphan_check; pub use self::coherence::overlapping_impls; pub use self::coherence::OrphanCheckErr; pub use self::fulfill::{FulfillmentContext, FulfilledPredicates, RegionObligation}; pub use self::project::MismatchedProjectionTypes; pub use self::project::normalize; pub use self::project::Normalized; pub use self::object_safety::is_object_safe; pub use self::object_safety::object_safety_violations; pub use self::object_safety::ObjectSafetyViolation; pub use self::object_safety::MethodViolationCode; pub use self::object_safety::is_vtable_safe_method; pub use self::select::SelectionContext; pub use self::select::SelectionCache; pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch}; pub use self::select::{MethodMatchedData}; // intentionally don't export variants pub use self::util::elaborate_predicates; pub use self::util::get_vtable_index_of_object_method; pub use self::util::trait_ref_for_builtin_bound; pub use self::util::predicate_for_trait_def; pub use self::util::supertraits; pub use self::util::Supertraits; pub use self::util::supertrait_def_ids; pub use self::util::SupertraitDefIds; pub use self::util::transitive_bounds; pub use self::util::upcast; mod coherence; mod error_reporting; mod fulfill; mod project; mod object_safety; mod select; mod util; /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for /// which the vtable must be found. The process of finding a vtable is /// called "resolving" the `Obligation`. This process consists of /// either identifying an `impl` (e.g., `impl Eq for int`) that /// provides the required vtable, or else finding a bound that is in /// scope. The eventual result is usually a `Selection` (defined below). #[derive(Clone, PartialEq, Eq)] pub struct Obligation<'tcx, T> { pub cause: ObligationCause<'tcx>, pub recursion_depth: usize, pub predicate: T, } pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>; pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>; /// Why did we incur this obligation? Used for error reporting. #[derive(Clone, PartialEq, Eq)] pub struct ObligationCause<'tcx> { pub span: Span, // The id of the fn body that triggered this obligation. This is // used for region obligations to determine the precise // environment in which the region obligation should be evaluated // (in particular, closures can add new assumptions). See the // field `region_obligations` of the `FulfillmentContext` for more // information. pub body_id: ast::NodeId, pub code: ObligationCauseCode<'tcx> } #[derive(Clone, PartialEq, Eq)] pub enum ObligationCauseCode<'tcx> { /// Not well classified or should be obvious from span. MiscObligation, /// In an impl of trait X for type Y, type Y must /// also implement all supertraits of X. ItemObligation(ast::DefId), /// Obligation incurred due to an object cast. ObjectCastObligation(/* Object type */ Ty<'tcx>), /// Various cases where expressions must be sized/copy/etc: AssignmentLhsSized, // L = X implies that L is Sized StructInitializerSized, // S {... } must be Sized VariableType(ast::NodeId), // Type of each variable must be Sized ReturnType, // Return type must be Sized RepeatVec, // [T,..n] --> T must be Copy // Captures of variable the given id by a closure (span is the // span of the closure) ClosureCapture(ast::NodeId, Span, ty::BuiltinBound), // Types of fields (other than the last) in a struct must be sized. FieldSized, // static items must have `Sync` type SharedStatic, BuiltinDerivedObligation(DerivedObligationCause<'tcx>), ImplDerivedObligation(DerivedObligationCause<'tcx>), CompareImplMethodObligation, } #[derive(Clone, PartialEq, Eq)] pub struct DerivedObligationCause<'tcx> { /// The trait reference of the parent obligation that led to the /// current obligation. Note that only trait obligations lead to /// derived obligations, so we just store the trait reference here /// directly. parent_trait_ref: ty::PolyTraitRef<'tcx>, /// The parent trait had this cause parent_code: Rc<ObligationCauseCode<'tcx>> } pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>; pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>; pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>; pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>; #[derive(Clone,Debug)] pub enum SelectionError<'tcx> { Unimplemented, OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>, ty::PolyTraitRef<'tcx>, ty::type_err<'tcx>), TraitNotObjectSafe(ast::DefId), } pub struct FulfillmentError<'tcx> { pub obligation: PredicateObligation<'tcx>, pub code: FulfillmentErrorCode<'tcx> } #[derive(Clone)] pub enum FulfillmentErrorCode<'tcx> { CodeSelectionError(SelectionError<'tcx>), CodeProjectionError(MismatchedProjectionTypes<'tcx>), CodeAmbiguity, } /// When performing resolution, it is typically the case that there /// can be one of three outcomes: /// /// - `Ok(Some(r))`: success occurred with result `r` /// - `Ok(None)`: could not definitely determine anything, usually due /// to inconclusive type inference. /// - `Err(e)`: error `e` occurred pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>; /// Given the successful resolution of an obligation, the `Vtable` /// indicates where the vtable comes from. Note that while we call this /// a "vtable", it does not necessarily indicate dynamic dispatch at /// runtime. `Vtable` instances just tell the compiler where to find /// methods, but in generic code those methods are typically statically /// dispatched -- only when an object is constructed is a `Vtable` /// instance reified into an actual vtable. /// /// For example, the vtable may be tied to a specific impl (case A), /// or it may be relative to some bound that is in scope (case B). /// /// /// ``` /// impl<T:Clone> Clone<T> for Option<T> {... } // Impl_1 /// impl<T:Clone> Clone<T> for Box<T> {... } // Impl_2 /// impl Clone for int {... } // Impl_3 /// /// fn foo<T:Clone>(concrete: Option<Box<int>>, /// param: T, /// mixed: Option<T>) { /// /// // Case A: Vtable points at a specific impl. Only possible when /// // type is concretely known. If the impl itself has bounded /// // type parameters, Vtable will carry resolutions for those as well: /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])]) /// /// // Case B: Vtable must be provided by caller. This applies when /// // type is a type parameter. /// param.clone(); // VtableParam /// /// // Case C: A mix of cases A and B. /// mixed.clone(); // Vtable(Impl_1, [VtableParam]) /// } /// ``` /// /// ### The type parameter `N` /// /// See explanation on `VtableImplData`. #[derive(Clone)] pub enum Vtable<'tcx, N> { /// Vtable identifying a particular impl. VtableImpl(VtableImplData<'tcx, N>), /// Vtable for default trait implementations /// This carries the information and nested obligations with regards /// to a default implementation for a trait `Trait`. The nested obligations /// ensure the trait implementation holds for all the constituent types. VtableDefaultImpl(VtableDefaultImplData<N>), /// Successful resolution to an obligation provided by the caller /// for some type parameter. The `Vec<N>` represents the /// obligations incurred from normalizing the where-clause (if /// any). VtableParam(Vec<N>), /// Virtual calls through an object VtableObject(VtableObjectData<'tcx>), /// Successful resolution for a builtin trait. VtableBuiltin(VtableBuiltinData<N>), /// Vtable automatically generated for a closure. The def ID is the ID /// of the closure expression. This is a `VtableImpl` in spirit, but the /// impl is generated by the compiler and does not appear in the source. VtableClosure(VtableClosureData<'tcx, N>), /// Same as above, but for a fn pointer type with the given signature. VtableFnPointer(ty::Ty<'tcx>), } /// Identifies a particular impl in the source, along with a set of /// substitutions from the impl's type/lifetime parameters. The /// `nested` vector corresponds to the nested obligations attached to /// the impl's type parameters. /// /// The type parameter `N` indicates the type used for "nested /// obligations" that are required by the impl. During type check, this /// is `Obligation`, as one might expect. During trans, however, this /// is `()`, because trans only requires a shallow resolution of an /// impl, and nested obligations are satisfied later. #[derive(Clone, PartialEq, Eq)] pub struct VtableImplData<'tcx, N> { pub impl_def_id: ast::DefId, pub substs: subst::Substs<'tcx>, pub nested: Vec<N> } #[derive(Clone, PartialEq, Eq)] pub struct VtableClosureData<'tcx, N> { pub closure_def_id: ast::DefId, pub substs: subst::Substs<'tcx>, /// Nested obligations. This can be non-empty if the closure /// signature contains associated types. pub nested: Vec<N> } #[derive(Clone)] pub struct VtableDefaultImplData<N> { pub trait_def_id: ast::DefId, pub nested: Vec<N> } #[derive(Clone)] pub struct VtableBuiltinData<N> { pub nested: Vec<N> } /// A vtable for some object-safe trait `Foo` automatically derived /// for the object type `Foo`. #[derive(PartialEq,Eq,Clone)] pub struct VtableObjectData<'tcx> { /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`. pub upcast_trait_ref: ty::PolyTraitRef<'tcx>, /// The vtable is formed by concatenating together the method lists of /// the base object trait and all supertraits; this is the start of /// `upcast_trait_ref`'s methods in that vtable. pub vtable_base: usize } /// Creates predicate obligations from the generic bounds. pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>, generic_bounds: &ty::InstantiatedPredicates<'tcx>) -> PredicateObligations<'tcx> { util::predicates_for_generics(cause, 0, generic_bounds) } /// Determines whether the type `ty` is known to meet `bound` and /// returns true if so. Returns false if `ty` either does not meet /// `bound` or is not known to meet bound (note that this is /// conservative towards *no impl*, which is the opposite of the /// `evaluate` methods). pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, ty: Ty<'tcx>, bound: ty::BuiltinBound, span: Span) -> bool { debug!("type_known_to_meet_builtin_bound(ty={:?}, bound={:?})", ty, bound); let mut fulfill_cx = FulfillmentContext::new(false); // We can use a dummy node-id here because we won't pay any mind // to region obligations that arise (there shouldn't really be any // anyhow). let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID); fulfill_cx.register_builtin_bound(infcx, ty, bound, cause); // Note: we only assume something is `Copy` if we can // *definitively* show that it implements `Copy`. Otherwise, // assume it is move; linear is always ok. match fulfill_cx.select_all_or_error(infcx) { Ok(()) => { debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} success", ty, bound); true } Err(e) => { debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} errors={:?}", ty, bound, e); false } } } // FIXME: this is gonna need to be removed... /// Normalizes the parameter environment, reporting errors if they occur. pub fn normalize_param_env_or_error<'a,'tcx>(unnormalized_env: ty::ParameterEnvironment<'a,'tcx>, cause: ObligationCause<'tcx>) -> ty::ParameterEnvironment<'a,'tcx> { // I'm not wild about reporting errors here; I'd prefer to // have the errors get reported at a defined place (e.g., // during typeck). Instead I have all parameter // environments, in effect, going through this function // and hence potentially reporting errors. This ensurse of // course that we never forget to normalize (the // alternative seemed like it would involve a lot of // manual invocations of this fn -- and then we'd have to // deal with the errors at each of those sites). // // In any case, in practice, typeck constructs all the // parameter environments once for every fn as it goes, // and errors will get reported then; so after typeck we // can be sure that no errors should occur. let tcx = unnormalized_env.tcx; let span = cause.span; let body_id = cause.body_id; debug!("normalize_param_env_or_error(unnormalized_env={:?})", unnormalized_env); let predicates: Vec<_> = util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone()) .filter(|p|!p.is_global()) // (*) .collect(); // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't // need to be in the *environment* to be proven, so screen those // out. This is important for the soundness of inter-fn // caching. Note though that we should probably check that these // predicates hold at the point where the environment is // constructed, but I am not currently doing so out of laziness. // -nmatsakis debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates); let elaborated_env = unnormalized_env.with_caller_bounds(predicates); let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(elaborated_env), false); let predicates = match fully_normalize(&infcx, cause, &infcx.parameter_environment.caller_bounds) { Ok(predicates) => predicates, Err(errors) => { report_fulfillment_errors(&infcx, &errors); return infcx.parameter_environment; // an unnormalized env is better than nothing } }; let free_regions = FreeRegionMap::new(); infcx.resolve_regions_and_report_errors(&free_regions, body_id); let predicates = match infcx.fully_resolve(&predicates) { Ok(predicates) => predicates, Err(fixup_err) => { // If we encounter a fixup error, it means that some type // variable wound up unconstrained. I actually don't know // if this can happen, and I certainly don't expect it to // happen often, but if it did happen it probably // represents a legitimate failure due to some kind of // unconstrained variable, and it seems better not to ICE, // all things considered. let err_msg = fixup_err_to_string(fixup_err); tcx.sess.span_err(span, &err_msg); return infcx.parameter_environment; // an unnormalized env is better than nothing } }; infcx.parameter_environment.with_caller_bounds(predicates) } pub fn
<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, cause: ObligationCause<'tcx>, value: &T) -> Result<T, Vec<FulfillmentError<'tcx>>> where T : TypeFoldable<'tcx> + HasTypeFlags { debug!("normalize_param_env(value={:?})", value); let mut selcx = &mut SelectionContext::new(infcx); // FIXME (@jroesch) ISSUE 26721 // I'm not sure if this is a bug or not, needs further investigation. // It appears that by reusing the fulfillment_cx here we incur more // obligations and later trip an asssertion on regionck.rs line 337. // // The two possibilities I see is: // - normalization is not actually fully happening and we // have a bug else where // - we are adding a duplicate bound into the list causing // its size to change. // // I think we should probably land this refactor and then come // back to this is a follow-up patch. let mut fulfill_cx = FulfillmentContext::new(false); let Normalized { value: normalized_value, obligations } = project::normalize(selcx, cause, value); debug!("normalize_param_env: normalized_value={:?} obligations={:?}", normalized_value, obligations); for obligation in obligations { fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation); } try!(fulfill_cx.select_all_or_error(infcx)); let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value); debug!("normalize_param_env: resolved_value={:?}", resolved_value); Ok(resolved_value) } impl<'tcx,O> Obligation<'tcx,O> { pub fn new(cause: ObligationCause<'tcx>, trait_ref: O) -> Obligation<'tcx, O> { Obligation { cause: cause, recursion_depth: 0, predicate: trait_ref } } fn with_depth(cause: ObligationCause<'tcx>, recursion_depth: usize, trait_ref: O) -> Obligation<'tcx, O> { Obligation { cause: cause, recursion_depth: recursion_depth, predicate: trait_ref } } pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> { Obligation::new(ObligationCause::misc(span, body_id), trait_ref) } pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> { Obligation { cause: self.cause.clone(), recursion_depth: self.recursion_depth, predicate: value } } } impl<'tcx> ObligationCause<'tcx> { pub fn new(span: Span, body_id: ast::NodeId, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> { ObligationCause { span: span, body_id: body_id, code: code } } pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> { ObligationCause { span: span, body_id: body_id, code: MiscObligation } } pub fn dummy() -> ObligationCause<'tcx> { ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation } } } impl<'tcx, N> Vtable<'tcx, N> { pub fn nested_obligations(self) -> Vec<N> { match self { VtableImpl(i) => i.nested, VtableParam(n) => n, VtableBuiltin(i) => i.nested, VtableDefaultImpl(d) => d.nested, VtableClosure(c) => c.nested, VtableObject(_) | VtableFnPointer(..) => vec![] } } pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M { match self { VtableImpl(i) => VtableImpl(VtableImplData { impl_def_id: i.impl_def_id, substs: i.substs, nested: i.nested.into_iter().map(f).collect() }), VtableParam(n) => VtableParam(n.into_iter().map(f).collect()), VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() }), VtableObject(o) => VtableObject(o), VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData { trait_def_id: d.trait_def_id, nested: d.nested.into_iter().map(f).collect() }), VtableFnPointer(f) => VtableFnPointer(f), VtableClosure(c) => VtableClosure(VtableClosureData { closure_def_id: c.closure_def_id, substs: c.substs, nested: c.nested.into_iter().map(f).collect() }) } } } impl<'tcx> FulfillmentError<'tcx> { fn new(obligation: PredicateObligation<'tcx>, code: FulfillmentErrorCode<'tcx>) -> FulfillmentError<'tcx> { FulfillmentError { obligation: obligation, code: code } } } impl<'tcx> TraitObligation<'tcx> { fn self_ty(&self) -> ty::Binder<Ty<'tcx>> { ty::Binder(self.predicate.skip_binder().self_ty()) } }
fully_normalize
identifier_name
test_utils.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Internal module containing convenience utility functions mainly for testing use crate::traits::Uniform; use serde::{Deserialize, Serialize}; /// A deterministic seed for PRNGs related to keys pub const TEST_SEED: [u8; 32] = [0u8; 32]; /// A keypair consisting of a private and public key #[cfg_attr(feature = "cloneable-private-keys", derive(Clone))] #[derive(Serialize, Deserialize, PartialEq, Eq)] pub struct KeyPair<S, P> where for<'a> P: From<&'a S>, { /// the private key component pub private_key: S, /// the public key component pub public_key: P, } impl<S, P> From<S> for KeyPair<S, P> where for<'a> P: From<&'a S>, { fn from(private_key: S) -> Self { KeyPair { public_key: (&private_key).into(), private_key, } } } impl<S, P> Uniform for KeyPair<S, P> where S: Uniform, for<'a> P: From<&'a S>, { fn generate<R>(rng: &mut R) -> Self where R: ::rand::RngCore + ::rand::CryptoRng, { let private_key = S::generate(rng); private_key.into() } } /// A pair consisting of a private and public key impl<S, P> Uniform for (S, P) where S: Uniform, for<'a> P: From<&'a S>, { fn generate<R>(rng: &mut R) -> Self where R: ::rand::RngCore + ::rand::CryptoRng, { let private_key = S::generate(rng); let public_key = (&private_key).into(); (private_key, public_key) } } impl<Priv, Pub> std::fmt::Debug for KeyPair<Priv, Pub> where Priv: Serialize, Pub: Serialize + for<'a> From<&'a Priv>, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut v = bcs::to_bytes(&self.private_key).unwrap(); v.extend(&bcs::to_bytes(&self.public_key).unwrap()); write!(f, "{}", hex::encode(&v[..])) } } #[cfg(any(test, feature = "fuzzing"))] use proptest::prelude::*; #[cfg(any(test, feature = "fuzzing"))] use rand::{rngs::StdRng, SeedableRng}; /// Produces a uniformly random keypair from a seed #[cfg(any(test, feature = "fuzzing"))] pub fn uniform_keypair_strategy<Priv, Pub>() -> impl Strategy<Value = KeyPair<Priv, Pub>> where Pub: Serialize + for<'a> From<&'a Priv>, Priv: Serialize + Uniform, { // The no_shrink is because keypairs should be fixed -- shrinking would cause a different // keypair to be generated, which appears to not be very useful. any::<[u8; 32]>() .prop_map(|seed| { let mut rng = StdRng::from_seed(seed); KeyPair::<Priv, Pub>::generate(&mut rng) }) .no_shrink() } /// This struct provides a means of testing signing and verification through /// BCS serialization and domain separation #[cfg(any(test, feature = "fuzzing"))] #[derive(Debug, Serialize, Deserialize)] pub struct TestDiemCrypto(pub String); // the following block is macro expanded from derive(CryptoHasher, BCSCryptoHash) /// Cryptographic hasher for an BCS-serializable #item #[cfg(any(test, feature = "fuzzing"))] pub struct TestDiemCryptoHasher(crate::hash::DefaultHasher); #[cfg(any(test, feature = "fuzzing"))] impl ::core::clone::Clone for TestDiemCryptoHasher { #[inline] fn clone(&self) -> TestDiemCryptoHasher { match *self { TestDiemCryptoHasher(ref __self_0_0) => { TestDiemCryptoHasher(::core::clone::Clone::clone(&(*__self_0_0))) } } } } #[cfg(any(test, feature = "fuzzing"))] static TEST_DIEM_CRYPTO_SEED: crate::_once_cell::sync::OnceCell<[u8; 32]> = crate::_once_cell::sync::OnceCell::new(); #[cfg(any(test, feature = "fuzzing"))] impl TestDiemCryptoHasher { fn new() -> Self { let name = crate::_serde_name::trace_name::<TestDiemCrypto>() .expect("The `CryptoHasher` macro only applies to structs and enums"); TestDiemCryptoHasher(crate::hash::DefaultHasher::new(&name.as_bytes())) } } #[cfg(any(test, feature = "fuzzing"))] static TEST_DIEM_CRYPTO_HASHER: crate::_once_cell::sync::Lazy<TestDiemCryptoHasher> = crate::_once_cell::sync::Lazy::new(TestDiemCryptoHasher::new); #[cfg(any(test, feature = "fuzzing"))] impl std::default::Default for TestDiemCryptoHasher { fn default() -> Self { TEST_DIEM_CRYPTO_HASHER.clone() } } #[cfg(any(test, feature = "fuzzing"))] impl crate::hash::CryptoHasher for TestDiemCryptoHasher { fn seed() -> &'static [u8; 32] {
let name = crate::_serde_name::trace_name::<TestDiemCrypto>() .expect("The `CryptoHasher` macro only applies to structs and enums.") .as_bytes(); crate::hash::DefaultHasher::prefixed_hash(&name) }) } fn update(&mut self, bytes: &[u8]) { self.0.update(bytes); } fn finish(self) -> crate::hash::HashValue { self.0.finish() } } #[cfg(any(test, feature = "fuzzing"))] impl std::io::Write for TestDiemCryptoHasher { fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { self.0.update(bytes); Ok(bytes.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[cfg(any(test, feature = "fuzzing"))] impl crate::hash::CryptoHash for TestDiemCrypto { type Hasher = TestDiemCryptoHasher; fn hash(&self) -> crate::hash::HashValue { use crate::hash::CryptoHasher; let mut state = Self::Hasher::default(); bcs::serialize_into(&mut state, &self) .expect("BCS serialization of TestDiemCrypto should not fail"); state.finish() } } /// Produces a random TestDiemCrypto signable / verifiable struct. #[cfg(any(test, feature = "fuzzing"))] pub fn random_serializable_struct() -> impl Strategy<Value = TestDiemCrypto> { (String::arbitrary()).prop_map(TestDiemCrypto).no_shrink() }
TEST_DIEM_CRYPTO_SEED.get_or_init(|| {
random_line_split
test_utils.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Internal module containing convenience utility functions mainly for testing use crate::traits::Uniform; use serde::{Deserialize, Serialize}; /// A deterministic seed for PRNGs related to keys pub const TEST_SEED: [u8; 32] = [0u8; 32]; /// A keypair consisting of a private and public key #[cfg_attr(feature = "cloneable-private-keys", derive(Clone))] #[derive(Serialize, Deserialize, PartialEq, Eq)] pub struct KeyPair<S, P> where for<'a> P: From<&'a S>, { /// the private key component pub private_key: S, /// the public key component pub public_key: P, } impl<S, P> From<S> for KeyPair<S, P> where for<'a> P: From<&'a S>, { fn from(private_key: S) -> Self { KeyPair { public_key: (&private_key).into(), private_key, } } } impl<S, P> Uniform for KeyPair<S, P> where S: Uniform, for<'a> P: From<&'a S>, { fn generate<R>(rng: &mut R) -> Self where R: ::rand::RngCore + ::rand::CryptoRng, { let private_key = S::generate(rng); private_key.into() } } /// A pair consisting of a private and public key impl<S, P> Uniform for (S, P) where S: Uniform, for<'a> P: From<&'a S>, { fn generate<R>(rng: &mut R) -> Self where R: ::rand::RngCore + ::rand::CryptoRng, { let private_key = S::generate(rng); let public_key = (&private_key).into(); (private_key, public_key) } } impl<Priv, Pub> std::fmt::Debug for KeyPair<Priv, Pub> where Priv: Serialize, Pub: Serialize + for<'a> From<&'a Priv>, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut v = bcs::to_bytes(&self.private_key).unwrap(); v.extend(&bcs::to_bytes(&self.public_key).unwrap()); write!(f, "{}", hex::encode(&v[..])) } } #[cfg(any(test, feature = "fuzzing"))] use proptest::prelude::*; #[cfg(any(test, feature = "fuzzing"))] use rand::{rngs::StdRng, SeedableRng}; /// Produces a uniformly random keypair from a seed #[cfg(any(test, feature = "fuzzing"))] pub fn uniform_keypair_strategy<Priv, Pub>() -> impl Strategy<Value = KeyPair<Priv, Pub>> where Pub: Serialize + for<'a> From<&'a Priv>, Priv: Serialize + Uniform, { // The no_shrink is because keypairs should be fixed -- shrinking would cause a different // keypair to be generated, which appears to not be very useful. any::<[u8; 32]>() .prop_map(|seed| { let mut rng = StdRng::from_seed(seed); KeyPair::<Priv, Pub>::generate(&mut rng) }) .no_shrink() } /// This struct provides a means of testing signing and verification through /// BCS serialization and domain separation #[cfg(any(test, feature = "fuzzing"))] #[derive(Debug, Serialize, Deserialize)] pub struct TestDiemCrypto(pub String); // the following block is macro expanded from derive(CryptoHasher, BCSCryptoHash) /// Cryptographic hasher for an BCS-serializable #item #[cfg(any(test, feature = "fuzzing"))] pub struct TestDiemCryptoHasher(crate::hash::DefaultHasher); #[cfg(any(test, feature = "fuzzing"))] impl ::core::clone::Clone for TestDiemCryptoHasher { #[inline] fn clone(&self) -> TestDiemCryptoHasher { match *self { TestDiemCryptoHasher(ref __self_0_0) => { TestDiemCryptoHasher(::core::clone::Clone::clone(&(*__self_0_0))) } } } } #[cfg(any(test, feature = "fuzzing"))] static TEST_DIEM_CRYPTO_SEED: crate::_once_cell::sync::OnceCell<[u8; 32]> = crate::_once_cell::sync::OnceCell::new(); #[cfg(any(test, feature = "fuzzing"))] impl TestDiemCryptoHasher { fn new() -> Self { let name = crate::_serde_name::trace_name::<TestDiemCrypto>() .expect("The `CryptoHasher` macro only applies to structs and enums"); TestDiemCryptoHasher(crate::hash::DefaultHasher::new(&name.as_bytes())) } } #[cfg(any(test, feature = "fuzzing"))] static TEST_DIEM_CRYPTO_HASHER: crate::_once_cell::sync::Lazy<TestDiemCryptoHasher> = crate::_once_cell::sync::Lazy::new(TestDiemCryptoHasher::new); #[cfg(any(test, feature = "fuzzing"))] impl std::default::Default for TestDiemCryptoHasher { fn default() -> Self { TEST_DIEM_CRYPTO_HASHER.clone() } } #[cfg(any(test, feature = "fuzzing"))] impl crate::hash::CryptoHasher for TestDiemCryptoHasher { fn seed() -> &'static [u8; 32] { TEST_DIEM_CRYPTO_SEED.get_or_init(|| { let name = crate::_serde_name::trace_name::<TestDiemCrypto>() .expect("The `CryptoHasher` macro only applies to structs and enums.") .as_bytes(); crate::hash::DefaultHasher::prefixed_hash(&name) }) } fn update(&mut self, bytes: &[u8]) { self.0.update(bytes); } fn finish(self) -> crate::hash::HashValue { self.0.finish() } } #[cfg(any(test, feature = "fuzzing"))] impl std::io::Write for TestDiemCryptoHasher { fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { self.0.update(bytes); Ok(bytes.len()) } fn flush(&mut self) -> std::io::Result<()>
} #[cfg(any(test, feature = "fuzzing"))] impl crate::hash::CryptoHash for TestDiemCrypto { type Hasher = TestDiemCryptoHasher; fn hash(&self) -> crate::hash::HashValue { use crate::hash::CryptoHasher; let mut state = Self::Hasher::default(); bcs::serialize_into(&mut state, &self) .expect("BCS serialization of TestDiemCrypto should not fail"); state.finish() } } /// Produces a random TestDiemCrypto signable / verifiable struct. #[cfg(any(test, feature = "fuzzing"))] pub fn random_serializable_struct() -> impl Strategy<Value = TestDiemCrypto> { (String::arbitrary()).prop_map(TestDiemCrypto).no_shrink() }
{ Ok(()) }
identifier_body
test_utils.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Internal module containing convenience utility functions mainly for testing use crate::traits::Uniform; use serde::{Deserialize, Serialize}; /// A deterministic seed for PRNGs related to keys pub const TEST_SEED: [u8; 32] = [0u8; 32]; /// A keypair consisting of a private and public key #[cfg_attr(feature = "cloneable-private-keys", derive(Clone))] #[derive(Serialize, Deserialize, PartialEq, Eq)] pub struct KeyPair<S, P> where for<'a> P: From<&'a S>, { /// the private key component pub private_key: S, /// the public key component pub public_key: P, } impl<S, P> From<S> for KeyPair<S, P> where for<'a> P: From<&'a S>, { fn from(private_key: S) -> Self { KeyPair { public_key: (&private_key).into(), private_key, } } } impl<S, P> Uniform for KeyPair<S, P> where S: Uniform, for<'a> P: From<&'a S>, { fn generate<R>(rng: &mut R) -> Self where R: ::rand::RngCore + ::rand::CryptoRng, { let private_key = S::generate(rng); private_key.into() } } /// A pair consisting of a private and public key impl<S, P> Uniform for (S, P) where S: Uniform, for<'a> P: From<&'a S>, { fn generate<R>(rng: &mut R) -> Self where R: ::rand::RngCore + ::rand::CryptoRng, { let private_key = S::generate(rng); let public_key = (&private_key).into(); (private_key, public_key) } } impl<Priv, Pub> std::fmt::Debug for KeyPair<Priv, Pub> where Priv: Serialize, Pub: Serialize + for<'a> From<&'a Priv>, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut v = bcs::to_bytes(&self.private_key).unwrap(); v.extend(&bcs::to_bytes(&self.public_key).unwrap()); write!(f, "{}", hex::encode(&v[..])) } } #[cfg(any(test, feature = "fuzzing"))] use proptest::prelude::*; #[cfg(any(test, feature = "fuzzing"))] use rand::{rngs::StdRng, SeedableRng}; /// Produces a uniformly random keypair from a seed #[cfg(any(test, feature = "fuzzing"))] pub fn uniform_keypair_strategy<Priv, Pub>() -> impl Strategy<Value = KeyPair<Priv, Pub>> where Pub: Serialize + for<'a> From<&'a Priv>, Priv: Serialize + Uniform, { // The no_shrink is because keypairs should be fixed -- shrinking would cause a different // keypair to be generated, which appears to not be very useful. any::<[u8; 32]>() .prop_map(|seed| { let mut rng = StdRng::from_seed(seed); KeyPair::<Priv, Pub>::generate(&mut rng) }) .no_shrink() } /// This struct provides a means of testing signing and verification through /// BCS serialization and domain separation #[cfg(any(test, feature = "fuzzing"))] #[derive(Debug, Serialize, Deserialize)] pub struct
(pub String); // the following block is macro expanded from derive(CryptoHasher, BCSCryptoHash) /// Cryptographic hasher for an BCS-serializable #item #[cfg(any(test, feature = "fuzzing"))] pub struct TestDiemCryptoHasher(crate::hash::DefaultHasher); #[cfg(any(test, feature = "fuzzing"))] impl ::core::clone::Clone for TestDiemCryptoHasher { #[inline] fn clone(&self) -> TestDiemCryptoHasher { match *self { TestDiemCryptoHasher(ref __self_0_0) => { TestDiemCryptoHasher(::core::clone::Clone::clone(&(*__self_0_0))) } } } } #[cfg(any(test, feature = "fuzzing"))] static TEST_DIEM_CRYPTO_SEED: crate::_once_cell::sync::OnceCell<[u8; 32]> = crate::_once_cell::sync::OnceCell::new(); #[cfg(any(test, feature = "fuzzing"))] impl TestDiemCryptoHasher { fn new() -> Self { let name = crate::_serde_name::trace_name::<TestDiemCrypto>() .expect("The `CryptoHasher` macro only applies to structs and enums"); TestDiemCryptoHasher(crate::hash::DefaultHasher::new(&name.as_bytes())) } } #[cfg(any(test, feature = "fuzzing"))] static TEST_DIEM_CRYPTO_HASHER: crate::_once_cell::sync::Lazy<TestDiemCryptoHasher> = crate::_once_cell::sync::Lazy::new(TestDiemCryptoHasher::new); #[cfg(any(test, feature = "fuzzing"))] impl std::default::Default for TestDiemCryptoHasher { fn default() -> Self { TEST_DIEM_CRYPTO_HASHER.clone() } } #[cfg(any(test, feature = "fuzzing"))] impl crate::hash::CryptoHasher for TestDiemCryptoHasher { fn seed() -> &'static [u8; 32] { TEST_DIEM_CRYPTO_SEED.get_or_init(|| { let name = crate::_serde_name::trace_name::<TestDiemCrypto>() .expect("The `CryptoHasher` macro only applies to structs and enums.") .as_bytes(); crate::hash::DefaultHasher::prefixed_hash(&name) }) } fn update(&mut self, bytes: &[u8]) { self.0.update(bytes); } fn finish(self) -> crate::hash::HashValue { self.0.finish() } } #[cfg(any(test, feature = "fuzzing"))] impl std::io::Write for TestDiemCryptoHasher { fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { self.0.update(bytes); Ok(bytes.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[cfg(any(test, feature = "fuzzing"))] impl crate::hash::CryptoHash for TestDiemCrypto { type Hasher = TestDiemCryptoHasher; fn hash(&self) -> crate::hash::HashValue { use crate::hash::CryptoHasher; let mut state = Self::Hasher::default(); bcs::serialize_into(&mut state, &self) .expect("BCS serialization of TestDiemCrypto should not fail"); state.finish() } } /// Produces a random TestDiemCrypto signable / verifiable struct. #[cfg(any(test, feature = "fuzzing"))] pub fn random_serializable_struct() -> impl Strategy<Value = TestDiemCrypto> { (String::arbitrary()).prop_map(TestDiemCrypto).no_shrink() }
TestDiemCrypto
identifier_name
overloaded_deref_with_ref_pattern.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we choose Deref or DerefMut appropriately based on mutability of ref bindings (#15609). use std::ops::{Deref, DerefMut}; struct DerefOk<T>(T); struct DerefMutOk<T>(T); impl<T> Deref for DerefOk<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for DerefOk<T> { fn deref_mut(&mut self) -> &mut Self::Target { panic!() } } impl<T> Deref for DerefMutOk<T> { type Target = T; fn deref(&self) -> &Self::Target { panic!() } } impl<T> DerefMut for DerefMutOk<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } fn main() { // Check that mutable ref binding in match picks DerefMut let mut b = DerefMutOk(0); match *b {
}; // Check that mutable ref binding in let picks DerefMut let mut y = DerefMutOk(1); let ref mut z = *y; // Check that immutable ref binding in match picks Deref let mut b = DerefOk(2); match *b { ref n => n, }; // Check that immutable ref binding in let picks Deref let mut y = DerefOk(3); let ref z = *y; // Check that mixed mutable/immutable ref binding in match picks DerefMut let mut b = DerefMutOk((0, 9)); match *b { (ref mut n, ref m) => (n, m), }; let mut b = DerefMutOk((0, 9)); match *b { (ref n, ref mut m) => (n, m), }; // Check that mixed mutable/immutable ref binding in let picks DerefMut let mut y = DerefMutOk((1, 8)); let (ref mut z, ref a) = *y; let mut y = DerefMutOk((1, 8)); let (ref z, ref mut a) = *y; // Check that multiple immutable ref bindings in match picks Deref let mut b = DerefOk((2, 7)); match *b { (ref n, ref m) => (n, m), }; // Check that multiple immutable ref bindings in let picks Deref let mut y = DerefOk((3, 6)); let (ref z, ref a) = *y; // Check that multiple mutable ref bindings in match picks DerefMut let mut b = DerefMutOk((4, 5)); match *b { (ref mut n, ref mut m) => (n, m), }; // Check that multiple mutable ref bindings in let picks DerefMut let mut y = DerefMutOk((5, 4)); let (ref mut z, ref mut a) = *y; }
ref mut n => n,
random_line_split
overloaded_deref_with_ref_pattern.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we choose Deref or DerefMut appropriately based on mutability of ref bindings (#15609). use std::ops::{Deref, DerefMut}; struct DerefOk<T>(T); struct DerefMutOk<T>(T); impl<T> Deref for DerefOk<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for DerefOk<T> { fn deref_mut(&mut self) -> &mut Self::Target { panic!() } } impl<T> Deref for DerefMutOk<T> { type Target = T; fn deref(&self) -> &Self::Target { panic!() } } impl<T> DerefMut for DerefMutOk<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } fn main()
// Check that mixed mutable/immutable ref binding in match picks DerefMut let mut b = DerefMutOk((0, 9)); match *b { (ref mut n, ref m) => (n, m), }; let mut b = DerefMutOk((0, 9)); match *b { (ref n, ref mut m) => (n, m), }; // Check that mixed mutable/immutable ref binding in let picks DerefMut let mut y = DerefMutOk((1, 8)); let (ref mut z, ref a) = *y; let mut y = DerefMutOk((1, 8)); let (ref z, ref mut a) = *y; // Check that multiple immutable ref bindings in match picks Deref let mut b = DerefOk((2, 7)); match *b { (ref n, ref m) => (n, m), }; // Check that multiple immutable ref bindings in let picks Deref let mut y = DerefOk((3, 6)); let (ref z, ref a) = *y; // Check that multiple mutable ref bindings in match picks DerefMut let mut b = DerefMutOk((4, 5)); match *b { (ref mut n, ref mut m) => (n, m), }; // Check that multiple mutable ref bindings in let picks DerefMut let mut y = DerefMutOk((5, 4)); let (ref mut z, ref mut a) = *y; }
{ // Check that mutable ref binding in match picks DerefMut let mut b = DerefMutOk(0); match *b { ref mut n => n, }; // Check that mutable ref binding in let picks DerefMut let mut y = DerefMutOk(1); let ref mut z = *y; // Check that immutable ref binding in match picks Deref let mut b = DerefOk(2); match *b { ref n => n, }; // Check that immutable ref binding in let picks Deref let mut y = DerefOk(3); let ref z = *y;
identifier_body
overloaded_deref_with_ref_pattern.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we choose Deref or DerefMut appropriately based on mutability of ref bindings (#15609). use std::ops::{Deref, DerefMut}; struct DerefOk<T>(T); struct DerefMutOk<T>(T); impl<T> Deref for DerefOk<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for DerefOk<T> { fn deref_mut(&mut self) -> &mut Self::Target { panic!() } } impl<T> Deref for DerefMutOk<T> { type Target = T; fn
(&self) -> &Self::Target { panic!() } } impl<T> DerefMut for DerefMutOk<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } fn main() { // Check that mutable ref binding in match picks DerefMut let mut b = DerefMutOk(0); match *b { ref mut n => n, }; // Check that mutable ref binding in let picks DerefMut let mut y = DerefMutOk(1); let ref mut z = *y; // Check that immutable ref binding in match picks Deref let mut b = DerefOk(2); match *b { ref n => n, }; // Check that immutable ref binding in let picks Deref let mut y = DerefOk(3); let ref z = *y; // Check that mixed mutable/immutable ref binding in match picks DerefMut let mut b = DerefMutOk((0, 9)); match *b { (ref mut n, ref m) => (n, m), }; let mut b = DerefMutOk((0, 9)); match *b { (ref n, ref mut m) => (n, m), }; // Check that mixed mutable/immutable ref binding in let picks DerefMut let mut y = DerefMutOk((1, 8)); let (ref mut z, ref a) = *y; let mut y = DerefMutOk((1, 8)); let (ref z, ref mut a) = *y; // Check that multiple immutable ref bindings in match picks Deref let mut b = DerefOk((2, 7)); match *b { (ref n, ref m) => (n, m), }; // Check that multiple immutable ref bindings in let picks Deref let mut y = DerefOk((3, 6)); let (ref z, ref a) = *y; // Check that multiple mutable ref bindings in match picks DerefMut let mut b = DerefMutOk((4, 5)); match *b { (ref mut n, ref mut m) => (n, m), }; // Check that multiple mutable ref bindings in let picks DerefMut let mut y = DerefMutOk((5, 4)); let (ref mut z, ref mut a) = *y; }
deref
identifier_name
graphical.rs
/******************************************************************************* * * kit/kernel/terminal/vga.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more information. * ******************************************************************************/ use core::fmt; use core::ops::Range; use alloc::collections::BTreeMap; use crate::framebuffer::Framebuffer; use crate::util::align_up; use super::{Color, CharStream, Terminal}; /// Emulates a terminal on a graphical framebuffer #[derive(Debug)] pub struct Graphical<T, U> { fb: T, font: U, row: usize, col: usize, rows: usize, cols: usize, font_w: usize, font_h: usize, fg: Color, bg: Color, native_fg: u32, native_bg: u32, char_buf: CharStream, } impl<T, U> Graphical<T, U> where T: Framebuffer, U: Font { pub fn new(fb: T, font: U) -> Graphical<T, U> { let mut g = Graphical { row: 0, col: 0, rows: 0, cols: 0, font_w: font.char_width() + 1, font_h: font.char_height(), fg: Color::White, bg: Color::Black, native_fg: 0, native_bg: 0, char_buf: CharStream::default(), fb, font, }; g.rows = g.fb.height()/g.font_h; g.cols = g.fb.width()/g.font_w; g.update_colors(); g } fn update_colors(&mut self) { self.native_fg = self.fb.color_format().format(self.fg.to_rgb()); self.native_bg = self.fb.color_format().format(self.bg.to_rgb()); } fn position_xy(&self, row: usize, col: usize) -> (usize, usize) { ( self.font_w * col, self.font_h * row ) } fn render(&self, ch: char, row: usize, col: usize, colors: (u32, u32)) { let (x, y) = self.position_xy(row, col); let fontdata = self.font.get(ch); let c_width = self.font.char_width(); let get_bit = |px, py, _| { let fg = if let Some(bits) = fontdata { if px >= c_width { false } else { let index = py * c_width + px; let byte = index >> 3; let bit = index & 0b111; let mask = 1u8 << (7 - bit); bits[byte] & mask!= 0u8 } } else { false }; if fg { colors.0 } else { colors.1 } }; self.fb.edit(x, y, self.font_w, self.font_h, get_bit); } fn update_cursor(&mut self) { // TODO: make this non-destructive so we can put back whatever we // replaced. Should merely invert the character really. let (x, y) = self.position_xy(self.row, self.col); self.fb.fill(x, y, self.font_w, self.font_h, self.native_fg); } fn put_here(&self, ch: char)
fn scroll(&mut self) { if self.fb.double_buffer_enabled() { let (x0, y0) = self.position_xy(1, 0); let (x1, y1) = self.position_xy(0, 0); // Move the contents of everything but the first row up one row self.fb.copy_within(x0, y0, x1, y1, self.font_w * self.cols, self.font_h * (self.rows-1)); // Clear the last row let (x2, y2) = self.position_xy(self.rows - 1, 0); self.fb.fill(x2, y2, self.font_w * self.cols, self.font_h, self.native_bg); } else { // If double buffer is not enabled, we can't really do a scroll // without it being super slow... so instead, we'll just jump up to // the top self.row = 0; self.col = 0; self.update_cursor(); } } fn new_line(&mut self) { let (x, y) = self.position_xy(self.row, self.col); // Fill end of line let remaining = self.cols - self.col; self.fb.fill(x, y, self.font_w * remaining, self.font_h, self.native_bg); self.row += 1; self.col = 0; if self.row >= self.rows { self.row = self.rows - 1; self.scroll(); } self.update_cursor(); } fn write_char(&mut self, ch: char) { match ch { '\n' => { self.new_line(); }, '\x08' /* backspace */ => { self.put_here(' '); if self.col > 0 { self.col -= 1; } self.update_cursor(); }, _ => { self.put_here(ch); self.col += 1; if self.col >= self.cols { self.new_line(); } else { self.update_cursor(); } } } } } impl<T, U> Terminal for Graphical<T, U> where T: Framebuffer, U: Font { fn reset(&mut self) -> fmt::Result { self.fg = Color::LightGrey; self.bg = Color::Black; self.update_colors(); self.clear() } fn clear(&mut self) -> fmt::Result { self.row = 0; self.col = 0; self.fb.fill(0, 0, self.fb.width(), self.fb.height(), self.native_bg); self.update_cursor(); Ok(()) } fn get_cursor(&self) -> (usize, usize) { (self.row, self.col) } fn set_cursor(&mut self, row: usize, col: usize) -> fmt::Result { self.row = row; self.col = col; self.update_cursor(); Ok(()) } fn get_color(&self) -> (Color, Color) { (self.fg, self.bg) } fn set_color(&mut self, fg: Color, bg: Color) -> fmt::Result { self.fg = fg; self.bg = bg; self.update_colors(); Ok(()) } fn put_raw_byte(&mut self, byte: u8, fg: Color, bg: Color, row: usize, col: usize) -> fmt::Result { // I think we should get rid of this method, it doesn't handle unicode properly self.render( char::from(byte), row, col, (self.fb.color_format().format(fg.to_rgb()), self.fb.color_format().format(bg.to_rgb()))); Ok(()) } fn write_raw_byte(&mut self, byte: u8) -> fmt::Result { // Build unicode self.char_buf.push(byte); while let Some(ch) = self.char_buf.consume() { self.write_char(ch); } Ok(()) } fn set_double_buffer(&mut self, enabled: bool) { self.fb.set_double_buffer(enabled); } fn flush(&mut self) -> fmt::Result { self.update_cursor(); Ok(()) } } impl<T, U> fmt::Write for Graphical<T, U> where T: Framebuffer, U: Font { fn write_char(&mut self, ch: char) -> fmt::Result { let mut buf = [0; 4]; self.write_raw_bytes(ch.encode_utf8(&mut buf).as_bytes())?; self.flush()?; Ok(()) } fn write_str(&mut self, s: &str) -> fmt::Result { self.write_raw_bytes(s.as_bytes())?; self.flush()?; Ok(()) } } static U_VGA16: &[u8] = include_bytes!("font/u_vga16.psf"); pub fn u_vga16() -> PsfFont<&'static [u8]> { PsfFont::new(U_VGA16).unwrap() } pub trait Font { fn char_width(&self) -> usize; fn char_height(&self) -> usize; fn char_bytes(&self) -> usize { align_up(self.char_width() * self.char_height(), 8) / 8 } fn get(&self, ch: char) -> Option<&[u8]>; } #[derive(Debug, Clone)] pub struct PsfFont<T: AsRef<[u8]>> { buf: T, chars_range: Range<usize>, unicode_table: BTreeMap<char, usize>, char_width: usize, char_height: usize, } const PSF1_MAGIC: u16 = 0x0436; /* little endian */ const PSF1_MODE_512: u8 = 0x01; const PSF1_MODE_HASTAB: u8 = 0x02; const PSF1_MODE_HASSEQ: u8 = 0x04; const PSF1_SEPARATOR: u32 = 0xffff; const PSF1_STARTSEQ: u32 = 0xfffe; #[derive(Debug, Clone)] pub enum PsfError { /// this is not a recognized PC Screen Font file WrongMagic, /// the mode field ({:x}) has unrecognized bits BadMode(u8), /// file is smaller than it should be FileTooSmall, } fn read_u16(slice: &[u8]) -> u16 { let mut bytes: [u8; 2] = [0; 2]; bytes.copy_from_slice(&slice[0..2]); u16::from_le_bytes(bytes) } impl<T> PsfFont<T> where T: AsRef<[u8]> { pub fn new(buf: T) -> Result<PsfFont<T>, PsfError> { let file: &[u8] = buf.as_ref(); if read_u16(&file[0..2])!= PSF1_MAGIC { return Err(PsfError::WrongMagic); } let mode: u8 = file[2]; if mode & 0x07!= mode { return Err(PsfError::BadMode(mode)); } let mode_512 = mode & PSF1_MODE_512!= 0; let mode_hastab = mode & PSF1_MODE_HASTAB!= 0; let mode_hasseq = mode & PSF1_MODE_HASSEQ!= 0; let charsize: usize = file[3] as usize; // height, also number of bytes let char_width = 8; let char_height = charsize; let length = if mode_512 { 512 } else { 256 }; let chars_range = 4.. (4 + charsize * length); // File too small if chars_range doesn't fit if chars_range.end > file.len() { return Err(PsfError::FileTooSmall); } let mut unicode_table = BTreeMap::new(); // Parse the unicode table, or generate it if it's not there if mode_hastab { let unicode_table_buf = &file[chars_range.end..]; let mut pos = 0; 'eof: for index in 0..length { loop { if pos >= file.len() { break 'eof; } let codepoint = read_u16(&unicode_table_buf[pos..]) as u32; pos += 2; if codepoint == PSF1_SEPARATOR { // End of sequences for this index break; } else if codepoint == PSF1_STARTSEQ && mode_hasseq { // Sequences not supported yet. pos += 4; } else if let Some(c) = char::from_u32(codepoint) { // Insert codepoint. unicode_table.insert(c, index); } } } } else { for index in 0..length { if let Some(c) = char::from_u32(index as u32) { unicode_table.insert(c, index); } } } Ok(PsfFont { buf, chars_range, unicode_table, char_width, char_height }) } } impl<T> Font for PsfFont<T> where T: AsRef<[u8]> { fn char_width(&self) -> usize { self.char_width } fn char_height(&self) -> usize { self.char_height } fn get(&self, ch: char) -> Option<&[u8]> { self.unicode_table.get(&ch).map(|index| { let start = self.char_height * index; &self.buf.as_ref()[self.chars_range.clone()][start.. (start + self.char_height)] }) } }
{ self.render(ch, self.row, self.col, (self.native_fg, self.native_bg)); }
identifier_body
graphical.rs
/******************************************************************************* * * kit/kernel/terminal/vga.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more information. * ******************************************************************************/ use core::fmt; use core::ops::Range; use alloc::collections::BTreeMap; use crate::framebuffer::Framebuffer; use crate::util::align_up; use super::{Color, CharStream, Terminal}; /// Emulates a terminal on a graphical framebuffer #[derive(Debug)] pub struct Graphical<T, U> { fb: T, font: U, row: usize, col: usize, rows: usize, cols: usize, font_w: usize, font_h: usize, fg: Color, bg: Color, native_fg: u32, native_bg: u32, char_buf: CharStream, } impl<T, U> Graphical<T, U> where T: Framebuffer, U: Font { pub fn new(fb: T, font: U) -> Graphical<T, U> { let mut g = Graphical { row: 0, col: 0, rows: 0, cols: 0, font_w: font.char_width() + 1, font_h: font.char_height(), fg: Color::White, bg: Color::Black, native_fg: 0, native_bg: 0, char_buf: CharStream::default(), fb, font, }; g.rows = g.fb.height()/g.font_h; g.cols = g.fb.width()/g.font_w; g.update_colors(); g } fn update_colors(&mut self) { self.native_fg = self.fb.color_format().format(self.fg.to_rgb()); self.native_bg = self.fb.color_format().format(self.bg.to_rgb()); } fn position_xy(&self, row: usize, col: usize) -> (usize, usize) { ( self.font_w * col, self.font_h * row ) } fn render(&self, ch: char, row: usize, col: usize, colors: (u32, u32)) { let (x, y) = self.position_xy(row, col); let fontdata = self.font.get(ch); let c_width = self.font.char_width(); let get_bit = |px, py, _| { let fg = if let Some(bits) = fontdata { if px >= c_width { false } else { let index = py * c_width + px; let byte = index >> 3; let bit = index & 0b111; let mask = 1u8 << (7 - bit); bits[byte] & mask!= 0u8 } } else { false }; if fg { colors.0 } else { colors.1 } }; self.fb.edit(x, y, self.font_w, self.font_h, get_bit); } fn update_cursor(&mut self) { // TODO: make this non-destructive so we can put back whatever we // replaced. Should merely invert the character really. let (x, y) = self.position_xy(self.row, self.col); self.fb.fill(x, y, self.font_w, self.font_h, self.native_fg); } fn put_here(&self, ch: char) { self.render(ch, self.row, self.col, (self.native_fg, self.native_bg)); } fn scroll(&mut self) { if self.fb.double_buffer_enabled() { let (x0, y0) = self.position_xy(1, 0); let (x1, y1) = self.position_xy(0, 0); // Move the contents of everything but the first row up one row self.fb.copy_within(x0, y0, x1, y1, self.font_w * self.cols, self.font_h * (self.rows-1)); // Clear the last row let (x2, y2) = self.position_xy(self.rows - 1, 0); self.fb.fill(x2, y2, self.font_w * self.cols, self.font_h, self.native_bg); } else { // If double buffer is not enabled, we can't really do a scroll // without it being super slow... so instead, we'll just jump up to // the top self.row = 0; self.col = 0; self.update_cursor(); } } fn new_line(&mut self) { let (x, y) = self.position_xy(self.row, self.col); // Fill end of line let remaining = self.cols - self.col; self.fb.fill(x, y, self.font_w * remaining, self.font_h, self.native_bg); self.row += 1; self.col = 0; if self.row >= self.rows { self.row = self.rows - 1; self.scroll(); } self.update_cursor(); } fn write_char(&mut self, ch: char) { match ch { '\n' => { self.new_line(); }, '\x08' /* backspace */ => { self.put_here(' '); if self.col > 0 { self.col -= 1; } self.update_cursor(); }, _ => { self.put_here(ch); self.col += 1; if self.col >= self.cols { self.new_line(); } else { self.update_cursor(); } } } } } impl<T, U> Terminal for Graphical<T, U> where T: Framebuffer, U: Font { fn reset(&mut self) -> fmt::Result { self.fg = Color::LightGrey; self.bg = Color::Black; self.update_colors(); self.clear() } fn clear(&mut self) -> fmt::Result { self.row = 0; self.col = 0; self.fb.fill(0, 0, self.fb.width(), self.fb.height(), self.native_bg); self.update_cursor(); Ok(()) } fn get_cursor(&self) -> (usize, usize) { (self.row, self.col) } fn set_cursor(&mut self, row: usize, col: usize) -> fmt::Result { self.row = row; self.col = col; self.update_cursor(); Ok(()) } fn get_color(&self) -> (Color, Color) { (self.fg, self.bg) } fn set_color(&mut self, fg: Color, bg: Color) -> fmt::Result { self.fg = fg; self.bg = bg; self.update_colors(); Ok(()) } fn put_raw_byte(&mut self, byte: u8, fg: Color, bg: Color, row: usize, col: usize) -> fmt::Result { // I think we should get rid of this method, it doesn't handle unicode properly self.render( char::from(byte), row, col, (self.fb.color_format().format(fg.to_rgb()), self.fb.color_format().format(bg.to_rgb()))); Ok(()) } fn write_raw_byte(&mut self, byte: u8) -> fmt::Result { // Build unicode self.char_buf.push(byte); while let Some(ch) = self.char_buf.consume() { self.write_char(ch); } Ok(()) } fn set_double_buffer(&mut self, enabled: bool) { self.fb.set_double_buffer(enabled); } fn flush(&mut self) -> fmt::Result { self.update_cursor(); Ok(()) } } impl<T, U> fmt::Write for Graphical<T, U> where T: Framebuffer, U: Font { fn write_char(&mut self, ch: char) -> fmt::Result { let mut buf = [0; 4]; self.write_raw_bytes(ch.encode_utf8(&mut buf).as_bytes())?; self.flush()?; Ok(()) } fn write_str(&mut self, s: &str) -> fmt::Result { self.write_raw_bytes(s.as_bytes())?; self.flush()?; Ok(()) } } static U_VGA16: &[u8] = include_bytes!("font/u_vga16.psf"); pub fn u_vga16() -> PsfFont<&'static [u8]> { PsfFont::new(U_VGA16).unwrap() } pub trait Font { fn char_width(&self) -> usize; fn char_height(&self) -> usize; fn char_bytes(&self) -> usize { align_up(self.char_width() * self.char_height(), 8) / 8 } fn get(&self, ch: char) -> Option<&[u8]>; } #[derive(Debug, Clone)] pub struct PsfFont<T: AsRef<[u8]>> { buf: T, chars_range: Range<usize>, unicode_table: BTreeMap<char, usize>, char_width: usize, char_height: usize, } const PSF1_MAGIC: u16 = 0x0436; /* little endian */ const PSF1_MODE_512: u8 = 0x01; const PSF1_MODE_HASTAB: u8 = 0x02; const PSF1_MODE_HASSEQ: u8 = 0x04; const PSF1_SEPARATOR: u32 = 0xffff; const PSF1_STARTSEQ: u32 = 0xfffe; #[derive(Debug, Clone)] pub enum PsfError { /// this is not a recognized PC Screen Font file WrongMagic, /// the mode field ({:x}) has unrecognized bits BadMode(u8), /// file is smaller than it should be FileTooSmall, } fn read_u16(slice: &[u8]) -> u16 { let mut bytes: [u8; 2] = [0; 2]; bytes.copy_from_slice(&slice[0..2]); u16::from_le_bytes(bytes) } impl<T> PsfFont<T> where T: AsRef<[u8]> { pub fn new(buf: T) -> Result<PsfFont<T>, PsfError> { let file: &[u8] = buf.as_ref(); if read_u16(&file[0..2])!= PSF1_MAGIC { return Err(PsfError::WrongMagic); } let mode: u8 = file[2]; if mode & 0x07!= mode { return Err(PsfError::BadMode(mode)); } let mode_512 = mode & PSF1_MODE_512!= 0; let mode_hastab = mode & PSF1_MODE_HASTAB!= 0; let mode_hasseq = mode & PSF1_MODE_HASSEQ!= 0; let charsize: usize = file[3] as usize; // height, also number of bytes let char_width = 8; let char_height = charsize; let length = if mode_512 { 512 } else { 256 }; let chars_range = 4.. (4 + charsize * length); // File too small if chars_range doesn't fit if chars_range.end > file.len() { return Err(PsfError::FileTooSmall); } let mut unicode_table = BTreeMap::new(); // Parse the unicode table, or generate it if it's not there if mode_hastab { let unicode_table_buf = &file[chars_range.end..]; let mut pos = 0; 'eof: for index in 0..length { loop { if pos >= file.len()
let codepoint = read_u16(&unicode_table_buf[pos..]) as u32; pos += 2; if codepoint == PSF1_SEPARATOR { // End of sequences for this index break; } else if codepoint == PSF1_STARTSEQ && mode_hasseq { // Sequences not supported yet. pos += 4; } else if let Some(c) = char::from_u32(codepoint) { // Insert codepoint. unicode_table.insert(c, index); } } } } else { for index in 0..length { if let Some(c) = char::from_u32(index as u32) { unicode_table.insert(c, index); } } } Ok(PsfFont { buf, chars_range, unicode_table, char_width, char_height }) } } impl<T> Font for PsfFont<T> where T: AsRef<[u8]> { fn char_width(&self) -> usize { self.char_width } fn char_height(&self) -> usize { self.char_height } fn get(&self, ch: char) -> Option<&[u8]> { self.unicode_table.get(&ch).map(|index| { let start = self.char_height * index; &self.buf.as_ref()[self.chars_range.clone()][start.. (start + self.char_height)] }) } }
{ break 'eof; }
conditional_block
graphical.rs
/******************************************************************************* * * kit/kernel/terminal/vga.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more information. * ******************************************************************************/ use core::fmt; use core::ops::Range; use alloc::collections::BTreeMap; use crate::framebuffer::Framebuffer; use crate::util::align_up; use super::{Color, CharStream, Terminal}; /// Emulates a terminal on a graphical framebuffer #[derive(Debug)] pub struct Graphical<T, U> { fb: T, font: U, row: usize, col: usize, rows: usize, cols: usize, font_w: usize, font_h: usize, fg: Color, bg: Color, native_fg: u32, native_bg: u32, char_buf: CharStream, } impl<T, U> Graphical<T, U> where T: Framebuffer, U: Font { pub fn new(fb: T, font: U) -> Graphical<T, U> { let mut g = Graphical { row: 0, col: 0, rows: 0,
fg: Color::White, bg: Color::Black, native_fg: 0, native_bg: 0, char_buf: CharStream::default(), fb, font, }; g.rows = g.fb.height()/g.font_h; g.cols = g.fb.width()/g.font_w; g.update_colors(); g } fn update_colors(&mut self) { self.native_fg = self.fb.color_format().format(self.fg.to_rgb()); self.native_bg = self.fb.color_format().format(self.bg.to_rgb()); } fn position_xy(&self, row: usize, col: usize) -> (usize, usize) { ( self.font_w * col, self.font_h * row ) } fn render(&self, ch: char, row: usize, col: usize, colors: (u32, u32)) { let (x, y) = self.position_xy(row, col); let fontdata = self.font.get(ch); let c_width = self.font.char_width(); let get_bit = |px, py, _| { let fg = if let Some(bits) = fontdata { if px >= c_width { false } else { let index = py * c_width + px; let byte = index >> 3; let bit = index & 0b111; let mask = 1u8 << (7 - bit); bits[byte] & mask!= 0u8 } } else { false }; if fg { colors.0 } else { colors.1 } }; self.fb.edit(x, y, self.font_w, self.font_h, get_bit); } fn update_cursor(&mut self) { // TODO: make this non-destructive so we can put back whatever we // replaced. Should merely invert the character really. let (x, y) = self.position_xy(self.row, self.col); self.fb.fill(x, y, self.font_w, self.font_h, self.native_fg); } fn put_here(&self, ch: char) { self.render(ch, self.row, self.col, (self.native_fg, self.native_bg)); } fn scroll(&mut self) { if self.fb.double_buffer_enabled() { let (x0, y0) = self.position_xy(1, 0); let (x1, y1) = self.position_xy(0, 0); // Move the contents of everything but the first row up one row self.fb.copy_within(x0, y0, x1, y1, self.font_w * self.cols, self.font_h * (self.rows-1)); // Clear the last row let (x2, y2) = self.position_xy(self.rows - 1, 0); self.fb.fill(x2, y2, self.font_w * self.cols, self.font_h, self.native_bg); } else { // If double buffer is not enabled, we can't really do a scroll // without it being super slow... so instead, we'll just jump up to // the top self.row = 0; self.col = 0; self.update_cursor(); } } fn new_line(&mut self) { let (x, y) = self.position_xy(self.row, self.col); // Fill end of line let remaining = self.cols - self.col; self.fb.fill(x, y, self.font_w * remaining, self.font_h, self.native_bg); self.row += 1; self.col = 0; if self.row >= self.rows { self.row = self.rows - 1; self.scroll(); } self.update_cursor(); } fn write_char(&mut self, ch: char) { match ch { '\n' => { self.new_line(); }, '\x08' /* backspace */ => { self.put_here(' '); if self.col > 0 { self.col -= 1; } self.update_cursor(); }, _ => { self.put_here(ch); self.col += 1; if self.col >= self.cols { self.new_line(); } else { self.update_cursor(); } } } } } impl<T, U> Terminal for Graphical<T, U> where T: Framebuffer, U: Font { fn reset(&mut self) -> fmt::Result { self.fg = Color::LightGrey; self.bg = Color::Black; self.update_colors(); self.clear() } fn clear(&mut self) -> fmt::Result { self.row = 0; self.col = 0; self.fb.fill(0, 0, self.fb.width(), self.fb.height(), self.native_bg); self.update_cursor(); Ok(()) } fn get_cursor(&self) -> (usize, usize) { (self.row, self.col) } fn set_cursor(&mut self, row: usize, col: usize) -> fmt::Result { self.row = row; self.col = col; self.update_cursor(); Ok(()) } fn get_color(&self) -> (Color, Color) { (self.fg, self.bg) } fn set_color(&mut self, fg: Color, bg: Color) -> fmt::Result { self.fg = fg; self.bg = bg; self.update_colors(); Ok(()) } fn put_raw_byte(&mut self, byte: u8, fg: Color, bg: Color, row: usize, col: usize) -> fmt::Result { // I think we should get rid of this method, it doesn't handle unicode properly self.render( char::from(byte), row, col, (self.fb.color_format().format(fg.to_rgb()), self.fb.color_format().format(bg.to_rgb()))); Ok(()) } fn write_raw_byte(&mut self, byte: u8) -> fmt::Result { // Build unicode self.char_buf.push(byte); while let Some(ch) = self.char_buf.consume() { self.write_char(ch); } Ok(()) } fn set_double_buffer(&mut self, enabled: bool) { self.fb.set_double_buffer(enabled); } fn flush(&mut self) -> fmt::Result { self.update_cursor(); Ok(()) } } impl<T, U> fmt::Write for Graphical<T, U> where T: Framebuffer, U: Font { fn write_char(&mut self, ch: char) -> fmt::Result { let mut buf = [0; 4]; self.write_raw_bytes(ch.encode_utf8(&mut buf).as_bytes())?; self.flush()?; Ok(()) } fn write_str(&mut self, s: &str) -> fmt::Result { self.write_raw_bytes(s.as_bytes())?; self.flush()?; Ok(()) } } static U_VGA16: &[u8] = include_bytes!("font/u_vga16.psf"); pub fn u_vga16() -> PsfFont<&'static [u8]> { PsfFont::new(U_VGA16).unwrap() } pub trait Font { fn char_width(&self) -> usize; fn char_height(&self) -> usize; fn char_bytes(&self) -> usize { align_up(self.char_width() * self.char_height(), 8) / 8 } fn get(&self, ch: char) -> Option<&[u8]>; } #[derive(Debug, Clone)] pub struct PsfFont<T: AsRef<[u8]>> { buf: T, chars_range: Range<usize>, unicode_table: BTreeMap<char, usize>, char_width: usize, char_height: usize, } const PSF1_MAGIC: u16 = 0x0436; /* little endian */ const PSF1_MODE_512: u8 = 0x01; const PSF1_MODE_HASTAB: u8 = 0x02; const PSF1_MODE_HASSEQ: u8 = 0x04; const PSF1_SEPARATOR: u32 = 0xffff; const PSF1_STARTSEQ: u32 = 0xfffe; #[derive(Debug, Clone)] pub enum PsfError { /// this is not a recognized PC Screen Font file WrongMagic, /// the mode field ({:x}) has unrecognized bits BadMode(u8), /// file is smaller than it should be FileTooSmall, } fn read_u16(slice: &[u8]) -> u16 { let mut bytes: [u8; 2] = [0; 2]; bytes.copy_from_slice(&slice[0..2]); u16::from_le_bytes(bytes) } impl<T> PsfFont<T> where T: AsRef<[u8]> { pub fn new(buf: T) -> Result<PsfFont<T>, PsfError> { let file: &[u8] = buf.as_ref(); if read_u16(&file[0..2])!= PSF1_MAGIC { return Err(PsfError::WrongMagic); } let mode: u8 = file[2]; if mode & 0x07!= mode { return Err(PsfError::BadMode(mode)); } let mode_512 = mode & PSF1_MODE_512!= 0; let mode_hastab = mode & PSF1_MODE_HASTAB!= 0; let mode_hasseq = mode & PSF1_MODE_HASSEQ!= 0; let charsize: usize = file[3] as usize; // height, also number of bytes let char_width = 8; let char_height = charsize; let length = if mode_512 { 512 } else { 256 }; let chars_range = 4.. (4 + charsize * length); // File too small if chars_range doesn't fit if chars_range.end > file.len() { return Err(PsfError::FileTooSmall); } let mut unicode_table = BTreeMap::new(); // Parse the unicode table, or generate it if it's not there if mode_hastab { let unicode_table_buf = &file[chars_range.end..]; let mut pos = 0; 'eof: for index in 0..length { loop { if pos >= file.len() { break 'eof; } let codepoint = read_u16(&unicode_table_buf[pos..]) as u32; pos += 2; if codepoint == PSF1_SEPARATOR { // End of sequences for this index break; } else if codepoint == PSF1_STARTSEQ && mode_hasseq { // Sequences not supported yet. pos += 4; } else if let Some(c) = char::from_u32(codepoint) { // Insert codepoint. unicode_table.insert(c, index); } } } } else { for index in 0..length { if let Some(c) = char::from_u32(index as u32) { unicode_table.insert(c, index); } } } Ok(PsfFont { buf, chars_range, unicode_table, char_width, char_height }) } } impl<T> Font for PsfFont<T> where T: AsRef<[u8]> { fn char_width(&self) -> usize { self.char_width } fn char_height(&self) -> usize { self.char_height } fn get(&self, ch: char) -> Option<&[u8]> { self.unicode_table.get(&ch).map(|index| { let start = self.char_height * index; &self.buf.as_ref()[self.chars_range.clone()][start.. (start + self.char_height)] }) } }
cols: 0, font_w: font.char_width() + 1, font_h: font.char_height(),
random_line_split
graphical.rs
/******************************************************************************* * * kit/kernel/terminal/vga.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more information. * ******************************************************************************/ use core::fmt; use core::ops::Range; use alloc::collections::BTreeMap; use crate::framebuffer::Framebuffer; use crate::util::align_up; use super::{Color, CharStream, Terminal}; /// Emulates a terminal on a graphical framebuffer #[derive(Debug)] pub struct Graphical<T, U> { fb: T, font: U, row: usize, col: usize, rows: usize, cols: usize, font_w: usize, font_h: usize, fg: Color, bg: Color, native_fg: u32, native_bg: u32, char_buf: CharStream, } impl<T, U> Graphical<T, U> where T: Framebuffer, U: Font { pub fn new(fb: T, font: U) -> Graphical<T, U> { let mut g = Graphical { row: 0, col: 0, rows: 0, cols: 0, font_w: font.char_width() + 1, font_h: font.char_height(), fg: Color::White, bg: Color::Black, native_fg: 0, native_bg: 0, char_buf: CharStream::default(), fb, font, }; g.rows = g.fb.height()/g.font_h; g.cols = g.fb.width()/g.font_w; g.update_colors(); g } fn update_colors(&mut self) { self.native_fg = self.fb.color_format().format(self.fg.to_rgb()); self.native_bg = self.fb.color_format().format(self.bg.to_rgb()); } fn position_xy(&self, row: usize, col: usize) -> (usize, usize) { ( self.font_w * col, self.font_h * row ) } fn render(&self, ch: char, row: usize, col: usize, colors: (u32, u32)) { let (x, y) = self.position_xy(row, col); let fontdata = self.font.get(ch); let c_width = self.font.char_width(); let get_bit = |px, py, _| { let fg = if let Some(bits) = fontdata { if px >= c_width { false } else { let index = py * c_width + px; let byte = index >> 3; let bit = index & 0b111; let mask = 1u8 << (7 - bit); bits[byte] & mask!= 0u8 } } else { false }; if fg { colors.0 } else { colors.1 } }; self.fb.edit(x, y, self.font_w, self.font_h, get_bit); } fn update_cursor(&mut self) { // TODO: make this non-destructive so we can put back whatever we // replaced. Should merely invert the character really. let (x, y) = self.position_xy(self.row, self.col); self.fb.fill(x, y, self.font_w, self.font_h, self.native_fg); } fn put_here(&self, ch: char) { self.render(ch, self.row, self.col, (self.native_fg, self.native_bg)); } fn scroll(&mut self) { if self.fb.double_buffer_enabled() { let (x0, y0) = self.position_xy(1, 0); let (x1, y1) = self.position_xy(0, 0); // Move the contents of everything but the first row up one row self.fb.copy_within(x0, y0, x1, y1, self.font_w * self.cols, self.font_h * (self.rows-1)); // Clear the last row let (x2, y2) = self.position_xy(self.rows - 1, 0); self.fb.fill(x2, y2, self.font_w * self.cols, self.font_h, self.native_bg); } else { // If double buffer is not enabled, we can't really do a scroll // without it being super slow... so instead, we'll just jump up to // the top self.row = 0; self.col = 0; self.update_cursor(); } } fn new_line(&mut self) { let (x, y) = self.position_xy(self.row, self.col); // Fill end of line let remaining = self.cols - self.col; self.fb.fill(x, y, self.font_w * remaining, self.font_h, self.native_bg); self.row += 1; self.col = 0; if self.row >= self.rows { self.row = self.rows - 1; self.scroll(); } self.update_cursor(); } fn write_char(&mut self, ch: char) { match ch { '\n' => { self.new_line(); }, '\x08' /* backspace */ => { self.put_here(' '); if self.col > 0 { self.col -= 1; } self.update_cursor(); }, _ => { self.put_here(ch); self.col += 1; if self.col >= self.cols { self.new_line(); } else { self.update_cursor(); } } } } } impl<T, U> Terminal for Graphical<T, U> where T: Framebuffer, U: Font { fn reset(&mut self) -> fmt::Result { self.fg = Color::LightGrey; self.bg = Color::Black; self.update_colors(); self.clear() } fn clear(&mut self) -> fmt::Result { self.row = 0; self.col = 0; self.fb.fill(0, 0, self.fb.width(), self.fb.height(), self.native_bg); self.update_cursor(); Ok(()) } fn get_cursor(&self) -> (usize, usize) { (self.row, self.col) } fn set_cursor(&mut self, row: usize, col: usize) -> fmt::Result { self.row = row; self.col = col; self.update_cursor(); Ok(()) } fn get_color(&self) -> (Color, Color) { (self.fg, self.bg) } fn set_color(&mut self, fg: Color, bg: Color) -> fmt::Result { self.fg = fg; self.bg = bg; self.update_colors(); Ok(()) } fn
(&mut self, byte: u8, fg: Color, bg: Color, row: usize, col: usize) -> fmt::Result { // I think we should get rid of this method, it doesn't handle unicode properly self.render( char::from(byte), row, col, (self.fb.color_format().format(fg.to_rgb()), self.fb.color_format().format(bg.to_rgb()))); Ok(()) } fn write_raw_byte(&mut self, byte: u8) -> fmt::Result { // Build unicode self.char_buf.push(byte); while let Some(ch) = self.char_buf.consume() { self.write_char(ch); } Ok(()) } fn set_double_buffer(&mut self, enabled: bool) { self.fb.set_double_buffer(enabled); } fn flush(&mut self) -> fmt::Result { self.update_cursor(); Ok(()) } } impl<T, U> fmt::Write for Graphical<T, U> where T: Framebuffer, U: Font { fn write_char(&mut self, ch: char) -> fmt::Result { let mut buf = [0; 4]; self.write_raw_bytes(ch.encode_utf8(&mut buf).as_bytes())?; self.flush()?; Ok(()) } fn write_str(&mut self, s: &str) -> fmt::Result { self.write_raw_bytes(s.as_bytes())?; self.flush()?; Ok(()) } } static U_VGA16: &[u8] = include_bytes!("font/u_vga16.psf"); pub fn u_vga16() -> PsfFont<&'static [u8]> { PsfFont::new(U_VGA16).unwrap() } pub trait Font { fn char_width(&self) -> usize; fn char_height(&self) -> usize; fn char_bytes(&self) -> usize { align_up(self.char_width() * self.char_height(), 8) / 8 } fn get(&self, ch: char) -> Option<&[u8]>; } #[derive(Debug, Clone)] pub struct PsfFont<T: AsRef<[u8]>> { buf: T, chars_range: Range<usize>, unicode_table: BTreeMap<char, usize>, char_width: usize, char_height: usize, } const PSF1_MAGIC: u16 = 0x0436; /* little endian */ const PSF1_MODE_512: u8 = 0x01; const PSF1_MODE_HASTAB: u8 = 0x02; const PSF1_MODE_HASSEQ: u8 = 0x04; const PSF1_SEPARATOR: u32 = 0xffff; const PSF1_STARTSEQ: u32 = 0xfffe; #[derive(Debug, Clone)] pub enum PsfError { /// this is not a recognized PC Screen Font file WrongMagic, /// the mode field ({:x}) has unrecognized bits BadMode(u8), /// file is smaller than it should be FileTooSmall, } fn read_u16(slice: &[u8]) -> u16 { let mut bytes: [u8; 2] = [0; 2]; bytes.copy_from_slice(&slice[0..2]); u16::from_le_bytes(bytes) } impl<T> PsfFont<T> where T: AsRef<[u8]> { pub fn new(buf: T) -> Result<PsfFont<T>, PsfError> { let file: &[u8] = buf.as_ref(); if read_u16(&file[0..2])!= PSF1_MAGIC { return Err(PsfError::WrongMagic); } let mode: u8 = file[2]; if mode & 0x07!= mode { return Err(PsfError::BadMode(mode)); } let mode_512 = mode & PSF1_MODE_512!= 0; let mode_hastab = mode & PSF1_MODE_HASTAB!= 0; let mode_hasseq = mode & PSF1_MODE_HASSEQ!= 0; let charsize: usize = file[3] as usize; // height, also number of bytes let char_width = 8; let char_height = charsize; let length = if mode_512 { 512 } else { 256 }; let chars_range = 4.. (4 + charsize * length); // File too small if chars_range doesn't fit if chars_range.end > file.len() { return Err(PsfError::FileTooSmall); } let mut unicode_table = BTreeMap::new(); // Parse the unicode table, or generate it if it's not there if mode_hastab { let unicode_table_buf = &file[chars_range.end..]; let mut pos = 0; 'eof: for index in 0..length { loop { if pos >= file.len() { break 'eof; } let codepoint = read_u16(&unicode_table_buf[pos..]) as u32; pos += 2; if codepoint == PSF1_SEPARATOR { // End of sequences for this index break; } else if codepoint == PSF1_STARTSEQ && mode_hasseq { // Sequences not supported yet. pos += 4; } else if let Some(c) = char::from_u32(codepoint) { // Insert codepoint. unicode_table.insert(c, index); } } } } else { for index in 0..length { if let Some(c) = char::from_u32(index as u32) { unicode_table.insert(c, index); } } } Ok(PsfFont { buf, chars_range, unicode_table, char_width, char_height }) } } impl<T> Font for PsfFont<T> where T: AsRef<[u8]> { fn char_width(&self) -> usize { self.char_width } fn char_height(&self) -> usize { self.char_height } fn get(&self, ch: char) -> Option<&[u8]> { self.unicode_table.get(&ch).map(|index| { let start = self.char_height * index; &self.buf.as_ref()[self.chars_range.clone()][start.. (start + self.char_height)] }) } }
put_raw_byte
identifier_name
hashset.rs
use containers::array::Array; use containers::list::List; use containers::reference::Ref; use containers::vector::Vector; use memory::page::Page; use memory::region::Region; #[derive(Copy, Clone)] pub struct HashSet<T: Hash<T> + Copy> { slots: Vector<Ref<List<Slot<T>>>>, } impl<T: Hash<T> + Copy> HashSet<T> { pub fn from_vector(_pr: &Region, _rp: *mut Page, vector: Ref<Vector<T>>) -> Ref<HashSet<T>> { let _r = Region::create(_pr); let hash_size = HashPrimeHelper::get_prime(vector.length); let mut array: Ref<Array<Ref<List<Slot<T>>>>> = Ref::new(_r.page, Array::new()); for _ in 0..hash_size { array.add(Ref::new(_r.page, List::new())); } let mut hash_set = Ref::new(_rp, HashSet { slots: Vector::from_array(_rp, array) }); hash_set.initialize_from_vector(vector); hash_set } fn initialize_from_vector(&mut self, vector: Ref<Vector<T>>) { for value in vector.iter() { self.add(value); } } fn add(&mut self, value: &T) { let hash_code = value.hash(); let slot_number = hash_code % self.slots.length; let mut slot_list = self.slots[slot_number]; for slot in slot_list.get_iterator() { if value.equals(&slot.value) { return; } } slot_list.add(Slot { hash_code: hash_code, value: *value, }); } pub fn contains(&self, value: T) -> bool { for slot in self.slots[value.hash() % self.slots.length].get_iterator() { if value.equals(&slot.value) { return true; }
false } } #[derive(Copy, Clone)] struct Slot<T: Copy> { value: T, hash_code: usize, } pub struct HashPrimeHelper {} // https://planetmath.org/goodhashtableprimes static HASH_PRIMES: &'static [usize] = &[ 3, 5, 11, 23, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, ]; impl HashPrimeHelper { pub fn get_prime(size: usize) -> usize { for i in HASH_PRIMES { if *i >= size { return *i; } } let mut i = size | 1; while i < std::usize::MAX { if HashPrimeHelper::is_prime(i) { return i; } i += 2; } size } fn is_prime(candidate: usize) -> bool { if (candidate & 1)!= 0 { let limit = (candidate as f64).sqrt() as usize; let mut divisor: usize = 3; while divisor <= limit { divisor += 2; if (candidate % divisor) == 0 { return false; } } return true; } candidate == 2 } } pub trait Equal<T:?Sized = Self> { fn equals(&self, other: &T) -> bool; } pub trait Hash<T:?Sized = Self>: Equal<T> { fn hash(&self) -> usize; } // FNV-1a hash pub fn hash(data: *const u8, length: usize) -> usize { let bytes = unsafe { std::slice::from_raw_parts(data, length) }; let mut hash: u64 = 0xcbf29ce484222325; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash.wrapping_mul(0x100000001b3); } hash as usize } #[test] fn test_hash_set() { use containers::String; use memory::Heap; use memory::Page; use memory::Region; use memory::StackBucket; let mut heap = Heap::create(); let root_stack_bucket = StackBucket::create(&mut heap); let root_page = Page::get(root_stack_bucket as usize); let _r = Region::create_from_page(root_page); let keywords = HashSet::from_vector( &_r, _r.page, Ref::new( _r.page, Vector::from_raw_array( _r.page, &[ String::from_string_slice(_r.page, "using"), String::from_string_slice(_r.page, "namespace"), String::from_string_slice(_r.page, "typedef"), ], ), ), ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "using")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "namespace")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "typedef")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "nix")), false ); }
}
random_line_split
hashset.rs
use containers::array::Array; use containers::list::List; use containers::reference::Ref; use containers::vector::Vector; use memory::page::Page; use memory::region::Region; #[derive(Copy, Clone)] pub struct HashSet<T: Hash<T> + Copy> { slots: Vector<Ref<List<Slot<T>>>>, } impl<T: Hash<T> + Copy> HashSet<T> { pub fn
(_pr: &Region, _rp: *mut Page, vector: Ref<Vector<T>>) -> Ref<HashSet<T>> { let _r = Region::create(_pr); let hash_size = HashPrimeHelper::get_prime(vector.length); let mut array: Ref<Array<Ref<List<Slot<T>>>>> = Ref::new(_r.page, Array::new()); for _ in 0..hash_size { array.add(Ref::new(_r.page, List::new())); } let mut hash_set = Ref::new(_rp, HashSet { slots: Vector::from_array(_rp, array) }); hash_set.initialize_from_vector(vector); hash_set } fn initialize_from_vector(&mut self, vector: Ref<Vector<T>>) { for value in vector.iter() { self.add(value); } } fn add(&mut self, value: &T) { let hash_code = value.hash(); let slot_number = hash_code % self.slots.length; let mut slot_list = self.slots[slot_number]; for slot in slot_list.get_iterator() { if value.equals(&slot.value) { return; } } slot_list.add(Slot { hash_code: hash_code, value: *value, }); } pub fn contains(&self, value: T) -> bool { for slot in self.slots[value.hash() % self.slots.length].get_iterator() { if value.equals(&slot.value) { return true; } } false } } #[derive(Copy, Clone)] struct Slot<T: Copy> { value: T, hash_code: usize, } pub struct HashPrimeHelper {} // https://planetmath.org/goodhashtableprimes static HASH_PRIMES: &'static [usize] = &[ 3, 5, 11, 23, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, ]; impl HashPrimeHelper { pub fn get_prime(size: usize) -> usize { for i in HASH_PRIMES { if *i >= size { return *i; } } let mut i = size | 1; while i < std::usize::MAX { if HashPrimeHelper::is_prime(i) { return i; } i += 2; } size } fn is_prime(candidate: usize) -> bool { if (candidate & 1)!= 0 { let limit = (candidate as f64).sqrt() as usize; let mut divisor: usize = 3; while divisor <= limit { divisor += 2; if (candidate % divisor) == 0 { return false; } } return true; } candidate == 2 } } pub trait Equal<T:?Sized = Self> { fn equals(&self, other: &T) -> bool; } pub trait Hash<T:?Sized = Self>: Equal<T> { fn hash(&self) -> usize; } // FNV-1a hash pub fn hash(data: *const u8, length: usize) -> usize { let bytes = unsafe { std::slice::from_raw_parts(data, length) }; let mut hash: u64 = 0xcbf29ce484222325; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash.wrapping_mul(0x100000001b3); } hash as usize } #[test] fn test_hash_set() { use containers::String; use memory::Heap; use memory::Page; use memory::Region; use memory::StackBucket; let mut heap = Heap::create(); let root_stack_bucket = StackBucket::create(&mut heap); let root_page = Page::get(root_stack_bucket as usize); let _r = Region::create_from_page(root_page); let keywords = HashSet::from_vector( &_r, _r.page, Ref::new( _r.page, Vector::from_raw_array( _r.page, &[ String::from_string_slice(_r.page, "using"), String::from_string_slice(_r.page, "namespace"), String::from_string_slice(_r.page, "typedef"), ], ), ), ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "using")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "namespace")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "typedef")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "nix")), false ); }
from_vector
identifier_name
hashset.rs
use containers::array::Array; use containers::list::List; use containers::reference::Ref; use containers::vector::Vector; use memory::page::Page; use memory::region::Region; #[derive(Copy, Clone)] pub struct HashSet<T: Hash<T> + Copy> { slots: Vector<Ref<List<Slot<T>>>>, } impl<T: Hash<T> + Copy> HashSet<T> { pub fn from_vector(_pr: &Region, _rp: *mut Page, vector: Ref<Vector<T>>) -> Ref<HashSet<T>> { let _r = Region::create(_pr); let hash_size = HashPrimeHelper::get_prime(vector.length); let mut array: Ref<Array<Ref<List<Slot<T>>>>> = Ref::new(_r.page, Array::new()); for _ in 0..hash_size { array.add(Ref::new(_r.page, List::new())); } let mut hash_set = Ref::new(_rp, HashSet { slots: Vector::from_array(_rp, array) }); hash_set.initialize_from_vector(vector); hash_set } fn initialize_from_vector(&mut self, vector: Ref<Vector<T>>) { for value in vector.iter() { self.add(value); } } fn add(&mut self, value: &T) { let hash_code = value.hash(); let slot_number = hash_code % self.slots.length; let mut slot_list = self.slots[slot_number]; for slot in slot_list.get_iterator() { if value.equals(&slot.value) { return; } } slot_list.add(Slot { hash_code: hash_code, value: *value, }); } pub fn contains(&self, value: T) -> bool { for slot in self.slots[value.hash() % self.slots.length].get_iterator() { if value.equals(&slot.value) { return true; } } false } } #[derive(Copy, Clone)] struct Slot<T: Copy> { value: T, hash_code: usize, } pub struct HashPrimeHelper {} // https://planetmath.org/goodhashtableprimes static HASH_PRIMES: &'static [usize] = &[ 3, 5, 11, 23, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, ]; impl HashPrimeHelper { pub fn get_prime(size: usize) -> usize
fn is_prime(candidate: usize) -> bool { if (candidate & 1)!= 0 { let limit = (candidate as f64).sqrt() as usize; let mut divisor: usize = 3; while divisor <= limit { divisor += 2; if (candidate % divisor) == 0 { return false; } } return true; } candidate == 2 } } pub trait Equal<T:?Sized = Self> { fn equals(&self, other: &T) -> bool; } pub trait Hash<T:?Sized = Self>: Equal<T> { fn hash(&self) -> usize; } // FNV-1a hash pub fn hash(data: *const u8, length: usize) -> usize { let bytes = unsafe { std::slice::from_raw_parts(data, length) }; let mut hash: u64 = 0xcbf29ce484222325; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash.wrapping_mul(0x100000001b3); } hash as usize } #[test] fn test_hash_set() { use containers::String; use memory::Heap; use memory::Page; use memory::Region; use memory::StackBucket; let mut heap = Heap::create(); let root_stack_bucket = StackBucket::create(&mut heap); let root_page = Page::get(root_stack_bucket as usize); let _r = Region::create_from_page(root_page); let keywords = HashSet::from_vector( &_r, _r.page, Ref::new( _r.page, Vector::from_raw_array( _r.page, &[ String::from_string_slice(_r.page, "using"), String::from_string_slice(_r.page, "namespace"), String::from_string_slice(_r.page, "typedef"), ], ), ), ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "using")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "namespace")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "typedef")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "nix")), false ); }
{ for i in HASH_PRIMES { if *i >= size { return *i; } } let mut i = size | 1; while i < std::usize::MAX { if HashPrimeHelper::is_prime(i) { return i; } i += 2; } size }
identifier_body
hashset.rs
use containers::array::Array; use containers::list::List; use containers::reference::Ref; use containers::vector::Vector; use memory::page::Page; use memory::region::Region; #[derive(Copy, Clone)] pub struct HashSet<T: Hash<T> + Copy> { slots: Vector<Ref<List<Slot<T>>>>, } impl<T: Hash<T> + Copy> HashSet<T> { pub fn from_vector(_pr: &Region, _rp: *mut Page, vector: Ref<Vector<T>>) -> Ref<HashSet<T>> { let _r = Region::create(_pr); let hash_size = HashPrimeHelper::get_prime(vector.length); let mut array: Ref<Array<Ref<List<Slot<T>>>>> = Ref::new(_r.page, Array::new()); for _ in 0..hash_size { array.add(Ref::new(_r.page, List::new())); } let mut hash_set = Ref::new(_rp, HashSet { slots: Vector::from_array(_rp, array) }); hash_set.initialize_from_vector(vector); hash_set } fn initialize_from_vector(&mut self, vector: Ref<Vector<T>>) { for value in vector.iter() { self.add(value); } } fn add(&mut self, value: &T) { let hash_code = value.hash(); let slot_number = hash_code % self.slots.length; let mut slot_list = self.slots[slot_number]; for slot in slot_list.get_iterator() { if value.equals(&slot.value) { return; } } slot_list.add(Slot { hash_code: hash_code, value: *value, }); } pub fn contains(&self, value: T) -> bool { for slot in self.slots[value.hash() % self.slots.length].get_iterator() { if value.equals(&slot.value) { return true; } } false } } #[derive(Copy, Clone)] struct Slot<T: Copy> { value: T, hash_code: usize, } pub struct HashPrimeHelper {} // https://planetmath.org/goodhashtableprimes static HASH_PRIMES: &'static [usize] = &[ 3, 5, 11, 23, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, ]; impl HashPrimeHelper { pub fn get_prime(size: usize) -> usize { for i in HASH_PRIMES { if *i >= size { return *i; } } let mut i = size | 1; while i < std::usize::MAX { if HashPrimeHelper::is_prime(i) { return i; } i += 2; } size } fn is_prime(candidate: usize) -> bool { if (candidate & 1)!= 0 { let limit = (candidate as f64).sqrt() as usize; let mut divisor: usize = 3; while divisor <= limit { divisor += 2; if (candidate % divisor) == 0
} return true; } candidate == 2 } } pub trait Equal<T:?Sized = Self> { fn equals(&self, other: &T) -> bool; } pub trait Hash<T:?Sized = Self>: Equal<T> { fn hash(&self) -> usize; } // FNV-1a hash pub fn hash(data: *const u8, length: usize) -> usize { let bytes = unsafe { std::slice::from_raw_parts(data, length) }; let mut hash: u64 = 0xcbf29ce484222325; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash.wrapping_mul(0x100000001b3); } hash as usize } #[test] fn test_hash_set() { use containers::String; use memory::Heap; use memory::Page; use memory::Region; use memory::StackBucket; let mut heap = Heap::create(); let root_stack_bucket = StackBucket::create(&mut heap); let root_page = Page::get(root_stack_bucket as usize); let _r = Region::create_from_page(root_page); let keywords = HashSet::from_vector( &_r, _r.page, Ref::new( _r.page, Vector::from_raw_array( _r.page, &[ String::from_string_slice(_r.page, "using"), String::from_string_slice(_r.page, "namespace"), String::from_string_slice(_r.page, "typedef"), ], ), ), ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "using")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "namespace")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "typedef")), true ); assert_eq!( (*keywords).contains(String::from_string_slice(_r.page, "nix")), false ); }
{ return false; }
conditional_block
numeric-method-autoexport.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. // no-pretty-expanded // This file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. use std::ops::Add; use std::num::ToPrimitive;
pub fn main() { // ints // num assert_eq!(15i.add(6), 21); assert_eq!(15i8.add(6i8), 21i8); assert_eq!(15i16.add(6i16), 21i16); assert_eq!(15i32.add(6i32), 21i32); assert_eq!(15i64.add(6i64), 21i64); // uints // num assert_eq!(15u.add(6u), 21u); assert_eq!(15u8.add(6u8), 21u8); assert_eq!(15u16.add(6u16), 21u16); assert_eq!(15u32.add(6u32), 21u32); assert_eq!(15u64.add(6u64), 21u64); // floats // num assert_eq!(10f32.to_int().unwrap(), 10); assert_eq!(10f64.to_int().unwrap(), 10); }
random_line_split
numeric-method-autoexport.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. // no-pretty-expanded // This file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. use std::ops::Add; use std::num::ToPrimitive; pub fn
() { // ints // num assert_eq!(15i.add(6), 21); assert_eq!(15i8.add(6i8), 21i8); assert_eq!(15i16.add(6i16), 21i16); assert_eq!(15i32.add(6i32), 21i32); assert_eq!(15i64.add(6i64), 21i64); // uints // num assert_eq!(15u.add(6u), 21u); assert_eq!(15u8.add(6u8), 21u8); assert_eq!(15u16.add(6u16), 21u16); assert_eq!(15u32.add(6u32), 21u32); assert_eq!(15u64.add(6u64), 21u64); // floats // num assert_eq!(10f32.to_int().unwrap(), 10); assert_eq!(10f64.to_int().unwrap(), 10); }
main
identifier_name
numeric-method-autoexport.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. // no-pretty-expanded // This file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. use std::ops::Add; use std::num::ToPrimitive; pub fn main()
assert_eq!(10f64.to_int().unwrap(), 10); }
{ // ints // num assert_eq!(15i.add(6), 21); assert_eq!(15i8.add(6i8), 21i8); assert_eq!(15i16.add(6i16), 21i16); assert_eq!(15i32.add(6i32), 21i32); assert_eq!(15i64.add(6i64), 21i64); // uints // num assert_eq!(15u.add(6u), 21u); assert_eq!(15u8.add(6u8), 21u8); assert_eq!(15u16.add(6u16), 21u16); assert_eq!(15u32.add(6u32), 21u32); assert_eq!(15u64.add(6u64), 21u64); // floats // num assert_eq!(10f32.to_int().unwrap(), 10);
identifier_body
explicit-self-generic.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. /** * A function that returns a hash of a value * * The hash should concentrate entropy in the lower bits. */ type HashFn<K> = proc(K):'static -> uint; type EqFn<K> = proc(K, K):'static -> bool; struct LM { resize_at: uint, size: uint }
impl<K,V> Copy for HashMap<K,V> {} fn linear_map<K,V>() -> HashMap<K,V> { HashMap::HashMap_(LM{ resize_at: 32, size: 0}) } impl<K,V> HashMap<K,V> { pub fn len(&mut self) -> uint { match *self { HashMap::HashMap_(l) => l.size } } } pub fn main() { let mut m = box linear_map::<(),()>(); assert_eq!(m.len(), 0); }
impl Copy for LM {} enum HashMap<K,V> { HashMap_(LM) }
random_line_split
explicit-self-generic.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. /** * A function that returns a hash of a value * * The hash should concentrate entropy in the lower bits. */ type HashFn<K> = proc(K):'static -> uint; type EqFn<K> = proc(K, K):'static -> bool; struct LM { resize_at: uint, size: uint } impl Copy for LM {} enum HashMap<K,V> { HashMap_(LM) } impl<K,V> Copy for HashMap<K,V> {} fn linear_map<K,V>() -> HashMap<K,V> { HashMap::HashMap_(LM{ resize_at: 32, size: 0}) } impl<K,V> HashMap<K,V> { pub fn
(&mut self) -> uint { match *self { HashMap::HashMap_(l) => l.size } } } pub fn main() { let mut m = box linear_map::<(),()>(); assert_eq!(m.len(), 0); }
len
identifier_name
explicit-self-generic.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. /** * A function that returns a hash of a value * * The hash should concentrate entropy in the lower bits. */ type HashFn<K> = proc(K):'static -> uint; type EqFn<K> = proc(K, K):'static -> bool; struct LM { resize_at: uint, size: uint } impl Copy for LM {} enum HashMap<K,V> { HashMap_(LM) } impl<K,V> Copy for HashMap<K,V> {} fn linear_map<K,V>() -> HashMap<K,V> { HashMap::HashMap_(LM{ resize_at: 32, size: 0}) } impl<K,V> HashMap<K,V> { pub fn len(&mut self) -> uint
} pub fn main() { let mut m = box linear_map::<(),()>(); assert_eq!(m.len(), 0); }
{ match *self { HashMap::HashMap_(l) => l.size } }
identifier_body
mod.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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. //! Propagation is a set of algorithmic components to verify the consistency of a constraint conjunction, called the *constraints store*. //! //! The constraints store is parametrized by the type of the variables store to keep both concrete implementation independents. Stores are stacked in a hierarchical manner and they communicate only from top to bottom; the variables store is not aware of the constraints store. pub mod reactor; pub mod reactors; pub mod scheduler; pub mod schedulers; pub mod events; pub mod store; pub mod ops; pub mod concept; pub use propagation::reactor::Reactor; pub use propagation::scheduler::Scheduler; pub use propagation::ops::*; pub use propagation::concept::*;
pub type CStoreFD<VStore> = store::Store<VStore, events::FDEvent, reactors::IndexedDeps, schedulers::RelaxedFifo>;
random_line_split
fs.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::io; use std::io::Read; use std::fs; use std::path::{Path, PathBuf}; use page::{LocalPageEndpoint, PageCache}; use endpoint::{Endpoints, EndpointInfo}; use apps::manifest::{MANIFEST_FILENAME, deserialize_manifest}; struct LocalDapp { id: String, path: PathBuf, info: EndpointInfo, } /// Tries to find and read manifest file in given `path` to extract `EndpointInfo` /// If manifest is not found sensible default `EndpointInfo` is returned based on given `name`. fn read_manifest(name: &str, mut path: PathBuf) -> EndpointInfo { path.push(MANIFEST_FILENAME); fs::File::open(path.clone()) .map_err(|e| format!("{:?}", e)) .and_then(|mut f| { // Reat file let mut s = String::new(); f.read_to_string(&mut s).map_err(|e| format!("{:?}", e))?; // Try to deserialize manifest deserialize_manifest(s) }) .map(Into::into) .unwrap_or_else(|e| { warn!(target: "dapps", "Cannot read manifest file at: {:?}. Error: {:?}", path, e); EndpointInfo { name: name.into(), description: name.into(), version: "0.0.0".into(), author: "?".into(), icon_url: "icon.png".into(), } }) } /// Returns Dapp Id and Local Dapp Endpoint for given filesystem path. /// Parses the path to extract last component (for name). /// `None` is returned when path is invalid or non-existent. pub fn local_endpoint<P: AsRef<Path>>(path: P, signer_address: Option<(String, u16)>) -> Option<(String, Box<LocalPageEndpoint>)> { let path = path.as_ref().to_owned(); path.canonicalize().ok().and_then(|path| { let name = path.file_name().and_then(|name| name.to_str()); name.map(|name| { let dapp = local_dapp(name.into(), path.clone()); (dapp.id, Box::new(LocalPageEndpoint::new( dapp.path, dapp.info, PageCache::Disabled, signer_address.clone()) )) }) }) } fn local_dapp(name: String, path: PathBuf) -> LocalDapp { // try to get manifest file let info = read_manifest(&name, path.clone()); LocalDapp { id: name, path: path, info: info, } } /// Returns endpoints for Local Dapps found for given filesystem path. /// Scans the directory and collects `LocalPageEndpoints`. pub fn local_endpoints<P: AsRef<Path>>(dapps_path: P, signer_address: Option<(String, u16)>) -> Endpoints { let mut pages = Endpoints::new(); for dapp in local_dapps(dapps_path.as_ref()) { pages.insert( dapp.id, Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, PageCache::Disabled, signer_address.clone())) ); } pages }
fn local_dapps(dapps_path: &Path) -> Vec<LocalDapp> { let files = fs::read_dir(dapps_path); if let Err(e) = files { warn!(target: "dapps", "Unable to load local dapps from: {}. Reason: {:?}", dapps_path.display(), e); return vec![]; } let files = files.expect("Check is done earlier"); files.map(|dir| { let entry = dir?; let file_type = entry.file_type()?; // skip files if file_type.is_file() { return Err(io::Error::new(io::ErrorKind::NotFound, "Not a file")); } // take directory name and path entry.file_name().into_string() .map(|name| (name, entry.path())) .map_err(|e| { info!(target: "dapps", "Unable to load dapp: {:?}. Reason: {:?}", entry.path(), e); io::Error::new(io::ErrorKind::NotFound, "Invalid name") }) }) .filter_map(|m| { if let Err(ref e) = m { debug!(target: "dapps", "Ignoring local dapp: {:?}", e); } m.ok() }) .map(|(name, path)| local_dapp(name, path)) .collect() }
random_line_split
fs.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::io; use std::io::Read; use std::fs; use std::path::{Path, PathBuf}; use page::{LocalPageEndpoint, PageCache}; use endpoint::{Endpoints, EndpointInfo}; use apps::manifest::{MANIFEST_FILENAME, deserialize_manifest}; struct LocalDapp { id: String, path: PathBuf, info: EndpointInfo, } /// Tries to find and read manifest file in given `path` to extract `EndpointInfo` /// If manifest is not found sensible default `EndpointInfo` is returned based on given `name`. fn read_manifest(name: &str, mut path: PathBuf) -> EndpointInfo { path.push(MANIFEST_FILENAME); fs::File::open(path.clone()) .map_err(|e| format!("{:?}", e)) .and_then(|mut f| { // Reat file let mut s = String::new(); f.read_to_string(&mut s).map_err(|e| format!("{:?}", e))?; // Try to deserialize manifest deserialize_manifest(s) }) .map(Into::into) .unwrap_or_else(|e| { warn!(target: "dapps", "Cannot read manifest file at: {:?}. Error: {:?}", path, e); EndpointInfo { name: name.into(), description: name.into(), version: "0.0.0".into(), author: "?".into(), icon_url: "icon.png".into(), } }) } /// Returns Dapp Id and Local Dapp Endpoint for given filesystem path. /// Parses the path to extract last component (for name). /// `None` is returned when path is invalid or non-existent. pub fn local_endpoint<P: AsRef<Path>>(path: P, signer_address: Option<(String, u16)>) -> Option<(String, Box<LocalPageEndpoint>)> { let path = path.as_ref().to_owned(); path.canonicalize().ok().and_then(|path| { let name = path.file_name().and_then(|name| name.to_str()); name.map(|name| { let dapp = local_dapp(name.into(), path.clone()); (dapp.id, Box::new(LocalPageEndpoint::new( dapp.path, dapp.info, PageCache::Disabled, signer_address.clone()) )) }) }) } fn
(name: String, path: PathBuf) -> LocalDapp { // try to get manifest file let info = read_manifest(&name, path.clone()); LocalDapp { id: name, path: path, info: info, } } /// Returns endpoints for Local Dapps found for given filesystem path. /// Scans the directory and collects `LocalPageEndpoints`. pub fn local_endpoints<P: AsRef<Path>>(dapps_path: P, signer_address: Option<(String, u16)>) -> Endpoints { let mut pages = Endpoints::new(); for dapp in local_dapps(dapps_path.as_ref()) { pages.insert( dapp.id, Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, PageCache::Disabled, signer_address.clone())) ); } pages } fn local_dapps(dapps_path: &Path) -> Vec<LocalDapp> { let files = fs::read_dir(dapps_path); if let Err(e) = files { warn!(target: "dapps", "Unable to load local dapps from: {}. Reason: {:?}", dapps_path.display(), e); return vec![]; } let files = files.expect("Check is done earlier"); files.map(|dir| { let entry = dir?; let file_type = entry.file_type()?; // skip files if file_type.is_file() { return Err(io::Error::new(io::ErrorKind::NotFound, "Not a file")); } // take directory name and path entry.file_name().into_string() .map(|name| (name, entry.path())) .map_err(|e| { info!(target: "dapps", "Unable to load dapp: {:?}. Reason: {:?}", entry.path(), e); io::Error::new(io::ErrorKind::NotFound, "Invalid name") }) }) .filter_map(|m| { if let Err(ref e) = m { debug!(target: "dapps", "Ignoring local dapp: {:?}", e); } m.ok() }) .map(|(name, path)| local_dapp(name, path)) .collect() }
local_dapp
identifier_name
fs.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::io; use std::io::Read; use std::fs; use std::path::{Path, PathBuf}; use page::{LocalPageEndpoint, PageCache}; use endpoint::{Endpoints, EndpointInfo}; use apps::manifest::{MANIFEST_FILENAME, deserialize_manifest}; struct LocalDapp { id: String, path: PathBuf, info: EndpointInfo, } /// Tries to find and read manifest file in given `path` to extract `EndpointInfo` /// If manifest is not found sensible default `EndpointInfo` is returned based on given `name`. fn read_manifest(name: &str, mut path: PathBuf) -> EndpointInfo { path.push(MANIFEST_FILENAME); fs::File::open(path.clone()) .map_err(|e| format!("{:?}", e)) .and_then(|mut f| { // Reat file let mut s = String::new(); f.read_to_string(&mut s).map_err(|e| format!("{:?}", e))?; // Try to deserialize manifest deserialize_manifest(s) }) .map(Into::into) .unwrap_or_else(|e| { warn!(target: "dapps", "Cannot read manifest file at: {:?}. Error: {:?}", path, e); EndpointInfo { name: name.into(), description: name.into(), version: "0.0.0".into(), author: "?".into(), icon_url: "icon.png".into(), } }) } /// Returns Dapp Id and Local Dapp Endpoint for given filesystem path. /// Parses the path to extract last component (for name). /// `None` is returned when path is invalid or non-existent. pub fn local_endpoint<P: AsRef<Path>>(path: P, signer_address: Option<(String, u16)>) -> Option<(String, Box<LocalPageEndpoint>)> { let path = path.as_ref().to_owned(); path.canonicalize().ok().and_then(|path| { let name = path.file_name().and_then(|name| name.to_str()); name.map(|name| { let dapp = local_dapp(name.into(), path.clone()); (dapp.id, Box::new(LocalPageEndpoint::new( dapp.path, dapp.info, PageCache::Disabled, signer_address.clone()) )) }) }) } fn local_dapp(name: String, path: PathBuf) -> LocalDapp { // try to get manifest file let info = read_manifest(&name, path.clone()); LocalDapp { id: name, path: path, info: info, } } /// Returns endpoints for Local Dapps found for given filesystem path. /// Scans the directory and collects `LocalPageEndpoints`. pub fn local_endpoints<P: AsRef<Path>>(dapps_path: P, signer_address: Option<(String, u16)>) -> Endpoints { let mut pages = Endpoints::new(); for dapp in local_dapps(dapps_path.as_ref()) { pages.insert( dapp.id, Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, PageCache::Disabled, signer_address.clone())) ); } pages } fn local_dapps(dapps_path: &Path) -> Vec<LocalDapp> { let files = fs::read_dir(dapps_path); if let Err(e) = files
let files = files.expect("Check is done earlier"); files.map(|dir| { let entry = dir?; let file_type = entry.file_type()?; // skip files if file_type.is_file() { return Err(io::Error::new(io::ErrorKind::NotFound, "Not a file")); } // take directory name and path entry.file_name().into_string() .map(|name| (name, entry.path())) .map_err(|e| { info!(target: "dapps", "Unable to load dapp: {:?}. Reason: {:?}", entry.path(), e); io::Error::new(io::ErrorKind::NotFound, "Invalid name") }) }) .filter_map(|m| { if let Err(ref e) = m { debug!(target: "dapps", "Ignoring local dapp: {:?}", e); } m.ok() }) .map(|(name, path)| local_dapp(name, path)) .collect() }
{ warn!(target: "dapps", "Unable to load local dapps from: {}. Reason: {:?}", dapps_path.display(), e); return vec![]; }
conditional_block
fs.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::io; use std::io::Read; use std::fs; use std::path::{Path, PathBuf}; use page::{LocalPageEndpoint, PageCache}; use endpoint::{Endpoints, EndpointInfo}; use apps::manifest::{MANIFEST_FILENAME, deserialize_manifest}; struct LocalDapp { id: String, path: PathBuf, info: EndpointInfo, } /// Tries to find and read manifest file in given `path` to extract `EndpointInfo` /// If manifest is not found sensible default `EndpointInfo` is returned based on given `name`. fn read_manifest(name: &str, mut path: PathBuf) -> EndpointInfo { path.push(MANIFEST_FILENAME); fs::File::open(path.clone()) .map_err(|e| format!("{:?}", e)) .and_then(|mut f| { // Reat file let mut s = String::new(); f.read_to_string(&mut s).map_err(|e| format!("{:?}", e))?; // Try to deserialize manifest deserialize_manifest(s) }) .map(Into::into) .unwrap_or_else(|e| { warn!(target: "dapps", "Cannot read manifest file at: {:?}. Error: {:?}", path, e); EndpointInfo { name: name.into(), description: name.into(), version: "0.0.0".into(), author: "?".into(), icon_url: "icon.png".into(), } }) } /// Returns Dapp Id and Local Dapp Endpoint for given filesystem path. /// Parses the path to extract last component (for name). /// `None` is returned when path is invalid or non-existent. pub fn local_endpoint<P: AsRef<Path>>(path: P, signer_address: Option<(String, u16)>) -> Option<(String, Box<LocalPageEndpoint>)> { let path = path.as_ref().to_owned(); path.canonicalize().ok().and_then(|path| { let name = path.file_name().and_then(|name| name.to_str()); name.map(|name| { let dapp = local_dapp(name.into(), path.clone()); (dapp.id, Box::new(LocalPageEndpoint::new( dapp.path, dapp.info, PageCache::Disabled, signer_address.clone()) )) }) }) } fn local_dapp(name: String, path: PathBuf) -> LocalDapp { // try to get manifest file let info = read_manifest(&name, path.clone()); LocalDapp { id: name, path: path, info: info, } } /// Returns endpoints for Local Dapps found for given filesystem path. /// Scans the directory and collects `LocalPageEndpoints`. pub fn local_endpoints<P: AsRef<Path>>(dapps_path: P, signer_address: Option<(String, u16)>) -> Endpoints
fn local_dapps(dapps_path: &Path) -> Vec<LocalDapp> { let files = fs::read_dir(dapps_path); if let Err(e) = files { warn!(target: "dapps", "Unable to load local dapps from: {}. Reason: {:?}", dapps_path.display(), e); return vec![]; } let files = files.expect("Check is done earlier"); files.map(|dir| { let entry = dir?; let file_type = entry.file_type()?; // skip files if file_type.is_file() { return Err(io::Error::new(io::ErrorKind::NotFound, "Not a file")); } // take directory name and path entry.file_name().into_string() .map(|name| (name, entry.path())) .map_err(|e| { info!(target: "dapps", "Unable to load dapp: {:?}. Reason: {:?}", entry.path(), e); io::Error::new(io::ErrorKind::NotFound, "Invalid name") }) }) .filter_map(|m| { if let Err(ref e) = m { debug!(target: "dapps", "Ignoring local dapp: {:?}", e); } m.ok() }) .map(|(name, path)| local_dapp(name, path)) .collect() }
{ let mut pages = Endpoints::new(); for dapp in local_dapps(dapps_path.as_ref()) { pages.insert( dapp.id, Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, PageCache::Disabled, signer_address.clone())) ); } pages }
identifier_body
sha2.rs
self) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { let (new_high_bits, new_low_bits) = bytes.to_bits(); if new_high_bits > Zero::zero() { fail!("numeric overflow occurred.") } match bits.checked_add(&new_low_bits) { Some(x) => return x, None => fail!("numeric overflow occurred.") } } /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modified /// results in those bytes being marked as used by the buffer. trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input(&mut self, input: &[u8], func: |&[u8]|); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: uint); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer<'s>(&'s mut self) -> &'s [u8]; /// Get the current position of the buffer. fn position(&self) -> uint; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> uint; /// Get the size of the buffer fn size(&self) -> uint; } /// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize. struct
{ buffer: [u8,..64], buffer_idx: uint, } impl FixedBuffer64 { /// Create a new FixedBuffer64 fn new() -> FixedBuffer64 { return FixedBuffer64 { buffer: [0u8,..64], buffer_idx: 0 }; } } impl FixedBuffer for FixedBuffer64 { fn input(&mut self, input: &[u8], func: |&[u8]|) { let mut i = 0; let size = self.size(); // If there is already data in the buffer, copy as much as we can into it and process // the data if the buffer becomes full. if self.buffer_idx!= 0 { let buffer_remaining = size - self.buffer_idx; if input.len() >= buffer_remaining { copy_memory( self.buffer.mut_slice(self.buffer_idx, size), input.slice_to(buffer_remaining)); self.buffer_idx = 0; func(self.buffer); i += buffer_remaining; } else { copy_memory( self.buffer.mut_slice(self.buffer_idx, self.buffer_idx + input.len()), input); self.buffer_idx += input.len(); return; } } // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { func(input.slice(i, i + size)); i += size; } // Copy any input data into the buffer. At this point in the method, the amount of // data left in the input vector will be less than the buffer size and the buffer will // be empty. let input_remaining = input.len() - i; copy_memory( self.buffer.mut_slice(0, input_remaining), input.slice_from(i)); self.buffer_idx += input_remaining; } fn reset(&mut self) { self.buffer_idx = 0; } fn zero_until(&mut self, idx: uint) { assert!(idx >= self.buffer_idx); self.buffer.mut_slice(self.buffer_idx, idx).set_memory(0); self.buffer_idx = idx; } fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] { self.buffer_idx += len; return self.buffer.mut_slice(self.buffer_idx - len, self.buffer_idx); } fn full_buffer<'s>(&'s mut self) -> &'s [u8] { assert!(self.buffer_idx == 64); self.buffer_idx = 0; return self.buffer.slice_to(64); } fn position(&self) -> uint { self.buffer_idx } fn remaining(&self) -> uint { 64 - self.buffer_idx } fn size(&self) -> uint { 64 } } /// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct. trait StandardPadding { /// Add padding to the buffer. The buffer must not be full when this method is called and is /// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least /// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled /// with zeros again until only rem bytes are remaining. fn standard_padding(&mut self, rem: uint, func: |&[u8]|); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding(&mut self, rem: uint, func: |&[u8]|) { let size = self.size(); self.next(1)[0] = 128; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2 /// family of digest functions. pub trait Digest { /// Provide message data. /// /// # Arguments /// /// * input - A vector of message data fn input(&mut self, input: &[u8]); /// Retrieve the digest result. This method may be called multiple times. /// /// # Arguments /// /// * out - the vector to hold the result. Must be large enough to contain output_bits(). fn result(&mut self, out: &mut [u8]); /// Reset the digest. This method must be called after result() and before supplying more /// data. fn reset(&mut self); /// Get the output size in bits. fn output_bits(&self) -> uint; /// Convenience function that feeds a string into a digest. /// /// # Arguments /// /// * `input` The string to feed into the digest fn input_str(&mut self, input: &str) { self.input(input.as_bytes()); } /// Convenience function that retrieves the result of a digest as a /// newly allocated vec of bytes. fn result_bytes(&mut self) -> Vec<u8> { let mut buf = Vec::from_elem((self.output_bits()+7)/8, 0u8); self.result(buf.as_mut_slice()); buf } /// Convenience function that retrieves the result of a digest as a /// String in hexadecimal format. fn result_str(&mut self) -> String { self.result_bytes().as_slice().to_hex().to_string() } } // A structure that represents that state of a digest computation for the SHA-2 512 family of digest // functions struct Engine256State { h0: u32, h1: u32, h2: u32, h3: u32, h4: u32, h5: u32, h6: u32, h7: u32, } impl Engine256State { fn new(h: &[u32,..8]) -> Engine256State { return Engine256State { h0: h[0], h1: h[1], h2: h[2], h3: h[3], h4: h[4], h5: h[5], h6: h[6], h7: h[7] }; } fn reset(&mut self, h: &[u32,..8]) { self.h0 = h[0]; self.h1 = h[1]; self.h2 = h[2]; self.h3 = h[3]; self.h4 = h[4]; self.h5 = h[5]; self.h6 = h[6]; self.h7 = h[7]; } fn process_block(&mut self, data: &[u8]) { fn ch(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ ((!x) & z)) } fn maj(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ (x & z) ^ (y & z)) } fn sum0(x: u32) -> u32 { ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)) } fn sum1(x: u32) -> u32 { ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)) } fn sigma0(x: u32) -> u32 { ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3) } fn sigma1(x: u32) -> u32 { ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10) } let mut a = self.h0; let mut b = self.h1; let mut c = self.h2; let mut d = self.h3; let mut e = self.h4; let mut f = self.h5; let mut g = self.h6; let mut h = self.h7; let mut w = [0u32,..64]; // Sha-512 and Sha-256 use basically the same calculations which are implemented // by these macros. Inlining the calculations seems to result in better generated code. macro_rules! schedule_round( ($t:expr) => ( w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16]; ) ) macro_rules! sha2_round( ($A:ident, $B:ident, $C:ident, $D:ident, $E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => ( { $H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t]; $D += $H; $H += sum0($A) + maj($A, $B, $C); } ) ) read_u32v_be(w.mut_slice(0, 16), data); // Putting the message schedule inside the same loop as the round calculations allows for // the compiler to generate better code. for t in range_step(0u, 48, 8) { schedule_round!(t + 16); schedule_round!(t + 17); schedule_round!(t + 18); schedule_round!(t + 19); schedule_round!(t + 20); schedule_round!(t + 21); schedule_round!(t + 22); schedule_round!(t + 23); sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } for t in range_step(48u, 64, 8) { sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } self.h0 += a; self.h1 += b; self.h2 += c; self.h3 += d; self.h4 += e; self.h5 += f; self.h6 += g; self.h7 += h; } } static K32: [u32,..64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // A structure that keeps track of the state of the Sha-256 operation and contains the logic // necessary to perform the final calculations. struct Engine256 { length_bits: u64, buffer: FixedBuffer64, state: Engine256State, finished: bool, } impl Engine256 { fn new(h: &[u32,..8]) -> Engine256 { return Engine256 { length_bits: 0, buffer: FixedBuffer64::new(), state: Engine256State::new(h), finished: false } } fn reset(&mut self, h: &[u32,..8]) { self.length_bits = 0; self.buffer.reset(); self.state.reset(h); self.finished = false; } fn input(&mut self, input: &[u8]) { assert!(!self.finished) // Assumes that input.len() can be converted to u64 without overflow self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64); let self_state = &mut self.state; self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) }); } fn finish(&mut self) { if self.finished { return; } let self_state = &mut self.state; self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) }); write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 ); write_u32_be(self.buffer.next(4), self.length_bits as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } } /// The SHA-256 hash algorithm pub struct Sha256 { engine: Engine256 } impl Sha256 { /// Construct a new instance of a SHA-256 digest. pub fn new() -> Sha256 { Sha256 { engine: Engine256::new(&H256) } } } impl Digest for Sha256 { fn input(&mut self, d: &[u8]) { self.engine.input(d); } fn result(&mut self, out: &mut [u8]) { self.engine.finish(); write_u32_be(out.mut_slice(0, 4), self.engine.state.h0); write_u32_be(out.mut_slice(4, 8), self.engine.state.h1); write_u32_be(out.mut_slice(8, 12), self.engine.state.h2); write_u32_be(out.mut_slice(12, 16), self.engine.state.h3); write_u32_be(out.mut_slice(16, 20), self.engine.state.h4); write_u32_be(out.mut_slice(20, 24), self.engine.state.h5); write_u32_be(out.mut_slice(24, 28), self.engine.state.h6); write_u32_be(out.mut_slice(28, 32), self.engine.state.h7); } fn reset(&mut self) { self.engine.reset(&H256); } fn output_bits(&self) -> uint { 256 } } static H256: [u32,..8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; #[cfg(test)] mod tests { extern crate rand; use super::{Digest, Sha256, FixedBuffer}; use std::num::Bounded; use self::rand::isaac::IsaacRng; use self::rand::Rng; use serialize::hex::FromHex; // A normal addition - no overflow occurs #[test] fn test_add_bytes_to_bits_ok() { assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180); } // A simple failure case - adding 1 to the max value #[test] #[should_fail] fn test_add_bytes_to_bits_overflow() { super::add_bytes_to_bits::<u64>(Bounded::max_value(), 1); } struct Test { input: String, output_str: String, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.reset(); sh.input_str(t.input.as_slice()); let out_str = sh.result_str(); assert!(out_str == t.output_str); } // Test that it works when accepting the message in pieces for t in tests.iter() { sh.reset(); let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input .as_slice() .slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str == t.output_str); } } #[test] fn test_sha256() { // Examples from wikipedia let wikipedia_tests = vec!( Test { input: "".to_string(), output_str: "e3b0c44298fc1c149afb\ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string() },
FixedBuffer64
identifier_name
sha2.rs
self) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { let (new_high_bits, new_low_bits) = bytes.to_bits(); if new_high_bits > Zero::zero() { fail!("numeric overflow occurred.") } match bits.checked_add(&new_low_bits) { Some(x) => return x, None => fail!("numeric overflow occurred.") } } /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modified /// results in those bytes being marked as used by the buffer. trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input(&mut self, input: &[u8], func: |&[u8]|); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: uint); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer<'s>(&'s mut self) -> &'s [u8]; /// Get the current position of the buffer. fn position(&self) -> uint; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> uint; /// Get the size of the buffer fn size(&self) -> uint; } /// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize. struct FixedBuffer64 { buffer: [u8,..64], buffer_idx: uint, } impl FixedBuffer64 { /// Create a new FixedBuffer64 fn new() -> FixedBuffer64 { return FixedBuffer64 { buffer: [0u8,..64], buffer_idx: 0 }; } } impl FixedBuffer for FixedBuffer64 { fn input(&mut self, input: &[u8], func: |&[u8]|) { let mut i = 0; let size = self.size(); // If there is already data in the buffer, copy as much as we can into it and process // the data if the buffer becomes full. if self.buffer_idx!= 0 { let buffer_remaining = size - self.buffer_idx; if input.len() >= buffer_remaining { copy_memory( self.buffer.mut_slice(self.buffer_idx, size), input.slice_to(buffer_remaining)); self.buffer_idx = 0; func(self.buffer); i += buffer_remaining; } else
} // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { func(input.slice(i, i + size)); i += size; } // Copy any input data into the buffer. At this point in the method, the amount of // data left in the input vector will be less than the buffer size and the buffer will // be empty. let input_remaining = input.len() - i; copy_memory( self.buffer.mut_slice(0, input_remaining), input.slice_from(i)); self.buffer_idx += input_remaining; } fn reset(&mut self) { self.buffer_idx = 0; } fn zero_until(&mut self, idx: uint) { assert!(idx >= self.buffer_idx); self.buffer.mut_slice(self.buffer_idx, idx).set_memory(0); self.buffer_idx = idx; } fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] { self.buffer_idx += len; return self.buffer.mut_slice(self.buffer_idx - len, self.buffer_idx); } fn full_buffer<'s>(&'s mut self) -> &'s [u8] { assert!(self.buffer_idx == 64); self.buffer_idx = 0; return self.buffer.slice_to(64); } fn position(&self) -> uint { self.buffer_idx } fn remaining(&self) -> uint { 64 - self.buffer_idx } fn size(&self) -> uint { 64 } } /// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct. trait StandardPadding { /// Add padding to the buffer. The buffer must not be full when this method is called and is /// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least /// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled /// with zeros again until only rem bytes are remaining. fn standard_padding(&mut self, rem: uint, func: |&[u8]|); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding(&mut self, rem: uint, func: |&[u8]|) { let size = self.size(); self.next(1)[0] = 128; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2 /// family of digest functions. pub trait Digest { /// Provide message data. /// /// # Arguments /// /// * input - A vector of message data fn input(&mut self, input: &[u8]); /// Retrieve the digest result. This method may be called multiple times. /// /// # Arguments /// /// * out - the vector to hold the result. Must be large enough to contain output_bits(). fn result(&mut self, out: &mut [u8]); /// Reset the digest. This method must be called after result() and before supplying more /// data. fn reset(&mut self); /// Get the output size in bits. fn output_bits(&self) -> uint; /// Convenience function that feeds a string into a digest. /// /// # Arguments /// /// * `input` The string to feed into the digest fn input_str(&mut self, input: &str) { self.input(input.as_bytes()); } /// Convenience function that retrieves the result of a digest as a /// newly allocated vec of bytes. fn result_bytes(&mut self) -> Vec<u8> { let mut buf = Vec::from_elem((self.output_bits()+7)/8, 0u8); self.result(buf.as_mut_slice()); buf } /// Convenience function that retrieves the result of a digest as a /// String in hexadecimal format. fn result_str(&mut self) -> String { self.result_bytes().as_slice().to_hex().to_string() } } // A structure that represents that state of a digest computation for the SHA-2 512 family of digest // functions struct Engine256State { h0: u32, h1: u32, h2: u32, h3: u32, h4: u32, h5: u32, h6: u32, h7: u32, } impl Engine256State { fn new(h: &[u32,..8]) -> Engine256State { return Engine256State { h0: h[0], h1: h[1], h2: h[2], h3: h[3], h4: h[4], h5: h[5], h6: h[6], h7: h[7] }; } fn reset(&mut self, h: &[u32,..8]) { self.h0 = h[0]; self.h1 = h[1]; self.h2 = h[2]; self.h3 = h[3]; self.h4 = h[4]; self.h5 = h[5]; self.h6 = h[6]; self.h7 = h[7]; } fn process_block(&mut self, data: &[u8]) { fn ch(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ ((!x) & z)) } fn maj(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ (x & z) ^ (y & z)) } fn sum0(x: u32) -> u32 { ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)) } fn sum1(x: u32) -> u32 { ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)) } fn sigma0(x: u32) -> u32 { ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3) } fn sigma1(x: u32) -> u32 { ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10) } let mut a = self.h0; let mut b = self.h1; let mut c = self.h2; let mut d = self.h3; let mut e = self.h4; let mut f = self.h5; let mut g = self.h6; let mut h = self.h7; let mut w = [0u32,..64]; // Sha-512 and Sha-256 use basically the same calculations which are implemented // by these macros. Inlining the calculations seems to result in better generated code. macro_rules! schedule_round( ($t:expr) => ( w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16]; ) ) macro_rules! sha2_round( ($A:ident, $B:ident, $C:ident, $D:ident, $E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => ( { $H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t]; $D += $H; $H += sum0($A) + maj($A, $B, $C); } ) ) read_u32v_be(w.mut_slice(0, 16), data); // Putting the message schedule inside the same loop as the round calculations allows for // the compiler to generate better code. for t in range_step(0u, 48, 8) { schedule_round!(t + 16); schedule_round!(t + 17); schedule_round!(t + 18); schedule_round!(t + 19); schedule_round!(t + 20); schedule_round!(t + 21); schedule_round!(t + 22); schedule_round!(t + 23); sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } for t in range_step(48u, 64, 8) { sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } self.h0 += a; self.h1 += b; self.h2 += c; self.h3 += d; self.h4 += e; self.h5 += f; self.h6 += g; self.h7 += h; } } static K32: [u32,..64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // A structure that keeps track of the state of the Sha-256 operation and contains the logic // necessary to perform the final calculations. struct Engine256 { length_bits: u64, buffer: FixedBuffer64, state: Engine256State, finished: bool, } impl Engine256 { fn new(h: &[u32,..8]) -> Engine256 { return Engine256 { length_bits: 0, buffer: FixedBuffer64::new(), state: Engine256State::new(h), finished: false } } fn reset(&mut self, h: &[u32,..8]) { self.length_bits = 0; self.buffer.reset(); self.state.reset(h); self.finished = false; } fn input(&mut self, input: &[u8]) { assert!(!self.finished) // Assumes that input.len() can be converted to u64 without overflow self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64); let self_state = &mut self.state; self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) }); } fn finish(&mut self) { if self.finished { return; } let self_state = &mut self.state; self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) }); write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 ); write_u32_be(self.buffer.next(4), self.length_bits as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } } /// The SHA-256 hash algorithm pub struct Sha256 { engine: Engine256 } impl Sha256 { /// Construct a new instance of a SHA-256 digest. pub fn new() -> Sha256 { Sha256 { engine: Engine256::new(&H256) } } } impl Digest for Sha256 { fn input(&mut self, d: &[u8]) { self.engine.input(d); } fn result(&mut self, out: &mut [u8]) { self.engine.finish(); write_u32_be(out.mut_slice(0, 4), self.engine.state.h0); write_u32_be(out.mut_slice(4, 8), self.engine.state.h1); write_u32_be(out.mut_slice(8, 12), self.engine.state.h2); write_u32_be(out.mut_slice(12, 16), self.engine.state.h3); write_u32_be(out.mut_slice(16, 20), self.engine.state.h4); write_u32_be(out.mut_slice(20, 24), self.engine.state.h5); write_u32_be(out.mut_slice(24, 28), self.engine.state.h6); write_u32_be(out.mut_slice(28, 32), self.engine.state.h7); } fn reset(&mut self) { self.engine.reset(&H256); } fn output_bits(&self) -> uint { 256 } } static H256: [u32,..8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; #[cfg(test)] mod tests { extern crate rand; use super::{Digest, Sha256, FixedBuffer}; use std::num::Bounded; use self::rand::isaac::IsaacRng; use self::rand::Rng; use serialize::hex::FromHex; // A normal addition - no overflow occurs #[test] fn test_add_bytes_to_bits_ok() { assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180); } // A simple failure case - adding 1 to the max value #[test] #[should_fail] fn test_add_bytes_to_bits_overflow() { super::add_bytes_to_bits::<u64>(Bounded::max_value(), 1); } struct Test { input: String, output_str: String, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.reset(); sh.input_str(t.input.as_slice()); let out_str = sh.result_str(); assert!(out_str == t.output_str); } // Test that it works when accepting the message in pieces for t in tests.iter() { sh.reset(); let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input .as_slice() .slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str == t.output_str); } } #[test] fn test_sha256() { // Examples from wikipedia let wikipedia_tests = vec!( Test { input: "".to_string(), output_str: "e3b0c44298fc1c149afb\ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string() },
{ copy_memory( self.buffer.mut_slice(self.buffer_idx, self.buffer_idx + input.len()), input); self.buffer_idx += input.len(); return; }
conditional_block
sha2.rs
(self) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { let (new_high_bits, new_low_bits) = bytes.to_bits(); if new_high_bits > Zero::zero() { fail!("numeric overflow occurred.") } match bits.checked_add(&new_low_bits) { Some(x) => return x, None => fail!("numeric overflow occurred.") } } /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modified /// results in those bytes being marked as used by the buffer. trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input(&mut self, input: &[u8], func: |&[u8]|); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: uint); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well.
/// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> uint; /// Get the size of the buffer fn size(&self) -> uint; } /// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize. struct FixedBuffer64 { buffer: [u8,..64], buffer_idx: uint, } impl FixedBuffer64 { /// Create a new FixedBuffer64 fn new() -> FixedBuffer64 { return FixedBuffer64 { buffer: [0u8,..64], buffer_idx: 0 }; } } impl FixedBuffer for FixedBuffer64 { fn input(&mut self, input: &[u8], func: |&[u8]|) { let mut i = 0; let size = self.size(); // If there is already data in the buffer, copy as much as we can into it and process // the data if the buffer becomes full. if self.buffer_idx!= 0 { let buffer_remaining = size - self.buffer_idx; if input.len() >= buffer_remaining { copy_memory( self.buffer.mut_slice(self.buffer_idx, size), input.slice_to(buffer_remaining)); self.buffer_idx = 0; func(self.buffer); i += buffer_remaining; } else { copy_memory( self.buffer.mut_slice(self.buffer_idx, self.buffer_idx + input.len()), input); self.buffer_idx += input.len(); return; } } // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { func(input.slice(i, i + size)); i += size; } // Copy any input data into the buffer. At this point in the method, the amount of // data left in the input vector will be less than the buffer size and the buffer will // be empty. let input_remaining = input.len() - i; copy_memory( self.buffer.mut_slice(0, input_remaining), input.slice_from(i)); self.buffer_idx += input_remaining; } fn reset(&mut self) { self.buffer_idx = 0; } fn zero_until(&mut self, idx: uint) { assert!(idx >= self.buffer_idx); self.buffer.mut_slice(self.buffer_idx, idx).set_memory(0); self.buffer_idx = idx; } fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] { self.buffer_idx += len; return self.buffer.mut_slice(self.buffer_idx - len, self.buffer_idx); } fn full_buffer<'s>(&'s mut self) -> &'s [u8] { assert!(self.buffer_idx == 64); self.buffer_idx = 0; return self.buffer.slice_to(64); } fn position(&self) -> uint { self.buffer_idx } fn remaining(&self) -> uint { 64 - self.buffer_idx } fn size(&self) -> uint { 64 } } /// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct. trait StandardPadding { /// Add padding to the buffer. The buffer must not be full when this method is called and is /// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least /// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled /// with zeros again until only rem bytes are remaining. fn standard_padding(&mut self, rem: uint, func: |&[u8]|); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding(&mut self, rem: uint, func: |&[u8]|) { let size = self.size(); self.next(1)[0] = 128; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2 /// family of digest functions. pub trait Digest { /// Provide message data. /// /// # Arguments /// /// * input - A vector of message data fn input(&mut self, input: &[u8]); /// Retrieve the digest result. This method may be called multiple times. /// /// # Arguments /// /// * out - the vector to hold the result. Must be large enough to contain output_bits(). fn result(&mut self, out: &mut [u8]); /// Reset the digest. This method must be called after result() and before supplying more /// data. fn reset(&mut self); /// Get the output size in bits. fn output_bits(&self) -> uint; /// Convenience function that feeds a string into a digest. /// /// # Arguments /// /// * `input` The string to feed into the digest fn input_str(&mut self, input: &str) { self.input(input.as_bytes()); } /// Convenience function that retrieves the result of a digest as a /// newly allocated vec of bytes. fn result_bytes(&mut self) -> Vec<u8> { let mut buf = Vec::from_elem((self.output_bits()+7)/8, 0u8); self.result(buf.as_mut_slice()); buf } /// Convenience function that retrieves the result of a digest as a /// String in hexadecimal format. fn result_str(&mut self) -> String { self.result_bytes().as_slice().to_hex().to_string() } } // A structure that represents that state of a digest computation for the SHA-2 512 family of digest // functions struct Engine256State { h0: u32, h1: u32, h2: u32, h3: u32, h4: u32, h5: u32, h6: u32, h7: u32, } impl Engine256State { fn new(h: &[u32,..8]) -> Engine256State { return Engine256State { h0: h[0], h1: h[1], h2: h[2], h3: h[3], h4: h[4], h5: h[5], h6: h[6], h7: h[7] }; } fn reset(&mut self, h: &[u32,..8]) { self.h0 = h[0]; self.h1 = h[1]; self.h2 = h[2]; self.h3 = h[3]; self.h4 = h[4]; self.h5 = h[5]; self.h6 = h[6]; self.h7 = h[7]; } fn process_block(&mut self, data: &[u8]) { fn ch(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ ((!x) & z)) } fn maj(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ (x & z) ^ (y & z)) } fn sum0(x: u32) -> u32 { ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)) } fn sum1(x: u32) -> u32 { ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)) } fn sigma0(x: u32) -> u32 { ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3) } fn sigma1(x: u32) -> u32 { ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10) } let mut a = self.h0; let mut b = self.h1; let mut c = self.h2; let mut d = self.h3; let mut e = self.h4; let mut f = self.h5; let mut g = self.h6; let mut h = self.h7; let mut w = [0u32,..64]; // Sha-512 and Sha-256 use basically the same calculations which are implemented // by these macros. Inlining the calculations seems to result in better generated code. macro_rules! schedule_round( ($t:expr) => ( w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16]; ) ) macro_rules! sha2_round( ($A:ident, $B:ident, $C:ident, $D:ident, $E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => ( { $H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t]; $D += $H; $H += sum0($A) + maj($A, $B, $C); } ) ) read_u32v_be(w.mut_slice(0, 16), data); // Putting the message schedule inside the same loop as the round calculations allows for // the compiler to generate better code. for t in range_step(0u, 48, 8) { schedule_round!(t + 16); schedule_round!(t + 17); schedule_round!(t + 18); schedule_round!(t + 19); schedule_round!(t + 20); schedule_round!(t + 21); schedule_round!(t + 22); schedule_round!(t + 23); sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } for t in range_step(48u, 64, 8) { sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } self.h0 += a; self.h1 += b; self.h2 += c; self.h3 += d; self.h4 += e; self.h5 += f; self.h6 += g; self.h7 += h; } } static K32: [u32,..64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // A structure that keeps track of the state of the Sha-256 operation and contains the logic // necessary to perform the final calculations. struct Engine256 { length_bits: u64, buffer: FixedBuffer64, state: Engine256State, finished: bool, } impl Engine256 { fn new(h: &[u32,..8]) -> Engine256 { return Engine256 { length_bits: 0, buffer: FixedBuffer64::new(), state: Engine256State::new(h), finished: false } } fn reset(&mut self, h: &[u32,..8]) { self.length_bits = 0; self.buffer.reset(); self.state.reset(h); self.finished = false; } fn input(&mut self, input: &[u8]) { assert!(!self.finished) // Assumes that input.len() can be converted to u64 without overflow self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64); let self_state = &mut self.state; self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) }); } fn finish(&mut self) { if self.finished { return; } let self_state = &mut self.state; self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) }); write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 ); write_u32_be(self.buffer.next(4), self.length_bits as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } } /// The SHA-256 hash algorithm pub struct Sha256 { engine: Engine256 } impl Sha256 { /// Construct a new instance of a SHA-256 digest. pub fn new() -> Sha256 { Sha256 { engine: Engine256::new(&H256) } } } impl Digest for Sha256 { fn input(&mut self, d: &[u8]) { self.engine.input(d); } fn result(&mut self, out: &mut [u8]) { self.engine.finish(); write_u32_be(out.mut_slice(0, 4), self.engine.state.h0); write_u32_be(out.mut_slice(4, 8), self.engine.state.h1); write_u32_be(out.mut_slice(8, 12), self.engine.state.h2); write_u32_be(out.mut_slice(12, 16), self.engine.state.h3); write_u32_be(out.mut_slice(16, 20), self.engine.state.h4); write_u32_be(out.mut_slice(20, 24), self.engine.state.h5); write_u32_be(out.mut_slice(24, 28), self.engine.state.h6); write_u32_be(out.mut_slice(28, 32), self.engine.state.h7); } fn reset(&mut self) { self.engine.reset(&H256); } fn output_bits(&self) -> uint { 256 } } static H256: [u32,..8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; #[cfg(test)] mod tests { extern crate rand; use super::{Digest, Sha256, FixedBuffer}; use std::num::Bounded; use self::rand::isaac::IsaacRng; use self::rand::Rng; use serialize::hex::FromHex; // A normal addition - no overflow occurs #[test] fn test_add_bytes_to_bits_ok() { assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180); } // A simple failure case - adding 1 to the max value #[test] #[should_fail] fn test_add_bytes_to_bits_overflow() { super::add_bytes_to_bits::<u64>(Bounded::max_value(), 1); } struct Test { input: String, output_str: String, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.reset(); sh.input_str(t.input.as_slice()); let out_str = sh.result_str(); assert!(out_str == t.output_str); } // Test that it works when accepting the message in pieces for t in tests.iter() { sh.reset(); let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input .as_slice() .slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str == t.output_str); } } #[test] fn test_sha256() { // Examples from wikipedia let wikipedia_tests = vec!( Test { input: "".to_string(), output_str: "e3b0c44298fc1c149afb\ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string() },
fn full_buffer<'s>(&'s mut self) -> &'s [u8]; /// Get the current position of the buffer. fn position(&self) -> uint;
random_line_split
sha2.rs
self) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { let (new_high_bits, new_low_bits) = bytes.to_bits(); if new_high_bits > Zero::zero() { fail!("numeric overflow occurred.") } match bits.checked_add(&new_low_bits) { Some(x) => return x, None => fail!("numeric overflow occurred.") } } /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modified /// results in those bytes being marked as used by the buffer. trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input(&mut self, input: &[u8], func: |&[u8]|); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: uint); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer<'s>(&'s mut self) -> &'s [u8]; /// Get the current position of the buffer. fn position(&self) -> uint; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> uint; /// Get the size of the buffer fn size(&self) -> uint; } /// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize. struct FixedBuffer64 { buffer: [u8,..64], buffer_idx: uint, } impl FixedBuffer64 { /// Create a new FixedBuffer64 fn new() -> FixedBuffer64 { return FixedBuffer64 { buffer: [0u8,..64], buffer_idx: 0 }; } } impl FixedBuffer for FixedBuffer64 { fn input(&mut self, input: &[u8], func: |&[u8]|) { let mut i = 0; let size = self.size(); // If there is already data in the buffer, copy as much as we can into it and process // the data if the buffer becomes full. if self.buffer_idx!= 0 { let buffer_remaining = size - self.buffer_idx; if input.len() >= buffer_remaining { copy_memory( self.buffer.mut_slice(self.buffer_idx, size), input.slice_to(buffer_remaining)); self.buffer_idx = 0; func(self.buffer); i += buffer_remaining; } else { copy_memory( self.buffer.mut_slice(self.buffer_idx, self.buffer_idx + input.len()), input); self.buffer_idx += input.len(); return; } } // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { func(input.slice(i, i + size)); i += size; } // Copy any input data into the buffer. At this point in the method, the amount of // data left in the input vector will be less than the buffer size and the buffer will // be empty. let input_remaining = input.len() - i; copy_memory( self.buffer.mut_slice(0, input_remaining), input.slice_from(i)); self.buffer_idx += input_remaining; } fn reset(&mut self) { self.buffer_idx = 0; } fn zero_until(&mut self, idx: uint) { assert!(idx >= self.buffer_idx); self.buffer.mut_slice(self.buffer_idx, idx).set_memory(0); self.buffer_idx = idx; } fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] { self.buffer_idx += len; return self.buffer.mut_slice(self.buffer_idx - len, self.buffer_idx); } fn full_buffer<'s>(&'s mut self) -> &'s [u8] { assert!(self.buffer_idx == 64); self.buffer_idx = 0; return self.buffer.slice_to(64); } fn position(&self) -> uint { self.buffer_idx } fn remaining(&self) -> uint { 64 - self.buffer_idx } fn size(&self) -> uint { 64 } } /// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct. trait StandardPadding { /// Add padding to the buffer. The buffer must not be full when this method is called and is /// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least /// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled /// with zeros again until only rem bytes are remaining. fn standard_padding(&mut self, rem: uint, func: |&[u8]|); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding(&mut self, rem: uint, func: |&[u8]|) { let size = self.size(); self.next(1)[0] = 128; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2 /// family of digest functions. pub trait Digest { /// Provide message data. /// /// # Arguments /// /// * input - A vector of message data fn input(&mut self, input: &[u8]); /// Retrieve the digest result. This method may be called multiple times. /// /// # Arguments /// /// * out - the vector to hold the result. Must be large enough to contain output_bits(). fn result(&mut self, out: &mut [u8]); /// Reset the digest. This method must be called after result() and before supplying more /// data. fn reset(&mut self); /// Get the output size in bits. fn output_bits(&self) -> uint; /// Convenience function that feeds a string into a digest. /// /// # Arguments /// /// * `input` The string to feed into the digest fn input_str(&mut self, input: &str) { self.input(input.as_bytes()); } /// Convenience function that retrieves the result of a digest as a /// newly allocated vec of bytes. fn result_bytes(&mut self) -> Vec<u8> { let mut buf = Vec::from_elem((self.output_bits()+7)/8, 0u8); self.result(buf.as_mut_slice()); buf } /// Convenience function that retrieves the result of a digest as a /// String in hexadecimal format. fn result_str(&mut self) -> String { self.result_bytes().as_slice().to_hex().to_string() } } // A structure that represents that state of a digest computation for the SHA-2 512 family of digest // functions struct Engine256State { h0: u32, h1: u32, h2: u32, h3: u32, h4: u32, h5: u32, h6: u32, h7: u32, } impl Engine256State { fn new(h: &[u32,..8]) -> Engine256State { return Engine256State { h0: h[0], h1: h[1], h2: h[2], h3: h[3], h4: h[4], h5: h[5], h6: h[6], h7: h[7] }; } fn reset(&mut self, h: &[u32,..8]) { self.h0 = h[0]; self.h1 = h[1]; self.h2 = h[2]; self.h3 = h[3]; self.h4 = h[4]; self.h5 = h[5]; self.h6 = h[6]; self.h7 = h[7]; } fn process_block(&mut self, data: &[u8]) { fn ch(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ ((!x) & z)) } fn maj(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ (x & z) ^ (y & z)) } fn sum0(x: u32) -> u32 { ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)) } fn sum1(x: u32) -> u32
fn sigma0(x: u32) -> u32 { ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3) } fn sigma1(x: u32) -> u32 { ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10) } let mut a = self.h0; let mut b = self.h1; let mut c = self.h2; let mut d = self.h3; let mut e = self.h4; let mut f = self.h5; let mut g = self.h6; let mut h = self.h7; let mut w = [0u32,..64]; // Sha-512 and Sha-256 use basically the same calculations which are implemented // by these macros. Inlining the calculations seems to result in better generated code. macro_rules! schedule_round( ($t:expr) => ( w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16]; ) ) macro_rules! sha2_round( ($A:ident, $B:ident, $C:ident, $D:ident, $E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => ( { $H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t]; $D += $H; $H += sum0($A) + maj($A, $B, $C); } ) ) read_u32v_be(w.mut_slice(0, 16), data); // Putting the message schedule inside the same loop as the round calculations allows for // the compiler to generate better code. for t in range_step(0u, 48, 8) { schedule_round!(t + 16); schedule_round!(t + 17); schedule_round!(t + 18); schedule_round!(t + 19); schedule_round!(t + 20); schedule_round!(t + 21); schedule_round!(t + 22); schedule_round!(t + 23); sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } for t in range_step(48u, 64, 8) { sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } self.h0 += a; self.h1 += b; self.h2 += c; self.h3 += d; self.h4 += e; self.h5 += f; self.h6 += g; self.h7 += h; } } static K32: [u32,..64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // A structure that keeps track of the state of the Sha-256 operation and contains the logic // necessary to perform the final calculations. struct Engine256 { length_bits: u64, buffer: FixedBuffer64, state: Engine256State, finished: bool, } impl Engine256 { fn new(h: &[u32,..8]) -> Engine256 { return Engine256 { length_bits: 0, buffer: FixedBuffer64::new(), state: Engine256State::new(h), finished: false } } fn reset(&mut self, h: &[u32,..8]) { self.length_bits = 0; self.buffer.reset(); self.state.reset(h); self.finished = false; } fn input(&mut self, input: &[u8]) { assert!(!self.finished) // Assumes that input.len() can be converted to u64 without overflow self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64); let self_state = &mut self.state; self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) }); } fn finish(&mut self) { if self.finished { return; } let self_state = &mut self.state; self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) }); write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 ); write_u32_be(self.buffer.next(4), self.length_bits as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } } /// The SHA-256 hash algorithm pub struct Sha256 { engine: Engine256 } impl Sha256 { /// Construct a new instance of a SHA-256 digest. pub fn new() -> Sha256 { Sha256 { engine: Engine256::new(&H256) } } } impl Digest for Sha256 { fn input(&mut self, d: &[u8]) { self.engine.input(d); } fn result(&mut self, out: &mut [u8]) { self.engine.finish(); write_u32_be(out.mut_slice(0, 4), self.engine.state.h0); write_u32_be(out.mut_slice(4, 8), self.engine.state.h1); write_u32_be(out.mut_slice(8, 12), self.engine.state.h2); write_u32_be(out.mut_slice(12, 16), self.engine.state.h3); write_u32_be(out.mut_slice(16, 20), self.engine.state.h4); write_u32_be(out.mut_slice(20, 24), self.engine.state.h5); write_u32_be(out.mut_slice(24, 28), self.engine.state.h6); write_u32_be(out.mut_slice(28, 32), self.engine.state.h7); } fn reset(&mut self) { self.engine.reset(&H256); } fn output_bits(&self) -> uint { 256 } } static H256: [u32,..8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; #[cfg(test)] mod tests { extern crate rand; use super::{Digest, Sha256, FixedBuffer}; use std::num::Bounded; use self::rand::isaac::IsaacRng; use self::rand::Rng; use serialize::hex::FromHex; // A normal addition - no overflow occurs #[test] fn test_add_bytes_to_bits_ok() { assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180); } // A simple failure case - adding 1 to the max value #[test] #[should_fail] fn test_add_bytes_to_bits_overflow() { super::add_bytes_to_bits::<u64>(Bounded::max_value(), 1); } struct Test { input: String, output_str: String, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.reset(); sh.input_str(t.input.as_slice()); let out_str = sh.result_str(); assert!(out_str == t.output_str); } // Test that it works when accepting the message in pieces for t in tests.iter() { sh.reset(); let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input .as_slice() .slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str == t.output_str); } } #[test] fn test_sha256() { // Examples from wikipedia let wikipedia_tests = vec!( Test { input: "".to_string(), output_str: "e3b0c44298fc1c149afb\ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string() },
{ ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)) }
identifier_body
config.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. use attr::AttrMetaMethods; use diagnostic::SpanHandler; use fold::Folder; use {ast, fold, attr}; use codemap::{Spanned, respan}; use ptr::P; use util::small_vector::SmallVector; /// A folder that strips out items that do not belong in the current /// configuration. struct Context<F> where F: FnMut(&[ast::Attribute]) -> bool { in_cfg: F, } // Support conditional compilation by transforming the AST, stripping out // any items that do not belong in the current configuration pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate { let krate = process_cfg_attr(diagnostic, krate); let config = krate.config.clone(); strip_items(krate, |attrs| in_cfg(diagnostic, &config, attrs)) } impl<F> fold::Folder for Context<F> where F: FnMut(&[ast::Attribute]) -> bool { fn fold_mod(&mut self, module: ast::Mod) -> ast::Mod { fold_mod(self, module) } fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> { fold_block(self, block) } fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod { fold_foreign_mod(self, foreign_mod) } fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ { fold_item_underscore(self, item) } fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> { fold_expr(self, expr) } fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac
fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { fold_item(self, item) } } pub fn strip_items<F>(krate: ast::Crate, in_cfg: F) -> ast::Crate where F: FnMut(&[ast::Attribute]) -> bool, { let mut ctxt = Context { in_cfg: in_cfg, }; ctxt.fold_crate(krate) } fn fold_mod<F>(cx: &mut Context<F>, ast::Mod {inner, items}: ast::Mod) -> ast::Mod where F: FnMut(&[ast::Attribute]) -> bool { ast::Mod { inner: inner, items: items.into_iter().flat_map(|a| { cx.fold_item(a).into_iter() }).collect() } } fn filter_foreign_item<F>(cx: &mut Context<F>, item: P<ast::ForeignItem>) -> Option<P<ast::ForeignItem>> where F: FnMut(&[ast::Attribute]) -> bool { if foreign_item_in_cfg(cx, &*item) { Some(item) } else { None } } fn fold_foreign_mod<F>(cx: &mut Context<F>, ast::ForeignMod {abi, items}: ast::ForeignMod) -> ast::ForeignMod where F: FnMut(&[ast::Attribute]) -> bool { ast::ForeignMod { abi: abi, items: items.into_iter() .filter_map(|a| filter_foreign_item(cx, a)) .collect() } } fn fold_item<F>(cx: &mut Context<F>, item: P<ast::Item>) -> SmallVector<P<ast::Item>> where F: FnMut(&[ast::Attribute]) -> bool { if item_in_cfg(cx, &*item) { SmallVector::one(item.map(|i| cx.fold_item_simple(i))) } else { SmallVector::zero() } } fn fold_item_underscore<F>(cx: &mut Context<F>, item: ast::Item_) -> ast::Item_ where F: FnMut(&[ast::Attribute]) -> bool { let item = match item { ast::ItemImpl(u, o, a, b, c, impl_items) => { let impl_items = impl_items.into_iter() .filter(|ii| (cx.in_cfg)(&ii.attrs)) .collect(); ast::ItemImpl(u, o, a, b, c, impl_items) } ast::ItemTrait(u, a, b, methods) => { let methods = methods.into_iter() .filter(|ti| (cx.in_cfg)(&ti.attrs)) .collect(); ast::ItemTrait(u, a, b, methods) } ast::ItemStruct(def, generics) => { ast::ItemStruct(fold_struct(cx, def), generics) } ast::ItemEnum(def, generics) => { let variants = def.variants.into_iter().filter_map(|v| { if!(cx.in_cfg)(&v.node.attrs) { None } else { Some(v.map(|Spanned {node: ast::Variant_ {id, name, attrs, kind, disr_expr, vis}, span}| { Spanned { node: ast::Variant_ { id: id, name: name, attrs: attrs, kind: match kind { ast::TupleVariantKind(..) => kind, ast::StructVariantKind(def) => { ast::StructVariantKind(fold_struct(cx, def)) } }, disr_expr: disr_expr, vis: vis }, span: span } })) } }); ast::ItemEnum(ast::EnumDef { variants: variants.collect(), }, generics) } item => item, }; fold::noop_fold_item_underscore(item, cx) } fn fold_struct<F>(cx: &mut Context<F>, def: P<ast::StructDef>) -> P<ast::StructDef> where F: FnMut(&[ast::Attribute]) -> bool { def.map(|ast::StructDef { fields, ctor_id }| { ast::StructDef { fields: fields.into_iter().filter(|m| { (cx.in_cfg)(&m.node.attrs) }).collect(), ctor_id: ctor_id, } }) } fn retain_stmt<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where F: FnMut(&[ast::Attribute]) -> bool { match stmt.node { ast::StmtDecl(ref decl, _) => { match decl.node { ast::DeclItem(ref item) => { item_in_cfg(cx, &**item) } _ => true } } _ => true } } fn fold_block<F>(cx: &mut Context<F>, b: P<ast::Block>) -> P<ast::Block> where F: FnMut(&[ast::Attribute]) -> bool { b.map(|ast::Block {id, stmts, expr, rules, span}| { let resulting_stmts: Vec<P<ast::Stmt>> = stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect(); let resulting_stmts = resulting_stmts.into_iter() .flat_map(|stmt| cx.fold_stmt(stmt).into_iter()) .collect(); ast::Block { id: id, stmts: resulting_stmts, expr: expr.map(|x| cx.fold_expr(x)), rules: rules, span: span, } }) } fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where F: FnMut(&[ast::Attribute]) -> bool { expr.map(|ast::Expr {id, span, node}| { fold::noop_fold_expr(ast::Expr { id: id, node: match node { ast::ExprMatch(m, arms, source) => { ast::ExprMatch(m, arms.into_iter() .filter(|a| (cx.in_cfg)(&a.attrs)) .collect(), source) } _ => node }, span: span }, cx) }) } fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where F: FnMut(&[ast::Attribute]) -> bool { return (cx.in_cfg)(&item.attrs); } fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where F: FnMut(&[ast::Attribute]) -> bool { return (cx.in_cfg)(&item.attrs); } // Determine if an item should be translated in the current crate // configuration based on the item's attributes fn in_cfg(diagnostic: &SpanHandler, cfg: &[P<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool { attrs.iter().all(|attr| { let mis = match attr.node.value.node { ast::MetaList(_, ref mis) if attr.check_name("cfg") => mis, _ => return true }; if mis.len()!= 1 { diagnostic.span_err(attr.span, "expected 1 cfg-pattern"); return true; } attr::cfg_matches(diagnostic, cfg, &*mis[0]) }) } struct CfgAttrFolder<'a> { diag: &'a SpanHandler, config: ast::CrateConfig, } // Process `#[cfg_attr]`. fn process_cfg_attr(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate { let mut fld = CfgAttrFolder { diag: diagnostic, config: krate.config.clone(), }; fld.fold_crate(krate) } impl<'a> fold::Folder for CfgAttrFolder<'a> { fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> { if!attr.check_name("cfg_attr") { return fold::noop_fold_attribute(attr, self); } let attr_list = match attr.meta_item_list() { Some(attr_list) => attr_list, None => { self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); return None; } }; let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) { (2, Some(cfg), Some(mi)) => (cfg, mi), _ => { self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); return None; } }; if attr::cfg_matches(self.diag, &self.config[..], &cfg) { Some(respan(mi.span, ast::Attribute_ { id: attr::mk_attr_id(), style: attr.node.style, value: mi.clone(), is_sugared_doc: false, })) } else { None } } // Need the ability to run pre-expansion. fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { fold::noop_fold_mac(mac, self) } }
{ fold::noop_fold_mac(mac, self) }
identifier_body
config.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. use attr::AttrMetaMethods; use diagnostic::SpanHandler; use fold::Folder; use {ast, fold, attr}; use codemap::{Spanned, respan}; use ptr::P; use util::small_vector::SmallVector; /// A folder that strips out items that do not belong in the current /// configuration. struct Context<F> where F: FnMut(&[ast::Attribute]) -> bool { in_cfg: F, } // Support conditional compilation by transforming the AST, stripping out // any items that do not belong in the current configuration pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate { let krate = process_cfg_attr(diagnostic, krate); let config = krate.config.clone(); strip_items(krate, |attrs| in_cfg(diagnostic, &config, attrs)) } impl<F> fold::Folder for Context<F> where F: FnMut(&[ast::Attribute]) -> bool { fn fold_mod(&mut self, module: ast::Mod) -> ast::Mod { fold_mod(self, module) } fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> { fold_block(self, block) } fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod { fold_foreign_mod(self, foreign_mod) } fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ { fold_item_underscore(self, item) } fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> { fold_expr(self, expr) } fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { fold::noop_fold_mac(mac, self) } fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { fold_item(self, item) } } pub fn strip_items<F>(krate: ast::Crate, in_cfg: F) -> ast::Crate where F: FnMut(&[ast::Attribute]) -> bool, { let mut ctxt = Context { in_cfg: in_cfg, }; ctxt.fold_crate(krate) } fn fold_mod<F>(cx: &mut Context<F>, ast::Mod {inner, items}: ast::Mod) -> ast::Mod where F: FnMut(&[ast::Attribute]) -> bool { ast::Mod { inner: inner, items: items.into_iter().flat_map(|a| { cx.fold_item(a).into_iter() }).collect() } } fn filter_foreign_item<F>(cx: &mut Context<F>, item: P<ast::ForeignItem>) -> Option<P<ast::ForeignItem>> where F: FnMut(&[ast::Attribute]) -> bool { if foreign_item_in_cfg(cx, &*item) { Some(item) } else { None } } fn
<F>(cx: &mut Context<F>, ast::ForeignMod {abi, items}: ast::ForeignMod) -> ast::ForeignMod where F: FnMut(&[ast::Attribute]) -> bool { ast::ForeignMod { abi: abi, items: items.into_iter() .filter_map(|a| filter_foreign_item(cx, a)) .collect() } } fn fold_item<F>(cx: &mut Context<F>, item: P<ast::Item>) -> SmallVector<P<ast::Item>> where F: FnMut(&[ast::Attribute]) -> bool { if item_in_cfg(cx, &*item) { SmallVector::one(item.map(|i| cx.fold_item_simple(i))) } else { SmallVector::zero() } } fn fold_item_underscore<F>(cx: &mut Context<F>, item: ast::Item_) -> ast::Item_ where F: FnMut(&[ast::Attribute]) -> bool { let item = match item { ast::ItemImpl(u, o, a, b, c, impl_items) => { let impl_items = impl_items.into_iter() .filter(|ii| (cx.in_cfg)(&ii.attrs)) .collect(); ast::ItemImpl(u, o, a, b, c, impl_items) } ast::ItemTrait(u, a, b, methods) => { let methods = methods.into_iter() .filter(|ti| (cx.in_cfg)(&ti.attrs)) .collect(); ast::ItemTrait(u, a, b, methods) } ast::ItemStruct(def, generics) => { ast::ItemStruct(fold_struct(cx, def), generics) } ast::ItemEnum(def, generics) => { let variants = def.variants.into_iter().filter_map(|v| { if!(cx.in_cfg)(&v.node.attrs) { None } else { Some(v.map(|Spanned {node: ast::Variant_ {id, name, attrs, kind, disr_expr, vis}, span}| { Spanned { node: ast::Variant_ { id: id, name: name, attrs: attrs, kind: match kind { ast::TupleVariantKind(..) => kind, ast::StructVariantKind(def) => { ast::StructVariantKind(fold_struct(cx, def)) } }, disr_expr: disr_expr, vis: vis }, span: span } })) } }); ast::ItemEnum(ast::EnumDef { variants: variants.collect(), }, generics) } item => item, }; fold::noop_fold_item_underscore(item, cx) } fn fold_struct<F>(cx: &mut Context<F>, def: P<ast::StructDef>) -> P<ast::StructDef> where F: FnMut(&[ast::Attribute]) -> bool { def.map(|ast::StructDef { fields, ctor_id }| { ast::StructDef { fields: fields.into_iter().filter(|m| { (cx.in_cfg)(&m.node.attrs) }).collect(), ctor_id: ctor_id, } }) } fn retain_stmt<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where F: FnMut(&[ast::Attribute]) -> bool { match stmt.node { ast::StmtDecl(ref decl, _) => { match decl.node { ast::DeclItem(ref item) => { item_in_cfg(cx, &**item) } _ => true } } _ => true } } fn fold_block<F>(cx: &mut Context<F>, b: P<ast::Block>) -> P<ast::Block> where F: FnMut(&[ast::Attribute]) -> bool { b.map(|ast::Block {id, stmts, expr, rules, span}| { let resulting_stmts: Vec<P<ast::Stmt>> = stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect(); let resulting_stmts = resulting_stmts.into_iter() .flat_map(|stmt| cx.fold_stmt(stmt).into_iter()) .collect(); ast::Block { id: id, stmts: resulting_stmts, expr: expr.map(|x| cx.fold_expr(x)), rules: rules, span: span, } }) } fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where F: FnMut(&[ast::Attribute]) -> bool { expr.map(|ast::Expr {id, span, node}| { fold::noop_fold_expr(ast::Expr { id: id, node: match node { ast::ExprMatch(m, arms, source) => { ast::ExprMatch(m, arms.into_iter() .filter(|a| (cx.in_cfg)(&a.attrs)) .collect(), source) } _ => node }, span: span }, cx) }) } fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where F: FnMut(&[ast::Attribute]) -> bool { return (cx.in_cfg)(&item.attrs); } fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where F: FnMut(&[ast::Attribute]) -> bool { return (cx.in_cfg)(&item.attrs); } // Determine if an item should be translated in the current crate // configuration based on the item's attributes fn in_cfg(diagnostic: &SpanHandler, cfg: &[P<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool { attrs.iter().all(|attr| { let mis = match attr.node.value.node { ast::MetaList(_, ref mis) if attr.check_name("cfg") => mis, _ => return true }; if mis.len()!= 1 { diagnostic.span_err(attr.span, "expected 1 cfg-pattern"); return true; } attr::cfg_matches(diagnostic, cfg, &*mis[0]) }) } struct CfgAttrFolder<'a> { diag: &'a SpanHandler, config: ast::CrateConfig, } // Process `#[cfg_attr]`. fn process_cfg_attr(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate { let mut fld = CfgAttrFolder { diag: diagnostic, config: krate.config.clone(), }; fld.fold_crate(krate) } impl<'a> fold::Folder for CfgAttrFolder<'a> { fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> { if!attr.check_name("cfg_attr") { return fold::noop_fold_attribute(attr, self); } let attr_list = match attr.meta_item_list() { Some(attr_list) => attr_list, None => { self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); return None; } }; let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) { (2, Some(cfg), Some(mi)) => (cfg, mi), _ => { self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); return None; } }; if attr::cfg_matches(self.diag, &self.config[..], &cfg) { Some(respan(mi.span, ast::Attribute_ { id: attr::mk_attr_id(), style: attr.node.style, value: mi.clone(), is_sugared_doc: false, })) } else { None } } // Need the ability to run pre-expansion. fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { fold::noop_fold_mac(mac, self) } }
fold_foreign_mod
identifier_name
config.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. use attr::AttrMetaMethods; use diagnostic::SpanHandler; use fold::Folder; use {ast, fold, attr}; use codemap::{Spanned, respan}; use ptr::P; use util::small_vector::SmallVector; /// A folder that strips out items that do not belong in the current /// configuration. struct Context<F> where F: FnMut(&[ast::Attribute]) -> bool { in_cfg: F, } // Support conditional compilation by transforming the AST, stripping out // any items that do not belong in the current configuration pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate { let krate = process_cfg_attr(diagnostic, krate); let config = krate.config.clone(); strip_items(krate, |attrs| in_cfg(diagnostic, &config, attrs)) } impl<F> fold::Folder for Context<F> where F: FnMut(&[ast::Attribute]) -> bool { fn fold_mod(&mut self, module: ast::Mod) -> ast::Mod { fold_mod(self, module) } fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> { fold_block(self, block) } fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod { fold_foreign_mod(self, foreign_mod) } fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ { fold_item_underscore(self, item) } fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> { fold_expr(self, expr) } fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { fold::noop_fold_mac(mac, self) } fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { fold_item(self, item) } } pub fn strip_items<F>(krate: ast::Crate, in_cfg: F) -> ast::Crate where F: FnMut(&[ast::Attribute]) -> bool, { let mut ctxt = Context { in_cfg: in_cfg, }; ctxt.fold_crate(krate) } fn fold_mod<F>(cx: &mut Context<F>, ast::Mod {inner, items}: ast::Mod) -> ast::Mod where F: FnMut(&[ast::Attribute]) -> bool { ast::Mod { inner: inner, items: items.into_iter().flat_map(|a| { cx.fold_item(a).into_iter() }).collect() } } fn filter_foreign_item<F>(cx: &mut Context<F>, item: P<ast::ForeignItem>) -> Option<P<ast::ForeignItem>> where F: FnMut(&[ast::Attribute]) -> bool { if foreign_item_in_cfg(cx, &*item) { Some(item) } else { None } } fn fold_foreign_mod<F>(cx: &mut Context<F>, ast::ForeignMod {abi, items}: ast::ForeignMod) -> ast::ForeignMod where F: FnMut(&[ast::Attribute]) -> bool { ast::ForeignMod { abi: abi, items: items.into_iter() .filter_map(|a| filter_foreign_item(cx, a)) .collect() } } fn fold_item<F>(cx: &mut Context<F>, item: P<ast::Item>) -> SmallVector<P<ast::Item>> where F: FnMut(&[ast::Attribute]) -> bool { if item_in_cfg(cx, &*item) { SmallVector::one(item.map(|i| cx.fold_item_simple(i))) } else { SmallVector::zero() } } fn fold_item_underscore<F>(cx: &mut Context<F>, item: ast::Item_) -> ast::Item_ where F: FnMut(&[ast::Attribute]) -> bool { let item = match item { ast::ItemImpl(u, o, a, b, c, impl_items) => { let impl_items = impl_items.into_iter() .filter(|ii| (cx.in_cfg)(&ii.attrs)) .collect(); ast::ItemImpl(u, o, a, b, c, impl_items) } ast::ItemTrait(u, a, b, methods) => { let methods = methods.into_iter() .filter(|ti| (cx.in_cfg)(&ti.attrs)) .collect(); ast::ItemTrait(u, a, b, methods) } ast::ItemStruct(def, generics) => { ast::ItemStruct(fold_struct(cx, def), generics) } ast::ItemEnum(def, generics) => { let variants = def.variants.into_iter().filter_map(|v| { if!(cx.in_cfg)(&v.node.attrs) { None } else { Some(v.map(|Spanned {node: ast::Variant_ {id, name, attrs, kind, disr_expr, vis}, span}| { Spanned { node: ast::Variant_ { id: id, name: name, attrs: attrs, kind: match kind { ast::TupleVariantKind(..) => kind, ast::StructVariantKind(def) => { ast::StructVariantKind(fold_struct(cx, def)) } }, disr_expr: disr_expr, vis: vis }, span: span } })) } }); ast::ItemEnum(ast::EnumDef { variants: variants.collect(), }, generics) } item => item, }; fold::noop_fold_item_underscore(item, cx) } fn fold_struct<F>(cx: &mut Context<F>, def: P<ast::StructDef>) -> P<ast::StructDef> where F: FnMut(&[ast::Attribute]) -> bool { def.map(|ast::StructDef { fields, ctor_id }| { ast::StructDef { fields: fields.into_iter().filter(|m| { (cx.in_cfg)(&m.node.attrs) }).collect(), ctor_id: ctor_id, } }) } fn retain_stmt<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where F: FnMut(&[ast::Attribute]) -> bool { match stmt.node { ast::StmtDecl(ref decl, _) =>
_ => true } } fn fold_block<F>(cx: &mut Context<F>, b: P<ast::Block>) -> P<ast::Block> where F: FnMut(&[ast::Attribute]) -> bool { b.map(|ast::Block {id, stmts, expr, rules, span}| { let resulting_stmts: Vec<P<ast::Stmt>> = stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect(); let resulting_stmts = resulting_stmts.into_iter() .flat_map(|stmt| cx.fold_stmt(stmt).into_iter()) .collect(); ast::Block { id: id, stmts: resulting_stmts, expr: expr.map(|x| cx.fold_expr(x)), rules: rules, span: span, } }) } fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where F: FnMut(&[ast::Attribute]) -> bool { expr.map(|ast::Expr {id, span, node}| { fold::noop_fold_expr(ast::Expr { id: id, node: match node { ast::ExprMatch(m, arms, source) => { ast::ExprMatch(m, arms.into_iter() .filter(|a| (cx.in_cfg)(&a.attrs)) .collect(), source) } _ => node }, span: span }, cx) }) } fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where F: FnMut(&[ast::Attribute]) -> bool { return (cx.in_cfg)(&item.attrs); } fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where F: FnMut(&[ast::Attribute]) -> bool { return (cx.in_cfg)(&item.attrs); } // Determine if an item should be translated in the current crate // configuration based on the item's attributes fn in_cfg(diagnostic: &SpanHandler, cfg: &[P<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool { attrs.iter().all(|attr| { let mis = match attr.node.value.node { ast::MetaList(_, ref mis) if attr.check_name("cfg") => mis, _ => return true }; if mis.len()!= 1 { diagnostic.span_err(attr.span, "expected 1 cfg-pattern"); return true; } attr::cfg_matches(diagnostic, cfg, &*mis[0]) }) } struct CfgAttrFolder<'a> { diag: &'a SpanHandler, config: ast::CrateConfig, } // Process `#[cfg_attr]`. fn process_cfg_attr(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate { let mut fld = CfgAttrFolder { diag: diagnostic, config: krate.config.clone(), }; fld.fold_crate(krate) } impl<'a> fold::Folder for CfgAttrFolder<'a> { fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> { if!attr.check_name("cfg_attr") { return fold::noop_fold_attribute(attr, self); } let attr_list = match attr.meta_item_list() { Some(attr_list) => attr_list, None => { self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); return None; } }; let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) { (2, Some(cfg), Some(mi)) => (cfg, mi), _ => { self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); return None; } }; if attr::cfg_matches(self.diag, &self.config[..], &cfg) { Some(respan(mi.span, ast::Attribute_ { id: attr::mk_attr_id(), style: attr.node.style, value: mi.clone(), is_sugared_doc: false, })) } else { None } } // Need the ability to run pre-expansion. fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { fold::noop_fold_mac(mac, self) } }
{ match decl.node { ast::DeclItem(ref item) => { item_in_cfg(cx, &**item) } _ => true } }
conditional_block
config.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. use attr::AttrMetaMethods; use diagnostic::SpanHandler; use fold::Folder; use {ast, fold, attr}; use codemap::{Spanned, respan}; use ptr::P; use util::small_vector::SmallVector; /// A folder that strips out items that do not belong in the current /// configuration. struct Context<F> where F: FnMut(&[ast::Attribute]) -> bool { in_cfg: F, } // Support conditional compilation by transforming the AST, stripping out // any items that do not belong in the current configuration pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate { let krate = process_cfg_attr(diagnostic, krate); let config = krate.config.clone(); strip_items(krate, |attrs| in_cfg(diagnostic, &config, attrs)) } impl<F> fold::Folder for Context<F> where F: FnMut(&[ast::Attribute]) -> bool { fn fold_mod(&mut self, module: ast::Mod) -> ast::Mod { fold_mod(self, module) } fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> { fold_block(self, block) } fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod { fold_foreign_mod(self, foreign_mod) } fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ { fold_item_underscore(self, item) } fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> { fold_expr(self, expr) } fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { fold::noop_fold_mac(mac, self) } fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { fold_item(self, item) } } pub fn strip_items<F>(krate: ast::Crate, in_cfg: F) -> ast::Crate where F: FnMut(&[ast::Attribute]) -> bool, { let mut ctxt = Context { in_cfg: in_cfg, }; ctxt.fold_crate(krate) } fn fold_mod<F>(cx: &mut Context<F>, ast::Mod {inner, items}: ast::Mod) -> ast::Mod where F: FnMut(&[ast::Attribute]) -> bool { ast::Mod { inner: inner, items: items.into_iter().flat_map(|a| { cx.fold_item(a).into_iter() }).collect() } } fn filter_foreign_item<F>(cx: &mut Context<F>, item: P<ast::ForeignItem>) -> Option<P<ast::ForeignItem>> where F: FnMut(&[ast::Attribute]) -> bool { if foreign_item_in_cfg(cx, &*item) { Some(item) } else { None } } fn fold_foreign_mod<F>(cx: &mut Context<F>, ast::ForeignMod {abi, items}: ast::ForeignMod) -> ast::ForeignMod where F: FnMut(&[ast::Attribute]) -> bool { ast::ForeignMod { abi: abi, items: items.into_iter() .filter_map(|a| filter_foreign_item(cx, a)) .collect() } } fn fold_item<F>(cx: &mut Context<F>, item: P<ast::Item>) -> SmallVector<P<ast::Item>> where F: FnMut(&[ast::Attribute]) -> bool { if item_in_cfg(cx, &*item) { SmallVector::one(item.map(|i| cx.fold_item_simple(i))) } else { SmallVector::zero() } } fn fold_item_underscore<F>(cx: &mut Context<F>, item: ast::Item_) -> ast::Item_ where F: FnMut(&[ast::Attribute]) -> bool { let item = match item { ast::ItemImpl(u, o, a, b, c, impl_items) => { let impl_items = impl_items.into_iter() .filter(|ii| (cx.in_cfg)(&ii.attrs)) .collect(); ast::ItemImpl(u, o, a, b, c, impl_items) } ast::ItemTrait(u, a, b, methods) => { let methods = methods.into_iter() .filter(|ti| (cx.in_cfg)(&ti.attrs)) .collect(); ast::ItemTrait(u, a, b, methods) } ast::ItemStruct(def, generics) => { ast::ItemStruct(fold_struct(cx, def), generics) } ast::ItemEnum(def, generics) => { let variants = def.variants.into_iter().filter_map(|v| { if!(cx.in_cfg)(&v.node.attrs) { None } else { Some(v.map(|Spanned {node: ast::Variant_ {id, name, attrs, kind, disr_expr, vis}, span}| { Spanned {
node: ast::Variant_ { id: id, name: name, attrs: attrs, kind: match kind { ast::TupleVariantKind(..) => kind, ast::StructVariantKind(def) => { ast::StructVariantKind(fold_struct(cx, def)) } }, disr_expr: disr_expr, vis: vis }, span: span } })) } }); ast::ItemEnum(ast::EnumDef { variants: variants.collect(), }, generics) } item => item, }; fold::noop_fold_item_underscore(item, cx) } fn fold_struct<F>(cx: &mut Context<F>, def: P<ast::StructDef>) -> P<ast::StructDef> where F: FnMut(&[ast::Attribute]) -> bool { def.map(|ast::StructDef { fields, ctor_id }| { ast::StructDef { fields: fields.into_iter().filter(|m| { (cx.in_cfg)(&m.node.attrs) }).collect(), ctor_id: ctor_id, } }) } fn retain_stmt<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where F: FnMut(&[ast::Attribute]) -> bool { match stmt.node { ast::StmtDecl(ref decl, _) => { match decl.node { ast::DeclItem(ref item) => { item_in_cfg(cx, &**item) } _ => true } } _ => true } } fn fold_block<F>(cx: &mut Context<F>, b: P<ast::Block>) -> P<ast::Block> where F: FnMut(&[ast::Attribute]) -> bool { b.map(|ast::Block {id, stmts, expr, rules, span}| { let resulting_stmts: Vec<P<ast::Stmt>> = stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect(); let resulting_stmts = resulting_stmts.into_iter() .flat_map(|stmt| cx.fold_stmt(stmt).into_iter()) .collect(); ast::Block { id: id, stmts: resulting_stmts, expr: expr.map(|x| cx.fold_expr(x)), rules: rules, span: span, } }) } fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where F: FnMut(&[ast::Attribute]) -> bool { expr.map(|ast::Expr {id, span, node}| { fold::noop_fold_expr(ast::Expr { id: id, node: match node { ast::ExprMatch(m, arms, source) => { ast::ExprMatch(m, arms.into_iter() .filter(|a| (cx.in_cfg)(&a.attrs)) .collect(), source) } _ => node }, span: span }, cx) }) } fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where F: FnMut(&[ast::Attribute]) -> bool { return (cx.in_cfg)(&item.attrs); } fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where F: FnMut(&[ast::Attribute]) -> bool { return (cx.in_cfg)(&item.attrs); } // Determine if an item should be translated in the current crate // configuration based on the item's attributes fn in_cfg(diagnostic: &SpanHandler, cfg: &[P<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool { attrs.iter().all(|attr| { let mis = match attr.node.value.node { ast::MetaList(_, ref mis) if attr.check_name("cfg") => mis, _ => return true }; if mis.len()!= 1 { diagnostic.span_err(attr.span, "expected 1 cfg-pattern"); return true; } attr::cfg_matches(diagnostic, cfg, &*mis[0]) }) } struct CfgAttrFolder<'a> { diag: &'a SpanHandler, config: ast::CrateConfig, } // Process `#[cfg_attr]`. fn process_cfg_attr(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate { let mut fld = CfgAttrFolder { diag: diagnostic, config: krate.config.clone(), }; fld.fold_crate(krate) } impl<'a> fold::Folder for CfgAttrFolder<'a> { fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> { if!attr.check_name("cfg_attr") { return fold::noop_fold_attribute(attr, self); } let attr_list = match attr.meta_item_list() { Some(attr_list) => attr_list, None => { self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); return None; } }; let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) { (2, Some(cfg), Some(mi)) => (cfg, mi), _ => { self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); return None; } }; if attr::cfg_matches(self.diag, &self.config[..], &cfg) { Some(respan(mi.span, ast::Attribute_ { id: attr::mk_attr_id(), style: attr.node.style, value: mi.clone(), is_sugared_doc: false, })) } else { None } } // Need the ability to run pre-expansion. fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { fold::noop_fold_mac(mac, self) } }
random_line_split
tests.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 regex::{Regex, NoExpand}; #[test] fn eq() { assert_eq!(regex!(r"[a-z]+"), Regex::new("[a-z]+").unwrap()); } #[test] fn splitn() { let re = regex!(r"\d+"); let text = "cauchy123plato456tyler789binx"; let subs: Vec<&str> = re.splitn(text, 2).collect(); assert_eq!(subs, vec!("cauchy", "plato456tyler789binx")); } #[test] fn split() { let re = regex!(r"\d+"); let text = "cauchy123plato456tyler789binx"; let subs: Vec<&str> = re.split(text).collect(); assert_eq!(subs, vec!("cauchy", "plato", "tyler", "binx")); } #[test] fn empty_regex_empty_match() { let re = regex!(""); let ms = re.find_iter("").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 0)]); } #[test] fn empty_regex_nonempty_match() { let re = regex!(""); let ms = re.find_iter("abc").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn quoted_bracket_set() { let re = regex!(r"([\x{5b}\x{5d}])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); let re = regex!(r"([\[\]])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); } #[test] fn first_range_starts_with_left_bracket() { let re = regex!(r"([[-z])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); }
fn range_ends_with_escape() { let re = regex!(r"([\[-\x{5d}])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); } #[test] fn empty_match_find_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.find_iter("abc").collect(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn empty_match_captures_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.captures_iter("abc") .map(|c| c.pos(0).unwrap()) .collect(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn empty_match_unicode_find_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.find_iter("Ⅰ1Ⅱ2").collect(); assert_eq!(ms, vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)]); } #[test] fn empty_match_unicode_captures_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.captures_iter("Ⅰ1Ⅱ2") .map(|c| c.pos(0).unwrap()) .collect(); assert_eq!(ms, vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)]); } #[test] fn invalid_regexes_no_crash() { // See: https://github.com/rust-lang/regex/issues/48 assert!(Regex::new("(*)").is_err()); assert!(Regex::new("(?:?)").is_err()); assert!(Regex::new("(?)").is_err()); assert!(Regex::new("*").is_err()); } macro_rules! searcher { ($name:ident, $re:expr, $haystack:expr) => ( searcher!($name, $re, $haystack, vec vec![]); ); ($name:ident, $re:expr, $haystack:expr, $($steps:expr,)*) => ( searcher!($name, $re, $haystack, vec vec![$($steps),*]); ); ($name:ident, $re:expr, $haystack:expr, $($steps:expr),*) => ( searcher!($name, $re, $haystack, vec vec![$($steps),*]); ); ($name:ident, $re:expr, $haystack:expr, vec $expect_steps:expr) => ( #[test] #[allow(unused_imports)] fn $name() { searcher_expr! {{ use std::str::pattern::{Pattern, Searcher}; use std::str::pattern::SearchStep::{Match, Reject, Done}; let re = regex!($re); let mut se = re.into_searcher($haystack); let mut got_steps = vec![]; loop { match se.next() { Done => break, step => { got_steps.push(step); } } } assert_eq!(got_steps, $expect_steps); }} } ); } searcher!(searcher_empty_regex_empty_haystack, r"", "", Match(0, 0)); searcher!(searcher_empty_regex, r"", "ab", Match(0, 0), Reject(0, 1), Match(1, 1), Reject(1, 2), Match(2, 2)); searcher!(searcher_empty_haystack, r"\d", ""); searcher!(searcher_one_match, r"\d", "5", Match(0, 1)); searcher!(searcher_no_match, r"\d", "a", Reject(0, 1)); searcher!(searcher_two_adjacent_matches, r"\d", "56", Match(0, 1), Match(1, 2)); searcher!(searcher_two_non_adjacent_matches, r"\d", "5a6", Match(0, 1), Reject(1, 2), Match(2, 3)); searcher!(searcher_reject_first, r"\d", "a6", Reject(0, 1), Match(1, 2)); searcher!(searcher_one_zero_length_matches, r"\d*", "a1b2", Match(0, 0), // ^ Reject(0, 1), // a Match(1, 2), // a1 Reject(2, 3), // a1b Match(3, 4), // a1b2 ); searcher!(searcher_many_zero_length_matches, r"\d*", "a1bbb2", Match(0, 0), // ^ Reject(0, 1), // a Match(1, 2), // a1 Reject(2, 3), // a1b Match(3, 3), // a1bb Reject(3, 4), // a1bb Match(4, 4), // a1bbb Reject(4, 5), // a1bbb Match(5, 6), // a1bbba ); searcher!(searcher_unicode, r".+?", "Ⅰ1Ⅱ2", Match(0, 3), Match(3, 4), Match(4, 7), Match(7, 8)); macro_rules! replace( ($name:ident, $which:ident, $re:expr, $search:expr, $replace:expr, $result:expr) => ( #[test] fn $name() { let re = regex!($re); assert_eq!(re.$which($search, $replace), $result); } ); ); replace!(rep_first, replace, r"\d", "age: 26", "Z", "age: Z6"); replace!(rep_plus, replace, r"\d+", "age: 26", "Z", "age: Z"); replace!(rep_all, replace_all, r"\d", "age: 26", "Z", "age: ZZ"); replace!(rep_groups, replace, r"(\S+)\s+(\S+)", "w1 w2", "$2 $1", "w2 w1"); replace!(rep_double_dollar, replace, r"(\S+)\s+(\S+)", "w1 w2", "$2 $$1", "w2 $1"); replace!(rep_adjacent_index, replace, r"([^aeiouy])ies$", "skies", "$1y", "sky"); replace!(rep_no_expand, replace, r"(\S+)\s+(\S+)", "w1 w2", NoExpand("$2 $1"), "$2 $1"); replace!(rep_named, replace_all, r"(?P<first>\S+)\s+(?P<last>\S+)(?P<space>\s*)", "w1 w2 w3 w4", "$last $first$space", "w2 w1 w4 w3"); replace!(rep_trim, replace_all, "^[ \t]+|[ \t]+$", " \t trim me\t \t", "", "trim me"); replace!(rep_number_hypen, replace, r"(.)(.)", "ab", "$1-$2", "a-b"); replace!(rep_number_underscore, replace, r"(.)(.)", "ab", "$1_$2", "a_b"); macro_rules! noparse( ($name:ident, $re:expr) => ( #[test] fn $name() { let re = $re; match Regex::new(re) { Err(_) => {}, Ok(_) => panic!("Regex '{}' should cause a parse error.", re), } } ); ); noparse!(fail_double_repeat, "a**"); noparse!(fail_no_repeat_arg, "*"); noparse!(fail_incomplete_escape, "\\"); noparse!(fail_class_incomplete, "[A-"); noparse!(fail_class_not_closed, "[A"); noparse!(fail_class_no_begin, r"[\A]"); noparse!(fail_class_no_end, r"[\z]"); noparse!(fail_class_no_boundary, r"[\b]"); noparse!(fail_open_paren, "("); noparse!(fail_close_paren, ")"); noparse!(fail_invalid_range, "[a-Z]"); noparse!(fail_empty_capture_name, "(?P<>a)"); noparse!(fail_empty_capture_exp, "(?P<name>)"); noparse!(fail_bad_capture_name, "(?P<na-me>)"); noparse!(fail_bad_flag, "(?a)a"); noparse!(fail_empty_alt_before, "|a"); noparse!(fail_empty_alt_after, "a|"); noparse!(fail_too_big, "a{10000000}"); noparse!(fail_counted_no_close, "a{1001"); noparse!(fail_unfinished_cap, "(?"); noparse!(fail_unfinished_escape, "\\"); noparse!(fail_octal_digit, r"\8"); noparse!(fail_hex_digit, r"\xG0"); noparse!(fail_hex_short, r"\xF"); noparse!(fail_hex_long_digits, r"\x{fffg}"); noparse!(fail_flag_bad, "(?a)"); noparse!(fail_flag_empty, "(?)"); noparse!(fail_double_neg, "(?-i-i)"); noparse!(fail_neg_empty, "(?i-)"); noparse!(fail_empty_group, "()"); noparse!(fail_dupe_named, "(?P<a>.)(?P<a>.)"); noparse!(fail_range_end_no_class, "[a-[:lower:]]"); noparse!(fail_range_end_no_begin, r"[a-\A]"); noparse!(fail_range_end_no_end, r"[a-\z]"); noparse!(fail_range_end_no_boundary, r"[a-\b]"); macro_rules! mat( ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( #[test] fn $name() { let text = $text; let expected: Vec<Option<_>> = vec!($($loc)+); let r = regex!($re); let got = match r.captures(text) { Some(c) => c.iter_pos().collect::<Vec<Option<_>>>(), None => vec!(None), }; // The test set sometimes leave out capture groups, so truncate // actual capture groups to match test set. let mut sgot = &got[..]; if sgot.len() > expected.len() { sgot = &sgot[0..expected.len()] } if expected!= sgot { panic!("For RE '{}' against '{:?}', \ expected '{:?}' but got '{:?}'", $re, text, expected, sgot); } } ); ); // Some crazy expressions from regular-expressions.info. mat!(match_ranges, r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", "num: 255", Some((5, 8))); mat!(match_ranges_not, r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", "num: 256", None); mat!(match_float1, r"[-+]?[0-9]*\.?[0-9]+", "0.1", Some((0, 3))); mat!(match_float2, r"[-+]?[0-9]*\.?[0-9]+", "0.1.2", Some((0, 3))); mat!(match_float3, r"[-+]?[0-9]*\.?[0-9]+", "a1.2", Some((1, 4))); mat!(match_float4, r"^[-+]?[0-9]*\.?[0-9]+$", "1.a", None); mat!(match_email, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", "mine is [email protected] ", Some((8, 26))); mat!(match_email_not, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", "mine is jam.slam@gmail ", None); mat!(match_email_big, r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", "mine is [email protected] ", Some((8, 26))); mat!(match_date1, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-01-01", Some((0, 10))); mat!(match_date2, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-00-01", None); mat!(match_date3, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-13-01", None); // Exercise the flags. mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4))); mat!(match_flag_case_dotnl_toggle_not, "(?is)a.(?-is)a.", "A\na\n", None); mat!(match_flag_case_dotnl_toggle_ok, "(?is)a.(?-is:a.)?", "A\na\n", Some((0, 2))); mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11))); mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2))); // Some Unicode tests. // A couple of these are commented out because something in the guts of macro // expansion is creating invalid byte strings. // mat!(uni_literal, r"Ⅰ", "Ⅰ", Some((0, 3))) // mat!(uni_case_not, r"Δ", "δ", None) mat!(uni_one, r"\pN", "Ⅰ", Some((0, 3))); mat!(uni_mixed, r"\pN+", "Ⅰ1Ⅱ2", Some((0, 8))); mat!(uni_not, r"\PN+", "abⅠ", Some((0, 2))); mat!(uni_not_class, r"[\PN]+", "abⅠ", Some((0, 2))); mat!(uni_not_class_neg, r"[^\PN]+", "abⅠ", Some((2, 5))); mat!(uni_case, r"(?i)Δ", "δ", Some((0, 2))); mat!(uni_case_upper, r"\p{Lu}+", "ΛΘΓΔα", Some((0, 8))); mat!(uni_case_upper_nocase_flag, r"(?i)\p{Lu}+", "ΛΘΓΔα", Some((0, 10))); mat!(uni_case_upper_nocase, r"\p{L}+", "ΛΘΓΔα", Some((0, 10))); mat!(uni_case_lower, r"\p{Ll}+", "ΛΘΓΔα", Some((8, 10))); // https://github.com/rust-lang/regex/issues/76 mat!(uni_case_lower_nocase_flag, r"(?i)\p{Ll}+", "ΛΘΓΔα", Some((0, 10))); // Test the Unicode friendliness of Perl character classes. mat!(uni_perl_w, r"\w+", "dδd", Some((0, 4))); mat!(uni_perl_w_not, r"\w+", "⥡", None); mat!(uni_perl_w_neg, r"\W+", "⥡", Some((0, 3))); mat!(uni_perl_d, r"\d+", "1२३9", Some((0, 8))); mat!(uni_perl_d_not, r"\d+", "Ⅱ", None); mat!(uni_perl_d_neg, r"\D+", "Ⅱ", Some((0, 3))); mat!(uni_perl_s, r"\s+", " ", Some((0, 3))); mat!(uni_perl_s_not, r"\s+", "☃", None); mat!(uni_perl_s_neg, r"\S+", "☃", Some((0, 3))); // And do the same for word boundaries. mat!(uni_boundary_none, r"\d\b", "6δ", None); mat!(uni_boundary_ogham, r"\d\b", "6 ", Some((0, 1))); // Test negated character classes. mat!(negclass_letters, r"[^ac]", "acx", Some((2, 3))); mat!(negclass_letter_comma, r"[^a,]", "a,x", Some((2, 3))); mat!(negclass_letter_space, r"[^a\s]", "a x", Some((2, 3))); mat!(negclass_comma, r"[^,]", ",,x", Some((2, 3))); mat!(negclass_space, r"[^\s]", " a", Some((1, 2))); mat!(negclass_space_comma, r"[^,\s]", ", a", Some((2, 3))); mat!(negclass_comma_space, r"[^\s,]", ",a", Some((2, 3))); mat!(negclass_ascii, r"[^[:alpha:]Z]", "A1", Some((1, 2))); // Regression test for https://github.com/rust-lang/regex/issues/75 mat!(regression_unsorted_binary_search_1, r"(?i)[a_]+", "A_", Some((0, 2))); mat!(regression_unsorted_binary_search_2, r"(?i)[A_]+", "a_", Some((0, 2))); // Regression tests for https://github.com/rust-lang/regex/issues/99 mat!(regression_negated_char_class_1, r"(?i)[^x]", "x", None); mat!(regression_negated_char_class_2, r"(?i)[^x]", "X", None); // Regression test for https://github.com/rust-lang/regex/issues/101 mat!(regression_ascii_word_underscore, r"[:word:]", "_", Some((0, 1))); // A whole mess of tests from Glenn Fowler's regex test suite. // Generated by the'src/etc/regex-match-tests' program. #[path = "matches.rs"] mod matches;
#[test]
random_line_split
tests.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 regex::{Regex, NoExpand}; #[test] fn eq() { assert_eq!(regex!(r"[a-z]+"), Regex::new("[a-z]+").unwrap()); } #[test] fn splitn() { let re = regex!(r"\d+"); let text = "cauchy123plato456tyler789binx"; let subs: Vec<&str> = re.splitn(text, 2).collect(); assert_eq!(subs, vec!("cauchy", "plato456tyler789binx")); } #[test] fn split() { let re = regex!(r"\d+"); let text = "cauchy123plato456tyler789binx"; let subs: Vec<&str> = re.split(text).collect(); assert_eq!(subs, vec!("cauchy", "plato", "tyler", "binx")); } #[test] fn empty_regex_empty_match() { let re = regex!(""); let ms = re.find_iter("").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 0)]); } #[test] fn empty_regex_nonempty_match() { let re = regex!(""); let ms = re.find_iter("abc").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn quoted_bracket_set() { let re = regex!(r"([\x{5b}\x{5d}])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); let re = regex!(r"([\[\]])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); } #[test] fn first_range_starts_with_left_bracket() { let re = regex!(r"([[-z])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); } #[test] fn
() { let re = regex!(r"([\[-\x{5d}])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); } #[test] fn empty_match_find_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.find_iter("abc").collect(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn empty_match_captures_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.captures_iter("abc") .map(|c| c.pos(0).unwrap()) .collect(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn empty_match_unicode_find_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.find_iter("Ⅰ1Ⅱ2").collect(); assert_eq!(ms, vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)]); } #[test] fn empty_match_unicode_captures_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.captures_iter("Ⅰ1Ⅱ2") .map(|c| c.pos(0).unwrap()) .collect(); assert_eq!(ms, vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)]); } #[test] fn invalid_regexes_no_crash() { // See: https://github.com/rust-lang/regex/issues/48 assert!(Regex::new("(*)").is_err()); assert!(Regex::new("(?:?)").is_err()); assert!(Regex::new("(?)").is_err()); assert!(Regex::new("*").is_err()); } macro_rules! searcher { ($name:ident, $re:expr, $haystack:expr) => ( searcher!($name, $re, $haystack, vec vec![]); ); ($name:ident, $re:expr, $haystack:expr, $($steps:expr,)*) => ( searcher!($name, $re, $haystack, vec vec![$($steps),*]); ); ($name:ident, $re:expr, $haystack:expr, $($steps:expr),*) => ( searcher!($name, $re, $haystack, vec vec![$($steps),*]); ); ($name:ident, $re:expr, $haystack:expr, vec $expect_steps:expr) => ( #[test] #[allow(unused_imports)] fn $name() { searcher_expr! {{ use std::str::pattern::{Pattern, Searcher}; use std::str::pattern::SearchStep::{Match, Reject, Done}; let re = regex!($re); let mut se = re.into_searcher($haystack); let mut got_steps = vec![]; loop { match se.next() { Done => break, step => { got_steps.push(step); } } } assert_eq!(got_steps, $expect_steps); }} } ); } searcher!(searcher_empty_regex_empty_haystack, r"", "", Match(0, 0)); searcher!(searcher_empty_regex, r"", "ab", Match(0, 0), Reject(0, 1), Match(1, 1), Reject(1, 2), Match(2, 2)); searcher!(searcher_empty_haystack, r"\d", ""); searcher!(searcher_one_match, r"\d", "5", Match(0, 1)); searcher!(searcher_no_match, r"\d", "a", Reject(0, 1)); searcher!(searcher_two_adjacent_matches, r"\d", "56", Match(0, 1), Match(1, 2)); searcher!(searcher_two_non_adjacent_matches, r"\d", "5a6", Match(0, 1), Reject(1, 2), Match(2, 3)); searcher!(searcher_reject_first, r"\d", "a6", Reject(0, 1), Match(1, 2)); searcher!(searcher_one_zero_length_matches, r"\d*", "a1b2", Match(0, 0), // ^ Reject(0, 1), // a Match(1, 2), // a1 Reject(2, 3), // a1b Match(3, 4), // a1b2 ); searcher!(searcher_many_zero_length_matches, r"\d*", "a1bbb2", Match(0, 0), // ^ Reject(0, 1), // a Match(1, 2), // a1 Reject(2, 3), // a1b Match(3, 3), // a1bb Reject(3, 4), // a1bb Match(4, 4), // a1bbb Reject(4, 5), // a1bbb Match(5, 6), // a1bbba ); searcher!(searcher_unicode, r".+?", "Ⅰ1Ⅱ2", Match(0, 3), Match(3, 4), Match(4, 7), Match(7, 8)); macro_rules! replace( ($name:ident, $which:ident, $re:expr, $search:expr, $replace:expr, $result:expr) => ( #[test] fn $name() { let re = regex!($re); assert_eq!(re.$which($search, $replace), $result); } ); ); replace!(rep_first, replace, r"\d", "age: 26", "Z", "age: Z6"); replace!(rep_plus, replace, r"\d+", "age: 26", "Z", "age: Z"); replace!(rep_all, replace_all, r"\d", "age: 26", "Z", "age: ZZ"); replace!(rep_groups, replace, r"(\S+)\s+(\S+)", "w1 w2", "$2 $1", "w2 w1"); replace!(rep_double_dollar, replace, r"(\S+)\s+(\S+)", "w1 w2", "$2 $$1", "w2 $1"); replace!(rep_adjacent_index, replace, r"([^aeiouy])ies$", "skies", "$1y", "sky"); replace!(rep_no_expand, replace, r"(\S+)\s+(\S+)", "w1 w2", NoExpand("$2 $1"), "$2 $1"); replace!(rep_named, replace_all, r"(?P<first>\S+)\s+(?P<last>\S+)(?P<space>\s*)", "w1 w2 w3 w4", "$last $first$space", "w2 w1 w4 w3"); replace!(rep_trim, replace_all, "^[ \t]+|[ \t]+$", " \t trim me\t \t", "", "trim me"); replace!(rep_number_hypen, replace, r"(.)(.)", "ab", "$1-$2", "a-b"); replace!(rep_number_underscore, replace, r"(.)(.)", "ab", "$1_$2", "a_b"); macro_rules! noparse( ($name:ident, $re:expr) => ( #[test] fn $name() { let re = $re; match Regex::new(re) { Err(_) => {}, Ok(_) => panic!("Regex '{}' should cause a parse error.", re), } } ); ); noparse!(fail_double_repeat, "a**"); noparse!(fail_no_repeat_arg, "*"); noparse!(fail_incomplete_escape, "\\"); noparse!(fail_class_incomplete, "[A-"); noparse!(fail_class_not_closed, "[A"); noparse!(fail_class_no_begin, r"[\A]"); noparse!(fail_class_no_end, r"[\z]"); noparse!(fail_class_no_boundary, r"[\b]"); noparse!(fail_open_paren, "("); noparse!(fail_close_paren, ")"); noparse!(fail_invalid_range, "[a-Z]"); noparse!(fail_empty_capture_name, "(?P<>a)"); noparse!(fail_empty_capture_exp, "(?P<name>)"); noparse!(fail_bad_capture_name, "(?P<na-me>)"); noparse!(fail_bad_flag, "(?a)a"); noparse!(fail_empty_alt_before, "|a"); noparse!(fail_empty_alt_after, "a|"); noparse!(fail_too_big, "a{10000000}"); noparse!(fail_counted_no_close, "a{1001"); noparse!(fail_unfinished_cap, "(?"); noparse!(fail_unfinished_escape, "\\"); noparse!(fail_octal_digit, r"\8"); noparse!(fail_hex_digit, r"\xG0"); noparse!(fail_hex_short, r"\xF"); noparse!(fail_hex_long_digits, r"\x{fffg}"); noparse!(fail_flag_bad, "(?a)"); noparse!(fail_flag_empty, "(?)"); noparse!(fail_double_neg, "(?-i-i)"); noparse!(fail_neg_empty, "(?i-)"); noparse!(fail_empty_group, "()"); noparse!(fail_dupe_named, "(?P<a>.)(?P<a>.)"); noparse!(fail_range_end_no_class, "[a-[:lower:]]"); noparse!(fail_range_end_no_begin, r"[a-\A]"); noparse!(fail_range_end_no_end, r"[a-\z]"); noparse!(fail_range_end_no_boundary, r"[a-\b]"); macro_rules! mat( ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( #[test] fn $name() { let text = $text; let expected: Vec<Option<_>> = vec!($($loc)+); let r = regex!($re); let got = match r.captures(text) { Some(c) => c.iter_pos().collect::<Vec<Option<_>>>(), None => vec!(None), }; // The test set sometimes leave out capture groups, so truncate // actual capture groups to match test set. let mut sgot = &got[..]; if sgot.len() > expected.len() { sgot = &sgot[0..expected.len()] } if expected!= sgot { panic!("For RE '{}' against '{:?}', \ expected '{:?}' but got '{:?}'", $re, text, expected, sgot); } } ); ); // Some crazy expressions from regular-expressions.info. mat!(match_ranges, r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", "num: 255", Some((5, 8))); mat!(match_ranges_not, r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", "num: 256", None); mat!(match_float1, r"[-+]?[0-9]*\.?[0-9]+", "0.1", Some((0, 3))); mat!(match_float2, r"[-+]?[0-9]*\.?[0-9]+", "0.1.2", Some((0, 3))); mat!(match_float3, r"[-+]?[0-9]*\.?[0-9]+", "a1.2", Some((1, 4))); mat!(match_float4, r"^[-+]?[0-9]*\.?[0-9]+$", "1.a", None); mat!(match_email, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", "mine is [email protected] ", Some((8, 26))); mat!(match_email_not, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", "mine is jam.slam@gmail ", None); mat!(match_email_big, r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", "mine is [email protected] ", Some((8, 26))); mat!(match_date1, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-01-01", Some((0, 10))); mat!(match_date2, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-00-01", None); mat!(match_date3, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-13-01", None); // Exercise the flags. mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4))); mat!(match_flag_case_dotnl_toggle_not, "(?is)a.(?-is)a.", "A\na\n", None); mat!(match_flag_case_dotnl_toggle_ok, "(?is)a.(?-is:a.)?", "A\na\n", Some((0, 2))); mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11))); mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2))); // Some Unicode tests. // A couple of these are commented out because something in the guts of macro // expansion is creating invalid byte strings. // mat!(uni_literal, r"Ⅰ", "Ⅰ", Some((0, 3))) // mat!(uni_case_not, r"Δ", "δ", None) mat!(uni_one, r"\pN", "Ⅰ", Some((0, 3))); mat!(uni_mixed, r"\pN+", "Ⅰ1Ⅱ2", Some((0, 8))); mat!(uni_not, r"\PN+", "abⅠ", Some((0, 2))); mat!(uni_not_class, r"[\PN]+", "abⅠ", Some((0, 2))); mat!(uni_not_class_neg, r"[^\PN]+", "abⅠ", Some((2, 5))); mat!(uni_case, r"(?i)Δ", "δ", Some((0, 2))); mat!(uni_case_upper, r"\p{Lu}+", "ΛΘΓΔα", Some((0, 8))); mat!(uni_case_upper_nocase_flag, r"(?i)\p{Lu}+", "ΛΘΓΔα", Some((0, 10))); mat!(uni_case_upper_nocase, r"\p{L}+", "ΛΘΓΔα", Some((0, 10))); mat!(uni_case_lower, r"\p{Ll}+", "ΛΘΓΔα", Some((8, 10))); // https://github.com/rust-lang/regex/issues/76 mat!(uni_case_lower_nocase_flag, r"(?i)\p{Ll}+", "ΛΘΓΔα", Some((0, 10))); // Test the Unicode friendliness of Perl character classes. mat!(uni_perl_w, r"\w+", "dδd", Some((0, 4))); mat!(uni_perl_w_not, r"\w+", "⥡", None); mat!(uni_perl_w_neg, r"\W+", "⥡", Some((0, 3))); mat!(uni_perl_d, r"\d+", "1२३9", Some((0, 8))); mat!(uni_perl_d_not, r"\d+", "Ⅱ", None); mat!(uni_perl_d_neg, r"\D+", "Ⅱ", Some((0, 3))); mat!(uni_perl_s, r"\s+", " ", Some((0, 3))); mat!(uni_perl_s_not, r"\s+", "☃", None); mat!(uni_perl_s_neg, r"\S+", "☃", Some((0, 3))); // And do the same for word boundaries. mat!(uni_boundary_none, r"\d\b", "6δ", None); mat!(uni_boundary_ogham, r"\d\b", "6 ", Some((0, 1))); // Test negated character classes. mat!(negclass_letters, r"[^ac]", "acx", Some((2, 3))); mat!(negclass_letter_comma, r"[^a,]", "a,x", Some((2, 3))); mat!(negclass_letter_space, r"[^a\s]", "a x", Some((2, 3))); mat!(negclass_comma, r"[^,]", ",,x", Some((2, 3))); mat!(negclass_space, r"[^\s]", " a", Some((1, 2))); mat!(negclass_space_comma, r"[^,\s]", ", a", Some((2, 3))); mat!(negclass_comma_space, r"[^\s,]", ",a", Some((2, 3))); mat!(negclass_ascii, r"[^[:alpha:]Z]", "A1", Some((1, 2))); // Regression test for https://github.com/rust-lang/regex/issues/75 mat!(regression_unsorted_binary_search_1, r"(?i)[a_]+", "A_", Some((0, 2))); mat!(regression_unsorted_binary_search_2, r"(?i)[A_]+", "a_", Some((0, 2))); // Regression tests for https://github.com/rust-lang/regex/issues/99 mat!(regression_negated_char_class_1, r"(?i)[^x]", "x", None); mat!(regression_negated_char_class_2, r"(?i)[^x]", "X", None); // Regression test for https://github.com/rust-lang/regex/issues/101 mat!(regression_ascii_word_underscore, r"[:word:]", "_", Some((0, 1))); // A whole mess of tests from Glenn Fowler's regex test suite. // Generated by the'src/etc/regex-match-tests' program. #[path = "matches.rs"] mod matches;
range_ends_with_escape
identifier_name
tests.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 regex::{Regex, NoExpand}; #[test] fn eq() { assert_eq!(regex!(r"[a-z]+"), Regex::new("[a-z]+").unwrap()); } #[test] fn splitn() { let re = regex!(r"\d+"); let text = "cauchy123plato456tyler789binx"; let subs: Vec<&str> = re.splitn(text, 2).collect(); assert_eq!(subs, vec!("cauchy", "plato456tyler789binx")); } #[test] fn split() { let re = regex!(r"\d+"); let text = "cauchy123plato456tyler789binx"; let subs: Vec<&str> = re.split(text).collect(); assert_eq!(subs, vec!("cauchy", "plato", "tyler", "binx")); } #[test] fn empty_regex_empty_match() { let re = regex!(""); let ms = re.find_iter("").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 0)]); } #[test] fn empty_regex_nonempty_match() { let re = regex!(""); let ms = re.find_iter("abc").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn quoted_bracket_set() { let re = regex!(r"([\x{5b}\x{5d}])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); let re = regex!(r"([\[\]])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); } #[test] fn first_range_starts_with_left_bracket()
#[test] fn range_ends_with_escape() { let re = regex!(r"([\[-\x{5d}])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); } #[test] fn empty_match_find_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.find_iter("abc").collect(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn empty_match_captures_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.captures_iter("abc") .map(|c| c.pos(0).unwrap()) .collect(); assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); } #[test] fn empty_match_unicode_find_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.find_iter("Ⅰ1Ⅱ2").collect(); assert_eq!(ms, vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)]); } #[test] fn empty_match_unicode_captures_iter() { let re = regex!(r".*?"); let ms: Vec<_> = re.captures_iter("Ⅰ1Ⅱ2") .map(|c| c.pos(0).unwrap()) .collect(); assert_eq!(ms, vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)]); } #[test] fn invalid_regexes_no_crash() { // See: https://github.com/rust-lang/regex/issues/48 assert!(Regex::new("(*)").is_err()); assert!(Regex::new("(?:?)").is_err()); assert!(Regex::new("(?)").is_err()); assert!(Regex::new("*").is_err()); } macro_rules! searcher { ($name:ident, $re:expr, $haystack:expr) => ( searcher!($name, $re, $haystack, vec vec![]); ); ($name:ident, $re:expr, $haystack:expr, $($steps:expr,)*) => ( searcher!($name, $re, $haystack, vec vec![$($steps),*]); ); ($name:ident, $re:expr, $haystack:expr, $($steps:expr),*) => ( searcher!($name, $re, $haystack, vec vec![$($steps),*]); ); ($name:ident, $re:expr, $haystack:expr, vec $expect_steps:expr) => ( #[test] #[allow(unused_imports)] fn $name() { searcher_expr! {{ use std::str::pattern::{Pattern, Searcher}; use std::str::pattern::SearchStep::{Match, Reject, Done}; let re = regex!($re); let mut se = re.into_searcher($haystack); let mut got_steps = vec![]; loop { match se.next() { Done => break, step => { got_steps.push(step); } } } assert_eq!(got_steps, $expect_steps); }} } ); } searcher!(searcher_empty_regex_empty_haystack, r"", "", Match(0, 0)); searcher!(searcher_empty_regex, r"", "ab", Match(0, 0), Reject(0, 1), Match(1, 1), Reject(1, 2), Match(2, 2)); searcher!(searcher_empty_haystack, r"\d", ""); searcher!(searcher_one_match, r"\d", "5", Match(0, 1)); searcher!(searcher_no_match, r"\d", "a", Reject(0, 1)); searcher!(searcher_two_adjacent_matches, r"\d", "56", Match(0, 1), Match(1, 2)); searcher!(searcher_two_non_adjacent_matches, r"\d", "5a6", Match(0, 1), Reject(1, 2), Match(2, 3)); searcher!(searcher_reject_first, r"\d", "a6", Reject(0, 1), Match(1, 2)); searcher!(searcher_one_zero_length_matches, r"\d*", "a1b2", Match(0, 0), // ^ Reject(0, 1), // a Match(1, 2), // a1 Reject(2, 3), // a1b Match(3, 4), // a1b2 ); searcher!(searcher_many_zero_length_matches, r"\d*", "a1bbb2", Match(0, 0), // ^ Reject(0, 1), // a Match(1, 2), // a1 Reject(2, 3), // a1b Match(3, 3), // a1bb Reject(3, 4), // a1bb Match(4, 4), // a1bbb Reject(4, 5), // a1bbb Match(5, 6), // a1bbba ); searcher!(searcher_unicode, r".+?", "Ⅰ1Ⅱ2", Match(0, 3), Match(3, 4), Match(4, 7), Match(7, 8)); macro_rules! replace( ($name:ident, $which:ident, $re:expr, $search:expr, $replace:expr, $result:expr) => ( #[test] fn $name() { let re = regex!($re); assert_eq!(re.$which($search, $replace), $result); } ); ); replace!(rep_first, replace, r"\d", "age: 26", "Z", "age: Z6"); replace!(rep_plus, replace, r"\d+", "age: 26", "Z", "age: Z"); replace!(rep_all, replace_all, r"\d", "age: 26", "Z", "age: ZZ"); replace!(rep_groups, replace, r"(\S+)\s+(\S+)", "w1 w2", "$2 $1", "w2 w1"); replace!(rep_double_dollar, replace, r"(\S+)\s+(\S+)", "w1 w2", "$2 $$1", "w2 $1"); replace!(rep_adjacent_index, replace, r"([^aeiouy])ies$", "skies", "$1y", "sky"); replace!(rep_no_expand, replace, r"(\S+)\s+(\S+)", "w1 w2", NoExpand("$2 $1"), "$2 $1"); replace!(rep_named, replace_all, r"(?P<first>\S+)\s+(?P<last>\S+)(?P<space>\s*)", "w1 w2 w3 w4", "$last $first$space", "w2 w1 w4 w3"); replace!(rep_trim, replace_all, "^[ \t]+|[ \t]+$", " \t trim me\t \t", "", "trim me"); replace!(rep_number_hypen, replace, r"(.)(.)", "ab", "$1-$2", "a-b"); replace!(rep_number_underscore, replace, r"(.)(.)", "ab", "$1_$2", "a_b"); macro_rules! noparse( ($name:ident, $re:expr) => ( #[test] fn $name() { let re = $re; match Regex::new(re) { Err(_) => {}, Ok(_) => panic!("Regex '{}' should cause a parse error.", re), } } ); ); noparse!(fail_double_repeat, "a**"); noparse!(fail_no_repeat_arg, "*"); noparse!(fail_incomplete_escape, "\\"); noparse!(fail_class_incomplete, "[A-"); noparse!(fail_class_not_closed, "[A"); noparse!(fail_class_no_begin, r"[\A]"); noparse!(fail_class_no_end, r"[\z]"); noparse!(fail_class_no_boundary, r"[\b]"); noparse!(fail_open_paren, "("); noparse!(fail_close_paren, ")"); noparse!(fail_invalid_range, "[a-Z]"); noparse!(fail_empty_capture_name, "(?P<>a)"); noparse!(fail_empty_capture_exp, "(?P<name>)"); noparse!(fail_bad_capture_name, "(?P<na-me>)"); noparse!(fail_bad_flag, "(?a)a"); noparse!(fail_empty_alt_before, "|a"); noparse!(fail_empty_alt_after, "a|"); noparse!(fail_too_big, "a{10000000}"); noparse!(fail_counted_no_close, "a{1001"); noparse!(fail_unfinished_cap, "(?"); noparse!(fail_unfinished_escape, "\\"); noparse!(fail_octal_digit, r"\8"); noparse!(fail_hex_digit, r"\xG0"); noparse!(fail_hex_short, r"\xF"); noparse!(fail_hex_long_digits, r"\x{fffg}"); noparse!(fail_flag_bad, "(?a)"); noparse!(fail_flag_empty, "(?)"); noparse!(fail_double_neg, "(?-i-i)"); noparse!(fail_neg_empty, "(?i-)"); noparse!(fail_empty_group, "()"); noparse!(fail_dupe_named, "(?P<a>.)(?P<a>.)"); noparse!(fail_range_end_no_class, "[a-[:lower:]]"); noparse!(fail_range_end_no_begin, r"[a-\A]"); noparse!(fail_range_end_no_end, r"[a-\z]"); noparse!(fail_range_end_no_boundary, r"[a-\b]"); macro_rules! mat( ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( #[test] fn $name() { let text = $text; let expected: Vec<Option<_>> = vec!($($loc)+); let r = regex!($re); let got = match r.captures(text) { Some(c) => c.iter_pos().collect::<Vec<Option<_>>>(), None => vec!(None), }; // The test set sometimes leave out capture groups, so truncate // actual capture groups to match test set. let mut sgot = &got[..]; if sgot.len() > expected.len() { sgot = &sgot[0..expected.len()] } if expected!= sgot { panic!("For RE '{}' against '{:?}', \ expected '{:?}' but got '{:?}'", $re, text, expected, sgot); } } ); ); // Some crazy expressions from regular-expressions.info. mat!(match_ranges, r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", "num: 255", Some((5, 8))); mat!(match_ranges_not, r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", "num: 256", None); mat!(match_float1, r"[-+]?[0-9]*\.?[0-9]+", "0.1", Some((0, 3))); mat!(match_float2, r"[-+]?[0-9]*\.?[0-9]+", "0.1.2", Some((0, 3))); mat!(match_float3, r"[-+]?[0-9]*\.?[0-9]+", "a1.2", Some((1, 4))); mat!(match_float4, r"^[-+]?[0-9]*\.?[0-9]+$", "1.a", None); mat!(match_email, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", "mine is [email protected] ", Some((8, 26))); mat!(match_email_not, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", "mine is jam.slam@gmail ", None); mat!(match_email_big, r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", "mine is [email protected] ", Some((8, 26))); mat!(match_date1, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-01-01", Some((0, 10))); mat!(match_date2, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-00-01", None); mat!(match_date3, r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "1900-13-01", None); // Exercise the flags. mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4))); mat!(match_flag_case_dotnl_toggle_not, "(?is)a.(?-is)a.", "A\na\n", None); mat!(match_flag_case_dotnl_toggle_ok, "(?is)a.(?-is:a.)?", "A\na\n", Some((0, 2))); mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11))); mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2))); // Some Unicode tests. // A couple of these are commented out because something in the guts of macro // expansion is creating invalid byte strings. // mat!(uni_literal, r"Ⅰ", "Ⅰ", Some((0, 3))) // mat!(uni_case_not, r"Δ", "δ", None) mat!(uni_one, r"\pN", "Ⅰ", Some((0, 3))); mat!(uni_mixed, r"\pN+", "Ⅰ1Ⅱ2", Some((0, 8))); mat!(uni_not, r"\PN+", "abⅠ", Some((0, 2))); mat!(uni_not_class, r"[\PN]+", "abⅠ", Some((0, 2))); mat!(uni_not_class_neg, r"[^\PN]+", "abⅠ", Some((2, 5))); mat!(uni_case, r"(?i)Δ", "δ", Some((0, 2))); mat!(uni_case_upper, r"\p{Lu}+", "ΛΘΓΔα", Some((0, 8))); mat!(uni_case_upper_nocase_flag, r"(?i)\p{Lu}+", "ΛΘΓΔα", Some((0, 10))); mat!(uni_case_upper_nocase, r"\p{L}+", "ΛΘΓΔα", Some((0, 10))); mat!(uni_case_lower, r"\p{Ll}+", "ΛΘΓΔα", Some((8, 10))); // https://github.com/rust-lang/regex/issues/76 mat!(uni_case_lower_nocase_flag, r"(?i)\p{Ll}+", "ΛΘΓΔα", Some((0, 10))); // Test the Unicode friendliness of Perl character classes. mat!(uni_perl_w, r"\w+", "dδd", Some((0, 4))); mat!(uni_perl_w_not, r"\w+", "⥡", None); mat!(uni_perl_w_neg, r"\W+", "⥡", Some((0, 3))); mat!(uni_perl_d, r"\d+", "1२३9", Some((0, 8))); mat!(uni_perl_d_not, r"\d+", "Ⅱ", None); mat!(uni_perl_d_neg, r"\D+", "Ⅱ", Some((0, 3))); mat!(uni_perl_s, r"\s+", " ", Some((0, 3))); mat!(uni_perl_s_not, r"\s+", "☃", None); mat!(uni_perl_s_neg, r"\S+", "☃", Some((0, 3))); // And do the same for word boundaries. mat!(uni_boundary_none, r"\d\b", "6δ", None); mat!(uni_boundary_ogham, r"\d\b", "6 ", Some((0, 1))); // Test negated character classes. mat!(negclass_letters, r"[^ac]", "acx", Some((2, 3))); mat!(negclass_letter_comma, r"[^a,]", "a,x", Some((2, 3))); mat!(negclass_letter_space, r"[^a\s]", "a x", Some((2, 3))); mat!(negclass_comma, r"[^,]", ",,x", Some((2, 3))); mat!(negclass_space, r"[^\s]", " a", Some((1, 2))); mat!(negclass_space_comma, r"[^,\s]", ", a", Some((2, 3))); mat!(negclass_comma_space, r"[^\s,]", ",a", Some((2, 3))); mat!(negclass_ascii, r"[^[:alpha:]Z]", "A1", Some((1, 2))); // Regression test for https://github.com/rust-lang/regex/issues/75 mat!(regression_unsorted_binary_search_1, r"(?i)[a_]+", "A_", Some((0, 2))); mat!(regression_unsorted_binary_search_2, r"(?i)[A_]+", "a_", Some((0, 2))); // Regression tests for https://github.com/rust-lang/regex/issues/99 mat!(regression_negated_char_class_1, r"(?i)[^x]", "x", None); mat!(regression_negated_char_class_2, r"(?i)[^x]", "X", None); // Regression test for https://github.com/rust-lang/regex/issues/101 mat!(regression_ascii_word_underscore, r"[:word:]", "_", Some((0, 1))); // A whole mess of tests from Glenn Fowler's regex test suite. // Generated by the'src/etc/regex-match-tests' program. #[path = "matches.rs"] mod matches;
{ let re = regex!(r"([[-z])"); let ms = re.find_iter("[]").collect::<Vec<_>>(); assert_eq!(ms, vec![(0, 1), (1, 2)]); }
identifier_body
visit_ast.rs
//! The Rust AST Visitor. Extracts useful information and massages it into a form //! usable for `clean`. use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::Node; use rustc_middle::middle::privacy::AccessLevel; use rustc_middle::ty::TyCtxt; use rustc_span; use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Symbol}; use std::mem; use crate::clean::{self, AttributesExt, NestedAttributesExt}; use crate::core; use crate::doctree::*; // FIXME: Should this be replaced with tcx.def_path_str? fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> { let crate_name = tcx.crate_name(did.krate).to_string(); let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| { // extern blocks have an empty name let s = elem.data.to_string(); if!s.is_empty() { Some(s) } else { None } }); std::iter::once(crate_name).chain(relative).collect() } crate fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool { while let Some(id) = tcx.hir().get_enclosing_scope(node) { node = id; if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) { return true; } } false } // Also, is there some reason that this doesn't use the 'visit' // framework from syntax?. crate struct RustdocVisitor<'a, 'tcx> { cx: &'a mut core::DocContext<'tcx>, view_item_stack: FxHashSet<hir::HirId>, inlining: bool, /// Are the current module and all of its parents public? inside_public_path: bool, exact_paths: FxHashMap<DefId, Vec<String>>, } impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { crate fn
(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> { // If the root is re-exported, terminate all recursion. let mut stack = FxHashSet::default(); stack.insert(hir::CRATE_HIR_ID); RustdocVisitor { cx, view_item_stack: stack, inlining: false, inside_public_path: true, exact_paths: FxHashMap::default(), } } fn store_path(&mut self, did: DefId) { let tcx = self.cx.tcx; self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did)); } crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> { let span = krate.module().inner; let mut top_level_module = self.visit_mod_contents( &Spanned { span, node: hir::VisibilityKind::Public }, hir::CRATE_HIR_ID, &krate.module(), self.cx.tcx.crate_name(LOCAL_CRATE), ); // `#[macro_export] macro_rules!` items are reexported at the top level of the // crate, regardless of where they're defined. We want to document the // top level rexport of the macro, not its original definition, since // the rexport defines the path that a user will actually see. Accordingly, // we add the rexport as an item here, and then skip over the original // definition in `visit_item()` below. for export in self.cx.tcx.module_exports(CRATE_DEF_ID).unwrap_or(&[]) { if let Res::Def(DefKind::Macro(_), def_id) = export.res { if let Some(local_def_id) = def_id.as_local() { if self.cx.tcx.has_attr(def_id, sym::macro_export) { let hir_id = self.cx.tcx.hir().local_def_id_to_hir_id(local_def_id); let item = self.cx.tcx.hir().expect_item(hir_id); top_level_module.items.push((item, None)); } } } } self.cx.cache.exact_paths = self.exact_paths; top_level_module } fn visit_mod_contents( &mut self, vis: &hir::Visibility<'_>, id: hir::HirId, m: &'tcx hir::Mod<'tcx>, name: Symbol, ) -> Module<'tcx> { let mut om = Module::new(name, id, m.inner); // Keep track of if there were any private modules in the path. let orig_inside_public_path = self.inside_public_path; self.inside_public_path &= vis.node.is_pub(); for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); self.visit_item(item, None, &mut om); } self.inside_public_path = orig_inside_public_path; om } /// Tries to resolve the target of a `pub use` statement and inlines the /// target if it is defined locally and would not be documented otherwise, /// or when it is specifically requested with `please_inline`. /// (the latter is the case when the import is marked `doc(inline)`) /// /// Cross-crate inlining occurs later on during crate cleaning /// and follows different rules. /// /// Returns `true` if the target has been inlined. fn maybe_inline_local( &mut self, id: hir::HirId, res: Res, renamed: Option<Symbol>, glob: bool, om: &mut Module<'tcx>, please_inline: bool, ) -> bool { debug!("maybe_inline_local res: {:?}", res); let tcx = self.cx.tcx; let res_did = if let Some(did) = res.opt_def_id() { did } else { return false; }; let use_attrs = tcx.hir().attrs(id); // Don't inline `doc(hidden)` imports so they can be stripped at a later stage. let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline) || use_attrs.lists(sym::doc).has_word(sym::hidden); // For cross-crate impl inlining we need to know whether items are // reachable in documentation -- a previously unreachable item can be // made reachable by cross-crate inlining which we're checking here. // (this is done here because we need to know this upfront). if!res_did.is_local() &&!is_no_inline { let attrs = clean::inline::load_attrs(self.cx, res_did); let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden); if!self_is_hidden { if let Res::Def(kind, did) = res { if kind == DefKind::Mod { crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did) } else { // All items need to be handled here in case someone wishes to link // to them with intra-doc links self.cx.cache.access_levels.map.insert(did, AccessLevel::Public); } } } return false; } let res_hir_id = match res_did.as_local() { Some(n) => tcx.hir().local_def_id_to_hir_id(n), None => return false, }; let is_private =!self.cx.cache.access_levels.is_public(res_did); let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id); // Only inline if requested or if the item would otherwise be stripped. if (!please_inline &&!is_private &&!is_hidden) || is_no_inline { return false; } if!self.view_item_stack.insert(res_hir_id) { return false; } let ret = match tcx.hir().get(res_hir_id) { Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m),.. }) if glob => { let prev = mem::replace(&mut self.inlining, true); for &i in m.item_ids { let i = self.cx.tcx.hir().item(i); self.visit_item(i, None, om); } self.inlining = prev; true } Node::Item(it) if!glob => { let prev = mem::replace(&mut self.inlining, true); self.visit_item(it, renamed, om); self.inlining = prev; true } Node::ForeignItem(it) if!glob => { let prev = mem::replace(&mut self.inlining, true); self.visit_foreign_item(it, renamed, om); self.inlining = prev; true } _ => false, }; self.view_item_stack.remove(&res_hir_id); ret } fn visit_item( &mut self, item: &'tcx hir::Item<'_>, renamed: Option<Symbol>, om: &mut Module<'tcx>, ) { debug!("visiting item {:?}", item); let name = renamed.unwrap_or(item.ident.name); let def_id = item.def_id.to_def_id(); let is_pub = item.vis.node.is_pub() || self.cx.tcx.has_attr(def_id, sym::macro_export); if is_pub { self.store_path(item.def_id.to_def_id()); } match item.kind { hir::ItemKind::ForeignMod { items,.. } => { for item in items { let item = self.cx.tcx.hir().foreign_item(item.id); self.visit_foreign_item(item, None, om); } } // If we're inlining, skip private items. _ if self.inlining &&!is_pub => {} hir::ItemKind::GlobalAsm(..) => {} hir::ItemKind::Use(_, hir::UseKind::ListStem) => {} hir::ItemKind::Use(ref path, kind) => { let is_glob = kind == hir::UseKind::Glob; // Struct and variant constructors and proc macro stubs always show up alongside // their definitions, we've already processed them so just discard these. if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res { return; } let attrs = self.cx.tcx.hir().attrs(item.hir_id()); // If there was a private module in the current path then don't bother inlining // anything as it will probably be stripped anyway. if is_pub && self.inside_public_path { let please_inline = attrs.iter().any(|item| match item.meta_item_list() { Some(ref list) if item.has_name(sym::doc) => { list.iter().any(|i| i.has_name(sym::inline)) } _ => false, }); let ident = if is_glob { None } else { Some(name) }; if self.maybe_inline_local( item.hir_id(), path.res, ident, is_glob, om, please_inline, ) { return; } } om.items.push((item, renamed)) } hir::ItemKind::Macro(ref macro_def) => { // `#[macro_export] macro_rules!` items are handled seperately in `visit()`, // above, since they need to be documented at the module top level. Accordingly, // we only want to handle macros if one of three conditions holds: // // 1. This macro was defined by `macro`, and thus isn't covered by the case // above. // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered // by the case above. // 3. We're inlining, since a reexport where inlining has been requested // should be inlined even if it is also documented at the top level. let def_id = item.def_id.to_def_id(); let is_macro_2_0 =!macro_def.macro_rules; let nonexported =!self.cx.tcx.has_attr(def_id, sym::macro_export); if is_macro_2_0 || nonexported || self.inlining { om.items.push((item, renamed)); } } hir::ItemKind::Mod(ref m) => { om.mods.push(self.visit_mod_contents(&item.vis, item.hir_id(), m, name)); } hir::ItemKind::Fn(..) | hir::ItemKind::ExternCrate(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::TyAlias(..) | hir::ItemKind::OpaqueTy(..) | hir::ItemKind::Static(..) | hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)), hir::ItemKind::Const(..) => { // Underscore constants do not correspond to a nameable item and // so are never useful in documentation. if name!= kw::Underscore { om.items.push((item, renamed)); } } hir::ItemKind::Impl(ref impl_) => { // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick // them up regardless of where they're located. if!self.inlining && impl_.of_trait.is_none() { om.items.push((item, None)); } } } } fn visit_foreign_item( &mut self, item: &'tcx hir::ForeignItem<'_>, renamed: Option<Symbol>, om: &mut Module<'tcx>, ) { // If inlining we only want to include public functions. if!self.inlining || item.vis.node.is_pub() { om.foreigns.push((item, renamed)); } } }
new
identifier_name
visit_ast.rs
//! The Rust AST Visitor. Extracts useful information and massages it into a form //! usable for `clean`. use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::Node; use rustc_middle::middle::privacy::AccessLevel; use rustc_middle::ty::TyCtxt; use rustc_span; use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Symbol}; use std::mem; use crate::clean::{self, AttributesExt, NestedAttributesExt}; use crate::core; use crate::doctree::*; // FIXME: Should this be replaced with tcx.def_path_str? fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> { let crate_name = tcx.crate_name(did.krate).to_string(); let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| { // extern blocks have an empty name let s = elem.data.to_string(); if!s.is_empty() { Some(s) } else { None } }); std::iter::once(crate_name).chain(relative).collect() } crate fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool { while let Some(id) = tcx.hir().get_enclosing_scope(node) { node = id; if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) { return true; } } false } // Also, is there some reason that this doesn't use the 'visit' // framework from syntax?. crate struct RustdocVisitor<'a, 'tcx> { cx: &'a mut core::DocContext<'tcx>, view_item_stack: FxHashSet<hir::HirId>, inlining: bool, /// Are the current module and all of its parents public? inside_public_path: bool, exact_paths: FxHashMap<DefId, Vec<String>>, } impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> { // If the root is re-exported, terminate all recursion. let mut stack = FxHashSet::default(); stack.insert(hir::CRATE_HIR_ID); RustdocVisitor { cx, view_item_stack: stack, inlining: false, inside_public_path: true, exact_paths: FxHashMap::default(), } } fn store_path(&mut self, did: DefId) { let tcx = self.cx.tcx; self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did)); } crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> { let span = krate.module().inner; let mut top_level_module = self.visit_mod_contents( &Spanned { span, node: hir::VisibilityKind::Public }, hir::CRATE_HIR_ID, &krate.module(), self.cx.tcx.crate_name(LOCAL_CRATE), ); // `#[macro_export] macro_rules!` items are reexported at the top level of the // crate, regardless of where they're defined. We want to document the // top level rexport of the macro, not its original definition, since // the rexport defines the path that a user will actually see. Accordingly, // we add the rexport as an item here, and then skip over the original // definition in `visit_item()` below. for export in self.cx.tcx.module_exports(CRATE_DEF_ID).unwrap_or(&[]) { if let Res::Def(DefKind::Macro(_), def_id) = export.res { if let Some(local_def_id) = def_id.as_local() { if self.cx.tcx.has_attr(def_id, sym::macro_export) { let hir_id = self.cx.tcx.hir().local_def_id_to_hir_id(local_def_id); let item = self.cx.tcx.hir().expect_item(hir_id); top_level_module.items.push((item, None)); } } } } self.cx.cache.exact_paths = self.exact_paths; top_level_module } fn visit_mod_contents( &mut self, vis: &hir::Visibility<'_>, id: hir::HirId, m: &'tcx hir::Mod<'tcx>, name: Symbol, ) -> Module<'tcx> { let mut om = Module::new(name, id, m.inner); // Keep track of if there were any private modules in the path. let orig_inside_public_path = self.inside_public_path; self.inside_public_path &= vis.node.is_pub(); for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); self.visit_item(item, None, &mut om); } self.inside_public_path = orig_inside_public_path; om } /// Tries to resolve the target of a `pub use` statement and inlines the /// target if it is defined locally and would not be documented otherwise, /// or when it is specifically requested with `please_inline`. /// (the latter is the case when the import is marked `doc(inline)`) /// /// Cross-crate inlining occurs later on during crate cleaning /// and follows different rules. /// /// Returns `true` if the target has been inlined. fn maybe_inline_local( &mut self, id: hir::HirId, res: Res, renamed: Option<Symbol>, glob: bool, om: &mut Module<'tcx>, please_inline: bool, ) -> bool { debug!("maybe_inline_local res: {:?}", res); let tcx = self.cx.tcx; let res_did = if let Some(did) = res.opt_def_id() { did } else { return false; }; let use_attrs = tcx.hir().attrs(id); // Don't inline `doc(hidden)` imports so they can be stripped at a later stage. let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline) || use_attrs.lists(sym::doc).has_word(sym::hidden); // For cross-crate impl inlining we need to know whether items are // reachable in documentation -- a previously unreachable item can be // made reachable by cross-crate inlining which we're checking here. // (this is done here because we need to know this upfront). if!res_did.is_local() &&!is_no_inline { let attrs = clean::inline::load_attrs(self.cx, res_did); let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden); if!self_is_hidden { if let Res::Def(kind, did) = res { if kind == DefKind::Mod { crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did) } else { // All items need to be handled here in case someone wishes to link // to them with intra-doc links self.cx.cache.access_levels.map.insert(did, AccessLevel::Public); } } } return false; } let res_hir_id = match res_did.as_local() { Some(n) => tcx.hir().local_def_id_to_hir_id(n), None => return false, }; let is_private =!self.cx.cache.access_levels.is_public(res_did); let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id); // Only inline if requested or if the item would otherwise be stripped. if (!please_inline &&!is_private &&!is_hidden) || is_no_inline { return false; } if!self.view_item_stack.insert(res_hir_id) { return false; } let ret = match tcx.hir().get(res_hir_id) { Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m),.. }) if glob => { let prev = mem::replace(&mut self.inlining, true); for &i in m.item_ids { let i = self.cx.tcx.hir().item(i); self.visit_item(i, None, om); } self.inlining = prev; true } Node::Item(it) if!glob => { let prev = mem::replace(&mut self.inlining, true); self.visit_item(it, renamed, om); self.inlining = prev; true } Node::ForeignItem(it) if!glob => { let prev = mem::replace(&mut self.inlining, true); self.visit_foreign_item(it, renamed, om); self.inlining = prev; true } _ => false, }; self.view_item_stack.remove(&res_hir_id); ret } fn visit_item( &mut self, item: &'tcx hir::Item<'_>, renamed: Option<Symbol>, om: &mut Module<'tcx>, ) { debug!("visiting item {:?}", item); let name = renamed.unwrap_or(item.ident.name); let def_id = item.def_id.to_def_id(); let is_pub = item.vis.node.is_pub() || self.cx.tcx.has_attr(def_id, sym::macro_export); if is_pub { self.store_path(item.def_id.to_def_id()); } match item.kind { hir::ItemKind::ForeignMod { items,.. } => { for item in items { let item = self.cx.tcx.hir().foreign_item(item.id); self.visit_foreign_item(item, None, om); } } // If we're inlining, skip private items. _ if self.inlining &&!is_pub => {} hir::ItemKind::GlobalAsm(..) => {} hir::ItemKind::Use(_, hir::UseKind::ListStem) => {} hir::ItemKind::Use(ref path, kind) => { let is_glob = kind == hir::UseKind::Glob; // Struct and variant constructors and proc macro stubs always show up alongside // their definitions, we've already processed them so just discard these. if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res { return; } let attrs = self.cx.tcx.hir().attrs(item.hir_id()); // If there was a private module in the current path then don't bother inlining // anything as it will probably be stripped anyway. if is_pub && self.inside_public_path { let please_inline = attrs.iter().any(|item| match item.meta_item_list() { Some(ref list) if item.has_name(sym::doc) => { list.iter().any(|i| i.has_name(sym::inline)) } _ => false, }); let ident = if is_glob { None } else { Some(name) }; if self.maybe_inline_local( item.hir_id(), path.res, ident, is_glob, om, please_inline, ) { return; } } om.items.push((item, renamed)) } hir::ItemKind::Macro(ref macro_def) => { // `#[macro_export] macro_rules!` items are handled seperately in `visit()`, // above, since they need to be documented at the module top level. Accordingly, // we only want to handle macros if one of three conditions holds: // // 1. This macro was defined by `macro`, and thus isn't covered by the case // above.
// should be inlined even if it is also documented at the top level. let def_id = item.def_id.to_def_id(); let is_macro_2_0 =!macro_def.macro_rules; let nonexported =!self.cx.tcx.has_attr(def_id, sym::macro_export); if is_macro_2_0 || nonexported || self.inlining { om.items.push((item, renamed)); } } hir::ItemKind::Mod(ref m) => { om.mods.push(self.visit_mod_contents(&item.vis, item.hir_id(), m, name)); } hir::ItemKind::Fn(..) | hir::ItemKind::ExternCrate(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::TyAlias(..) | hir::ItemKind::OpaqueTy(..) | hir::ItemKind::Static(..) | hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)), hir::ItemKind::Const(..) => { // Underscore constants do not correspond to a nameable item and // so are never useful in documentation. if name!= kw::Underscore { om.items.push((item, renamed)); } } hir::ItemKind::Impl(ref impl_) => { // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick // them up regardless of where they're located. if!self.inlining && impl_.of_trait.is_none() { om.items.push((item, None)); } } } } fn visit_foreign_item( &mut self, item: &'tcx hir::ForeignItem<'_>, renamed: Option<Symbol>, om: &mut Module<'tcx>, ) { // If inlining we only want to include public functions. if!self.inlining || item.vis.node.is_pub() { om.foreigns.push((item, renamed)); } } }
// 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered // by the case above. // 3. We're inlining, since a reexport where inlining has been requested
random_line_split
visit_ast.rs
//! The Rust AST Visitor. Extracts useful information and massages it into a form //! usable for `clean`. use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::Node; use rustc_middle::middle::privacy::AccessLevel; use rustc_middle::ty::TyCtxt; use rustc_span; use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Symbol}; use std::mem; use crate::clean::{self, AttributesExt, NestedAttributesExt}; use crate::core; use crate::doctree::*; // FIXME: Should this be replaced with tcx.def_path_str? fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> { let crate_name = tcx.crate_name(did.krate).to_string(); let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| { // extern blocks have an empty name let s = elem.data.to_string(); if!s.is_empty() { Some(s) } else { None } }); std::iter::once(crate_name).chain(relative).collect() } crate fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool { while let Some(id) = tcx.hir().get_enclosing_scope(node) { node = id; if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) { return true; } } false } // Also, is there some reason that this doesn't use the 'visit' // framework from syntax?. crate struct RustdocVisitor<'a, 'tcx> { cx: &'a mut core::DocContext<'tcx>, view_item_stack: FxHashSet<hir::HirId>, inlining: bool, /// Are the current module and all of its parents public? inside_public_path: bool, exact_paths: FxHashMap<DefId, Vec<String>>, } impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> { // If the root is re-exported, terminate all recursion. let mut stack = FxHashSet::default(); stack.insert(hir::CRATE_HIR_ID); RustdocVisitor { cx, view_item_stack: stack, inlining: false, inside_public_path: true, exact_paths: FxHashMap::default(), } } fn store_path(&mut self, did: DefId) { let tcx = self.cx.tcx; self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did)); } crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> { let span = krate.module().inner; let mut top_level_module = self.visit_mod_contents( &Spanned { span, node: hir::VisibilityKind::Public }, hir::CRATE_HIR_ID, &krate.module(), self.cx.tcx.crate_name(LOCAL_CRATE), ); // `#[macro_export] macro_rules!` items are reexported at the top level of the // crate, regardless of where they're defined. We want to document the // top level rexport of the macro, not its original definition, since // the rexport defines the path that a user will actually see. Accordingly, // we add the rexport as an item here, and then skip over the original // definition in `visit_item()` below. for export in self.cx.tcx.module_exports(CRATE_DEF_ID).unwrap_or(&[]) { if let Res::Def(DefKind::Macro(_), def_id) = export.res { if let Some(local_def_id) = def_id.as_local() { if self.cx.tcx.has_attr(def_id, sym::macro_export) { let hir_id = self.cx.tcx.hir().local_def_id_to_hir_id(local_def_id); let item = self.cx.tcx.hir().expect_item(hir_id); top_level_module.items.push((item, None)); } } } } self.cx.cache.exact_paths = self.exact_paths; top_level_module } fn visit_mod_contents( &mut self, vis: &hir::Visibility<'_>, id: hir::HirId, m: &'tcx hir::Mod<'tcx>, name: Symbol, ) -> Module<'tcx> { let mut om = Module::new(name, id, m.inner); // Keep track of if there were any private modules in the path. let orig_inside_public_path = self.inside_public_path; self.inside_public_path &= vis.node.is_pub(); for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); self.visit_item(item, None, &mut om); } self.inside_public_path = orig_inside_public_path; om } /// Tries to resolve the target of a `pub use` statement and inlines the /// target if it is defined locally and would not be documented otherwise, /// or when it is specifically requested with `please_inline`. /// (the latter is the case when the import is marked `doc(inline)`) /// /// Cross-crate inlining occurs later on during crate cleaning /// and follows different rules. /// /// Returns `true` if the target has been inlined. fn maybe_inline_local( &mut self, id: hir::HirId, res: Res, renamed: Option<Symbol>, glob: bool, om: &mut Module<'tcx>, please_inline: bool, ) -> bool { debug!("maybe_inline_local res: {:?}", res); let tcx = self.cx.tcx; let res_did = if let Some(did) = res.opt_def_id() { did } else { return false; }; let use_attrs = tcx.hir().attrs(id); // Don't inline `doc(hidden)` imports so they can be stripped at a later stage. let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline) || use_attrs.lists(sym::doc).has_word(sym::hidden); // For cross-crate impl inlining we need to know whether items are // reachable in documentation -- a previously unreachable item can be // made reachable by cross-crate inlining which we're checking here. // (this is done here because we need to know this upfront). if!res_did.is_local() &&!is_no_inline { let attrs = clean::inline::load_attrs(self.cx, res_did); let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden); if!self_is_hidden { if let Res::Def(kind, did) = res { if kind == DefKind::Mod { crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did) } else { // All items need to be handled here in case someone wishes to link // to them with intra-doc links self.cx.cache.access_levels.map.insert(did, AccessLevel::Public); } } } return false; } let res_hir_id = match res_did.as_local() { Some(n) => tcx.hir().local_def_id_to_hir_id(n), None => return false, }; let is_private =!self.cx.cache.access_levels.is_public(res_did); let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id); // Only inline if requested or if the item would otherwise be stripped. if (!please_inline &&!is_private &&!is_hidden) || is_no_inline { return false; } if!self.view_item_stack.insert(res_hir_id) { return false; } let ret = match tcx.hir().get(res_hir_id) { Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m),.. }) if glob => { let prev = mem::replace(&mut self.inlining, true); for &i in m.item_ids { let i = self.cx.tcx.hir().item(i); self.visit_item(i, None, om); } self.inlining = prev; true } Node::Item(it) if!glob => { let prev = mem::replace(&mut self.inlining, true); self.visit_item(it, renamed, om); self.inlining = prev; true } Node::ForeignItem(it) if!glob => { let prev = mem::replace(&mut self.inlining, true); self.visit_foreign_item(it, renamed, om); self.inlining = prev; true } _ => false, }; self.view_item_stack.remove(&res_hir_id); ret } fn visit_item( &mut self, item: &'tcx hir::Item<'_>, renamed: Option<Symbol>, om: &mut Module<'tcx>, ) { debug!("visiting item {:?}", item); let name = renamed.unwrap_or(item.ident.name); let def_id = item.def_id.to_def_id(); let is_pub = item.vis.node.is_pub() || self.cx.tcx.has_attr(def_id, sym::macro_export); if is_pub { self.store_path(item.def_id.to_def_id()); } match item.kind { hir::ItemKind::ForeignMod { items,.. } => { for item in items { let item = self.cx.tcx.hir().foreign_item(item.id); self.visit_foreign_item(item, None, om); } } // If we're inlining, skip private items. _ if self.inlining &&!is_pub => {} hir::ItemKind::GlobalAsm(..) => {} hir::ItemKind::Use(_, hir::UseKind::ListStem) => {} hir::ItemKind::Use(ref path, kind) => { let is_glob = kind == hir::UseKind::Glob; // Struct and variant constructors and proc macro stubs always show up alongside // their definitions, we've already processed them so just discard these. if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res
let attrs = self.cx.tcx.hir().attrs(item.hir_id()); // If there was a private module in the current path then don't bother inlining // anything as it will probably be stripped anyway. if is_pub && self.inside_public_path { let please_inline = attrs.iter().any(|item| match item.meta_item_list() { Some(ref list) if item.has_name(sym::doc) => { list.iter().any(|i| i.has_name(sym::inline)) } _ => false, }); let ident = if is_glob { None } else { Some(name) }; if self.maybe_inline_local( item.hir_id(), path.res, ident, is_glob, om, please_inline, ) { return; } } om.items.push((item, renamed)) } hir::ItemKind::Macro(ref macro_def) => { // `#[macro_export] macro_rules!` items are handled seperately in `visit()`, // above, since they need to be documented at the module top level. Accordingly, // we only want to handle macros if one of three conditions holds: // // 1. This macro was defined by `macro`, and thus isn't covered by the case // above. // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered // by the case above. // 3. We're inlining, since a reexport where inlining has been requested // should be inlined even if it is also documented at the top level. let def_id = item.def_id.to_def_id(); let is_macro_2_0 =!macro_def.macro_rules; let nonexported =!self.cx.tcx.has_attr(def_id, sym::macro_export); if is_macro_2_0 || nonexported || self.inlining { om.items.push((item, renamed)); } } hir::ItemKind::Mod(ref m) => { om.mods.push(self.visit_mod_contents(&item.vis, item.hir_id(), m, name)); } hir::ItemKind::Fn(..) | hir::ItemKind::ExternCrate(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::TyAlias(..) | hir::ItemKind::OpaqueTy(..) | hir::ItemKind::Static(..) | hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)), hir::ItemKind::Const(..) => { // Underscore constants do not correspond to a nameable item and // so are never useful in documentation. if name!= kw::Underscore { om.items.push((item, renamed)); } } hir::ItemKind::Impl(ref impl_) => { // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick // them up regardless of where they're located. if!self.inlining && impl_.of_trait.is_none() { om.items.push((item, None)); } } } } fn visit_foreign_item( &mut self, item: &'tcx hir::ForeignItem<'_>, renamed: Option<Symbol>, om: &mut Module<'tcx>, ) { // If inlining we only want to include public functions. if!self.inlining || item.vis.node.is_pub() { om.foreigns.push((item, renamed)); } } }
{ return; }
conditional_block
visit_ast.rs
//! The Rust AST Visitor. Extracts useful information and massages it into a form //! usable for `clean`. use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::Node; use rustc_middle::middle::privacy::AccessLevel; use rustc_middle::ty::TyCtxt; use rustc_span; use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Symbol}; use std::mem; use crate::clean::{self, AttributesExt, NestedAttributesExt}; use crate::core; use crate::doctree::*; // FIXME: Should this be replaced with tcx.def_path_str? fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> { let crate_name = tcx.crate_name(did.krate).to_string(); let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| { // extern blocks have an empty name let s = elem.data.to_string(); if!s.is_empty() { Some(s) } else { None } }); std::iter::once(crate_name).chain(relative).collect() } crate fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool
// Also, is there some reason that this doesn't use the 'visit' // framework from syntax?. crate struct RustdocVisitor<'a, 'tcx> { cx: &'a mut core::DocContext<'tcx>, view_item_stack: FxHashSet<hir::HirId>, inlining: bool, /// Are the current module and all of its parents public? inside_public_path: bool, exact_paths: FxHashMap<DefId, Vec<String>>, } impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> { // If the root is re-exported, terminate all recursion. let mut stack = FxHashSet::default(); stack.insert(hir::CRATE_HIR_ID); RustdocVisitor { cx, view_item_stack: stack, inlining: false, inside_public_path: true, exact_paths: FxHashMap::default(), } } fn store_path(&mut self, did: DefId) { let tcx = self.cx.tcx; self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did)); } crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> { let span = krate.module().inner; let mut top_level_module = self.visit_mod_contents( &Spanned { span, node: hir::VisibilityKind::Public }, hir::CRATE_HIR_ID, &krate.module(), self.cx.tcx.crate_name(LOCAL_CRATE), ); // `#[macro_export] macro_rules!` items are reexported at the top level of the // crate, regardless of where they're defined. We want to document the // top level rexport of the macro, not its original definition, since // the rexport defines the path that a user will actually see. Accordingly, // we add the rexport as an item here, and then skip over the original // definition in `visit_item()` below. for export in self.cx.tcx.module_exports(CRATE_DEF_ID).unwrap_or(&[]) { if let Res::Def(DefKind::Macro(_), def_id) = export.res { if let Some(local_def_id) = def_id.as_local() { if self.cx.tcx.has_attr(def_id, sym::macro_export) { let hir_id = self.cx.tcx.hir().local_def_id_to_hir_id(local_def_id); let item = self.cx.tcx.hir().expect_item(hir_id); top_level_module.items.push((item, None)); } } } } self.cx.cache.exact_paths = self.exact_paths; top_level_module } fn visit_mod_contents( &mut self, vis: &hir::Visibility<'_>, id: hir::HirId, m: &'tcx hir::Mod<'tcx>, name: Symbol, ) -> Module<'tcx> { let mut om = Module::new(name, id, m.inner); // Keep track of if there were any private modules in the path. let orig_inside_public_path = self.inside_public_path; self.inside_public_path &= vis.node.is_pub(); for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); self.visit_item(item, None, &mut om); } self.inside_public_path = orig_inside_public_path; om } /// Tries to resolve the target of a `pub use` statement and inlines the /// target if it is defined locally and would not be documented otherwise, /// or when it is specifically requested with `please_inline`. /// (the latter is the case when the import is marked `doc(inline)`) /// /// Cross-crate inlining occurs later on during crate cleaning /// and follows different rules. /// /// Returns `true` if the target has been inlined. fn maybe_inline_local( &mut self, id: hir::HirId, res: Res, renamed: Option<Symbol>, glob: bool, om: &mut Module<'tcx>, please_inline: bool, ) -> bool { debug!("maybe_inline_local res: {:?}", res); let tcx = self.cx.tcx; let res_did = if let Some(did) = res.opt_def_id() { did } else { return false; }; let use_attrs = tcx.hir().attrs(id); // Don't inline `doc(hidden)` imports so they can be stripped at a later stage. let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline) || use_attrs.lists(sym::doc).has_word(sym::hidden); // For cross-crate impl inlining we need to know whether items are // reachable in documentation -- a previously unreachable item can be // made reachable by cross-crate inlining which we're checking here. // (this is done here because we need to know this upfront). if!res_did.is_local() &&!is_no_inline { let attrs = clean::inline::load_attrs(self.cx, res_did); let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden); if!self_is_hidden { if let Res::Def(kind, did) = res { if kind == DefKind::Mod { crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did) } else { // All items need to be handled here in case someone wishes to link // to them with intra-doc links self.cx.cache.access_levels.map.insert(did, AccessLevel::Public); } } } return false; } let res_hir_id = match res_did.as_local() { Some(n) => tcx.hir().local_def_id_to_hir_id(n), None => return false, }; let is_private =!self.cx.cache.access_levels.is_public(res_did); let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id); // Only inline if requested or if the item would otherwise be stripped. if (!please_inline &&!is_private &&!is_hidden) || is_no_inline { return false; } if!self.view_item_stack.insert(res_hir_id) { return false; } let ret = match tcx.hir().get(res_hir_id) { Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m),.. }) if glob => { let prev = mem::replace(&mut self.inlining, true); for &i in m.item_ids { let i = self.cx.tcx.hir().item(i); self.visit_item(i, None, om); } self.inlining = prev; true } Node::Item(it) if!glob => { let prev = mem::replace(&mut self.inlining, true); self.visit_item(it, renamed, om); self.inlining = prev; true } Node::ForeignItem(it) if!glob => { let prev = mem::replace(&mut self.inlining, true); self.visit_foreign_item(it, renamed, om); self.inlining = prev; true } _ => false, }; self.view_item_stack.remove(&res_hir_id); ret } fn visit_item( &mut self, item: &'tcx hir::Item<'_>, renamed: Option<Symbol>, om: &mut Module<'tcx>, ) { debug!("visiting item {:?}", item); let name = renamed.unwrap_or(item.ident.name); let def_id = item.def_id.to_def_id(); let is_pub = item.vis.node.is_pub() || self.cx.tcx.has_attr(def_id, sym::macro_export); if is_pub { self.store_path(item.def_id.to_def_id()); } match item.kind { hir::ItemKind::ForeignMod { items,.. } => { for item in items { let item = self.cx.tcx.hir().foreign_item(item.id); self.visit_foreign_item(item, None, om); } } // If we're inlining, skip private items. _ if self.inlining &&!is_pub => {} hir::ItemKind::GlobalAsm(..) => {} hir::ItemKind::Use(_, hir::UseKind::ListStem) => {} hir::ItemKind::Use(ref path, kind) => { let is_glob = kind == hir::UseKind::Glob; // Struct and variant constructors and proc macro stubs always show up alongside // their definitions, we've already processed them so just discard these. if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res { return; } let attrs = self.cx.tcx.hir().attrs(item.hir_id()); // If there was a private module in the current path then don't bother inlining // anything as it will probably be stripped anyway. if is_pub && self.inside_public_path { let please_inline = attrs.iter().any(|item| match item.meta_item_list() { Some(ref list) if item.has_name(sym::doc) => { list.iter().any(|i| i.has_name(sym::inline)) } _ => false, }); let ident = if is_glob { None } else { Some(name) }; if self.maybe_inline_local( item.hir_id(), path.res, ident, is_glob, om, please_inline, ) { return; } } om.items.push((item, renamed)) } hir::ItemKind::Macro(ref macro_def) => { // `#[macro_export] macro_rules!` items are handled seperately in `visit()`, // above, since they need to be documented at the module top level. Accordingly, // we only want to handle macros if one of three conditions holds: // // 1. This macro was defined by `macro`, and thus isn't covered by the case // above. // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered // by the case above. // 3. We're inlining, since a reexport where inlining has been requested // should be inlined even if it is also documented at the top level. let def_id = item.def_id.to_def_id(); let is_macro_2_0 =!macro_def.macro_rules; let nonexported =!self.cx.tcx.has_attr(def_id, sym::macro_export); if is_macro_2_0 || nonexported || self.inlining { om.items.push((item, renamed)); } } hir::ItemKind::Mod(ref m) => { om.mods.push(self.visit_mod_contents(&item.vis, item.hir_id(), m, name)); } hir::ItemKind::Fn(..) | hir::ItemKind::ExternCrate(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::TyAlias(..) | hir::ItemKind::OpaqueTy(..) | hir::ItemKind::Static(..) | hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)), hir::ItemKind::Const(..) => { // Underscore constants do not correspond to a nameable item and // so are never useful in documentation. if name!= kw::Underscore { om.items.push((item, renamed)); } } hir::ItemKind::Impl(ref impl_) => { // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick // them up regardless of where they're located. if!self.inlining && impl_.of_trait.is_none() { om.items.push((item, None)); } } } } fn visit_foreign_item( &mut self, item: &'tcx hir::ForeignItem<'_>, renamed: Option<Symbol>, om: &mut Module<'tcx>, ) { // If inlining we only want to include public functions. if!self.inlining || item.vis.node.is_pub() { om.foreigns.push((item, renamed)); } } }
{ while let Some(id) = tcx.hir().get_enclosing_scope(node) { node = id; if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) { return true; } } false }
identifier_body
lib.rs
mod front_of_house; mod back_of_house; pub use crate::front_of_house::{hosting,serving}; pub use crate::back_of_house::{kitchen,special_services}; pub use crate::back_of_house::Appetizer::{Soup,Salad,NoApp}; pub use crate::back_of_house::Toast::{White,Wheat,Rye,SourDough}; pub use crate::back_of_house::Breakfast; pub fn
() { println!(); hosting::add_to_waitlist("Dr. Strange"); hosting::seat_at_table(); serving::take_order(Rye, Soup); serving::serve_order(); special_services::fix_incorrect_order(); serving::take_payment(); println!(); hosting::add_to_waitlist("Mr. Bogus"); hosting::seat_at_table(); serving::take_order(White, NoApp); serving::serve_order(); serving::take_payment(); special_services::call_bouncer(); println!(); hosting::add_to_waitlist("Miss Nami"); hosting::seat_at_table(); serving::take_order(SourDough, Salad); serving::serve_order(); serving::take_payment(); }
eat_at_restaurant
identifier_name
lib.rs
mod front_of_house; mod back_of_house; pub use crate::front_of_house::{hosting,serving}; pub use crate::back_of_house::{kitchen,special_services}; pub use crate::back_of_house::Appetizer::{Soup,Salad,NoApp}; pub use crate::back_of_house::Toast::{White,Wheat,Rye,SourDough}; pub use crate::back_of_house::Breakfast; pub fn eat_at_restaurant() { println!(); hosting::add_to_waitlist("Dr. Strange"); hosting::seat_at_table(); serving::take_order(Rye, Soup); serving::serve_order(); special_services::fix_incorrect_order();
hosting::seat_at_table(); serving::take_order(White, NoApp); serving::serve_order(); serving::take_payment(); special_services::call_bouncer(); println!(); hosting::add_to_waitlist("Miss Nami"); hosting::seat_at_table(); serving::take_order(SourDough, Salad); serving::serve_order(); serving::take_payment(); }
serving::take_payment(); println!(); hosting::add_to_waitlist("Mr. Bogus");
random_line_split
lib.rs
mod front_of_house; mod back_of_house; pub use crate::front_of_house::{hosting,serving}; pub use crate::back_of_house::{kitchen,special_services}; pub use crate::back_of_house::Appetizer::{Soup,Salad,NoApp}; pub use crate::back_of_house::Toast::{White,Wheat,Rye,SourDough}; pub use crate::back_of_house::Breakfast; pub fn eat_at_restaurant()
hosting::add_to_waitlist("Miss Nami"); hosting::seat_at_table(); serving::take_order(SourDough, Salad); serving::serve_order(); serving::take_payment(); }
{ println!(); hosting::add_to_waitlist("Dr. Strange"); hosting::seat_at_table(); serving::take_order(Rye, Soup); serving::serve_order(); special_services::fix_incorrect_order(); serving::take_payment(); println!(); hosting::add_to_waitlist("Mr. Bogus"); hosting::seat_at_table(); serving::take_order(White, NoApp); serving::serve_order(); serving::take_payment(); special_services::call_bouncer(); println!();
identifier_body
kill.rs
use anyhow::Result; use pretty_assertions::assert_eq; use rstest::rstest; use pueue_lib::network::message::*; use pueue_lib::state::GroupStatus; use pueue_lib::task::*; use crate::fixtures::*; use crate::helper::*; #[rstest] #[case( Message::Kill(KillMessage { tasks: TaskSelection::All, children: false, signal: None, }), true )] #[case( Message::Kill(KillMessage { tasks: TaskSelection::Group(PUEUE_DEFAULT_GROUP.into()), children: false, signal: None, }), true )] #[case( Message::Kill(KillMessage { tasks: TaskSelection::TaskIds(vec![0, 1, 2]), children: false, signal: None, }), false )] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] /// Test if killing running tasks works as intended. /// /// We test different ways of killing those tasks. /// - Via the --all flag, which just kills everything. /// - Via the --group flag, which just kills everything in the default group. /// - Via specific ids. /// /// If a whole group or everything is killed, the respective groups should also be paused! /// This is security measure to prevent unwanted task execution in an emergency. async fn
( #[case] kill_message: Message, #[case] group_should_pause: bool, ) -> Result<()> { let daemon = daemon().await?; let shared = &daemon.settings.shared; // Add multiple tasks and start them immediately for _ in 0..3 { assert_success(add_task(shared, "sleep 60", true).await?); } // Wait until all tasks are running for id in 0..3 { wait_for_task_condition(shared, id, |task| task.is_running()).await?; } // Send the kill message send_message(shared, kill_message).await?; // Make sure all tasks get killed for id in 0..3 { wait_for_task_condition(shared, id, |task| { matches!(task.status, TaskStatus::Done(TaskResult::Killed)) }) .await?; } // Groups should be paused in specific modes. if group_should_pause { let state = get_state(shared).await?; assert_eq!( state.groups.get(PUEUE_DEFAULT_GROUP).unwrap().status, GroupStatus::Paused ); } Ok(()) }
test_kill_tasks
identifier_name
kill.rs
use anyhow::Result; use pretty_assertions::assert_eq; use rstest::rstest; use pueue_lib::network::message::*; use pueue_lib::state::GroupStatus; use pueue_lib::task::*; use crate::fixtures::*; use crate::helper::*; #[rstest] #[case( Message::Kill(KillMessage { tasks: TaskSelection::All, children: false, signal: None, }), true )] #[case( Message::Kill(KillMessage { tasks: TaskSelection::Group(PUEUE_DEFAULT_GROUP.into()), children: false, signal: None, }), true )] #[case( Message::Kill(KillMessage { tasks: TaskSelection::TaskIds(vec![0, 1, 2]), children: false, signal: None, }), false )] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] /// Test if killing running tasks works as intended. ///
/// /// If a whole group or everything is killed, the respective groups should also be paused! /// This is security measure to prevent unwanted task execution in an emergency. async fn test_kill_tasks( #[case] kill_message: Message, #[case] group_should_pause: bool, ) -> Result<()> { let daemon = daemon().await?; let shared = &daemon.settings.shared; // Add multiple tasks and start them immediately for _ in 0..3 { assert_success(add_task(shared, "sleep 60", true).await?); } // Wait until all tasks are running for id in 0..3 { wait_for_task_condition(shared, id, |task| task.is_running()).await?; } // Send the kill message send_message(shared, kill_message).await?; // Make sure all tasks get killed for id in 0..3 { wait_for_task_condition(shared, id, |task| { matches!(task.status, TaskStatus::Done(TaskResult::Killed)) }) .await?; } // Groups should be paused in specific modes. if group_should_pause { let state = get_state(shared).await?; assert_eq!( state.groups.get(PUEUE_DEFAULT_GROUP).unwrap().status, GroupStatus::Paused ); } Ok(()) }
/// We test different ways of killing those tasks. /// - Via the --all flag, which just kills everything. /// - Via the --group flag, which just kills everything in the default group. /// - Via specific ids.
random_line_split
kill.rs
use anyhow::Result; use pretty_assertions::assert_eq; use rstest::rstest; use pueue_lib::network::message::*; use pueue_lib::state::GroupStatus; use pueue_lib::task::*; use crate::fixtures::*; use crate::helper::*; #[rstest] #[case( Message::Kill(KillMessage { tasks: TaskSelection::All, children: false, signal: None, }), true )] #[case( Message::Kill(KillMessage { tasks: TaskSelection::Group(PUEUE_DEFAULT_GROUP.into()), children: false, signal: None, }), true )] #[case( Message::Kill(KillMessage { tasks: TaskSelection::TaskIds(vec![0, 1, 2]), children: false, signal: None, }), false )] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] /// Test if killing running tasks works as intended. /// /// We test different ways of killing those tasks. /// - Via the --all flag, which just kills everything. /// - Via the --group flag, which just kills everything in the default group. /// - Via specific ids. /// /// If a whole group or everything is killed, the respective groups should also be paused! /// This is security measure to prevent unwanted task execution in an emergency. async fn test_kill_tasks( #[case] kill_message: Message, #[case] group_should_pause: bool, ) -> Result<()>
}) .await?; } // Groups should be paused in specific modes. if group_should_pause { let state = get_state(shared).await?; assert_eq!( state.groups.get(PUEUE_DEFAULT_GROUP).unwrap().status, GroupStatus::Paused ); } Ok(()) }
{ let daemon = daemon().await?; let shared = &daemon.settings.shared; // Add multiple tasks and start them immediately for _ in 0..3 { assert_success(add_task(shared, "sleep 60", true).await?); } // Wait until all tasks are running for id in 0..3 { wait_for_task_condition(shared, id, |task| task.is_running()).await?; } // Send the kill message send_message(shared, kill_message).await?; // Make sure all tasks get killed for id in 0..3 { wait_for_task_condition(shared, id, |task| { matches!(task.status, TaskStatus::Done(TaskResult::Killed))
identifier_body
kill.rs
use anyhow::Result; use pretty_assertions::assert_eq; use rstest::rstest; use pueue_lib::network::message::*; use pueue_lib::state::GroupStatus; use pueue_lib::task::*; use crate::fixtures::*; use crate::helper::*; #[rstest] #[case( Message::Kill(KillMessage { tasks: TaskSelection::All, children: false, signal: None, }), true )] #[case( Message::Kill(KillMessage { tasks: TaskSelection::Group(PUEUE_DEFAULT_GROUP.into()), children: false, signal: None, }), true )] #[case( Message::Kill(KillMessage { tasks: TaskSelection::TaskIds(vec![0, 1, 2]), children: false, signal: None, }), false )] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] /// Test if killing running tasks works as intended. /// /// We test different ways of killing those tasks. /// - Via the --all flag, which just kills everything. /// - Via the --group flag, which just kills everything in the default group. /// - Via specific ids. /// /// If a whole group or everything is killed, the respective groups should also be paused! /// This is security measure to prevent unwanted task execution in an emergency. async fn test_kill_tasks( #[case] kill_message: Message, #[case] group_should_pause: bool, ) -> Result<()> { let daemon = daemon().await?; let shared = &daemon.settings.shared; // Add multiple tasks and start them immediately for _ in 0..3 { assert_success(add_task(shared, "sleep 60", true).await?); } // Wait until all tasks are running for id in 0..3 { wait_for_task_condition(shared, id, |task| task.is_running()).await?; } // Send the kill message send_message(shared, kill_message).await?; // Make sure all tasks get killed for id in 0..3 { wait_for_task_condition(shared, id, |task| { matches!(task.status, TaskStatus::Done(TaskResult::Killed)) }) .await?; } // Groups should be paused in specific modes. if group_should_pause
Ok(()) }
{ let state = get_state(shared).await?; assert_eq!( state.groups.get(PUEUE_DEFAULT_GROUP).unwrap().status, GroupStatus::Paused ); }
conditional_block
tests.rs
use super::*; fn create_graph() -> VecGraph<usize>
#[test] fn num_nodes() { let graph = create_graph(); assert_eq!(graph.num_nodes(), 7); } #[test] fn successors() { let graph = create_graph(); assert_eq!(graph.successors(0), &[1]); assert_eq!(graph.successors(1), &[2, 3]); assert_eq!(graph.successors(2), &[]); assert_eq!(graph.successors(3), &[4]); assert_eq!(graph.successors(4), &[]); assert_eq!(graph.successors(5), &[1]); assert_eq!(graph.successors(6), &[]); } #[test] fn dfs() { let graph = create_graph(); let dfs: Vec<_> = graph.depth_first_search(0).collect(); assert_eq!(dfs, vec![0, 1, 3, 4, 2]); }
{ // Create a simple graph // // 5 // | // V // 0 --> 1 --> 2 // | // v // 3 --> 4 // // 6 VecGraph::new(7, vec![(0, 1), (1, 2), (1, 3), (3, 4), (5, 1)]) }
identifier_body
tests.rs
use super::*; fn
() -> VecGraph<usize> { // Create a simple graph // // 5 // | // V // 0 --> 1 --> 2 // | // v // 3 --> 4 // // 6 VecGraph::new(7, vec![(0, 1), (1, 2), (1, 3), (3, 4), (5, 1)]) } #[test] fn num_nodes() { let graph = create_graph(); assert_eq!(graph.num_nodes(), 7); } #[test] fn successors() { let graph = create_graph(); assert_eq!(graph.successors(0), &[1]); assert_eq!(graph.successors(1), &[2, 3]); assert_eq!(graph.successors(2), &[]); assert_eq!(graph.successors(3), &[4]); assert_eq!(graph.successors(4), &[]); assert_eq!(graph.successors(5), &[1]); assert_eq!(graph.successors(6), &[]); } #[test] fn dfs() { let graph = create_graph(); let dfs: Vec<_> = graph.depth_first_search(0).collect(); assert_eq!(dfs, vec![0, 1, 3, 4, 2]); }
create_graph
identifier_name
tests.rs
use super::*; fn create_graph() -> VecGraph<usize> { // Create a simple graph // // 5 // | // V // 0 --> 1 --> 2 // | // v // 3 --> 4 // // 6 VecGraph::new(7, vec![(0, 1), (1, 2), (1, 3), (3, 4), (5, 1)]) } #[test] fn num_nodes() { let graph = create_graph(); assert_eq!(graph.num_nodes(), 7); } #[test] fn successors() { let graph = create_graph(); assert_eq!(graph.successors(0), &[1]); assert_eq!(graph.successors(1), &[2, 3]); assert_eq!(graph.successors(2), &[]); assert_eq!(graph.successors(3), &[4]);
assert_eq!(graph.successors(4), &[]); assert_eq!(graph.successors(5), &[1]); assert_eq!(graph.successors(6), &[]); } #[test] fn dfs() { let graph = create_graph(); let dfs: Vec<_> = graph.depth_first_search(0).collect(); assert_eq!(dfs, vec![0, 1, 3, 4, 2]); }
random_line_split
mod.rs
//! //! Metapackage to extend an interface to ai //! // // Ai behaviors are inherited from specific objects that have the AI trait // // How many times should AI randomly try stuff // Since there will probably be a lot of AI, and since each one might be doing stuff randomly, // the larger this gets, the more it impacts performance in the absolute worst case pub const RANDOM_TRIES : usize = 10; // How far away the player has to be in order for the AI to talk. // NOTE: Probably going to get rid of this at some point pub const TALK_DISTANCE: f32 = 20.0; pub mod blink; pub use self::blink::BlinkAI; pub mod player; pub use self::player::PlayerAI; pub mod simple; pub use self::simple::SimpleAI; pub mod smeller; pub use self::smeller::SmellerAI; pub mod talker; pub use self::talker::TalkerAI; pub mod tracker; pub use self::tracker::TrackerAI; use core::world::dungeon::map::{self, Measurable, Tile}; use core::creature::{Actions, Creature, Actor, Stats}; // As AI becomes more complex it might be a good idea to put 'general' functions in this file to help guide and maintain // certain'motifs' of AI such as boundary checking, creature overlap checking, etc. /// /// Represents basic actions AI can take in the game /// /// AIs are intended to be used as trait objects. The idea is that creatures are given some boxed /// AI object to hold. This object is then guaranteed to have a `take_turn()` function, meaning /// that all creatures have a uniform way of taking a turn without needing to know the exact AI /// implementation. /// /// This gives us the primary advantage of being able to swap AI objects out at will, and also allow /// AIs to track data about themselves such as turns spent asleep, turns spent confused, etc. AIs really are just /// the state deciders for creatures, and thus the implementation of the creature's AI and their actual codified data /// are separate entities, which is a good thing. /// /// This concept of using trait objects for their unified function is similar to abstract classes in other languages, /// and directly creates a pseudo ECS system since AI is now simply a component of a creature. /// pub trait AI { /// /// Make the AI take it's turn based on map, player, and itself /// /// NOTE: AIs are basically just state deciders at this point but more complex AIs have to be state machines in of themselves /// in order to create complex behaviors. At some point they should take in a state, a vector of all creatures on the floor /// (for monster infighting, fight-flight) and maybe even some sort of "mood" though that would be a part of the `Creature`. I am /// completely considering adding randomized personalities to monsters to create even more combinations of behavior. /// fn take_turn(&mut self, map: &map::Grid<Tile>, player: &Creature, me: &mut Actor, stats: &mut Stats) -> Actions; /// /// Determine if the AI has gone out of bounds with respect to the given map /// fn is_oob(&mut self, x: isize, y: isize, map: &map::Grid<Tile>) -> bool { // Check for below map (< 0) and above map (> map.width() - 1) x < 0 || y < 0 || y >= (map.height() - 1) as isize || x >= (map.width() - 1) as isize } /// /// Allow boxed trait objects to be cloned /// fn box_clone(&self) -> Box<dyn AI>; } /// /// Allow cloning of boxed trait objects via box_clone() /// /// https://users.rust-lang.org/t/solved-is-it-possible-to-clone-a-boxed-trait-object/1714 /// /// The downside is that all things that impl AI need to have a very similar box clone, but that's not an issue impl Clone for Box<dyn AI> { fn
(&self) -> Box<dyn AI> { self.box_clone() } }
clone
identifier_name
mod.rs
//! // // Ai behaviors are inherited from specific objects that have the AI trait // // How many times should AI randomly try stuff // Since there will probably be a lot of AI, and since each one might be doing stuff randomly, // the larger this gets, the more it impacts performance in the absolute worst case pub const RANDOM_TRIES : usize = 10; // How far away the player has to be in order for the AI to talk. // NOTE: Probably going to get rid of this at some point pub const TALK_DISTANCE: f32 = 20.0; pub mod blink; pub use self::blink::BlinkAI; pub mod player; pub use self::player::PlayerAI; pub mod simple; pub use self::simple::SimpleAI; pub mod smeller; pub use self::smeller::SmellerAI; pub mod talker; pub use self::talker::TalkerAI; pub mod tracker; pub use self::tracker::TrackerAI; use core::world::dungeon::map::{self, Measurable, Tile}; use core::creature::{Actions, Creature, Actor, Stats}; // As AI becomes more complex it might be a good idea to put 'general' functions in this file to help guide and maintain // certain'motifs' of AI such as boundary checking, creature overlap checking, etc. /// /// Represents basic actions AI can take in the game /// /// AIs are intended to be used as trait objects. The idea is that creatures are given some boxed /// AI object to hold. This object is then guaranteed to have a `take_turn()` function, meaning /// that all creatures have a uniform way of taking a turn without needing to know the exact AI /// implementation. /// /// This gives us the primary advantage of being able to swap AI objects out at will, and also allow /// AIs to track data about themselves such as turns spent asleep, turns spent confused, etc. AIs really are just /// the state deciders for creatures, and thus the implementation of the creature's AI and their actual codified data /// are separate entities, which is a good thing. /// /// This concept of using trait objects for their unified function is similar to abstract classes in other languages, /// and directly creates a pseudo ECS system since AI is now simply a component of a creature. /// pub trait AI { /// /// Make the AI take it's turn based on map, player, and itself /// /// NOTE: AIs are basically just state deciders at this point but more complex AIs have to be state machines in of themselves /// in order to create complex behaviors. At some point they should take in a state, a vector of all creatures on the floor /// (for monster infighting, fight-flight) and maybe even some sort of "mood" though that would be a part of the `Creature`. I am /// completely considering adding randomized personalities to monsters to create even more combinations of behavior. /// fn take_turn(&mut self, map: &map::Grid<Tile>, player: &Creature, me: &mut Actor, stats: &mut Stats) -> Actions; /// /// Determine if the AI has gone out of bounds with respect to the given map /// fn is_oob(&mut self, x: isize, y: isize, map: &map::Grid<Tile>) -> bool { // Check for below map (< 0) and above map (> map.width() - 1) x < 0 || y < 0 || y >= (map.height() - 1) as isize || x >= (map.width() - 1) as isize } /// /// Allow boxed trait objects to be cloned /// fn box_clone(&self) -> Box<dyn AI>; } /// /// Allow cloning of boxed trait objects via box_clone() /// /// https://users.rust-lang.org/t/solved-is-it-possible-to-clone-a-boxed-trait-object/1714 /// /// The downside is that all things that impl AI need to have a very similar box clone, but that's not an issue impl Clone for Box<dyn AI> { fn clone(&self) -> Box<dyn AI> { self.box_clone() } }
//! //! Metapackage to extend an interface to ai
random_line_split
mod.rs
//! //! Metapackage to extend an interface to ai //! // // Ai behaviors are inherited from specific objects that have the AI trait // // How many times should AI randomly try stuff // Since there will probably be a lot of AI, and since each one might be doing stuff randomly, // the larger this gets, the more it impacts performance in the absolute worst case pub const RANDOM_TRIES : usize = 10; // How far away the player has to be in order for the AI to talk. // NOTE: Probably going to get rid of this at some point pub const TALK_DISTANCE: f32 = 20.0; pub mod blink; pub use self::blink::BlinkAI; pub mod player; pub use self::player::PlayerAI; pub mod simple; pub use self::simple::SimpleAI; pub mod smeller; pub use self::smeller::SmellerAI; pub mod talker; pub use self::talker::TalkerAI; pub mod tracker; pub use self::tracker::TrackerAI; use core::world::dungeon::map::{self, Measurable, Tile}; use core::creature::{Actions, Creature, Actor, Stats}; // As AI becomes more complex it might be a good idea to put 'general' functions in this file to help guide and maintain // certain'motifs' of AI such as boundary checking, creature overlap checking, etc. /// /// Represents basic actions AI can take in the game /// /// AIs are intended to be used as trait objects. The idea is that creatures are given some boxed /// AI object to hold. This object is then guaranteed to have a `take_turn()` function, meaning /// that all creatures have a uniform way of taking a turn without needing to know the exact AI /// implementation. /// /// This gives us the primary advantage of being able to swap AI objects out at will, and also allow /// AIs to track data about themselves such as turns spent asleep, turns spent confused, etc. AIs really are just /// the state deciders for creatures, and thus the implementation of the creature's AI and their actual codified data /// are separate entities, which is a good thing. /// /// This concept of using trait objects for their unified function is similar to abstract classes in other languages, /// and directly creates a pseudo ECS system since AI is now simply a component of a creature. /// pub trait AI { /// /// Make the AI take it's turn based on map, player, and itself /// /// NOTE: AIs are basically just state deciders at this point but more complex AIs have to be state machines in of themselves /// in order to create complex behaviors. At some point they should take in a state, a vector of all creatures on the floor /// (for monster infighting, fight-flight) and maybe even some sort of "mood" though that would be a part of the `Creature`. I am /// completely considering adding randomized personalities to monsters to create even more combinations of behavior. /// fn take_turn(&mut self, map: &map::Grid<Tile>, player: &Creature, me: &mut Actor, stats: &mut Stats) -> Actions; /// /// Determine if the AI has gone out of bounds with respect to the given map /// fn is_oob(&mut self, x: isize, y: isize, map: &map::Grid<Tile>) -> bool
/// /// Allow boxed trait objects to be cloned /// fn box_clone(&self) -> Box<dyn AI>; } /// /// Allow cloning of boxed trait objects via box_clone() /// /// https://users.rust-lang.org/t/solved-is-it-possible-to-clone-a-boxed-trait-object/1714 /// /// The downside is that all things that impl AI need to have a very similar box clone, but that's not an issue impl Clone for Box<dyn AI> { fn clone(&self) -> Box<dyn AI> { self.box_clone() } }
{ // Check for below map (< 0) and above map (> map.width() - 1) x < 0 || y < 0 || y >= (map.height() - 1) as isize || x >= (map.width() - 1) as isize }
identifier_body
raw_block.rs
use Renderable; use Block; use context::Context; use LiquidOptions; use tags::RawBlock; use lexer::Token; use lexer::Element; use lexer::Element::{Expression, Tag, Raw}; #[cfg(test)] use std::default::Default;
struct RawT{ content : String } impl Renderable for RawT{ fn render(&self, _context: &mut Context) -> Option<String>{ Some(self.content.to_string()) } } impl Block for RawBlock{ fn initialize(&self, _tag_name: &str, _arguments: &[Token], tokens: Vec<Element>, _options : &LiquidOptions) -> Result<Box<Renderable>, String>{ let content = tokens.iter().fold("".to_string(), |a, b| match b { &Expression(_, ref text) => text, &Tag(_, ref text) => text, &Raw(ref text) => text }.to_string() + &a ); Ok(Box::new(RawT{content: content}) as Box<Renderable>) } } #[test] fn test_raw() { let block = RawBlock; let options : LiquidOptions = Default::default(); let raw = block.initialize("raw", &vec![], vec![Expression(vec![], "This is a test".to_string())], &options); assert_eq!(raw.unwrap().render(&mut Default::default()).unwrap(), "This is a test".to_string()); }
random_line_split
raw_block.rs
use Renderable; use Block; use context::Context; use LiquidOptions; use tags::RawBlock; use lexer::Token; use lexer::Element; use lexer::Element::{Expression, Tag, Raw}; #[cfg(test)] use std::default::Default; struct RawT{ content : String } impl Renderable for RawT{ fn render(&self, _context: &mut Context) -> Option<String>{ Some(self.content.to_string()) } } impl Block for RawBlock{ fn
(&self, _tag_name: &str, _arguments: &[Token], tokens: Vec<Element>, _options : &LiquidOptions) -> Result<Box<Renderable>, String>{ let content = tokens.iter().fold("".to_string(), |a, b| match b { &Expression(_, ref text) => text, &Tag(_, ref text) => text, &Raw(ref text) => text }.to_string() + &a ); Ok(Box::new(RawT{content: content}) as Box<Renderable>) } } #[test] fn test_raw() { let block = RawBlock; let options : LiquidOptions = Default::default(); let raw = block.initialize("raw", &vec![], vec![Expression(vec![], "This is a test".to_string())], &options); assert_eq!(raw.unwrap().render(&mut Default::default()).unwrap(), "This is a test".to_string()); }
initialize
identifier_name
error.rs
//! Contains the different error codes that were in psm.h in the C version. pub enum Error { Ok, NoProgress, ParamError, NoMemory, NotIinitalized, BadApiVersion, NoAffinity, InternalError, ShmemSegmentError, OptReadOnly, Timeout, TooManyEps, Finalized, EpClosed, NoDevice, UnitNotFound, DeviceFailure, CloseTimeout, NoPortsAvailable, NoNetwork, InvalidUuidKey, EpNoResources, UnkownEpid, UnreachableEpid, InvalidNode, InvalidMtu, InvalidVersion, InvalidConnect, AlreadyConnected, NetworkError, InvalidPkey, EpidPathResolution, MqNoCompletions, MqTruncation, AmInvalidReply, AlreadyInitialized, UnknownError } pub fn error_to_string(error: Error) -> &'static str
{ "Unknown Error" }
identifier_body
error.rs
//! Contains the different error codes that were in psm.h in the C version. pub enum
{ Ok, NoProgress, ParamError, NoMemory, NotIinitalized, BadApiVersion, NoAffinity, InternalError, ShmemSegmentError, OptReadOnly, Timeout, TooManyEps, Finalized, EpClosed, NoDevice, UnitNotFound, DeviceFailure, CloseTimeout, NoPortsAvailable, NoNetwork, InvalidUuidKey, EpNoResources, UnkownEpid, UnreachableEpid, InvalidNode, InvalidMtu, InvalidVersion, InvalidConnect, AlreadyConnected, NetworkError, InvalidPkey, EpidPathResolution, MqNoCompletions, MqTruncation, AmInvalidReply, AlreadyInitialized, UnknownError } pub fn error_to_string(error: Error) -> &'static str { "Unknown Error" }
Error
identifier_name
error.rs
//! Contains the different error codes that were in psm.h in the C version. pub enum Error { Ok, NoProgress, ParamError, NoMemory, NotIinitalized, BadApiVersion, NoAffinity, InternalError, ShmemSegmentError, OptReadOnly, Timeout, TooManyEps, Finalized, EpClosed, NoDevice, UnitNotFound, DeviceFailure, CloseTimeout, NoPortsAvailable, NoNetwork, InvalidUuidKey, EpNoResources, UnkownEpid, UnreachableEpid, InvalidNode, InvalidMtu, InvalidVersion, InvalidConnect, AlreadyConnected, NetworkError, InvalidPkey, EpidPathResolution,
MqTruncation, AmInvalidReply, AlreadyInitialized, UnknownError } pub fn error_to_string(error: Error) -> &'static str { "Unknown Error" }
MqNoCompletions,
random_line_split
tmux.rs
use std::os::unix::fs::PermissionsExt; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::{env, fs, io}; use nix::unistd::Uid; use nmk::bin_name::{TMUX, ZSH}; use nmk::env_name::NMK_TMUX_VERSION; use nmk::tmux::config::Context; use nmk::tmux::version::{TmuxVersionError, Version}; use crate::cmdline::CmdOpt; use crate::utils::print_usage_time; pub struct Tmux { pub bin: PathBuf, pub version: Version, } fn find_version() -> Result<Version, TmuxVersionError> { if let Ok(s) = std::env::var(NMK_TMUX_VERSION) { log::debug!("Using tmux version from environment variable"); Version::from_version_number(&s) } else { let Output { status, stdout,.. } = Command::new(TMUX) .arg("-V") .output() .expect("tmux not found"); if!status.success() { let code = status.code().expect("tmux is terminated by signal"); panic!("tmux exit with status: {}", code); } let version_output = std::str::from_utf8(&stdout).expect("tmux version output contain non utf-8"); Version::from_version_output(version_output) } } impl Tmux { pub fn new() -> Tmux { let bin = which::which(TMUX).expect("Cannot find tmux binary"); let version = find_version().expect("Find tmux version error"); Tmux { bin, version } } pub fn exec(&self, cmd_opt: &CmdOpt, config: &Path, is_color_term: bool) ->! { let mut cmd = Command::new(TMUX); cmd.args(&["-L", &cmd_opt.socket]); if is_color_term { cmd.arg("-2"); } if cmd_opt.unicode { cmd.arg("-u"); } cmd.arg("-f"); cmd.arg(config); if cmd_opt.args.is_empty() { // Attach to tmux or create new session cmd.args(&["new-session", "-A"]); if self.version < Version::V31 { cmd.args(&["-s", "0"]); } } else { log::debug!("Positional arguments: {:?}", cmd_opt.args); cmd.args(cmd_opt.args.iter()); } log::debug!("exec command: {:?}", cmd); print_usage_time(&cmd_opt); let err = cmd.exec(); panic!("exec {:?} fail with {:?}", cmd, err); } pub fn write_config_in_temp_dir( &self, cmd_opt: &CmdOpt, contents: &[u8], ) -> io::Result<PathBuf> { let nmk_tmp_dir = create_nmk_tmp_dir()?; let config = nmk_tmp_dir.join(format!("{}.tmux.conf", cmd_opt.socket)); fs::write(&config, contents)?; Ok(config) } } fn create_nmk_tmp_dir() -> io::Result<PathBuf> { let tmp_dir = env::temp_dir(); let nmk_tmp_dir = tmp_dir.join(format!("nmk-{}", Uid::current())); if!nmk_tmp_dir.exists() { fs::create_dir(&nmk_tmp_dir)?; let mut permissions = nmk_tmp_dir.metadata()?.permissions(); permissions.set_mode(0o700); fs::set_permissions(&nmk_tmp_dir, permissions)?; } Ok(nmk_tmp_dir) } pub fn make_config_context(cmd_opt: &CmdOpt, use_8bit_color: bool) -> Context { let default_term = if use_8bit_color
else { "screen" }; Context { support_256_color: use_8bit_color, detach_on_destroy: cmd_opt.detach_on_destroy, default_term: default_term.to_owned(), default_shell: which::which(ZSH).expect("zsh not found"), } }
{ "screen-256color" }
conditional_block
tmux.rs
use std::os::unix::fs::PermissionsExt; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::{env, fs, io}; use nix::unistd::Uid; use nmk::bin_name::{TMUX, ZSH}; use nmk::env_name::NMK_TMUX_VERSION; use nmk::tmux::config::Context;
use crate::cmdline::CmdOpt; use crate::utils::print_usage_time; pub struct Tmux { pub bin: PathBuf, pub version: Version, } fn find_version() -> Result<Version, TmuxVersionError> { if let Ok(s) = std::env::var(NMK_TMUX_VERSION) { log::debug!("Using tmux version from environment variable"); Version::from_version_number(&s) } else { let Output { status, stdout,.. } = Command::new(TMUX) .arg("-V") .output() .expect("tmux not found"); if!status.success() { let code = status.code().expect("tmux is terminated by signal"); panic!("tmux exit with status: {}", code); } let version_output = std::str::from_utf8(&stdout).expect("tmux version output contain non utf-8"); Version::from_version_output(version_output) } } impl Tmux { pub fn new() -> Tmux { let bin = which::which(TMUX).expect("Cannot find tmux binary"); let version = find_version().expect("Find tmux version error"); Tmux { bin, version } } pub fn exec(&self, cmd_opt: &CmdOpt, config: &Path, is_color_term: bool) ->! { let mut cmd = Command::new(TMUX); cmd.args(&["-L", &cmd_opt.socket]); if is_color_term { cmd.arg("-2"); } if cmd_opt.unicode { cmd.arg("-u"); } cmd.arg("-f"); cmd.arg(config); if cmd_opt.args.is_empty() { // Attach to tmux or create new session cmd.args(&["new-session", "-A"]); if self.version < Version::V31 { cmd.args(&["-s", "0"]); } } else { log::debug!("Positional arguments: {:?}", cmd_opt.args); cmd.args(cmd_opt.args.iter()); } log::debug!("exec command: {:?}", cmd); print_usage_time(&cmd_opt); let err = cmd.exec(); panic!("exec {:?} fail with {:?}", cmd, err); } pub fn write_config_in_temp_dir( &self, cmd_opt: &CmdOpt, contents: &[u8], ) -> io::Result<PathBuf> { let nmk_tmp_dir = create_nmk_tmp_dir()?; let config = nmk_tmp_dir.join(format!("{}.tmux.conf", cmd_opt.socket)); fs::write(&config, contents)?; Ok(config) } } fn create_nmk_tmp_dir() -> io::Result<PathBuf> { let tmp_dir = env::temp_dir(); let nmk_tmp_dir = tmp_dir.join(format!("nmk-{}", Uid::current())); if!nmk_tmp_dir.exists() { fs::create_dir(&nmk_tmp_dir)?; let mut permissions = nmk_tmp_dir.metadata()?.permissions(); permissions.set_mode(0o700); fs::set_permissions(&nmk_tmp_dir, permissions)?; } Ok(nmk_tmp_dir) } pub fn make_config_context(cmd_opt: &CmdOpt, use_8bit_color: bool) -> Context { let default_term = if use_8bit_color { "screen-256color" } else { "screen" }; Context { support_256_color: use_8bit_color, detach_on_destroy: cmd_opt.detach_on_destroy, default_term: default_term.to_owned(), default_shell: which::which(ZSH).expect("zsh not found"), } }
use nmk::tmux::version::{TmuxVersionError, Version};
random_line_split
tmux.rs
use std::os::unix::fs::PermissionsExt; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::{env, fs, io}; use nix::unistd::Uid; use nmk::bin_name::{TMUX, ZSH}; use nmk::env_name::NMK_TMUX_VERSION; use nmk::tmux::config::Context; use nmk::tmux::version::{TmuxVersionError, Version}; use crate::cmdline::CmdOpt; use crate::utils::print_usage_time; pub struct Tmux { pub bin: PathBuf, pub version: Version, } fn find_version() -> Result<Version, TmuxVersionError> { if let Ok(s) = std::env::var(NMK_TMUX_VERSION) { log::debug!("Using tmux version from environment variable"); Version::from_version_number(&s) } else { let Output { status, stdout,.. } = Command::new(TMUX) .arg("-V") .output() .expect("tmux not found"); if!status.success() { let code = status.code().expect("tmux is terminated by signal"); panic!("tmux exit with status: {}", code); } let version_output = std::str::from_utf8(&stdout).expect("tmux version output contain non utf-8"); Version::from_version_output(version_output) } } impl Tmux { pub fn new() -> Tmux { let bin = which::which(TMUX).expect("Cannot find tmux binary"); let version = find_version().expect("Find tmux version error"); Tmux { bin, version } } pub fn exec(&self, cmd_opt: &CmdOpt, config: &Path, is_color_term: bool) ->! { let mut cmd = Command::new(TMUX); cmd.args(&["-L", &cmd_opt.socket]); if is_color_term { cmd.arg("-2"); } if cmd_opt.unicode { cmd.arg("-u"); } cmd.arg("-f"); cmd.arg(config); if cmd_opt.args.is_empty() { // Attach to tmux or create new session cmd.args(&["new-session", "-A"]); if self.version < Version::V31 { cmd.args(&["-s", "0"]); } } else { log::debug!("Positional arguments: {:?}", cmd_opt.args); cmd.args(cmd_opt.args.iter()); } log::debug!("exec command: {:?}", cmd); print_usage_time(&cmd_opt); let err = cmd.exec(); panic!("exec {:?} fail with {:?}", cmd, err); } pub fn write_config_in_temp_dir( &self, cmd_opt: &CmdOpt, contents: &[u8], ) -> io::Result<PathBuf> { let nmk_tmp_dir = create_nmk_tmp_dir()?; let config = nmk_tmp_dir.join(format!("{}.tmux.conf", cmd_opt.socket)); fs::write(&config, contents)?; Ok(config) } } fn
() -> io::Result<PathBuf> { let tmp_dir = env::temp_dir(); let nmk_tmp_dir = tmp_dir.join(format!("nmk-{}", Uid::current())); if!nmk_tmp_dir.exists() { fs::create_dir(&nmk_tmp_dir)?; let mut permissions = nmk_tmp_dir.metadata()?.permissions(); permissions.set_mode(0o700); fs::set_permissions(&nmk_tmp_dir, permissions)?; } Ok(nmk_tmp_dir) } pub fn make_config_context(cmd_opt: &CmdOpt, use_8bit_color: bool) -> Context { let default_term = if use_8bit_color { "screen-256color" } else { "screen" }; Context { support_256_color: use_8bit_color, detach_on_destroy: cmd_opt.detach_on_destroy, default_term: default_term.to_owned(), default_shell: which::which(ZSH).expect("zsh not found"), } }
create_nmk_tmp_dir
identifier_name
infinite_iter.rs
use clippy_utils::diagnostics::span_lint; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; use clippy_utils::{get_trait_def_id, higher, is_qpath_def_path, paths}; use rustc_hir::{BorrowKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::{sym, Symbol}; declare_clippy_lint! { /// ### What it does /// Checks for iteration that is guaranteed to be infinite. /// /// ### Why is this bad? /// While there may be places where this is acceptable /// (e.g., in event streams), in most cases this is simply an error. /// /// ### Example /// ```no_run /// use std::iter; /// /// iter::repeat(1_u8).collect::<Vec<_>>(); /// ``` pub INFINITE_ITER, correctness, "infinite iteration" } declare_clippy_lint! { /// ### What it does /// Checks for iteration that may be infinite. /// /// ### Why is this bad? /// While there may be places where this is acceptable /// (e.g., in event streams), in most cases this is simply an error. /// /// ### Known problems /// The code may have a condition to stop iteration, but /// this lint is not clever enough to analyze it. /// /// ### Example /// ```rust /// let infinite_iter = 0..; /// [0..].iter().zip(infinite_iter.take_while(|x| *x > 5)); /// ``` pub MAYBE_INFINITE_ITER, pedantic, "possible infinite iteration" } declare_lint_pass!(InfiniteIter => [INFINITE_ITER, MAYBE_INFINITE_ITER]); impl<'tcx> LateLintPass<'tcx> for InfiniteIter { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { let (lint, msg) = match complete_infinite_iter(cx, expr) { Infinite => (INFINITE_ITER, "infinite iteration detected"), MaybeInfinite => (MAYBE_INFINITE_ITER, "possible infinite iteration detected"), Finite => { return; }, }; span_lint(cx, lint, expr.span, msg); } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum
{ Infinite, MaybeInfinite, Finite, } use self::Finiteness::{Finite, Infinite, MaybeInfinite}; impl Finiteness { #[must_use] fn and(self, b: Self) -> Self { match (self, b) { (Finite, _) | (_, Finite) => Finite, (MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite, _ => Infinite, } } #[must_use] fn or(self, b: Self) -> Self { match (self, b) { (Infinite, _) | (_, Infinite) => Infinite, (MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite, _ => Finite, } } } impl From<bool> for Finiteness { #[must_use] fn from(b: bool) -> Self { if b { Infinite } else { Finite } } } /// This tells us what to look for to know if the iterator returned by /// this method is infinite #[derive(Copy, Clone)] enum Heuristic { /// infinite no matter what Always, /// infinite if the first argument is First, /// infinite if any of the supplied arguments is Any, /// infinite if all of the supplied arguments are All, } use self::Heuristic::{All, Always, Any, First}; /// a slice of (method name, number of args, heuristic, bounds) tuples /// that will be used to determine whether the method in question /// returns an infinite or possibly infinite iterator. The finiteness /// is an upper bound, e.g., some methods can return a possibly /// infinite iterator at worst, e.g., `take_while`. const HEURISTICS: [(&str, usize, Heuristic, Finiteness); 19] = [ ("zip", 2, All, Infinite), ("chain", 2, Any, Infinite), ("cycle", 1, Always, Infinite), ("map", 2, First, Infinite), ("by_ref", 1, First, Infinite), ("cloned", 1, First, Infinite), ("rev", 1, First, Infinite), ("inspect", 1, First, Infinite), ("enumerate", 1, First, Infinite), ("peekable", 2, First, Infinite), ("fuse", 1, First, Infinite), ("skip", 2, First, Infinite), ("skip_while", 1, First, Infinite), ("filter", 2, First, Infinite), ("filter_map", 2, First, Infinite), ("flat_map", 2, First, Infinite), ("unzip", 1, First, Infinite), ("take_while", 2, First, MaybeInfinite), ("scan", 3, First, MaybeInfinite), ]; fn is_infinite(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { match expr.kind { ExprKind::MethodCall(method, _, args, _) => { for &(name, len, heuristic, cap) in &HEURISTICS { if method.ident.name.as_str() == name && args.len() == len { return (match heuristic { Always => Infinite, First => is_infinite(cx, &args[0]), Any => is_infinite(cx, &args[0]).or(is_infinite(cx, &args[1])), All => is_infinite(cx, &args[0]).and(is_infinite(cx, &args[1])), }) .and(cap); } } if method.ident.name == sym!(flat_map) && args.len() == 2 { if let ExprKind::Closure(_, _, body_id, _, _) = args[1].kind { let body = cx.tcx.hir().body(body_id); return is_infinite(cx, &body.value); } } Finite }, ExprKind::Block(block, _) => block.expr.as_ref().map_or(Finite, |e| is_infinite(cx, e)), ExprKind::Box(e) | ExprKind::AddrOf(BorrowKind::Ref, _, e) => is_infinite(cx, e), ExprKind::Call(path, _) => { if let ExprKind::Path(ref qpath) = path.kind { is_qpath_def_path(cx, qpath, path.hir_id, &paths::ITER_REPEAT).into() } else { Finite } }, ExprKind::Struct(..) => higher::Range::hir(expr).map_or(false, |r| r.end.is_none()).into(), _ => Finite, } } /// the names and argument lengths of methods that *may* exhaust their /// iterators const POSSIBLY_COMPLETING_METHODS: [(&str, usize); 6] = [ ("find", 2), ("rfind", 2), ("position", 2), ("rposition", 2), ("any", 2), ("all", 2), ]; /// the names and argument lengths of methods that *always* exhaust /// their iterators const COMPLETING_METHODS: [(&str, usize); 12] = [ ("count", 1), ("fold", 3), ("for_each", 2), ("partition", 2), ("max", 1), ("max_by", 2), ("max_by_key", 2), ("min", 1), ("min_by", 2), ("min_by_key", 2), ("sum", 1), ("product", 1), ]; /// the paths of types that are known to be infinitely allocating const INFINITE_COLLECTORS: &[Symbol] = &[ sym::BinaryHeap, sym::BTreeMap, sym::BTreeSet, sym::hashmap_type, sym::hashset_type, sym::LinkedList, sym::vec_type, sym::vecdeque_type, ]; fn complete_infinite_iter(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { match expr.kind { ExprKind::MethodCall(method, _, args, _) => { for &(name, len) in &COMPLETING_METHODS { if method.ident.name.as_str() == name && args.len() == len { return is_infinite(cx, &args[0]); } } for &(name, len) in &POSSIBLY_COMPLETING_METHODS { if method.ident.name.as_str() == name && args.len() == len { return MaybeInfinite.and(is_infinite(cx, &args[0])); } } if method.ident.name == sym!(last) && args.len() == 1 { let not_double_ended = get_trait_def_id(cx, &paths::DOUBLE_ENDED_ITERATOR).map_or(false, |id| { !implements_trait(cx, cx.typeck_results().expr_ty(&args[0]), id, &[]) }); if not_double_ended { return is_infinite(cx, &args[0]); } } else if method.ident.name == sym!(collect) { let ty = cx.typeck_results().expr_ty(expr); if INFINITE_COLLECTORS .iter() .any(|diag_item| is_type_diagnostic_item(cx, ty, *diag_item)) { return is_infinite(cx, &args[0]); } } }, ExprKind::Binary(op, l, r) => { if op.node.is_comparison() { return is_infinite(cx, l).and(is_infinite(cx, r)).and(MaybeInfinite); } }, // TODO: ExprKind::Loop + Match _ => (), } Finite }
Finiteness
identifier_name
infinite_iter.rs
use clippy_utils::diagnostics::span_lint; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; use clippy_utils::{get_trait_def_id, higher, is_qpath_def_path, paths}; use rustc_hir::{BorrowKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::{sym, Symbol}; declare_clippy_lint! { /// ### What it does /// Checks for iteration that is guaranteed to be infinite. /// /// ### Why is this bad? /// While there may be places where this is acceptable /// (e.g., in event streams), in most cases this is simply an error. /// /// ### Example /// ```no_run /// use std::iter; /// /// iter::repeat(1_u8).collect::<Vec<_>>(); /// ``` pub INFINITE_ITER, correctness, "infinite iteration" } declare_clippy_lint! { /// ### What it does /// Checks for iteration that may be infinite. /// /// ### Why is this bad? /// While there may be places where this is acceptable /// (e.g., in event streams), in most cases this is simply an error. /// /// ### Known problems /// The code may have a condition to stop iteration, but /// this lint is not clever enough to analyze it. /// /// ### Example /// ```rust /// let infinite_iter = 0..; /// [0..].iter().zip(infinite_iter.take_while(|x| *x > 5)); /// ``` pub MAYBE_INFINITE_ITER, pedantic, "possible infinite iteration" } declare_lint_pass!(InfiniteIter => [INFINITE_ITER, MAYBE_INFINITE_ITER]); impl<'tcx> LateLintPass<'tcx> for InfiniteIter { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { let (lint, msg) = match complete_infinite_iter(cx, expr) { Infinite => (INFINITE_ITER, "infinite iteration detected"), MaybeInfinite => (MAYBE_INFINITE_ITER, "possible infinite iteration detected"), Finite => { return; }, }; span_lint(cx, lint, expr.span, msg); } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum Finiteness { Infinite, MaybeInfinite, Finite, } use self::Finiteness::{Finite, Infinite, MaybeInfinite}; impl Finiteness { #[must_use] fn and(self, b: Self) -> Self { match (self, b) { (Finite, _) | (_, Finite) => Finite, (MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite, _ => Infinite, } } #[must_use] fn or(self, b: Self) -> Self { match (self, b) { (Infinite, _) | (_, Infinite) => Infinite, (MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite, _ => Finite, } } } impl From<bool> for Finiteness { #[must_use] fn from(b: bool) -> Self { if b { Infinite } else { Finite } } } /// This tells us what to look for to know if the iterator returned by /// this method is infinite #[derive(Copy, Clone)] enum Heuristic { /// infinite no matter what Always, /// infinite if the first argument is First, /// infinite if any of the supplied arguments is Any, /// infinite if all of the supplied arguments are All, } use self::Heuristic::{All, Always, Any, First}; /// a slice of (method name, number of args, heuristic, bounds) tuples /// that will be used to determine whether the method in question /// returns an infinite or possibly infinite iterator. The finiteness /// is an upper bound, e.g., some methods can return a possibly /// infinite iterator at worst, e.g., `take_while`. const HEURISTICS: [(&str, usize, Heuristic, Finiteness); 19] = [ ("zip", 2, All, Infinite), ("chain", 2, Any, Infinite), ("cycle", 1, Always, Infinite), ("map", 2, First, Infinite), ("by_ref", 1, First, Infinite), ("cloned", 1, First, Infinite), ("rev", 1, First, Infinite), ("inspect", 1, First, Infinite), ("enumerate", 1, First, Infinite), ("peekable", 2, First, Infinite), ("fuse", 1, First, Infinite), ("skip", 2, First, Infinite), ("skip_while", 1, First, Infinite), ("filter", 2, First, Infinite), ("filter_map", 2, First, Infinite), ("flat_map", 2, First, Infinite), ("unzip", 1, First, Infinite), ("take_while", 2, First, MaybeInfinite), ("scan", 3, First, MaybeInfinite), ]; fn is_infinite(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { match expr.kind { ExprKind::MethodCall(method, _, args, _) => { for &(name, len, heuristic, cap) in &HEURISTICS { if method.ident.name.as_str() == name && args.len() == len { return (match heuristic { Always => Infinite, First => is_infinite(cx, &args[0]), Any => is_infinite(cx, &args[0]).or(is_infinite(cx, &args[1])), All => is_infinite(cx, &args[0]).and(is_infinite(cx, &args[1])), }) .and(cap); } } if method.ident.name == sym!(flat_map) && args.len() == 2 { if let ExprKind::Closure(_, _, body_id, _, _) = args[1].kind { let body = cx.tcx.hir().body(body_id); return is_infinite(cx, &body.value); } } Finite }, ExprKind::Block(block, _) => block.expr.as_ref().map_or(Finite, |e| is_infinite(cx, e)), ExprKind::Box(e) | ExprKind::AddrOf(BorrowKind::Ref, _, e) => is_infinite(cx, e), ExprKind::Call(path, _) => { if let ExprKind::Path(ref qpath) = path.kind { is_qpath_def_path(cx, qpath, path.hir_id, &paths::ITER_REPEAT).into() } else { Finite } }, ExprKind::Struct(..) => higher::Range::hir(expr).map_or(false, |r| r.end.is_none()).into(), _ => Finite, } } /// the names and argument lengths of methods that *may* exhaust their /// iterators const POSSIBLY_COMPLETING_METHODS: [(&str, usize); 6] = [ ("find", 2), ("rfind", 2), ("position", 2), ("rposition", 2), ("any", 2), ("all", 2), ]; /// the names and argument lengths of methods that *always* exhaust /// their iterators const COMPLETING_METHODS: [(&str, usize); 12] = [ ("count", 1), ("fold", 3), ("for_each", 2), ("partition", 2), ("max", 1), ("max_by", 2), ("max_by_key", 2), ("min", 1), ("min_by", 2), ("min_by_key", 2), ("sum", 1), ("product", 1), ]; /// the paths of types that are known to be infinitely allocating const INFINITE_COLLECTORS: &[Symbol] = &[ sym::BinaryHeap, sym::BTreeMap, sym::BTreeSet, sym::hashmap_type, sym::hashset_type, sym::LinkedList, sym::vec_type, sym::vecdeque_type, ]; fn complete_infinite_iter(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { match expr.kind { ExprKind::MethodCall(method, _, args, _) => { for &(name, len) in &COMPLETING_METHODS { if method.ident.name.as_str() == name && args.len() == len { return is_infinite(cx, &args[0]); } } for &(name, len) in &POSSIBLY_COMPLETING_METHODS { if method.ident.name.as_str() == name && args.len() == len { return MaybeInfinite.and(is_infinite(cx, &args[0])); } } if method.ident.name == sym!(last) && args.len() == 1
else if method.ident.name == sym!(collect) { let ty = cx.typeck_results().expr_ty(expr); if INFINITE_COLLECTORS .iter() .any(|diag_item| is_type_diagnostic_item(cx, ty, *diag_item)) { return is_infinite(cx, &args[0]); } } }, ExprKind::Binary(op, l, r) => { if op.node.is_comparison() { return is_infinite(cx, l).and(is_infinite(cx, r)).and(MaybeInfinite); } }, // TODO: ExprKind::Loop + Match _ => (), } Finite }
{ let not_double_ended = get_trait_def_id(cx, &paths::DOUBLE_ENDED_ITERATOR).map_or(false, |id| { !implements_trait(cx, cx.typeck_results().expr_ty(&args[0]), id, &[]) }); if not_double_ended { return is_infinite(cx, &args[0]); } }
conditional_block
infinite_iter.rs
use clippy_utils::diagnostics::span_lint; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; use clippy_utils::{get_trait_def_id, higher, is_qpath_def_path, paths}; use rustc_hir::{BorrowKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::{sym, Symbol}; declare_clippy_lint! { /// ### What it does /// Checks for iteration that is guaranteed to be infinite. /// /// ### Why is this bad? /// While there may be places where this is acceptable /// (e.g., in event streams), in most cases this is simply an error. /// /// ### Example /// ```no_run /// use std::iter; /// /// iter::repeat(1_u8).collect::<Vec<_>>(); /// ``` pub INFINITE_ITER, correctness, "infinite iteration" } declare_clippy_lint! { /// ### What it does /// Checks for iteration that may be infinite. /// /// ### Why is this bad? /// While there may be places where this is acceptable /// (e.g., in event streams), in most cases this is simply an error. /// /// ### Known problems /// The code may have a condition to stop iteration, but /// this lint is not clever enough to analyze it. /// /// ### Example /// ```rust /// let infinite_iter = 0..; /// [0..].iter().zip(infinite_iter.take_while(|x| *x > 5)); /// ``` pub MAYBE_INFINITE_ITER, pedantic, "possible infinite iteration" } declare_lint_pass!(InfiniteIter => [INFINITE_ITER, MAYBE_INFINITE_ITER]); impl<'tcx> LateLintPass<'tcx> for InfiniteIter { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { let (lint, msg) = match complete_infinite_iter(cx, expr) { Infinite => (INFINITE_ITER, "infinite iteration detected"), MaybeInfinite => (MAYBE_INFINITE_ITER, "possible infinite iteration detected"), Finite => { return; }, }; span_lint(cx, lint, expr.span, msg); } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum Finiteness { Infinite, MaybeInfinite, Finite, } use self::Finiteness::{Finite, Infinite, MaybeInfinite}; impl Finiteness { #[must_use] fn and(self, b: Self) -> Self { match (self, b) { (Finite, _) | (_, Finite) => Finite, (MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite, _ => Infinite, } } #[must_use] fn or(self, b: Self) -> Self { match (self, b) { (Infinite, _) | (_, Infinite) => Infinite, (MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite, _ => Finite, } } } impl From<bool> for Finiteness { #[must_use] fn from(b: bool) -> Self { if b { Infinite } else { Finite } } } /// This tells us what to look for to know if the iterator returned by /// this method is infinite #[derive(Copy, Clone)] enum Heuristic { /// infinite no matter what Always, /// infinite if the first argument is First, /// infinite if any of the supplied arguments is Any, /// infinite if all of the supplied arguments are All, } use self::Heuristic::{All, Always, Any, First}; /// a slice of (method name, number of args, heuristic, bounds) tuples /// that will be used to determine whether the method in question /// returns an infinite or possibly infinite iterator. The finiteness /// is an upper bound, e.g., some methods can return a possibly /// infinite iterator at worst, e.g., `take_while`. const HEURISTICS: [(&str, usize, Heuristic, Finiteness); 19] = [ ("zip", 2, All, Infinite), ("chain", 2, Any, Infinite), ("cycle", 1, Always, Infinite), ("map", 2, First, Infinite), ("by_ref", 1, First, Infinite), ("cloned", 1, First, Infinite), ("rev", 1, First, Infinite), ("inspect", 1, First, Infinite), ("enumerate", 1, First, Infinite), ("peekable", 2, First, Infinite), ("fuse", 1, First, Infinite), ("skip", 2, First, Infinite), ("skip_while", 1, First, Infinite), ("filter", 2, First, Infinite), ("filter_map", 2, First, Infinite), ("flat_map", 2, First, Infinite), ("unzip", 1, First, Infinite), ("take_while", 2, First, MaybeInfinite), ("scan", 3, First, MaybeInfinite), ]; fn is_infinite(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { match expr.kind { ExprKind::MethodCall(method, _, args, _) => { for &(name, len, heuristic, cap) in &HEURISTICS { if method.ident.name.as_str() == name && args.len() == len { return (match heuristic { Always => Infinite, First => is_infinite(cx, &args[0]), Any => is_infinite(cx, &args[0]).or(is_infinite(cx, &args[1])), All => is_infinite(cx, &args[0]).and(is_infinite(cx, &args[1])), }) .and(cap); } } if method.ident.name == sym!(flat_map) && args.len() == 2 { if let ExprKind::Closure(_, _, body_id, _, _) = args[1].kind { let body = cx.tcx.hir().body(body_id); return is_infinite(cx, &body.value); } } Finite }, ExprKind::Block(block, _) => block.expr.as_ref().map_or(Finite, |e| is_infinite(cx, e)), ExprKind::Box(e) | ExprKind::AddrOf(BorrowKind::Ref, _, e) => is_infinite(cx, e), ExprKind::Call(path, _) => { if let ExprKind::Path(ref qpath) = path.kind { is_qpath_def_path(cx, qpath, path.hir_id, &paths::ITER_REPEAT).into() } else { Finite } }, ExprKind::Struct(..) => higher::Range::hir(expr).map_or(false, |r| r.end.is_none()).into(), _ => Finite, } } /// the names and argument lengths of methods that *may* exhaust their /// iterators const POSSIBLY_COMPLETING_METHODS: [(&str, usize); 6] = [ ("find", 2), ("rfind", 2), ("position", 2), ("rposition", 2), ("any", 2), ("all", 2), ]; /// the names and argument lengths of methods that *always* exhaust /// their iterators const COMPLETING_METHODS: [(&str, usize); 12] = [ ("count", 1), ("fold", 3), ("for_each", 2), ("partition", 2), ("max", 1), ("max_by", 2), ("max_by_key", 2), ("min", 1), ("min_by", 2),
("product", 1), ]; /// the paths of types that are known to be infinitely allocating const INFINITE_COLLECTORS: &[Symbol] = &[ sym::BinaryHeap, sym::BTreeMap, sym::BTreeSet, sym::hashmap_type, sym::hashset_type, sym::LinkedList, sym::vec_type, sym::vecdeque_type, ]; fn complete_infinite_iter(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { match expr.kind { ExprKind::MethodCall(method, _, args, _) => { for &(name, len) in &COMPLETING_METHODS { if method.ident.name.as_str() == name && args.len() == len { return is_infinite(cx, &args[0]); } } for &(name, len) in &POSSIBLY_COMPLETING_METHODS { if method.ident.name.as_str() == name && args.len() == len { return MaybeInfinite.and(is_infinite(cx, &args[0])); } } if method.ident.name == sym!(last) && args.len() == 1 { let not_double_ended = get_trait_def_id(cx, &paths::DOUBLE_ENDED_ITERATOR).map_or(false, |id| { !implements_trait(cx, cx.typeck_results().expr_ty(&args[0]), id, &[]) }); if not_double_ended { return is_infinite(cx, &args[0]); } } else if method.ident.name == sym!(collect) { let ty = cx.typeck_results().expr_ty(expr); if INFINITE_COLLECTORS .iter() .any(|diag_item| is_type_diagnostic_item(cx, ty, *diag_item)) { return is_infinite(cx, &args[0]); } } }, ExprKind::Binary(op, l, r) => { if op.node.is_comparison() { return is_infinite(cx, l).and(is_infinite(cx, r)).and(MaybeInfinite); } }, // TODO: ExprKind::Loop + Match _ => (), } Finite }
("min_by_key", 2), ("sum", 1),
random_line_split
main.rs
#![feature(box_syntax)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; const CONVERSION_FACTOR: f64 = 1000000000.; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone +'static, S: Scheduler + Sized, { println!("Receiving started"); let pipelines: Vec<_> = ports .iter() .map(|port| tcp_nf(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len()); for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn main() { let opts = basic_opts();
let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 512; // Travis allocates at most 512 hugepages. match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); let mut pkts_so_far = (0, 0); let mut last_printed = 0.; const MAX_PRINT_INTERVAL: f64 = 120.; const PRINT_DELAY: f64 = 60.; let sleep_delay = (PRINT_DELAY / 2.) as u64; let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR; let sleep_time = Duration::from_millis(sleep_delay); println!("0 OVERALL RX 0.00 TX 0.00 CYCLE_PER_DELAY 0 0 0"); loop { thread::sleep(sleep_time); // Sleep for a bit let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR; if now - start > PRINT_DELAY { let mut rx = 0; let mut tx = 0; for port in context.ports.values() { for q in 0..port.rxqs() { let (rp, tp) = port.stats(q); rx += rp; tx += tp; } } let pkts = (rx, tx); let rx_pkts = pkts.0 - pkts_so_far.0; if rx_pkts > 0 || now - last_printed > MAX_PRINT_INTERVAL { println!( "{:.2} OVERALL RX {:.2} TX {:.2}", now - start, rx_pkts as f64 / (now - start), (pkts.1 - pkts_so_far.1) as f64 / (now - start) ); last_printed = now; start = now; pkts_so_far = pkts; } } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
random_line_split
main.rs
#![feature(box_syntax)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; const CONVERSION_FACTOR: f64 = 1000000000.; fn
<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone +'static, S: Scheduler + Sized, { println!("Receiving started"); let pipelines: Vec<_> = ports .iter() .map(|port| tcp_nf(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len()); for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn main() { let opts = basic_opts(); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 512; // Travis allocates at most 512 hugepages. match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); let mut pkts_so_far = (0, 0); let mut last_printed = 0.; const MAX_PRINT_INTERVAL: f64 = 120.; const PRINT_DELAY: f64 = 60.; let sleep_delay = (PRINT_DELAY / 2.) as u64; let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR; let sleep_time = Duration::from_millis(sleep_delay); println!("0 OVERALL RX 0.00 TX 0.00 CYCLE_PER_DELAY 0 0 0"); loop { thread::sleep(sleep_time); // Sleep for a bit let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR; if now - start > PRINT_DELAY { let mut rx = 0; let mut tx = 0; for port in context.ports.values() { for q in 0..port.rxqs() { let (rp, tp) = port.stats(q); rx += rp; tx += tp; } } let pkts = (rx, tx); let rx_pkts = pkts.0 - pkts_so_far.0; if rx_pkts > 0 || now - last_printed > MAX_PRINT_INTERVAL { println!( "{:.2} OVERALL RX {:.2} TX {:.2}", now - start, rx_pkts as f64 / (now - start), (pkts.1 - pkts_so_far.1) as f64 / (now - start) ); last_printed = now; start = now; pkts_so_far = pkts; } } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
test
identifier_name
main.rs
#![feature(box_syntax)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; const CONVERSION_FACTOR: f64 = 1000000000.; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone +'static, S: Scheduler + Sized,
fn main() { let opts = basic_opts(); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 512; // Travis allocates at most 512 hugepages. match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); let mut pkts_so_far = (0, 0); let mut last_printed = 0.; const MAX_PRINT_INTERVAL: f64 = 120.; const PRINT_DELAY: f64 = 60.; let sleep_delay = (PRINT_DELAY / 2.) as u64; let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR; let sleep_time = Duration::from_millis(sleep_delay); println!("0 OVERALL RX 0.00 TX 0.00 CYCLE_PER_DELAY 0 0 0"); loop { thread::sleep(sleep_time); // Sleep for a bit let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR; if now - start > PRINT_DELAY { let mut rx = 0; let mut tx = 0; for port in context.ports.values() { for q in 0..port.rxqs() { let (rp, tp) = port.stats(q); rx += rp; tx += tp; } } let pkts = (rx, tx); let rx_pkts = pkts.0 - pkts_so_far.0; if rx_pkts > 0 || now - last_printed > MAX_PRINT_INTERVAL { println!( "{:.2} OVERALL RX {:.2} TX {:.2}", now - start, rx_pkts as f64 / (now - start), (pkts.1 - pkts_so_far.1) as f64 / (now - start) ); last_printed = now; start = now; pkts_so_far = pkts; } } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
{ println!("Receiving started"); let pipelines: Vec<_> = ports .iter() .map(|port| tcp_nf(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len()); for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } }
identifier_body
main.rs
#![feature(box_syntax)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; const CONVERSION_FACTOR: f64 = 1000000000.; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone +'static, S: Scheduler + Sized, { println!("Receiving started"); let pipelines: Vec<_> = ports .iter() .map(|port| tcp_nf(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len()); for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn main() { let opts = basic_opts(); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 512; // Travis allocates at most 512 hugepages. match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); let mut pkts_so_far = (0, 0); let mut last_printed = 0.; const MAX_PRINT_INTERVAL: f64 = 120.; const PRINT_DELAY: f64 = 60.; let sleep_delay = (PRINT_DELAY / 2.) as u64; let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR; let sleep_time = Duration::from_millis(sleep_delay); println!("0 OVERALL RX 0.00 TX 0.00 CYCLE_PER_DELAY 0 0 0"); loop { thread::sleep(sleep_time); // Sleep for a bit let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR; if now - start > PRINT_DELAY { let mut rx = 0; let mut tx = 0; for port in context.ports.values() { for q in 0..port.rxqs() { let (rp, tp) = port.stats(q); rx += rp; tx += tp; } } let pkts = (rx, tx); let rx_pkts = pkts.0 - pkts_so_far.0; if rx_pkts > 0 || now - last_printed > MAX_PRINT_INTERVAL { println!( "{:.2} OVERALL RX {:.2} TX {:.2}", now - start, rx_pkts as f64 / (now - start), (pkts.1 - pkts_so_far.1) as f64 / (now - start) ); last_printed = now; start = now; pkts_so_far = pkts; } } } } Err(ref e) =>
} }
{ println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); }
conditional_block
take_until.rs
use consumer::*; use std::cell::Cell; use std::rc::Rc; use stream::*; /// Emit items until it receive an item from another stream. /// /// This struct is created by the /// [`take_until()`](./trait.Stream.html#method.take_until) method on /// [Stream](./trait.Stream.html). See its documentation for more. #[must_use = "stream adaptors are lazy and do nothing unless consumed"] pub struct TakeUntil<S, T> { stream: S, trigger: T, } struct TakeUntilState<C> { consumer: C, is_closed: Rc<Cell<bool>>, } struct TriggerConsumer { is_closed: Rc<Cell<bool>>, } impl<T> Consumer<T> for TriggerConsumer { fn emit(&mut self, _: T) -> bool { self.is_closed.set(true); false } } impl<C, T> Consumer<T> for TakeUntilState<C> where C: Consumer<T> { fn
(&mut self, item: T) -> bool { !self.is_closed.get() && self.consumer.emit(item) } } impl<S, T> Stream for TakeUntil<S, T> where S: Stream, T: Stream { type Item = S::Item; fn consume<C>(self, consumer: C) where C: Consumer<Self::Item> { let is_closed = Rc::new(Cell::new(false)); self.trigger.consume(TriggerConsumer { is_closed: is_closed.clone() }); self.stream.consume(TakeUntilState { consumer: consumer, is_closed: is_closed, }); } } impl<S, T> TakeUntil<S, T> { pub fn new(stream: S, trigger: T) -> Self { TakeUntil { stream: stream, trigger: trigger, } } }
emit
identifier_name
take_until.rs
use consumer::*; use std::cell::Cell; use std::rc::Rc; use stream::*; /// Emit items until it receive an item from another stream. /// /// This struct is created by the /// [`take_until()`](./trait.Stream.html#method.take_until) method on /// [Stream](./trait.Stream.html). See its documentation for more. #[must_use = "stream adaptors are lazy and do nothing unless consumed"] pub struct TakeUntil<S, T> { stream: S, trigger: T, } struct TakeUntilState<C> { consumer: C, is_closed: Rc<Cell<bool>>, } struct TriggerConsumer { is_closed: Rc<Cell<bool>>, } impl<T> Consumer<T> for TriggerConsumer { fn emit(&mut self, _: T) -> bool { self.is_closed.set(true); false } } impl<C, T> Consumer<T> for TakeUntilState<C> where C: Consumer<T> { fn emit(&mut self, item: T) -> bool
} impl<S, T> Stream for TakeUntil<S, T> where S: Stream, T: Stream { type Item = S::Item; fn consume<C>(self, consumer: C) where C: Consumer<Self::Item> { let is_closed = Rc::new(Cell::new(false)); self.trigger.consume(TriggerConsumer { is_closed: is_closed.clone() }); self.stream.consume(TakeUntilState { consumer: consumer, is_closed: is_closed, }); } } impl<S, T> TakeUntil<S, T> { pub fn new(stream: S, trigger: T) -> Self { TakeUntil { stream: stream, trigger: trigger, } } }
{ !self.is_closed.get() && self.consumer.emit(item) }
identifier_body
take_until.rs
use consumer::*; use std::cell::Cell; use std::rc::Rc; use stream::*; /// Emit items until it receive an item from another stream.
pub struct TakeUntil<S, T> { stream: S, trigger: T, } struct TakeUntilState<C> { consumer: C, is_closed: Rc<Cell<bool>>, } struct TriggerConsumer { is_closed: Rc<Cell<bool>>, } impl<T> Consumer<T> for TriggerConsumer { fn emit(&mut self, _: T) -> bool { self.is_closed.set(true); false } } impl<C, T> Consumer<T> for TakeUntilState<C> where C: Consumer<T> { fn emit(&mut self, item: T) -> bool { !self.is_closed.get() && self.consumer.emit(item) } } impl<S, T> Stream for TakeUntil<S, T> where S: Stream, T: Stream { type Item = S::Item; fn consume<C>(self, consumer: C) where C: Consumer<Self::Item> { let is_closed = Rc::new(Cell::new(false)); self.trigger.consume(TriggerConsumer { is_closed: is_closed.clone() }); self.stream.consume(TakeUntilState { consumer: consumer, is_closed: is_closed, }); } } impl<S, T> TakeUntil<S, T> { pub fn new(stream: S, trigger: T) -> Self { TakeUntil { stream: stream, trigger: trigger, } } }
/// /// This struct is created by the /// [`take_until()`](./trait.Stream.html#method.take_until) method on /// [Stream](./trait.Stream.html). See its documentation for more. #[must_use = "stream adaptors are lazy and do nothing unless consumed"]
random_line_split
orgs.rs
use clap::{App, Arg, ArgMatches, SubCommand}; use config; use git_hub::{GitHubResponse, orgs}; use serde_json; use serde_json::Error; pub fn SUBCOMMAND<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("orgs") .about("List, Get, Edit your GitHub Organizations") .version(version!()) .author("penland365 <[email protected]>") .subcommand(SubCommand::with_name("list") .about("Lists GitHub Organizations for the credentialed user.") .arg(Arg::with_name("user") .short("u") .long("user") .help("Searches for public organizations for this user") .value_name("octocat") .takes_value(true)) .arg(Arg::with_name("format") .short("f") .long("format") .help("Sets the output format.") .value_name("json") .takes_value(true))) } pub fn handle(matches: &ArgMatches) -> () { match matches.subcommand() { ("list", Some(list_matches)) => list::handle(list_matches), ("", None) => println!("No subcommand was used for orgs"), (_, _) => unreachable!() } } mod list { use clap::ArgMatches; use config::load_config; use evidence::json_ops; use git_hub::{GitHubResponse, orgs}; use hyper::status::StatusCode; use git_hub::orgs::OrgSummary; #[cfg(windows)] pub const NL: &'static str = "\r\n"; #[cfg(not(windows))] pub const NL: &'static str = "\n"; pub fn handle(matches: &ArgMatches) -> () { let response = match matches.value_of("user") { None => orgs::get_authed_user_orgs(&load_config()), Some(user) => orgs::get_user_public_orgs(user, &load_config()), }; let is_json = match matches.value_of("format") { None => false, Some(format) => format == "json" }; let output = &build_output(&response, is_json); println!("{}", output.trim()); } fn build_output(response: &GitHubResponse, is_json: bool) -> String { match response.status { StatusCode::Forbidden => FORBIDDEN.to_owned(), StatusCode::Unauthorized => UNAUTHORIZED.to_owned(), StatusCode::Ok => match response.body { None => build_200_ok_no_string_body_output(), Some(ref body) => format_output(body.to_owned(), is_json), }, x => format!("Unexpected Http Response Code {}", x) } } fn build_200_ok_no_string_body_output() -> String { format!("An unknown error occurred. GitHub responded with {}, but no string body was found.", StatusCode::Ok) } fn format_output(body: String, is_json: bool) -> String { let orgs: Vec<OrgSummary> = json_ops::from_str_or_die(&body, DESERIALIZE_ORG_SUMMARY); if is_json { json_ops::to_pretty_json_or_die(&orgs, SERIALIZE_ORG_SUMMARY) } else { let mut output = String::with_capacity(100); let header = format!("{0: <10} {1: <10} {2: <45} {3: <30}", "login", "id", "url", "description"); output.push_str(&header); output.push_str(NL); for org in orgs { let line = format!("{0: <10} {1: <10} {2: <45} {3: <30}", org.login, org.id, org.url, org.description); output.push_str(&line); output.push_str(NL); } output } } const DESERIALIZE_ORG_SUMMARY: &'static str = "Error deserializing GitHub Organization Summary JSON."; const SERIALIZE_ORG_SUMMARY: &'static str = "Error serializing GitHub Organization Summary JSON."; const UNAUTHORIZED: &'static str = "401 Unauthorized. Bad Credentials. See https://developer.github.com/v3"; const FORBIDDEN: &'static str = "403 Forbidden. Does your OAuth token have suffecient scope? A minimum of `user` or `read:org` is required. See https://developer.github.com/v3/orgs/"; #[cfg(test)] mod tests { use git_hub::GitHubResponse; use hyper::header::Headers; use hyper::status::StatusCode; use super::{build_output, FORBIDDEN, UNAUTHORIZED}; #[test] fn
() -> () { let response = GitHubResponse { status: StatusCode::Forbidden, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), FORBIDDEN); } #[test] fn test_build_output_unauthorized() -> () { let response = GitHubResponse { status: StatusCode::Unauthorized, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), UNAUTHORIZED); } #[test] fn test_build_output_unknown() -> () { let response = GitHubResponse { status: StatusCode::ImATeapot, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), "Unexpected Http Response Code 418 I'm a teapot"); } #[test] fn test_build_200_ok_no_string_body_output() -> () { assert_eq!(super::build_200_ok_no_string_body_output(), "An unknown error occurred. GitHub responded with 200 OK, but no string body was found."); } #[test] fn test_build_output_no_string_body() -> () { let response = GitHubResponse { status: StatusCode::Ok, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), "An unknown error occurred. GitHub responded with 200 OK, but no string body was found."); } } } // get finagle // patch finagle // list
test_build_output_forbidden
identifier_name
orgs.rs
use clap::{App, Arg, ArgMatches, SubCommand}; use config; use git_hub::{GitHubResponse, orgs}; use serde_json; use serde_json::Error; pub fn SUBCOMMAND<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("orgs") .about("List, Get, Edit your GitHub Organizations") .version(version!()) .author("penland365 <[email protected]>") .subcommand(SubCommand::with_name("list") .about("Lists GitHub Organizations for the credentialed user.") .arg(Arg::with_name("user") .short("u") .long("user") .help("Searches for public organizations for this user") .value_name("octocat") .takes_value(true)) .arg(Arg::with_name("format") .short("f") .long("format") .help("Sets the output format.") .value_name("json") .takes_value(true))) } pub fn handle(matches: &ArgMatches) -> () { match matches.subcommand() { ("list", Some(list_matches)) => list::handle(list_matches), ("", None) => println!("No subcommand was used for orgs"),
mod list { use clap::ArgMatches; use config::load_config; use evidence::json_ops; use git_hub::{GitHubResponse, orgs}; use hyper::status::StatusCode; use git_hub::orgs::OrgSummary; #[cfg(windows)] pub const NL: &'static str = "\r\n"; #[cfg(not(windows))] pub const NL: &'static str = "\n"; pub fn handle(matches: &ArgMatches) -> () { let response = match matches.value_of("user") { None => orgs::get_authed_user_orgs(&load_config()), Some(user) => orgs::get_user_public_orgs(user, &load_config()), }; let is_json = match matches.value_of("format") { None => false, Some(format) => format == "json" }; let output = &build_output(&response, is_json); println!("{}", output.trim()); } fn build_output(response: &GitHubResponse, is_json: bool) -> String { match response.status { StatusCode::Forbidden => FORBIDDEN.to_owned(), StatusCode::Unauthorized => UNAUTHORIZED.to_owned(), StatusCode::Ok => match response.body { None => build_200_ok_no_string_body_output(), Some(ref body) => format_output(body.to_owned(), is_json), }, x => format!("Unexpected Http Response Code {}", x) } } fn build_200_ok_no_string_body_output() -> String { format!("An unknown error occurred. GitHub responded with {}, but no string body was found.", StatusCode::Ok) } fn format_output(body: String, is_json: bool) -> String { let orgs: Vec<OrgSummary> = json_ops::from_str_or_die(&body, DESERIALIZE_ORG_SUMMARY); if is_json { json_ops::to_pretty_json_or_die(&orgs, SERIALIZE_ORG_SUMMARY) } else { let mut output = String::with_capacity(100); let header = format!("{0: <10} {1: <10} {2: <45} {3: <30}", "login", "id", "url", "description"); output.push_str(&header); output.push_str(NL); for org in orgs { let line = format!("{0: <10} {1: <10} {2: <45} {3: <30}", org.login, org.id, org.url, org.description); output.push_str(&line); output.push_str(NL); } output } } const DESERIALIZE_ORG_SUMMARY: &'static str = "Error deserializing GitHub Organization Summary JSON."; const SERIALIZE_ORG_SUMMARY: &'static str = "Error serializing GitHub Organization Summary JSON."; const UNAUTHORIZED: &'static str = "401 Unauthorized. Bad Credentials. See https://developer.github.com/v3"; const FORBIDDEN: &'static str = "403 Forbidden. Does your OAuth token have suffecient scope? A minimum of `user` or `read:org` is required. See https://developer.github.com/v3/orgs/"; #[cfg(test)] mod tests { use git_hub::GitHubResponse; use hyper::header::Headers; use hyper::status::StatusCode; use super::{build_output, FORBIDDEN, UNAUTHORIZED}; #[test] fn test_build_output_forbidden() -> () { let response = GitHubResponse { status: StatusCode::Forbidden, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), FORBIDDEN); } #[test] fn test_build_output_unauthorized() -> () { let response = GitHubResponse { status: StatusCode::Unauthorized, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), UNAUTHORIZED); } #[test] fn test_build_output_unknown() -> () { let response = GitHubResponse { status: StatusCode::ImATeapot, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), "Unexpected Http Response Code 418 I'm a teapot"); } #[test] fn test_build_200_ok_no_string_body_output() -> () { assert_eq!(super::build_200_ok_no_string_body_output(), "An unknown error occurred. GitHub responded with 200 OK, but no string body was found."); } #[test] fn test_build_output_no_string_body() -> () { let response = GitHubResponse { status: StatusCode::Ok, headers: Headers::new(), body: None }; assert_eq!(build_output(&response, false), "An unknown error occurred. GitHub responded with 200 OK, but no string body was found."); } } } // get finagle // patch finagle // list
(_, _) => unreachable!() } }
random_line_split