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
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use crate::log::*; use crate::kerberos::*; use crate::smb::smb::*; use crate::smb::smb1_session::*; use crate::smb::auth::*; #[derive(Debug)] pub struct SMBTransactionSessionSetup { pub request_host: Option<SessionSetupRequest>, pub response_host: Option<SessionSetupResponse>, pub ntlmssp: Option<NtlmsspData>, pub krb_ticket: Option<Kerberos5Ticket>, } impl SMBTransactionSessionSetup { pub fn
() -> SMBTransactionSessionSetup { return SMBTransactionSessionSetup { request_host: None, response_host: None, ntlmssp: None, krb_ticket: None, } } } impl SMBState { pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> &mut SMBTransaction { let mut tx = self.new_tx(); tx.hdr = hdr; tx.type_data = Some(SMBTransactionTypeData::SESSIONSETUP( SMBTransactionSessionSetup::new())); tx.request_done = true; tx.response_done = self.tc_trunc; // no response expected if tc is truncated SCLogDebug!("SMB: TX SESSIONSETUP created: ID {}", tx.id); self.transactions.push(tx); let tx_ref = self.transactions.last_mut(); return tx_ref.unwrap(); } pub fn get_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> Option<&mut SMBTransaction> { for tx in &mut self.transactions { let hit = tx.hdr.compare(&hdr) && match tx.type_data { Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true }, _ => { false }, }; if hit { return Some(tx); } } return None; } }
new
identifier_name
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use crate::log::*; use crate::kerberos::*; use crate::smb::smb::*; use crate::smb::smb1_session::*; use crate::smb::auth::*; #[derive(Debug)] pub struct SMBTransactionSessionSetup { pub request_host: Option<SessionSetupRequest>, pub response_host: Option<SessionSetupResponse>, pub ntlmssp: Option<NtlmsspData>, pub krb_ticket: Option<Kerberos5Ticket>,
return SMBTransactionSessionSetup { request_host: None, response_host: None, ntlmssp: None, krb_ticket: None, } } } impl SMBState { pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> &mut SMBTransaction { let mut tx = self.new_tx(); tx.hdr = hdr; tx.type_data = Some(SMBTransactionTypeData::SESSIONSETUP( SMBTransactionSessionSetup::new())); tx.request_done = true; tx.response_done = self.tc_trunc; // no response expected if tc is truncated SCLogDebug!("SMB: TX SESSIONSETUP created: ID {}", tx.id); self.transactions.push(tx); let tx_ref = self.transactions.last_mut(); return tx_ref.unwrap(); } pub fn get_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> Option<&mut SMBTransaction> { for tx in &mut self.transactions { let hit = tx.hdr.compare(&hdr) && match tx.type_data { Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true }, _ => { false }, }; if hit { return Some(tx); } } return None; } }
} impl SMBTransactionSessionSetup { pub fn new() -> SMBTransactionSessionSetup {
random_line_split
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use crate::log::*; use crate::kerberos::*; use crate::smb::smb::*; use crate::smb::smb1_session::*; use crate::smb::auth::*; #[derive(Debug)] pub struct SMBTransactionSessionSetup { pub request_host: Option<SessionSetupRequest>, pub response_host: Option<SessionSetupResponse>, pub ntlmssp: Option<NtlmsspData>, pub krb_ticket: Option<Kerberos5Ticket>, } impl SMBTransactionSessionSetup { pub fn new() -> SMBTransactionSessionSetup { return SMBTransactionSessionSetup { request_host: None, response_host: None, ntlmssp: None, krb_ticket: None, } } } impl SMBState { pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> &mut SMBTransaction { let mut tx = self.new_tx(); tx.hdr = hdr; tx.type_data = Some(SMBTransactionTypeData::SESSIONSETUP( SMBTransactionSessionSetup::new())); tx.request_done = true; tx.response_done = self.tc_trunc; // no response expected if tc is truncated SCLogDebug!("SMB: TX SESSIONSETUP created: ID {}", tx.id); self.transactions.push(tx); let tx_ref = self.transactions.last_mut(); return tx_ref.unwrap(); } pub fn get_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> Option<&mut SMBTransaction>
}
{ for tx in &mut self.transactions { let hit = tx.hdr.compare(&hdr) && match tx.type_data { Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true }, _ => { false }, }; if hit { return Some(tx); } } return None; }
identifier_body
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { let mut rand_str = vec![0; len]; thread_rng().fill_bytes(&mut rand_str); rand_str } #[inline] fn generate_requests(map: &HashMap<&[u8], &[u8]>) -> Vec<Request> { let mut reqs = vec![]; for (key, value) in map { let mut r = Request::default(); r.set_cmd_type(CmdType::Put); r.mut_put().set_cf("tikv".to_owned()); r.mut_put().set_key(key.to_vec()); r.mut_put().set_value(value.to_vec()); reqs.push(r); } reqs } fn encode(map: &HashMap<&[u8], &[u8]>) -> Vec<u8> { let mut e = Entry::default(); let mut cmd = RaftCmdRequest::default(); let reqs = generate_requests(map); cmd.set_requests(reqs.into()); let cmd_msg = cmd.write_to_bytes().unwrap(); e.set_data(cmd_msg.into()); e.write_to_bytes().unwrap() } fn decode(data: &[u8]) { let mut entry = Entry::default(); entry.merge_from_bytes(data).unwrap(); let mut cmd = RaftCmdRequest::default(); cmd.merge_from_bytes(entry.get_data()).unwrap(); } #[bench] fn bench_encode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); let data = encode(&map); b.iter(|| { decode(&data); }); } #[bench] fn bench_encode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock);
b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); let data = encode(&map); b.iter(|| { decode(&data); }); }
map.insert(&key_for_data, &value_for_data);
random_line_split
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { let mut rand_str = vec![0; len]; thread_rng().fill_bytes(&mut rand_str); rand_str } #[inline] fn generate_requests(map: &HashMap<&[u8], &[u8]>) -> Vec<Request> { let mut reqs = vec![]; for (key, value) in map { let mut r = Request::default(); r.set_cmd_type(CmdType::Put); r.mut_put().set_cf("tikv".to_owned()); r.mut_put().set_key(key.to_vec()); r.mut_put().set_value(value.to_vec()); reqs.push(r); } reqs } fn encode(map: &HashMap<&[u8], &[u8]>) -> Vec<u8> { let mut e = Entry::default(); let mut cmd = RaftCmdRequest::default(); let reqs = generate_requests(map); cmd.set_requests(reqs.into()); let cmd_msg = cmd.write_to_bytes().unwrap(); e.set_data(cmd_msg.into()); e.write_to_bytes().unwrap() } fn decode(data: &[u8]) { let mut entry = Entry::default(); entry.merge_from_bytes(data).unwrap(); let mut cmd = RaftCmdRequest::default(); cmd.merge_from_bytes(entry.get_data()).unwrap(); } #[bench] fn bench_encode_one(b: &mut Bencher)
#[bench] fn bench_decode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); let data = encode(&map); b.iter(|| { decode(&data); }); } #[bench] fn bench_encode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); let data = encode(&map); b.iter(|| { decode(&data); }); }
{ let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); b.iter(|| { encode(&map); }); }
identifier_body
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { let mut rand_str = vec![0; len]; thread_rng().fill_bytes(&mut rand_str); rand_str } #[inline] fn generate_requests(map: &HashMap<&[u8], &[u8]>) -> Vec<Request> { let mut reqs = vec![]; for (key, value) in map { let mut r = Request::default(); r.set_cmd_type(CmdType::Put); r.mut_put().set_cf("tikv".to_owned()); r.mut_put().set_key(key.to_vec()); r.mut_put().set_value(value.to_vec()); reqs.push(r); } reqs } fn encode(map: &HashMap<&[u8], &[u8]>) -> Vec<u8> { let mut e = Entry::default(); let mut cmd = RaftCmdRequest::default(); let reqs = generate_requests(map); cmd.set_requests(reqs.into()); let cmd_msg = cmd.write_to_bytes().unwrap(); e.set_data(cmd_msg.into()); e.write_to_bytes().unwrap() } fn decode(data: &[u8]) { let mut entry = Entry::default(); entry.merge_from_bytes(data).unwrap(); let mut cmd = RaftCmdRequest::default(); cmd.merge_from_bytes(entry.get_data()).unwrap(); } #[bench] fn bench_encode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); let data = encode(&map); b.iter(|| { decode(&data); }); } #[bench] fn bench_encode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); b.iter(|| { encode(&map); }); } #[bench] fn
(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); let data = encode(&map); b.iter(|| { decode(&data); }); }
bench_decode_two
identifier_name
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn
() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); // シャドーイングにより、16行目で定義したguess変数を隠し、新しい変数定義を利用できる let guess: u32 = match guess.trim().parse() { // 入力には改行文字が含まれるため、 trim()で削除する Ok(num) => num, Err(_) => continue, // 数値以外が入ってきてもエラーにはせずループを続行させる }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
main
identifier_name
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main()
println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
{ println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); // シャドーイングにより、16行目で定義したguess変数を隠し、新しい変数定義を利用できる let guess: u32 = match guess.trim().parse() { // 入力には改行文字が含まれるため、 trim()で削除する Ok(num) => num, Err(_) => continue, // 数値以外が入ってきてもエラーにはせずループを続行させる };
identifier_body
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); // シャドーイングにより、16行目で定義したguess変数を隠し、新しい変数定義を利用できる let guess: u32 = match guess.trim().parse() { // 入力には改行文字が含まれるため、 trim()で削除する Ok(num) => num, Err(_) => continue, // 数値以外が入ってきてもエラーにはせずループを続行させる }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
conditional_block
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); // シャドーイングにより、16行目で定義したguess変数を隠し、新しい変数定義を利用できる let guess: u32 = match guess.trim().parse() { // 入力には改行文字が含まれるため、 trim()で削除する Ok(num) => num, Err(_) => continue, // 数値以外が入ってきてもエラーにはせずループを続行させる }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"),
break; } } } }
Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!");
random_line_split
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum State { Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Left, Right, Up, Down, Space, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Shift, LeftCtrl, RightCtrl, LeftAlt, RightAlt, CapsLock, Pause, PageUp, PageDown, PrintScreen, Insert, End, Home, Delete, Add, Subtract, Multiply, Separator, Decimal, Divide, BackTick, BackSlash, ForwardSlash, Plus, Minus, FullStop, Comma, Tab, Numlock, LeftSquareBracket, RightSquareBracket, SemiColon, Apostrophe, Hash, } /// Mouse Buttons #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum MouseButton { Left, Right, Middle, Button4, Button5, } #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum Axis { X, Y, Z, RX, RY, RZ, SLIDER, } /// Event types /// /// The usize entry acts as a device ID unique to each DeviceType (Mouse, Keyboard, Hid). /// Keyboard press events repeat when a key is held down. #[derive(Clone, Debug)] pub enum RawEvent { MouseButtonEvent(usize, MouseButton, State), MouseMoveEvent(usize, i32, i32), MouseWheelEvent(usize, f32), KeyboardEvent(usize, KeyId, State), JoystickButtonEvent(usize, usize, State), JoystickAxisEvent(usize, Axis, f64), JoystickHatSwitchEvent(usize, HatSwitch), } impl JoystickState { pub fn compare_states(&self, other_state: JoystickState, id: usize) -> Vec<RawEvent> { let mut output: Vec<RawEvent> = Vec::new(); for (index, (&press_state, _)) in self .button_states .iter() .zip(other_state.button_states.iter()) .enumerate() .filter(|&(_, (&a, &b))| a!= b) { output.push(RawEvent::JoystickButtonEvent( id, index, if press_state { State::Released } else { State::Pressed }, )); } if self.raw_axis_states.x!= other_state.raw_axis_states.x { if let Some(value) = other_state.axis_states.x { output.push(RawEvent::JoystickAxisEvent(id, Axis::X, value)); } } if self.raw_axis_states.y!= other_state.raw_axis_states.y { if let Some(value) = other_state.axis_states.y { output.push(RawEvent::JoystickAxisEvent(id, Axis::Y, value)); } } if self.raw_axis_states.z!= other_state.raw_axis_states.z { if let Some(value) = other_state.axis_states.z { output.push(RawEvent::JoystickAxisEvent(id, Axis::Z, value)); } } if self.raw_axis_states.rx!= other_state.raw_axis_states.rx { if let Some(value) = other_state.axis_states.rx { output.push(RawEvent::JoystickAxisEvent(id, Axis::RX, value)); } } if self.raw_axis_states.ry!= other_state.raw_axis_states.ry { if let Some(value) = other_state.axis_states.ry { output.push(RawEvent::JoystickAxisEvent(id, Axis::RY, value)); } } if self.raw_axis_states.rz!= other_state.raw_axis_states.rz { if let Some(value) = other_state.axis_states.rz { output.push(RawEvent::JoystickAxisEvent(id, Axis::RZ, value)); } } if self.raw_axis_states.slider!= other_state.raw_axis_states.slider { if let Some(value) = other_state.axis_states.slider { output.push(RawEvent::JoystickAxisEvent(id, Axis::SLIDER, value)); } }
if let Some(value_self) = self.hatswitch.clone() { if value_self!= value_other { output.push(RawEvent::JoystickHatSwitchEvent(id, value_other)); } } } output } }
if let Some(value_other) = other_state.hatswitch {
random_line_split
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum State { Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Left, Right, Up, Down, Space, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Shift, LeftCtrl, RightCtrl, LeftAlt, RightAlt, CapsLock, Pause, PageUp, PageDown, PrintScreen, Insert, End, Home, Delete, Add, Subtract, Multiply, Separator, Decimal, Divide, BackTick, BackSlash, ForwardSlash, Plus, Minus, FullStop, Comma, Tab, Numlock, LeftSquareBracket, RightSquareBracket, SemiColon, Apostrophe, Hash, } /// Mouse Buttons #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum MouseButton { Left, Right, Middle, Button4, Button5, } #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum Axis { X, Y, Z, RX, RY, RZ, SLIDER, } /// Event types /// /// The usize entry acts as a device ID unique to each DeviceType (Mouse, Keyboard, Hid). /// Keyboard press events repeat when a key is held down. #[derive(Clone, Debug)] pub enum RawEvent { MouseButtonEvent(usize, MouseButton, State), MouseMoveEvent(usize, i32, i32), MouseWheelEvent(usize, f32), KeyboardEvent(usize, KeyId, State), JoystickButtonEvent(usize, usize, State), JoystickAxisEvent(usize, Axis, f64), JoystickHatSwitchEvent(usize, HatSwitch), } impl JoystickState { pub fn compare_states(&self, other_state: JoystickState, id: usize) -> Vec<RawEvent> { let mut output: Vec<RawEvent> = Vec::new(); for (index, (&press_state, _)) in self .button_states .iter() .zip(other_state.button_states.iter()) .enumerate() .filter(|&(_, (&a, &b))| a!= b) { output.push(RawEvent::JoystickButtonEvent( id, index, if press_state { State::Released } else { State::Pressed }, )); } if self.raw_axis_states.x!= other_state.raw_axis_states.x { if let Some(value) = other_state.axis_states.x { output.push(RawEvent::JoystickAxisEvent(id, Axis::X, value)); } } if self.raw_axis_states.y!= other_state.raw_axis_states.y { if let Some(value) = other_state.axis_states.y { output.push(RawEvent::JoystickAxisEvent(id, Axis::Y, value)); } } if self.raw_axis_states.z!= other_state.raw_axis_states.z { if let Some(value) = other_state.axis_states.z { output.push(RawEvent::JoystickAxisEvent(id, Axis::Z, value)); } } if self.raw_axis_states.rx!= other_state.raw_axis_states.rx { if let Some(value) = other_state.axis_states.rx { output.push(RawEvent::JoystickAxisEvent(id, Axis::RX, value)); } } if self.raw_axis_states.ry!= other_state.raw_axis_states.ry { if let Some(value) = other_state.axis_states.ry { output.push(RawEvent::JoystickAxisEvent(id, Axis::RY, value)); } } if self.raw_axis_states.rz!= other_state.raw_axis_states.rz { if let Some(value) = other_state.axis_states.rz { output.push(RawEvent::JoystickAxisEvent(id, Axis::RZ, value)); } } if self.raw_axis_states.slider!= other_state.raw_axis_states.slider { if let Some(value) = other_state.axis_states.slider
} if let Some(value_other) = other_state.hatswitch { if let Some(value_self) = self.hatswitch.clone() { if value_self!= value_other { output.push(RawEvent::JoystickHatSwitchEvent(id, value_other)); } } } output } }
{ output.push(RawEvent::JoystickAxisEvent(id, Axis::SLIDER, value)); }
conditional_block
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum
{ Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Left, Right, Up, Down, Space, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Shift, LeftCtrl, RightCtrl, LeftAlt, RightAlt, CapsLock, Pause, PageUp, PageDown, PrintScreen, Insert, End, Home, Delete, Add, Subtract, Multiply, Separator, Decimal, Divide, BackTick, BackSlash, ForwardSlash, Plus, Minus, FullStop, Comma, Tab, Numlock, LeftSquareBracket, RightSquareBracket, SemiColon, Apostrophe, Hash, } /// Mouse Buttons #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum MouseButton { Left, Right, Middle, Button4, Button5, } #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum Axis { X, Y, Z, RX, RY, RZ, SLIDER, } /// Event types /// /// The usize entry acts as a device ID unique to each DeviceType (Mouse, Keyboard, Hid). /// Keyboard press events repeat when a key is held down. #[derive(Clone, Debug)] pub enum RawEvent { MouseButtonEvent(usize, MouseButton, State), MouseMoveEvent(usize, i32, i32), MouseWheelEvent(usize, f32), KeyboardEvent(usize, KeyId, State), JoystickButtonEvent(usize, usize, State), JoystickAxisEvent(usize, Axis, f64), JoystickHatSwitchEvent(usize, HatSwitch), } impl JoystickState { pub fn compare_states(&self, other_state: JoystickState, id: usize) -> Vec<RawEvent> { let mut output: Vec<RawEvent> = Vec::new(); for (index, (&press_state, _)) in self .button_states .iter() .zip(other_state.button_states.iter()) .enumerate() .filter(|&(_, (&a, &b))| a!= b) { output.push(RawEvent::JoystickButtonEvent( id, index, if press_state { State::Released } else { State::Pressed }, )); } if self.raw_axis_states.x!= other_state.raw_axis_states.x { if let Some(value) = other_state.axis_states.x { output.push(RawEvent::JoystickAxisEvent(id, Axis::X, value)); } } if self.raw_axis_states.y!= other_state.raw_axis_states.y { if let Some(value) = other_state.axis_states.y { output.push(RawEvent::JoystickAxisEvent(id, Axis::Y, value)); } } if self.raw_axis_states.z!= other_state.raw_axis_states.z { if let Some(value) = other_state.axis_states.z { output.push(RawEvent::JoystickAxisEvent(id, Axis::Z, value)); } } if self.raw_axis_states.rx!= other_state.raw_axis_states.rx { if let Some(value) = other_state.axis_states.rx { output.push(RawEvent::JoystickAxisEvent(id, Axis::RX, value)); } } if self.raw_axis_states.ry!= other_state.raw_axis_states.ry { if let Some(value) = other_state.axis_states.ry { output.push(RawEvent::JoystickAxisEvent(id, Axis::RY, value)); } } if self.raw_axis_states.rz!= other_state.raw_axis_states.rz { if let Some(value) = other_state.axis_states.rz { output.push(RawEvent::JoystickAxisEvent(id, Axis::RZ, value)); } } if self.raw_axis_states.slider!= other_state.raw_axis_states.slider { if let Some(value) = other_state.axis_states.slider { output.push(RawEvent::JoystickAxisEvent(id, Axis::SLIDER, value)); } } if let Some(value_other) = other_state.hatswitch { if let Some(value_self) = self.hatswitch.clone() { if value_self!= value_other { output.push(RawEvent::JoystickHatSwitchEvent(id, value_other)); } } } output } }
State
identifier_name
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol; use self::nanomsg::{Socket, Protocol, Error}; pub fn run(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>)
if let Err(_) = tx_state.send(state) { break; } }, Err(Error::TryAgain) => {}, Err(err) => panic!("Problem receiving msg: {}", err), } thread::sleep(Duration::from_millis(super::HOST_SYNC_INTERVAL_MS / 2)); } }
{ let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); match subscriber.connect("tcp://*:5555") { Ok(_) => println!("Connected to server..."), Err(err) => panic!("Failed to bind socket: {}", err) } let mut msg_buffer: [u8; 9] = [0; 9]; while let Err(_) = rx_quit.try_recv() { match subscriber.nb_read(&mut msg_buffer) { Ok(_) => { let state = protocol::into_state(&msg_buffer[0..9]); println!("Received {:?}", state); // debug
identifier_body
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol; use self::nanomsg::{Socket, Protocol, Error}; pub fn
(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) { let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); match subscriber.connect("tcp://*:5555") { Ok(_) => println!("Connected to server..."), Err(err) => panic!("Failed to bind socket: {}", err) } let mut msg_buffer: [u8; 9] = [0; 9]; while let Err(_) = rx_quit.try_recv() { match subscriber.nb_read(&mut msg_buffer) { Ok(_) => { let state = protocol::into_state(&msg_buffer[0..9]); println!("Received {:?}", state); // debug if let Err(_) = tx_state.send(state) { break; } }, Err(Error::TryAgain) => {}, Err(err) => panic!("Problem receiving msg: {}", err), } thread::sleep(Duration::from_millis(super::HOST_SYNC_INTERVAL_MS / 2)); } }
run
identifier_name
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol;
pub fn run(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) { let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); match subscriber.connect("tcp://*:5555") { Ok(_) => println!("Connected to server..."), Err(err) => panic!("Failed to bind socket: {}", err) } let mut msg_buffer: [u8; 9] = [0; 9]; while let Err(_) = rx_quit.try_recv() { match subscriber.nb_read(&mut msg_buffer) { Ok(_) => { let state = protocol::into_state(&msg_buffer[0..9]); println!("Received {:?}", state); // debug if let Err(_) = tx_state.send(state) { break; } }, Err(Error::TryAgain) => {}, Err(err) => panic!("Problem receiving msg: {}", err), } thread::sleep(Duration::from_millis(super::HOST_SYNC_INTERVAL_MS / 2)); } }
use self::nanomsg::{Socket, Protocol, Error};
random_line_split
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route; #[get("/<path..>")] fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::local::Client; fn assert_path(client: &Client, path: &str) { let mut res = client.get(path).dispatch(); assert_eq!(res.body_string(), Some(path.into())); } #[test] fn check_mount_path()
}
{ let rocket = rocket::ignite() .mount("/first", routes![files]) .mount("/second", routes![files]); let client = Client::new(rocket).unwrap(); assert_path(&client, "/first/some/path"); assert_path(&client, "/second/some/path"); assert_path(&client, "/first/second/b/c"); assert_path(&client, "/second/a/b/c"); }
identifier_body
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route;
fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::local::Client; fn assert_path(client: &Client, path: &str) { let mut res = client.get(path).dispatch(); assert_eq!(res.body_string(), Some(path.into())); } #[test] fn check_mount_path() { let rocket = rocket::ignite() .mount("/first", routes![files]) .mount("/second", routes![files]); let client = Client::new(rocket).unwrap(); assert_path(&client, "/first/some/path"); assert_path(&client, "/second/some/path"); assert_path(&client, "/first/second/b/c"); assert_path(&client, "/second/a/b/c"); } }
#[get("/<path..>")]
random_line_split
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route; #[get("/<path..>")] fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::local::Client; fn
(client: &Client, path: &str) { let mut res = client.get(path).dispatch(); assert_eq!(res.body_string(), Some(path.into())); } #[test] fn check_mount_path() { let rocket = rocket::ignite() .mount("/first", routes![files]) .mount("/second", routes![files]); let client = Client::new(rocket).unwrap(); assert_path(&client, "/first/some/path"); assert_path(&client, "/second/some/path"); assert_path(&client, "/first/second/b/c"); assert_path(&client, "/second/a/b/c"); } }
assert_path
identifier_name
rcvr-borrowed-to-region.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. trait get { fn get(self) -> int; } // Note: impl on a slice; we're checking that the pointers below // correctly get borrowed to `&`. (similar to impling for `int`, with // `&self` instead of `self`.) impl<'self> get for &'self int { fn get(self) -> int { return *self; } }
assert_eq!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); }
pub fn main() { let x = @mut 6; let y = x.get();
random_line_split
rcvr-borrowed-to-region.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. trait get { fn get(self) -> int; } // Note: impl on a slice; we're checking that the pointers below // correctly get borrowed to `&`. (similar to impling for `int`, with // `&self` instead of `self`.) impl<'self> get for &'self int { fn get(self) -> int { return *self; } } pub fn main()
{ let x = @mut 6; let y = x.get(); assert_eq!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); }
identifier_body
rcvr-borrowed-to-region.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. trait get { fn get(self) -> int; } // Note: impl on a slice; we're checking that the pointers below // correctly get borrowed to `&`. (similar to impling for `int`, with // `&self` instead of `self`.) impl<'self> get for &'self int { fn
(self) -> int { return *self; } } pub fn main() { let x = @mut 6; let y = x.get(); assert_eq!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); }
get
identifier_name
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct Ast(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &str) -> Result<Ast, ~str> { /* We parse loops by making a context to group its operators, pushing on it until the matching loop end. As we create the context, we push the previous one onto a stack. After the nest has been collected, we pop the context and replace it with the subprocess operator. */ let mut stack:~[ ~[Operator] ] = ~[]; let mut ops: ~[Operator] = ~[]; for token in source.chars() { match from_str::<Operator>(token.to_str()) { /* Start of a loop. Produce a new context in which to push operators, and push the old one on the stack. */ Some(Skip) => { stack.push(ops); ops = ~[]; } /* End of a loop. Make a subprocess operator out of the just-collected context, and push that on the previous context. */ Some(Loop) => { let sub_ast = Sub(Ast( ops )); // Try to pop the previous context from the stack. // If this does not work, it's an unmatched `]`. ops = match stack.pop() { Some(ops) => ops, _ => return Err(~"Unmatched `]`."), }; ops.push(sub_ast); } // Push the operator onto the context. Some(op) => ops.push(op), // Unknown. Probably comments. Nop. _ => continue } } // If we still have things on the stack, then we have one or // more unmatched `[`. if! stack.is_empty() { return Err(~"Unmatched `[`."); } // Everything went well. return Ok(Ast(ops)); } } impl FromStr for Ast { fn from_str(source: &str) -> Option<Ast> { Ast::parse_str(source).ok() } } impl fmt::Show for Ast { /** Parses a string into the matching operator. */
) } }
fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let &Ast(ref ops) = self; let display = |op: &Operator| -> ~str { format!("{}", op) }; let repr: ~[~str] = ops.iter().map(display).collect(); f.buf.write(format!("{}", repr.concat()).as_bytes()
random_line_split
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct Ast(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &str) -> Result<Ast, ~str>
ops = ~[]; } /* End of a loop. Make a subprocess operator out of the just-collected context, and push that on the previous context. */ Some(Loop) => { let sub_ast = Sub(Ast( ops )); // Try to pop the previous context from the stack. // If this does not work, it's an unmatched `]`. ops = match stack.pop() { Some(ops) => ops, _ => return Err(~"Unmatched `]`."), }; ops.push(sub_ast); } // Push the operator onto the context. Some(op) => ops.push(op), // Unknown. Probably comments. Nop. _ => continue } } // If we still have things on the stack, then we have one or // more unmatched `[`. if! stack.is_empty() { return Err(~"Unmatched `[`."); } // Everything went well. return Ok(Ast(ops)); } } impl FromStr for Ast { fn from_str(source: &str) -> Option<Ast> { Ast::parse_str(source).ok() } } impl fmt::Show for Ast { /** Parses a string into the matching operator. */ fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let &Ast(ref ops) = self; let display = |op: &Operator| -> ~str { format!("{}", op) }; let repr: ~[~str] = ops.iter().map(display).collect(); f.buf.write(format!("{}", repr.concat()).as_bytes() ) } }
{ /* We parse loops by making a context to group its operators, pushing on it until the matching loop end. As we create the context, we push the previous one onto a stack. After the nest has been collected, we pop the context and replace it with the subprocess operator. */ let mut stack:~[ ~[Operator] ] = ~[]; let mut ops: ~[Operator] = ~[]; for token in source.chars() { match from_str::<Operator>(token.to_str()) { /* Start of a loop. Produce a new context in which to push operators, and push the old one on the stack. */ Some(Skip) => { stack.push(ops);
identifier_body
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct
(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &str) -> Result<Ast, ~str> { /* We parse loops by making a context to group its operators, pushing on it until the matching loop end. As we create the context, we push the previous one onto a stack. After the nest has been collected, we pop the context and replace it with the subprocess operator. */ let mut stack:~[ ~[Operator] ] = ~[]; let mut ops: ~[Operator] = ~[]; for token in source.chars() { match from_str::<Operator>(token.to_str()) { /* Start of a loop. Produce a new context in which to push operators, and push the old one on the stack. */ Some(Skip) => { stack.push(ops); ops = ~[]; } /* End of a loop. Make a subprocess operator out of the just-collected context, and push that on the previous context. */ Some(Loop) => { let sub_ast = Sub(Ast( ops )); // Try to pop the previous context from the stack. // If this does not work, it's an unmatched `]`. ops = match stack.pop() { Some(ops) => ops, _ => return Err(~"Unmatched `]`."), }; ops.push(sub_ast); } // Push the operator onto the context. Some(op) => ops.push(op), // Unknown. Probably comments. Nop. _ => continue } } // If we still have things on the stack, then we have one or // more unmatched `[`. if! stack.is_empty() { return Err(~"Unmatched `[`."); } // Everything went well. return Ok(Ast(ops)); } } impl FromStr for Ast { fn from_str(source: &str) -> Option<Ast> { Ast::parse_str(source).ok() } } impl fmt::Show for Ast { /** Parses a string into the matching operator. */ fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let &Ast(ref ops) = self; let display = |op: &Operator| -> ~str { format!("{}", op) }; let repr: ~[~str] = ops.iter().map(display).collect(); f.buf.write(format!("{}", repr.concat()).as_bytes() ) } }
Ast
identifier_name
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) translation from a value range to a color range Exponential { min: f32, max: f32}, /// Apply no transformation Equal, } #[inline] // Called once per pixel, I believe it make sense to inline it (might be wrong) /// Describe how a value will be translated to a color domain /// /// Returns a float in [0; 1] /// pub fn
(scale: &Scale, value: f32) -> f32 { match scale { &Scale::Linear{min, max} => { if value < min { 0. } else if value > max { 1. } else { (value - min) / (max - min) } }, &Scale::Log{min, max} => { if value < min { 0. } else if value > max { 1. } else { (1. + value - min).log(10.) / (1. + max - min).log(10.) } }, &Scale::Exponential {min, max} => { if value <= min { 0. } else if value >= max { 1. } else { ((value - min) / (max - min)).exp() / (1_f32).exp() } }, &Scale::Equal => { value }, } }
normalize
identifier_name
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) translation from a value range to a color range Exponential { min: f32, max: f32}, /// Apply no transformation Equal, } #[inline] // Called once per pixel, I believe it make sense to inline it (might be wrong) /// Describe how a value will be translated to a color domain /// /// Returns a float in [0; 1] /// pub fn normalize(scale: &Scale, value: f32) -> f32 { match scale { &Scale::Linear{min, max} => { if value < min { 0. } else if value > max { 1. } else { (value - min) / (max - min) } }, &Scale::Log{min, max} => { if value < min { 0. } else if value > max { 1. } else { (1. + value - min).log(10.) / (1. + max - min).log(10.) } }, &Scale::Exponential {min, max} => { if value <= min { 0. } else if value >= max { 1. } else { ((value - min) / (max - min)).exp() / (1_f32).exp() } }, &Scale::Equal =>
, } }
{ value }
conditional_block
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) translation from a value range to a color range Exponential { min: f32, max: f32}, /// Apply no transformation Equal, } #[inline] // Called once per pixel, I believe it make sense to inline it (might be wrong) /// Describe how a value will be translated to a color domain /// /// Returns a float in [0; 1] /// pub fn normalize(scale: &Scale, value: f32) -> f32 { match scale { &Scale::Linear{min, max} => { if value < min { 0. } else if value > max { 1. } else { (value - min) / (max - min) } }, &Scale::Log{min, max} => { if value < min { 0. } else if value > max { 1. } else { (1. + value - min).log(10.) / (1. + max - min).log(10.) } }, &Scale::Exponential {min, max} => { if value <= min { 0. } else if value >= max { 1. } else { ((value - min) / (max - min)).exp() / (1_f32).exp() }
} }
}, &Scale::Equal => { value },
random_line_split
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{CString, CStr, OsString, OsStr}; use fmt; use io::{self, Error, SeekFrom}; use libc::{self, c_int, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use sync::Arc; use sys::fd::FileDesc; use sys::platform::raw; use sys::{c, cvt, cvt_r}; use sys_common::{AsInner, FromInner}; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: raw::stat, } pub struct ReadDir { dirp: Dir, root: Arc<PathBuf>, } struct Dir(*mut libc::DIR); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { buf: Vec<u8>, // actually *mut libc::dirent_t root: Arc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct FileType { mode: mode_t } pub struct DirBuilder { mode: mode_t } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as mode_t } } pub fn raw(&self) -> &raw::stat
// times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw_stat(&self) -> &raw::stat; } impl MetadataExt for ::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat } } impl MetadataExt for ::os::unix::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { self.as_inner() } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> raw::mode_t { self.mode } } impl FileType { pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } } impl FromInner<raw::mode_t> for FilePermissions { fn from_inner(mode: raw::mode_t) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for Dir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.0) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { extern { fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int; } unsafe { match rust_dir_get_mode(self.dirent()) { -1 => lstat(&self.path()).map(|m| m.file_type()), n => Ok(FileType { mode: n as mode_t }), } } } pub fn ino(&self) -> raw::ino_t { extern { fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t; } unsafe { rust_dir_get_ino(self.dirent()) } } fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes() } } fn dirent(&self) -> *mut libc::dirent_t { self.buf.as_ptr() as *mut _ } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = try!(cstr(path)); File::open_c(&path, opts) } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); let fd = FileDesc::new(fd); fd.set_cloexec(); Ok(File(fd)) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })); Ok(()) } pub fn set_mode(&mut self, mode: mode_t) { self.mode = mode; } } fn cstr(path: &Path) -> io::Result<CString> { path.as_os_str().to_cstring().ok_or( io::Error::new(io::ErrorKind::InvalidInput, "path contained a null")) } impl FromInner<c_int> for File { fn from_inner(fd: c_int) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[cfg(target_os = "linux")] fn get_path(fd: c_int) -> Option<PathBuf> { use string::ToString; let mut p = PathBuf::from("/proc/self/fd"); p.push(&fd.to_string()); readlink(&p).ok() } #[cfg(not(target_os = "linux"))] fn get_path(_fd: c_int) -> Option<PathBuf> { // FIXME(#24570): implement this for other Unix platforms None } #[cfg(target_os = "linux")] fn get_mode(fd: c_int) -> Option<(bool, bool)> { let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if mode == -1 { return None; } match mode & libc::O_ACCMODE { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), _ => None } } #[cfg(not(target_os = "linux"))] fn get_mode(_fd: c_int) -> Option<(bool, bool)> { // FIXME(#24570): implement this for other Unix platforms None } let fd = self.0.raw(); let mut b = f.debug_struct("File"); b.field("fd", &fd); if let Some(path) = get_path(fd) { b.field("path", &path); } if let Some((read, write)) = get_mode(fd) { b.field("read", &read).field("write", &write); } b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let p = try!(cstr(p)); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: Dir(ptr), root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = try!(cstr(old)); let new = try!(cstr(new)); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = try!(cstr(p)); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } Ok(PathBuf::from(OsString::from_vec(buf))) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = try!(cstr(p)); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let path = try!(CString::new(p.as_os_str().as_bytes())); let mut buf = vec![0u8; 16 * 1024]; unsafe { let r = c::realpath(path.as_ptr(), buf.as_mut_ptr() as *mut _); if r.is_null() { return Err(io::Error::last_os_error()) } } let p = buf.iter().position(|i| *i == 0).unwrap(); buf.truncate(p); Ok(PathBuf::from(OsString::from_vec(buf))) }
{ &self.stat }
identifier_body
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{CString, CStr, OsString, OsStr}; use fmt; use io::{self, Error, SeekFrom}; use libc::{self, c_int, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use sync::Arc; use sys::fd::FileDesc; use sys::platform::raw; use sys::{c, cvt, cvt_r}; use sys_common::{AsInner, FromInner}; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: raw::stat, } pub struct ReadDir { dirp: Dir, root: Arc<PathBuf>, } struct Dir(*mut libc::DIR); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { buf: Vec<u8>, // actually *mut libc::dirent_t root: Arc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct FileType { mode: mode_t } pub struct DirBuilder { mode: mode_t } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as mode_t } } pub fn raw(&self) -> &raw::stat { &self.stat } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw_stat(&self) -> &raw::stat; } impl MetadataExt for ::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat } } impl MetadataExt for ::os::unix::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { self.as_inner() } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> raw::mode_t { self.mode } } impl FileType { pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } } impl FromInner<raw::mode_t> for FilePermissions { fn from_inner(mode: raw::mode_t) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for Dir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.0) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { extern { fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int; } unsafe { match rust_dir_get_mode(self.dirent()) { -1 => lstat(&self.path()).map(|m| m.file_type()), n => Ok(FileType { mode: n as mode_t }), } } } pub fn ino(&self) -> raw::ino_t { extern { fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t; } unsafe { rust_dir_get_ino(self.dirent()) } } fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes() } } fn dirent(&self) -> *mut libc::dirent_t { self.buf.as_ptr() as *mut _ } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn
(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = try!(cstr(path)); File::open_c(&path, opts) } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); let fd = FileDesc::new(fd); fd.set_cloexec(); Ok(File(fd)) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })); Ok(()) } pub fn set_mode(&mut self, mode: mode_t) { self.mode = mode; } } fn cstr(path: &Path) -> io::Result<CString> { path.as_os_str().to_cstring().ok_or( io::Error::new(io::ErrorKind::InvalidInput, "path contained a null")) } impl FromInner<c_int> for File { fn from_inner(fd: c_int) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[cfg(target_os = "linux")] fn get_path(fd: c_int) -> Option<PathBuf> { use string::ToString; let mut p = PathBuf::from("/proc/self/fd"); p.push(&fd.to_string()); readlink(&p).ok() } #[cfg(not(target_os = "linux"))] fn get_path(_fd: c_int) -> Option<PathBuf> { // FIXME(#24570): implement this for other Unix platforms None } #[cfg(target_os = "linux")] fn get_mode(fd: c_int) -> Option<(bool, bool)> { let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if mode == -1 { return None; } match mode & libc::O_ACCMODE { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), _ => None } } #[cfg(not(target_os = "linux"))] fn get_mode(_fd: c_int) -> Option<(bool, bool)> { // FIXME(#24570): implement this for other Unix platforms None } let fd = self.0.raw(); let mut b = f.debug_struct("File"); b.field("fd", &fd); if let Some(path) = get_path(fd) { b.field("path", &path); } if let Some((read, write)) = get_mode(fd) { b.field("read", &read).field("write", &write); } b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let p = try!(cstr(p)); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: Dir(ptr), root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = try!(cstr(old)); let new = try!(cstr(new)); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = try!(cstr(p)); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } Ok(PathBuf::from(OsString::from_vec(buf))) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = try!(cstr(p)); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let path = try!(CString::new(p.as_os_str().as_bytes())); let mut buf = vec![0u8; 16 * 1024]; unsafe { let r = c::realpath(path.as_ptr(), buf.as_mut_ptr() as *mut _); if r.is_null() { return Err(io::Error::last_os_error()) } } let p = buf.iter().position(|i| *i == 0).unwrap(); buf.truncate(p); Ok(PathBuf::from(OsString::from_vec(buf))) }
create
identifier_name
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{CString, CStr, OsString, OsStr}; use fmt; use io::{self, Error, SeekFrom}; use libc::{self, c_int, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use sync::Arc; use sys::fd::FileDesc; use sys::platform::raw; use sys::{c, cvt, cvt_r}; use sys_common::{AsInner, FromInner}; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: raw::stat, } pub struct ReadDir { dirp: Dir, root: Arc<PathBuf>, } struct Dir(*mut libc::DIR); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { buf: Vec<u8>, // actually *mut libc::dirent_t root: Arc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct FileType { mode: mode_t } pub struct DirBuilder { mode: mode_t } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as mode_t } } pub fn raw(&self) -> &raw::stat { &self.stat } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw_stat(&self) -> &raw::stat; } impl MetadataExt for ::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat } } impl MetadataExt for ::os::unix::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { self.as_inner() } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> raw::mode_t { self.mode } } impl FileType { pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } } impl FromInner<raw::mode_t> for FilePermissions { fn from_inner(mode: raw::mode_t) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null()
let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for Dir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.0) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { extern { fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int; } unsafe { match rust_dir_get_mode(self.dirent()) { -1 => lstat(&self.path()).map(|m| m.file_type()), n => Ok(FileType { mode: n as mode_t }), } } } pub fn ino(&self) -> raw::ino_t { extern { fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t; } unsafe { rust_dir_get_ino(self.dirent()) } } fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes() } } fn dirent(&self) -> *mut libc::dirent_t { self.buf.as_ptr() as *mut _ } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = try!(cstr(path)); File::open_c(&path, opts) } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); let fd = FileDesc::new(fd); fd.set_cloexec(); Ok(File(fd)) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })); Ok(()) } pub fn set_mode(&mut self, mode: mode_t) { self.mode = mode; } } fn cstr(path: &Path) -> io::Result<CString> { path.as_os_str().to_cstring().ok_or( io::Error::new(io::ErrorKind::InvalidInput, "path contained a null")) } impl FromInner<c_int> for File { fn from_inner(fd: c_int) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[cfg(target_os = "linux")] fn get_path(fd: c_int) -> Option<PathBuf> { use string::ToString; let mut p = PathBuf::from("/proc/self/fd"); p.push(&fd.to_string()); readlink(&p).ok() } #[cfg(not(target_os = "linux"))] fn get_path(_fd: c_int) -> Option<PathBuf> { // FIXME(#24570): implement this for other Unix platforms None } #[cfg(target_os = "linux")] fn get_mode(fd: c_int) -> Option<(bool, bool)> { let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if mode == -1 { return None; } match mode & libc::O_ACCMODE { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), _ => None } } #[cfg(not(target_os = "linux"))] fn get_mode(_fd: c_int) -> Option<(bool, bool)> { // FIXME(#24570): implement this for other Unix platforms None } let fd = self.0.raw(); let mut b = f.debug_struct("File"); b.field("fd", &fd); if let Some(path) = get_path(fd) { b.field("path", &path); } if let Some((read, write)) = get_mode(fd) { b.field("read", &read).field("write", &write); } b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let p = try!(cstr(p)); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: Dir(ptr), root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = try!(cstr(old)); let new = try!(cstr(new)); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = try!(cstr(p)); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } Ok(PathBuf::from(OsString::from_vec(buf))) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = try!(cstr(p)); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let path = try!(CString::new(p.as_os_str().as_bytes())); let mut buf = vec![0u8; 16 * 1024]; unsafe { let r = c::realpath(path.as_ptr(), buf.as_mut_ptr() as *mut _); if r.is_null() { return Err(io::Error::last_os_error()) } } let p = buf.iter().position(|i| *i == 0).unwrap(); buf.truncate(p); Ok(PathBuf::from(OsString::from_vec(buf))) }
{ return None }
conditional_block
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{CString, CStr, OsString, OsStr}; use fmt; use io::{self, Error, SeekFrom}; use libc::{self, c_int, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use sync::Arc; use sys::fd::FileDesc; use sys::platform::raw; use sys::{c, cvt, cvt_r}; use sys_common::{AsInner, FromInner}; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: raw::stat, } pub struct ReadDir { dirp: Dir, root: Arc<PathBuf>, } struct Dir(*mut libc::DIR); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { buf: Vec<u8>, // actually *mut libc::dirent_t root: Arc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct FileType { mode: mode_t } pub struct DirBuilder { mode: mode_t } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as mode_t } } pub fn raw(&self) -> &raw::stat { &self.stat } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw_stat(&self) -> &raw::stat; } impl MetadataExt for ::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat } } impl MetadataExt for ::os::unix::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { self.as_inner() } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> raw::mode_t { self.mode } } impl FileType { pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } } impl FromInner<raw::mode_t> for FilePermissions { fn from_inner(mode: raw::mode_t) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for Dir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.0) }; debug_assert_eq!(r, 0);
pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { extern { fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int; } unsafe { match rust_dir_get_mode(self.dirent()) { -1 => lstat(&self.path()).map(|m| m.file_type()), n => Ok(FileType { mode: n as mode_t }), } } } pub fn ino(&self) -> raw::ino_t { extern { fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t; } unsafe { rust_dir_get_ino(self.dirent()) } } fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes() } } fn dirent(&self) -> *mut libc::dirent_t { self.buf.as_ptr() as *mut _ } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = try!(cstr(path)); File::open_c(&path, opts) } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); let fd = FileDesc::new(fd); fd.set_cloexec(); Ok(File(fd)) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })); Ok(()) } pub fn set_mode(&mut self, mode: mode_t) { self.mode = mode; } } fn cstr(path: &Path) -> io::Result<CString> { path.as_os_str().to_cstring().ok_or( io::Error::new(io::ErrorKind::InvalidInput, "path contained a null")) } impl FromInner<c_int> for File { fn from_inner(fd: c_int) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[cfg(target_os = "linux")] fn get_path(fd: c_int) -> Option<PathBuf> { use string::ToString; let mut p = PathBuf::from("/proc/self/fd"); p.push(&fd.to_string()); readlink(&p).ok() } #[cfg(not(target_os = "linux"))] fn get_path(_fd: c_int) -> Option<PathBuf> { // FIXME(#24570): implement this for other Unix platforms None } #[cfg(target_os = "linux")] fn get_mode(fd: c_int) -> Option<(bool, bool)> { let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if mode == -1 { return None; } match mode & libc::O_ACCMODE { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), _ => None } } #[cfg(not(target_os = "linux"))] fn get_mode(_fd: c_int) -> Option<(bool, bool)> { // FIXME(#24570): implement this for other Unix platforms None } let fd = self.0.raw(); let mut b = f.debug_struct("File"); b.field("fd", &fd); if let Some(path) = get_path(fd) { b.field("path", &path); } if let Some((read, write)) = get_mode(fd) { b.field("read", &read).field("write", &write); } b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let p = try!(cstr(p)); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: Dir(ptr), root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = try!(cstr(old)); let new = try!(cstr(new)); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = try!(cstr(p)); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } Ok(PathBuf::from(OsString::from_vec(buf))) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = try!(cstr(p)); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let path = try!(CString::new(p.as_os_str().as_bytes())); let mut buf = vec![0u8; 16 * 1024]; unsafe { let r = c::realpath(path.as_ptr(), buf.as_mut_ptr() as *mut _); if r.is_null() { return Err(io::Error::last_os_error()) } } let p = buf.iter().position(|i| *i == 0).unwrap(); buf.truncate(p); Ok(PathBuf::from(OsString::from_vec(buf))) }
} } impl DirEntry {
random_line_split
mod.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Networking I/O use io::{IoError, IoResult, InvalidInput}; use option::None; use result::{Ok, Err}; use self::ip::{SocketAddr, ToSocketAddr}; pub use self::addrinfo::get_host_addresses; pub mod addrinfo; pub mod tcp; pub mod udp; pub mod ip; pub mod pipe; fn with_addresses<A: ToSocketAddr, T>(addr: A, action: |SocketAddr| -> IoResult<T>) -> IoResult<T> { const DEFAULT_ERROR: IoError = IoError { kind: InvalidInput, desc: "no addresses found for hostname", detail: None }; let addresses = try!(addr.to_socket_addr_all()); let mut err = DEFAULT_ERROR;
match action(addr) { Ok(r) => return Ok(r), Err(e) => err = e } } Err(err) }
for addr in addresses.into_iter() {
random_line_split
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng; use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimName, U1, U2, U3, U4, U5, U6}; use crate::base::{DefaultAllocator, Scalar, VectorN}; use crate::geometry::Translation; impl<N: Scalar + Zero, D: DimName> Translation<N, D> where DefaultAllocator: Allocator<N, D>, { /// Creates a new identity translation. /// /// # Example /// ``` /// # use nalgebra::{Point2, Point3, Translation2, Translation3}; /// let t = Translation2::identity(); /// let p = Point2::new(1.0, 2.0); /// assert_eq!(t * p, p); /// /// // Works in all dimensions. /// let t = Translation3::identity(); /// let p = Point3::new(1.0, 2.0, 3.0); /// assert_eq!(t * p, p); /// ``` #[inline] pub fn identity() -> Translation<N, D> { Self::from(VectorN::<N, D>::from_element(N::zero())) } } impl<N: Scalar + Zero + ClosedAdd, D: DimName> One for Translation<N, D> where DefaultAllocator: Allocator<N, D>, { #[inline] fn one() -> Self { Self::identity() } } impl<N: Scalar, D: DimName> Distribution<Translation<N, D>> for Standard where DefaultAllocator: Allocator<N, D>, Standard: Distribution<N>, { #[inline] fn
<'a, G: Rng +?Sized>(&self, rng: &'a mut G) -> Translation<N, D> { Translation::from(rng.gen::<VectorN<N, D>>()) } } #[cfg(feature = "arbitrary")] impl<N: Scalar + Arbitrary, D: DimName> Arbitrary for Translation<N, D> where DefaultAllocator: Allocator<N, D>, Owned<N, D>: Send, { #[inline] fn arbitrary<G: Gen>(rng: &mut G) -> Self { let v: VectorN<N, D> = Arbitrary::arbitrary(rng); Self::from(v) } } /* * * Small translation construction from components. * */ macro_rules! componentwise_constructors_impl( ($($doc: expr; $D: ty, $($args: ident:$irow: expr),*);* $(;)*) => {$( impl<N: Scalar> Translation<N, $D> where DefaultAllocator: Allocator<N, $D> { #[doc = "Initializes this translation from its components."] #[doc = "# Example\n```"] #[doc = $doc] #[doc = "```"] #[inline] pub fn new($($args: N),*) -> Self { Self::from(VectorN::<N, $D>::new($($args),*)) } } )*} ); componentwise_constructors_impl!( "# use nalgebra::Translation1;\nlet t = Translation1::new(1.0);\nassert!(t.vector.x == 1.0);"; U1, x:0; "# use nalgebra::Translation2;\nlet t = Translation2::new(1.0, 2.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0);"; U2, x:0, y:1; "# use nalgebra::Translation3;\nlet t = Translation3::new(1.0, 2.0, 3.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0);"; U3, x:0, y:1, z:2; "# use nalgebra::Translation4;\nlet t = Translation4::new(1.0, 2.0, 3.0, 4.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0);"; U4, x:0, y:1, z:2, w:3; "# use nalgebra::Translation5;\nlet t = Translation5::new(1.0, 2.0, 3.0, 4.0, 5.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0 && t.vector.a == 5.0);"; U5, x:0, y:1, z:2, w:3, a:4; "# use nalgebra::Translation6;\nlet t = Translation6::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0 && t.vector.a == 5.0 && t.vector.b == 6.0);"; U6, x:0, y:1, z:2, w:3, a:4, b:5; );
sample
identifier_name
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")]
use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimName, U1, U2, U3, U4, U5, U6}; use crate::base::{DefaultAllocator, Scalar, VectorN}; use crate::geometry::Translation; impl<N: Scalar + Zero, D: DimName> Translation<N, D> where DefaultAllocator: Allocator<N, D>, { /// Creates a new identity translation. /// /// # Example /// ``` /// # use nalgebra::{Point2, Point3, Translation2, Translation3}; /// let t = Translation2::identity(); /// let p = Point2::new(1.0, 2.0); /// assert_eq!(t * p, p); /// /// // Works in all dimensions. /// let t = Translation3::identity(); /// let p = Point3::new(1.0, 2.0, 3.0); /// assert_eq!(t * p, p); /// ``` #[inline] pub fn identity() -> Translation<N, D> { Self::from(VectorN::<N, D>::from_element(N::zero())) } } impl<N: Scalar + Zero + ClosedAdd, D: DimName> One for Translation<N, D> where DefaultAllocator: Allocator<N, D>, { #[inline] fn one() -> Self { Self::identity() } } impl<N: Scalar, D: DimName> Distribution<Translation<N, D>> for Standard where DefaultAllocator: Allocator<N, D>, Standard: Distribution<N>, { #[inline] fn sample<'a, G: Rng +?Sized>(&self, rng: &'a mut G) -> Translation<N, D> { Translation::from(rng.gen::<VectorN<N, D>>()) } } #[cfg(feature = "arbitrary")] impl<N: Scalar + Arbitrary, D: DimName> Arbitrary for Translation<N, D> where DefaultAllocator: Allocator<N, D>, Owned<N, D>: Send, { #[inline] fn arbitrary<G: Gen>(rng: &mut G) -> Self { let v: VectorN<N, D> = Arbitrary::arbitrary(rng); Self::from(v) } } /* * * Small translation construction from components. * */ macro_rules! componentwise_constructors_impl( ($($doc: expr; $D: ty, $($args: ident:$irow: expr),*);* $(;)*) => {$( impl<N: Scalar> Translation<N, $D> where DefaultAllocator: Allocator<N, $D> { #[doc = "Initializes this translation from its components."] #[doc = "# Example\n```"] #[doc = $doc] #[doc = "```"] #[inline] pub fn new($($args: N),*) -> Self { Self::from(VectorN::<N, $D>::new($($args),*)) } } )*} ); componentwise_constructors_impl!( "# use nalgebra::Translation1;\nlet t = Translation1::new(1.0);\nassert!(t.vector.x == 1.0);"; U1, x:0; "# use nalgebra::Translation2;\nlet t = Translation2::new(1.0, 2.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0);"; U2, x:0, y:1; "# use nalgebra::Translation3;\nlet t = Translation3::new(1.0, 2.0, 3.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0);"; U3, x:0, y:1, z:2; "# use nalgebra::Translation4;\nlet t = Translation4::new(1.0, 2.0, 3.0, 4.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0);"; U4, x:0, y:1, z:2, w:3; "# use nalgebra::Translation5;\nlet t = Translation5::new(1.0, 2.0, 3.0, 4.0, 5.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0 && t.vector.a == 5.0);"; U5, x:0, y:1, z:2, w:3, a:4; "# use nalgebra::Translation6;\nlet t = Translation6::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0 && t.vector.a == 5.0 && t.vector.b == 6.0);"; U6, x:0, y:1, z:2, w:3, a:4, b:5; );
use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng;
random_line_split
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng; use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimName, U1, U2, U3, U4, U5, U6}; use crate::base::{DefaultAllocator, Scalar, VectorN}; use crate::geometry::Translation; impl<N: Scalar + Zero, D: DimName> Translation<N, D> where DefaultAllocator: Allocator<N, D>, { /// Creates a new identity translation. /// /// # Example /// ``` /// # use nalgebra::{Point2, Point3, Translation2, Translation3}; /// let t = Translation2::identity(); /// let p = Point2::new(1.0, 2.0); /// assert_eq!(t * p, p); /// /// // Works in all dimensions. /// let t = Translation3::identity(); /// let p = Point3::new(1.0, 2.0, 3.0); /// assert_eq!(t * p, p); /// ``` #[inline] pub fn identity() -> Translation<N, D> { Self::from(VectorN::<N, D>::from_element(N::zero())) } } impl<N: Scalar + Zero + ClosedAdd, D: DimName> One for Translation<N, D> where DefaultAllocator: Allocator<N, D>, { #[inline] fn one() -> Self
} impl<N: Scalar, D: DimName> Distribution<Translation<N, D>> for Standard where DefaultAllocator: Allocator<N, D>, Standard: Distribution<N>, { #[inline] fn sample<'a, G: Rng +?Sized>(&self, rng: &'a mut G) -> Translation<N, D> { Translation::from(rng.gen::<VectorN<N, D>>()) } } #[cfg(feature = "arbitrary")] impl<N: Scalar + Arbitrary, D: DimName> Arbitrary for Translation<N, D> where DefaultAllocator: Allocator<N, D>, Owned<N, D>: Send, { #[inline] fn arbitrary<G: Gen>(rng: &mut G) -> Self { let v: VectorN<N, D> = Arbitrary::arbitrary(rng); Self::from(v) } } /* * * Small translation construction from components. * */ macro_rules! componentwise_constructors_impl( ($($doc: expr; $D: ty, $($args: ident:$irow: expr),*);* $(;)*) => {$( impl<N: Scalar> Translation<N, $D> where DefaultAllocator: Allocator<N, $D> { #[doc = "Initializes this translation from its components."] #[doc = "# Example\n```"] #[doc = $doc] #[doc = "```"] #[inline] pub fn new($($args: N),*) -> Self { Self::from(VectorN::<N, $D>::new($($args),*)) } } )*} ); componentwise_constructors_impl!( "# use nalgebra::Translation1;\nlet t = Translation1::new(1.0);\nassert!(t.vector.x == 1.0);"; U1, x:0; "# use nalgebra::Translation2;\nlet t = Translation2::new(1.0, 2.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0);"; U2, x:0, y:1; "# use nalgebra::Translation3;\nlet t = Translation3::new(1.0, 2.0, 3.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0);"; U3, x:0, y:1, z:2; "# use nalgebra::Translation4;\nlet t = Translation4::new(1.0, 2.0, 3.0, 4.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0);"; U4, x:0, y:1, z:2, w:3; "# use nalgebra::Translation5;\nlet t = Translation5::new(1.0, 2.0, 3.0, 4.0, 5.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0 && t.vector.a == 5.0);"; U5, x:0, y:1, z:2, w:3, a:4; "# use nalgebra::Translation6;\nlet t = Translation6::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);\nassert!(t.vector.x == 1.0 && t.vector.y == 2.0 && t.vector.z == 3.0 && t.vector.w == 4.0 && t.vector.a == 5.0 && t.vector.b == 6.0);"; U6, x:0, y:1, z:2, w:3, a:4, b:5; );
{ Self::identity() }
identifier_body
stream.rs
// Copyright © 2017-2018 Mozilla Foundation // // This program is made available under an ISC-style license. See the // accompanying file LICENSE for details. use callbacks::cubeb_device_changed_callback; use channel::cubeb_channel_layout; use device::cubeb_device; use format::cubeb_sample_format; use std::{fmt, mem}; use std::os::raw::{c_float, c_int, c_uint, c_void, c_char}; cubeb_enum! { pub enum cubeb_stream_prefs { CUBEB_STREAM_PREF_NONE = 0x00, CUBEB_STREAM_PREF_LOOPBACK = 0x01, CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING = 0x02, CUBEB_STREAM_PREF_VOICE = 0x04, } } cubeb_enum! { pub enum cubeb_state { CUBEB_STATE_STARTED, CUBEB_STATE_STOPPED, CUBEB_STATE_DRAINED, CUBEB_STATE_ERROR, } } pub enum c
{} #[repr(C)] #[derive(Clone, Copy)] pub struct cubeb_stream_params { pub format: cubeb_sample_format, pub rate: c_uint, pub channels: c_uint, pub layout: cubeb_channel_layout, pub prefs: cubeb_stream_prefs, } impl Default for cubeb_stream_params { fn default() -> Self { unsafe { mem::zeroed() } } } // Explicit Debug impl to work around bug in ctest impl fmt::Debug for cubeb_stream_params { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("cubeb_stream_params") .field("format", &self.format) .field("rate", &self.rate) .field("channels", &self.channels) .field("layout", &self.layout) .field("prefs", &self.prefs) .finish() } } extern "C" { pub fn cubeb_stream_destroy(stream: *mut cubeb_stream); pub fn cubeb_stream_start(stream: *mut cubeb_stream) -> c_int; pub fn cubeb_stream_stop(stream: *mut cubeb_stream) -> c_int; pub fn cubeb_stream_reset_default_device(stream: *mut cubeb_stream) -> c_int; pub fn cubeb_stream_get_position(stream: *mut cubeb_stream, position: *mut u64) -> c_int; pub fn cubeb_stream_get_latency(stream: *mut cubeb_stream, latency: *mut c_uint) -> c_int; pub fn cubeb_stream_get_input_latency(stream: *mut cubeb_stream, latency: *mut c_uint) -> c_int; pub fn cubeb_stream_set_volume(stream: *mut cubeb_stream, volume: c_float) -> c_int; pub fn cubeb_stream_set_name(stream: *mut cubeb_stream, name: *const c_char) -> c_int; pub fn cubeb_stream_get_current_device( stream: *mut cubeb_stream, device: *mut *mut cubeb_device, ) -> c_int; pub fn cubeb_stream_device_destroy( stream: *mut cubeb_stream, devices: *mut cubeb_device, ) -> c_int; pub fn cubeb_stream_register_device_changed_callback( stream: *mut cubeb_stream, device_changed_callback: cubeb_device_changed_callback, ) -> c_int; pub fn cubeb_stream_user_ptr(stream: *mut cubeb_stream) -> *mut c_void; }
ubeb_stream
identifier_name
stream.rs
// Copyright © 2017-2018 Mozilla Foundation // // This program is made available under an ISC-style license. See the // accompanying file LICENSE for details. use callbacks::cubeb_device_changed_callback; use channel::cubeb_channel_layout; use device::cubeb_device; use format::cubeb_sample_format; use std::{fmt, mem}; use std::os::raw::{c_float, c_int, c_uint, c_void, c_char}; cubeb_enum! { pub enum cubeb_stream_prefs {
CUBEB_STREAM_PREF_NONE = 0x00, CUBEB_STREAM_PREF_LOOPBACK = 0x01, CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING = 0x02, CUBEB_STREAM_PREF_VOICE = 0x04, } } cubeb_enum! { pub enum cubeb_state { CUBEB_STATE_STARTED, CUBEB_STATE_STOPPED, CUBEB_STATE_DRAINED, CUBEB_STATE_ERROR, } } pub enum cubeb_stream {} #[repr(C)] #[derive(Clone, Copy)] pub struct cubeb_stream_params { pub format: cubeb_sample_format, pub rate: c_uint, pub channels: c_uint, pub layout: cubeb_channel_layout, pub prefs: cubeb_stream_prefs, } impl Default for cubeb_stream_params { fn default() -> Self { unsafe { mem::zeroed() } } } // Explicit Debug impl to work around bug in ctest impl fmt::Debug for cubeb_stream_params { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("cubeb_stream_params") .field("format", &self.format) .field("rate", &self.rate) .field("channels", &self.channels) .field("layout", &self.layout) .field("prefs", &self.prefs) .finish() } } extern "C" { pub fn cubeb_stream_destroy(stream: *mut cubeb_stream); pub fn cubeb_stream_start(stream: *mut cubeb_stream) -> c_int; pub fn cubeb_stream_stop(stream: *mut cubeb_stream) -> c_int; pub fn cubeb_stream_reset_default_device(stream: *mut cubeb_stream) -> c_int; pub fn cubeb_stream_get_position(stream: *mut cubeb_stream, position: *mut u64) -> c_int; pub fn cubeb_stream_get_latency(stream: *mut cubeb_stream, latency: *mut c_uint) -> c_int; pub fn cubeb_stream_get_input_latency(stream: *mut cubeb_stream, latency: *mut c_uint) -> c_int; pub fn cubeb_stream_set_volume(stream: *mut cubeb_stream, volume: c_float) -> c_int; pub fn cubeb_stream_set_name(stream: *mut cubeb_stream, name: *const c_char) -> c_int; pub fn cubeb_stream_get_current_device( stream: *mut cubeb_stream, device: *mut *mut cubeb_device, ) -> c_int; pub fn cubeb_stream_device_destroy( stream: *mut cubeb_stream, devices: *mut cubeb_device, ) -> c_int; pub fn cubeb_stream_register_device_changed_callback( stream: *mut cubeb_stream, device_changed_callback: cubeb_device_changed_callback, ) -> c_int; pub fn cubeb_stream_user_ptr(stream: *mut cubeb_stream) -> *mut c_void; }
random_line_split
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals)] mod bindings; "#; fn main() { for header in HEADERS.iter() { gen(header); } } fn gen(header: &str) { let dir = "src/mbed/".to_string() + header + "/"; let file = dir.clone() + "bindings.rs"; create_dir_all(&dir).unwrap(); let bindings_file = File::create(file).unwrap(); bindgen::Builder::default() .header(HEADER_BASE.to_string() + header + ".h") .link("mbedtls") .link("mbedx509") .link("mbedcrypto") .emit_builtins() .generate().unwrap() .write(Box::new(bindings_file)) .unwrap(); ; let mod_file_str = dir.clone() + "/mod.rs"; let metadata = metadata(Path::new(&mod_file_str)); if let Err(e) = metadata { if let ErrorKind::NotFound = e.kind()
} }
{ let mut mod_file = File::create(mod_file_str).unwrap(); mod_file.write(MOD_FILE.as_bytes()).unwrap(); }
conditional_block
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata};
use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals)] mod bindings; "#; fn main() { for header in HEADERS.iter() { gen(header); } } fn gen(header: &str) { let dir = "src/mbed/".to_string() + header + "/"; let file = dir.clone() + "bindings.rs"; create_dir_all(&dir).unwrap(); let bindings_file = File::create(file).unwrap(); bindgen::Builder::default() .header(HEADER_BASE.to_string() + header + ".h") .link("mbedtls") .link("mbedx509") .link("mbedcrypto") .emit_builtins() .generate().unwrap() .write(Box::new(bindings_file)) .unwrap(); ; let mod_file_str = dir.clone() + "/mod.rs"; let metadata = metadata(Path::new(&mod_file_str)); if let Err(e) = metadata { if let ErrorKind::NotFound = e.kind() { let mut mod_file = File::create(mod_file_str).unwrap(); mod_file.write(MOD_FILE.as_bytes()).unwrap(); } } }
use std::path::Path;
random_line_split
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals)] mod bindings; "#; fn main()
fn gen(header: &str) { let dir = "src/mbed/".to_string() + header + "/"; let file = dir.clone() + "bindings.rs"; create_dir_all(&dir).unwrap(); let bindings_file = File::create(file).unwrap(); bindgen::Builder::default() .header(HEADER_BASE.to_string() + header + ".h") .link("mbedtls") .link("mbedx509") .link("mbedcrypto") .emit_builtins() .generate().unwrap() .write(Box::new(bindings_file)) .unwrap(); ; let mod_file_str = dir.clone() + "/mod.rs"; let metadata = metadata(Path::new(&mod_file_str)); if let Err(e) = metadata { if let ErrorKind::NotFound = e.kind() { let mut mod_file = File::create(mod_file_str).unwrap(); mod_file.write(MOD_FILE.as_bytes()).unwrap(); } } }
{ for header in HEADERS.iter() { gen(header); } }
identifier_body
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals)] mod bindings; "#; fn
() { for header in HEADERS.iter() { gen(header); } } fn gen(header: &str) { let dir = "src/mbed/".to_string() + header + "/"; let file = dir.clone() + "bindings.rs"; create_dir_all(&dir).unwrap(); let bindings_file = File::create(file).unwrap(); bindgen::Builder::default() .header(HEADER_BASE.to_string() + header + ".h") .link("mbedtls") .link("mbedx509") .link("mbedcrypto") .emit_builtins() .generate().unwrap() .write(Box::new(bindings_file)) .unwrap(); ; let mod_file_str = dir.clone() + "/mod.rs"; let metadata = metadata(Path::new(&mod_file_str)); if let Err(e) = metadata { if let ErrorKind::NotFound = e.kind() { let mut mod_file = File::create(mod_file_str).unwrap(); mod_file.write(MOD_FILE.as_bytes()).unwrap(); } } }
main
identifier_name
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum ParseTree { Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree {
let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes, the random walk overflows the stack, so we have a max, and if // it is exceeded, we just try again if let Some(result) = gen.nonterminal(symbol.clone()) { return result; } gen.depth = 0; } } struct Generator<'grammar> { grammar: &'grammar Grammar, rng: rand::rngs::ThreadRng, depth: u32, } const MAX_DEPTH: u32 = 10000; impl<'grammar> Generator<'grammar> { fn nonterminal(&mut self, nt: NonterminalString) -> Option<ParseTree> { if self.depth > MAX_DEPTH { return None; } self.depth += 1; let productions = self.grammar.productions_for(&nt); let index: usize = self.rng.gen_range(0, productions.len()); let production = &productions[index]; let trees: Option<Vec<_>> = production .symbols .iter() .map(|sym| self.symbol(sym.clone())) .collect(); trees.map(|trees| ParseTree::Nonterminal(nt, trees)) } fn symbol(&mut self, symbol: Symbol) -> Option<ParseTree> { match symbol { Symbol::Nonterminal(nt) => self.nonterminal(nt), Symbol::Terminal(t) => Some(ParseTree::Terminal(t)), } } } impl ParseTree { pub fn terminals(&self) -> Vec<TerminalString> { let mut vec = vec![]; self.push_terminals(&mut vec); vec } fn push_terminals(&self, vec: &mut Vec<TerminalString>) { match *self { ParseTree::Terminal(ref s) => vec.push(s.clone()), ParseTree::Nonterminal(_, ref trees) => { for tree in trees { tree.push_terminals(vec); } } } } }
random_line_split
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum ParseTree { Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree
struct Generator<'grammar> { grammar: &'grammar Grammar, rng: rand::rngs::ThreadRng, depth: u32, } const MAX_DEPTH: u32 = 10000; impl<'grammar> Generator<'grammar> { fn nonterminal(&mut self, nt: NonterminalString) -> Option<ParseTree> { if self.depth > MAX_DEPTH { return None; } self.depth += 1; let productions = self.grammar.productions_for(&nt); let index: usize = self.rng.gen_range(0, productions.len()); let production = &productions[index]; let trees: Option<Vec<_>> = production .symbols .iter() .map(|sym| self.symbol(sym.clone())) .collect(); trees.map(|trees| ParseTree::Nonterminal(nt, trees)) } fn symbol(&mut self, symbol: Symbol) -> Option<ParseTree> { match symbol { Symbol::Nonterminal(nt) => self.nonterminal(nt), Symbol::Terminal(t) => Some(ParseTree::Terminal(t)), } } } impl ParseTree { pub fn terminals(&self) -> Vec<TerminalString> { let mut vec = vec![]; self.push_terminals(&mut vec); vec } fn push_terminals(&self, vec: &mut Vec<TerminalString>) { match *self { ParseTree::Terminal(ref s) => vec.push(s.clone()), ParseTree::Nonterminal(_, ref trees) => { for tree in trees { tree.push_terminals(vec); } } } } }
{ let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes, the random walk overflows the stack, so we have a max, and if // it is exceeded, we just try again if let Some(result) = gen.nonterminal(symbol.clone()) { return result; } gen.depth = 0; } }
identifier_body
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum
{ Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree { let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes, the random walk overflows the stack, so we have a max, and if // it is exceeded, we just try again if let Some(result) = gen.nonterminal(symbol.clone()) { return result; } gen.depth = 0; } } struct Generator<'grammar> { grammar: &'grammar Grammar, rng: rand::rngs::ThreadRng, depth: u32, } const MAX_DEPTH: u32 = 10000; impl<'grammar> Generator<'grammar> { fn nonterminal(&mut self, nt: NonterminalString) -> Option<ParseTree> { if self.depth > MAX_DEPTH { return None; } self.depth += 1; let productions = self.grammar.productions_for(&nt); let index: usize = self.rng.gen_range(0, productions.len()); let production = &productions[index]; let trees: Option<Vec<_>> = production .symbols .iter() .map(|sym| self.symbol(sym.clone())) .collect(); trees.map(|trees| ParseTree::Nonterminal(nt, trees)) } fn symbol(&mut self, symbol: Symbol) -> Option<ParseTree> { match symbol { Symbol::Nonterminal(nt) => self.nonterminal(nt), Symbol::Terminal(t) => Some(ParseTree::Terminal(t)), } } } impl ParseTree { pub fn terminals(&self) -> Vec<TerminalString> { let mut vec = vec![]; self.push_terminals(&mut vec); vec } fn push_terminals(&self, vec: &mut Vec<TerminalString>) { match *self { ParseTree::Terminal(ref s) => vec.push(s.clone()), ParseTree::Nonterminal(_, ref trees) => { for tree in trees { tree.push_terminals(vec); } } } } }
ParseTree
identifier_name
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::cell::RefCell; use std::io; use std::net::{Ipv4Addr, SocketAddr}; use std::rc::{Rc, Weak}; use std::time::Instant; use log::Level; use mio::{Event, PollOpt, Ready, Token}; use mio::net::UdpSocket; use super::binary; use super::client::{Client, ClientChannel}; use super::connection::{Connection, ConnectionId}; use super::datagram_buffer::DatagramBuffer; use super::ipv4_header::Ipv4Header; use super::ipv4_packet::{Ipv4Packet, MAX_PACKET_LENGTH}; use super::packetizer::Packetizer; use super::selector::Selector; use super::transport_header::TransportHeader; const TAG: &'static str = "UdpConnection"; pub const IDLE_TIMEOUT_SECONDS: u64 = 2 * 60; pub struct UdpConnection { id: ConnectionId, client: Weak<RefCell<Client>>, socket: UdpSocket, interests: Ready, token: Token, client_to_network: DatagramBuffer, network_to_client: Packetizer, closed: bool, idle_since: Instant, } impl UdpConnection { pub fn new( selector: &mut Selector, id: ConnectionId, client: Weak<RefCell<Client>>, ipv4_header: Ipv4Header, transport_header: TransportHeader, ) -> io::Result<Rc<RefCell<Self>>>
let rc2 = rc.clone(); // must anotate selector type: https://stackoverflow.com/a/44004103/1987178 let handler = move |selector: &mut Selector, event| rc2.borrow_mut().on_ready(selector, event); let token = selector.register( &self_ref.socket, handler, interests, PollOpt::level(), )?; self_ref.token = token; } Ok(rc) } fn create_socket(id: &ConnectionId) -> io::Result<UdpSocket> { let autobind_addr = SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0); let udp_socket = UdpSocket::bind(&autobind_addr)?; udp_socket.connect(id.rewritten_destination().into())?; Ok(udp_socket) } fn remove_from_router(&self) { // route is embedded in router which is embedded in client: the client necessarily exists let client_rc = self.client.upgrade().expect("Expected client not found"); let mut client = client_rc.borrow_mut(); client.router().remove(self); } fn on_ready(&mut self, selector: &mut Selector, event: Event) { match self.process(selector, event) { Ok(_) => (), Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { cx_debug!(target: TAG, self.id, "Spurious event, ignoring") } Err(_) => panic!("Unexpected unhandled error"), } } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process(&mut self, selector: &mut Selector, event: Event) -> io::Result<()> { if!self.closed { self.touch(); let ready = event.readiness(); if ready.is_readable() || ready.is_writable() { if ready.is_writable() { self.process_send(selector)?; } if!self.closed && ready.is_readable() { self.process_receive(selector)?; } if!self.closed { self.update_interests(selector); } } else { // error or hup self.close(selector); } if self.closed { // on_ready is not called from the router, so the connection must remove itself self.remove_from_router(); } } Ok(()) } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process_send(&mut self, selector: &mut Selector) -> io::Result<()> { match self.write() { Ok(_) => (), Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { cx_debug!(target: TAG, self.id, "Spurious event, ignoring") } Err(err) => { if err.kind() == io::ErrorKind::WouldBlock { // rethrow return Err(err); } cx_error!( target: TAG, self.id, "Cannot write: [{:?}] {}", err.kind(), err ); self.close(selector); } } Ok(()) } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process_receive(&mut self, selector: &mut Selector) -> io::Result<()> { match self.read(selector) { Ok(_) => (), Err(err) => { if err.kind() == io::ErrorKind::WouldBlock { // rethrow return Err(err); } cx_error!( target: TAG, self.id, "Cannot read: [{:?}] {}", err.kind(), err ); self.close(selector); } } Ok(()) } fn read(&mut self, selector: &mut Selector) -> io::Result<()> { let ipv4_packet = self.network_to_client.packetize(&mut self.socket)?; let client_rc = self.client.upgrade().expect("Expected client not found"); match client_rc.borrow_mut().send_to_client( selector, &ipv4_packet, ) { Ok(_) => { cx_debug!( target: TAG, self.id, "Packet ({} bytes) sent to client", ipv4_packet.length() ); if log_enabled!(target: TAG, Level::Trace) { cx_trace!( target: TAG, self.id, "{}", binary::to_string(ipv4_packet.raw()) ); } } Err(_) => cx_warn!(target: TAG, self.id, "Cannot send to client, drop packet"), } Ok(()) } fn write(&mut self) -> io::Result<()> { self.client_to_network.write_to(&mut self.socket)?; Ok(()) } fn update_interests(&mut self, selector: &mut Selector) { let ready = if self.client_to_network.is_empty() { Ready::readable() } else { Ready::readable() | Ready::writable() }; cx_debug!(target: TAG, self.id, "interests: {:?}", ready); if self.interests!= ready { // interests must be changed self.interests = ready; selector .reregister(&self.socket, self.token, ready, PollOpt::level()) .expect("Cannot register on poll"); } } fn touch(&mut self) { self.idle_since = Instant::now(); } } impl Connection for UdpConnection { fn id(&self) -> &ConnectionId { &self.id } fn send_to_network( &mut self, selector: &mut Selector, _: &mut ClientChannel, ipv4_packet: &Ipv4Packet, ) { match self.client_to_network.read_from( ipv4_packet.payload().expect( "No payload", ), ) { Ok(_) => { self.update_interests(selector); } Err(err) => { cx_warn!( target: TAG, self.id, "Cannot send to network, drop packet: {}", err ) } } } fn close(&mut self, selector: &mut Selector) { cx_info!(target: TAG, self.id, "Close"); self.closed = true; selector.deregister(&self.socket, self.token).unwrap(); // socket will be closed by RAII } fn is_expired(&self) -> bool { self.idle_since.elapsed().as_secs() > IDLE_TIMEOUT_SECONDS } fn is_closed(&self) -> bool { self.closed } }
{ cx_info!(target: TAG, id, "Open"); let socket = Self::create_socket(&id)?; let packetizer = Packetizer::new(&ipv4_header, &transport_header); let interests = Ready::readable(); let rc = Rc::new(RefCell::new(Self { id: id, client: client, socket: socket, interests: interests, token: Token(0), // default value, will be set afterwards client_to_network: DatagramBuffer::new(4 * MAX_PACKET_LENGTH), network_to_client: packetizer, closed: false, idle_since: Instant::now(), })); { let mut self_ref = rc.borrow_mut();
identifier_body
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::cell::RefCell; use std::io; use std::net::{Ipv4Addr, SocketAddr}; use std::rc::{Rc, Weak}; use std::time::Instant; use log::Level; use mio::{Event, PollOpt, Ready, Token}; use mio::net::UdpSocket; use super::binary; use super::client::{Client, ClientChannel}; use super::connection::{Connection, ConnectionId}; use super::datagram_buffer::DatagramBuffer; use super::ipv4_header::Ipv4Header; use super::ipv4_packet::{Ipv4Packet, MAX_PACKET_LENGTH}; use super::packetizer::Packetizer; use super::selector::Selector; use super::transport_header::TransportHeader; const TAG: &'static str = "UdpConnection"; pub const IDLE_TIMEOUT_SECONDS: u64 = 2 * 60; pub struct UdpConnection { id: ConnectionId, client: Weak<RefCell<Client>>, socket: UdpSocket, interests: Ready, token: Token, client_to_network: DatagramBuffer, network_to_client: Packetizer, closed: bool, idle_since: Instant, } impl UdpConnection { pub fn new( selector: &mut Selector, id: ConnectionId, client: Weak<RefCell<Client>>, ipv4_header: Ipv4Header, transport_header: TransportHeader, ) -> io::Result<Rc<RefCell<Self>>> { cx_info!(target: TAG, id, "Open"); let socket = Self::create_socket(&id)?; let packetizer = Packetizer::new(&ipv4_header, &transport_header); let interests = Ready::readable(); let rc = Rc::new(RefCell::new(Self { id: id, client: client, socket: socket, interests: interests, token: Token(0), // default value, will be set afterwards client_to_network: DatagramBuffer::new(4 * MAX_PACKET_LENGTH), network_to_client: packetizer, closed: false, idle_since: Instant::now(), })); { let mut self_ref = rc.borrow_mut(); let rc2 = rc.clone(); // must anotate selector type: https://stackoverflow.com/a/44004103/1987178 let handler = move |selector: &mut Selector, event| rc2.borrow_mut().on_ready(selector, event); let token = selector.register( &self_ref.socket, handler, interests, PollOpt::level(), )?; self_ref.token = token; } Ok(rc) } fn create_socket(id: &ConnectionId) -> io::Result<UdpSocket> { let autobind_addr = SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0); let udp_socket = UdpSocket::bind(&autobind_addr)?; udp_socket.connect(id.rewritten_destination().into())?; Ok(udp_socket) } fn remove_from_router(&self) { // route is embedded in router which is embedded in client: the client necessarily exists let client_rc = self.client.upgrade().expect("Expected client not found"); let mut client = client_rc.borrow_mut(); client.router().remove(self); } fn on_ready(&mut self, selector: &mut Selector, event: Event) { match self.process(selector, event) { Ok(_) => (), Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { cx_debug!(target: TAG, self.id, "Spurious event, ignoring") } Err(_) => panic!("Unexpected unhandled error"), } } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process(&mut self, selector: &mut Selector, event: Event) -> io::Result<()> { if!self.closed { self.touch(); let ready = event.readiness(); if ready.is_readable() || ready.is_writable() { if ready.is_writable() { self.process_send(selector)?; } if!self.closed && ready.is_readable() { self.process_receive(selector)?; } if!self.closed { self.update_interests(selector); } } else { // error or hup self.close(selector); } if self.closed { // on_ready is not called from the router, so the connection must remove itself self.remove_from_router(); } } Ok(()) } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process_send(&mut self, selector: &mut Selector) -> io::Result<()> { match self.write() { Ok(_) => (), Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { cx_debug!(target: TAG, self.id, "Spurious event, ignoring") } Err(err) => { if err.kind() == io::ErrorKind::WouldBlock { // rethrow return Err(err); } cx_error!( target: TAG, self.id, "Cannot write: [{:?}] {}", err.kind(), err ); self.close(selector); } } Ok(()) } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process_receive(&mut self, selector: &mut Selector) -> io::Result<()> { match self.read(selector) { Ok(_) => (), Err(err) => { if err.kind() == io::ErrorKind::WouldBlock { // rethrow return Err(err); } cx_error!( target: TAG, self.id, "Cannot read: [{:?}] {}", err.kind(), err ); self.close(selector); } } Ok(()) } fn read(&mut self, selector: &mut Selector) -> io::Result<()> { let ipv4_packet = self.network_to_client.packetize(&mut self.socket)?; let client_rc = self.client.upgrade().expect("Expected client not found"); match client_rc.borrow_mut().send_to_client( selector, &ipv4_packet, ) { Ok(_) => { cx_debug!( target: TAG, self.id, "Packet ({} bytes) sent to client", ipv4_packet.length() ); if log_enabled!(target: TAG, Level::Trace) { cx_trace!( target: TAG, self.id, "{}", binary::to_string(ipv4_packet.raw()) ); } } Err(_) => cx_warn!(target: TAG, self.id, "Cannot send to client, drop packet"), } Ok(()) } fn write(&mut self) -> io::Result<()> { self.client_to_network.write_to(&mut self.socket)?; Ok(()) } fn update_interests(&mut self, selector: &mut Selector) { let ready = if self.client_to_network.is_empty() { Ready::readable() } else { Ready::readable() | Ready::writable() }; cx_debug!(target: TAG, self.id, "interests: {:?}", ready); if self.interests!= ready { // interests must be changed self.interests = ready; selector .reregister(&self.socket, self.token, ready, PollOpt::level()) .expect("Cannot register on poll"); } } fn touch(&mut self) { self.idle_since = Instant::now(); } } impl Connection for UdpConnection { fn id(&self) -> &ConnectionId { &self.id } fn send_to_network( &mut self, selector: &mut Selector, _: &mut ClientChannel, ipv4_packet: &Ipv4Packet, ) { match self.client_to_network.read_from( ipv4_packet.payload().expect( "No payload", ),
Err(err) => { cx_warn!( target: TAG, self.id, "Cannot send to network, drop packet: {}", err ) } } } fn close(&mut self, selector: &mut Selector) { cx_info!(target: TAG, self.id, "Close"); self.closed = true; selector.deregister(&self.socket, self.token).unwrap(); // socket will be closed by RAII } fn is_expired(&self) -> bool { self.idle_since.elapsed().as_secs() > IDLE_TIMEOUT_SECONDS } fn is_closed(&self) -> bool { self.closed } }
) { Ok(_) => { self.update_interests(selector); }
random_line_split
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::cell::RefCell; use std::io; use std::net::{Ipv4Addr, SocketAddr}; use std::rc::{Rc, Weak}; use std::time::Instant; use log::Level; use mio::{Event, PollOpt, Ready, Token}; use mio::net::UdpSocket; use super::binary; use super::client::{Client, ClientChannel}; use super::connection::{Connection, ConnectionId}; use super::datagram_buffer::DatagramBuffer; use super::ipv4_header::Ipv4Header; use super::ipv4_packet::{Ipv4Packet, MAX_PACKET_LENGTH}; use super::packetizer::Packetizer; use super::selector::Selector; use super::transport_header::TransportHeader; const TAG: &'static str = "UdpConnection"; pub const IDLE_TIMEOUT_SECONDS: u64 = 2 * 60; pub struct UdpConnection { id: ConnectionId, client: Weak<RefCell<Client>>, socket: UdpSocket, interests: Ready, token: Token, client_to_network: DatagramBuffer, network_to_client: Packetizer, closed: bool, idle_since: Instant, } impl UdpConnection { pub fn new( selector: &mut Selector, id: ConnectionId, client: Weak<RefCell<Client>>, ipv4_header: Ipv4Header, transport_header: TransportHeader, ) -> io::Result<Rc<RefCell<Self>>> { cx_info!(target: TAG, id, "Open"); let socket = Self::create_socket(&id)?; let packetizer = Packetizer::new(&ipv4_header, &transport_header); let interests = Ready::readable(); let rc = Rc::new(RefCell::new(Self { id: id, client: client, socket: socket, interests: interests, token: Token(0), // default value, will be set afterwards client_to_network: DatagramBuffer::new(4 * MAX_PACKET_LENGTH), network_to_client: packetizer, closed: false, idle_since: Instant::now(), })); { let mut self_ref = rc.borrow_mut(); let rc2 = rc.clone(); // must anotate selector type: https://stackoverflow.com/a/44004103/1987178 let handler = move |selector: &mut Selector, event| rc2.borrow_mut().on_ready(selector, event); let token = selector.register( &self_ref.socket, handler, interests, PollOpt::level(), )?; self_ref.token = token; } Ok(rc) } fn create_socket(id: &ConnectionId) -> io::Result<UdpSocket> { let autobind_addr = SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0); let udp_socket = UdpSocket::bind(&autobind_addr)?; udp_socket.connect(id.rewritten_destination().into())?; Ok(udp_socket) } fn remove_from_router(&self) { // route is embedded in router which is embedded in client: the client necessarily exists let client_rc = self.client.upgrade().expect("Expected client not found"); let mut client = client_rc.borrow_mut(); client.router().remove(self); } fn on_ready(&mut self, selector: &mut Selector, event: Event) { match self.process(selector, event) { Ok(_) => (), Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { cx_debug!(target: TAG, self.id, "Spurious event, ignoring") } Err(_) => panic!("Unexpected unhandled error"), } } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process(&mut self, selector: &mut Selector, event: Event) -> io::Result<()> { if!self.closed { self.touch(); let ready = event.readiness(); if ready.is_readable() || ready.is_writable() { if ready.is_writable() { self.process_send(selector)?; } if!self.closed && ready.is_readable() { self.process_receive(selector)?; } if!self.closed { self.update_interests(selector); } } else { // error or hup self.close(selector); } if self.closed { // on_ready is not called from the router, so the connection must remove itself self.remove_from_router(); } } Ok(()) } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process_send(&mut self, selector: &mut Selector) -> io::Result<()> { match self.write() { Ok(_) => (), Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { cx_debug!(target: TAG, self.id, "Spurious event, ignoring") } Err(err) => { if err.kind() == io::ErrorKind::WouldBlock { // rethrow return Err(err); } cx_error!( target: TAG, self.id, "Cannot write: [{:?}] {}", err.kind(), err ); self.close(selector); } } Ok(()) } // return Err(err) with err.kind() == io::ErrorKind::WouldBlock on spurious event fn process_receive(&mut self, selector: &mut Selector) -> io::Result<()> { match self.read(selector) { Ok(_) => (), Err(err) => { if err.kind() == io::ErrorKind::WouldBlock { // rethrow return Err(err); } cx_error!( target: TAG, self.id, "Cannot read: [{:?}] {}", err.kind(), err ); self.close(selector); } } Ok(()) } fn read(&mut self, selector: &mut Selector) -> io::Result<()> { let ipv4_packet = self.network_to_client.packetize(&mut self.socket)?; let client_rc = self.client.upgrade().expect("Expected client not found"); match client_rc.borrow_mut().send_to_client( selector, &ipv4_packet, ) { Ok(_) => { cx_debug!( target: TAG, self.id, "Packet ({} bytes) sent to client", ipv4_packet.length() ); if log_enabled!(target: TAG, Level::Trace) { cx_trace!( target: TAG, self.id, "{}", binary::to_string(ipv4_packet.raw()) ); } } Err(_) => cx_warn!(target: TAG, self.id, "Cannot send to client, drop packet"), } Ok(()) } fn write(&mut self) -> io::Result<()> { self.client_to_network.write_to(&mut self.socket)?; Ok(()) } fn update_interests(&mut self, selector: &mut Selector) { let ready = if self.client_to_network.is_empty() { Ready::readable() } else { Ready::readable() | Ready::writable() }; cx_debug!(target: TAG, self.id, "interests: {:?}", ready); if self.interests!= ready { // interests must be changed self.interests = ready; selector .reregister(&self.socket, self.token, ready, PollOpt::level()) .expect("Cannot register on poll"); } } fn touch(&mut self) { self.idle_since = Instant::now(); } } impl Connection for UdpConnection { fn id(&self) -> &ConnectionId { &self.id } fn send_to_network( &mut self, selector: &mut Selector, _: &mut ClientChannel, ipv4_packet: &Ipv4Packet, ) { match self.client_to_network.read_from( ipv4_packet.payload().expect( "No payload", ), ) { Ok(_) => { self.update_interests(selector); } Err(err) => { cx_warn!( target: TAG, self.id, "Cannot send to network, drop packet: {}", err ) } } } fn close(&mut self, selector: &mut Selector) { cx_info!(target: TAG, self.id, "Close"); self.closed = true; selector.deregister(&self.socket, self.token).unwrap(); // socket will be closed by RAII } fn is_expired(&self) -> bool { self.idle_since.elapsed().as_secs() > IDLE_TIMEOUT_SECONDS } fn
(&self) -> bool { self.closed } }
is_closed
identifier_name
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct Pan { params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } impl Pan { pub fn new(params: PanParams) -> Pan { Pan { params: params } } } impl Efx for Pan { fn sample(&mut self, sample: SampleValue) -> SoundSample { let right_v = self.params.pan.value(); let left_v = 1. - right_v; match sample { SampleValue::Mono(x) => stereo_value(x * right_v, x * left_v), SampleValue::Stereo(r, l) => stereo_value(right_v * r, left_v * l), //?? }
}
}
random_line_split
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct
{ params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } impl Pan { pub fn new(params: PanParams) -> Pan { Pan { params: params } } } impl Efx for Pan { fn sample(&mut self, sample: SampleValue) -> SoundSample { let right_v = self.params.pan.value(); let left_v = 1. - right_v; match sample { SampleValue::Mono(x) => stereo_value(x * right_v, x * left_v), SampleValue::Stereo(r, l) => stereo_value(right_v * r, left_v * l), //?? } } }
Pan
identifier_name
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct Pan { params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } impl Pan { pub fn new(params: PanParams) -> Pan
} impl Efx for Pan { fn sample(&mut self, sample: SampleValue) -> SoundSample { let right_v = self.params.pan.value(); let left_v = 1. - right_v; match sample { SampleValue::Mono(x) => stereo_value(x * right_v, x * left_v), SampleValue::Stereo(r, l) => stereo_value(right_v * r, left_v * l), //?? } } }
{ Pan { params: params } }
identifier_body
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::FractalAnimation; use fractal_lib::color; use fractal_lib::escapetime::EscapeTime; use fractal_lib::geometry; use num::complex::Complex64; use std::cmp; use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; pub struct EscapeTimeAnimation { /// The rendering context. ctx: CanvasRenderingContext2d, /// Which EscapeTime system is being animated. Boxed to encapsulate/avoid generics. etsystem: Box<dyn EscapeTime>, /// The current part of the fractal we're viewing. view_area: [geometry::Point; 2], }
ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation { let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } } fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); log::debug!("View area: {:?}", self.view_area); log::debug!("pixel 0,0 maps to {}", vat.map_pixel_to_point([0.0, 0.0])); log::debug!( "pixel {},{} maps to {}", screen_width as u32, screen_height as u32, vat.map_pixel_to_point([screen_width.into(), screen_height.into()]) ); log::debug!("build color range"); let colors = color::color_range_linear( color::BLACK_U8, color::WHITE_U8, cmp::min(self.etsystem.max_iterations(), 50) as usize, ); log::debug!("build image pixels"); let mut image_pixels = (0..screen_height) .map(|y| { (0..screen_width) .map(|x| { let c: Complex64 = vat.map_pixel_to_point([f64::from(x), f64::from(y)]).into(); let (attracted, time) = self.etsystem.test_point(c); if attracted { color::AEBLUE_U8.0.iter() } else { colors[cmp::min(time, 50 - 1) as usize].0.iter() } }) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clamped(image_pixels.as_mut_slice()); // Create an ImageData from the array log::debug!("Create Image Data"); let image = ImageData::new_with_u8_clamped_array_and_sh( clamped_image_array, screen_width, screen_height, ) .unwrap(); log::debug!("Put Image Data"); self.ctx.put_image_data(&image, 0.0, 0.0).unwrap(); } } impl FractalAnimation for EscapeTimeAnimation { fn draw_one_frame(&mut self) -> bool { self.render(); false } fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); let pos_point = vat.map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); // compute the new view area in the fractal's coordinate system let tlp = vat.map_pixel_to_point([x1, y1]); let brp = vat.map_pixel_to_point([x2, y2]); // update self.view_area = [tlp, brp]; true } }
impl EscapeTimeAnimation { pub fn new(
random_line_split
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::FractalAnimation; use fractal_lib::color; use fractal_lib::escapetime::EscapeTime; use fractal_lib::geometry; use num::complex::Complex64; use std::cmp; use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; pub struct EscapeTimeAnimation { /// The rendering context. ctx: CanvasRenderingContext2d, /// Which EscapeTime system is being animated. Boxed to encapsulate/avoid generics. etsystem: Box<dyn EscapeTime>, /// The current part of the fractal we're viewing. view_area: [geometry::Point; 2], } impl EscapeTimeAnimation { pub fn new( ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation { let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } } fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); log::debug!("View area: {:?}", self.view_area); log::debug!("pixel 0,0 maps to {}", vat.map_pixel_to_point([0.0, 0.0])); log::debug!( "pixel {},{} maps to {}", screen_width as u32, screen_height as u32, vat.map_pixel_to_point([screen_width.into(), screen_height.into()]) ); log::debug!("build color range"); let colors = color::color_range_linear( color::BLACK_U8, color::WHITE_U8, cmp::min(self.etsystem.max_iterations(), 50) as usize, ); log::debug!("build image pixels"); let mut image_pixels = (0..screen_height) .map(|y| { (0..screen_width) .map(|x| { let c: Complex64 = vat.map_pixel_to_point([f64::from(x), f64::from(y)]).into(); let (attracted, time) = self.etsystem.test_point(c); if attracted { color::AEBLUE_U8.0.iter() } else
}) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clamped(image_pixels.as_mut_slice()); // Create an ImageData from the array log::debug!("Create Image Data"); let image = ImageData::new_with_u8_clamped_array_and_sh( clamped_image_array, screen_width, screen_height, ) .unwrap(); log::debug!("Put Image Data"); self.ctx.put_image_data(&image, 0.0, 0.0).unwrap(); } } impl FractalAnimation for EscapeTimeAnimation { fn draw_one_frame(&mut self) -> bool { self.render(); false } fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); let pos_point = vat.map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); // compute the new view area in the fractal's coordinate system let tlp = vat.map_pixel_to_point([x1, y1]); let brp = vat.map_pixel_to_point([x2, y2]); // update self.view_area = [tlp, brp]; true } }
{ colors[cmp::min(time, 50 - 1) as usize].0.iter() }
conditional_block
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::FractalAnimation; use fractal_lib::color; use fractal_lib::escapetime::EscapeTime; use fractal_lib::geometry; use num::complex::Complex64; use std::cmp; use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; pub struct EscapeTimeAnimation { /// The rendering context. ctx: CanvasRenderingContext2d, /// Which EscapeTime system is being animated. Boxed to encapsulate/avoid generics. etsystem: Box<dyn EscapeTime>, /// The current part of the fractal we're viewing. view_area: [geometry::Point; 2], } impl EscapeTimeAnimation { pub fn new( ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation
fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); log::debug!("View area: {:?}", self.view_area); log::debug!("pixel 0,0 maps to {}", vat.map_pixel_to_point([0.0, 0.0])); log::debug!( "pixel {},{} maps to {}", screen_width as u32, screen_height as u32, vat.map_pixel_to_point([screen_width.into(), screen_height.into()]) ); log::debug!("build color range"); let colors = color::color_range_linear( color::BLACK_U8, color::WHITE_U8, cmp::min(self.etsystem.max_iterations(), 50) as usize, ); log::debug!("build image pixels"); let mut image_pixels = (0..screen_height) .map(|y| { (0..screen_width) .map(|x| { let c: Complex64 = vat.map_pixel_to_point([f64::from(x), f64::from(y)]).into(); let (attracted, time) = self.etsystem.test_point(c); if attracted { color::AEBLUE_U8.0.iter() } else { colors[cmp::min(time, 50 - 1) as usize].0.iter() } }) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clamped(image_pixels.as_mut_slice()); // Create an ImageData from the array log::debug!("Create Image Data"); let image = ImageData::new_with_u8_clamped_array_and_sh( clamped_image_array, screen_width, screen_height, ) .unwrap(); log::debug!("Put Image Data"); self.ctx.put_image_data(&image, 0.0, 0.0).unwrap(); } } impl FractalAnimation for EscapeTimeAnimation { fn draw_one_frame(&mut self) -> bool { self.render(); false } fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); let pos_point = vat.map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); // compute the new view area in the fractal's coordinate system let tlp = vat.map_pixel_to_point([x1, y1]); let brp = vat.map_pixel_to_point([x2, y2]); // update self.view_area = [tlp, brp]; true } }
{ let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } }
identifier_body
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::FractalAnimation; use fractal_lib::color; use fractal_lib::escapetime::EscapeTime; use fractal_lib::geometry; use num::complex::Complex64; use std::cmp; use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; pub struct EscapeTimeAnimation { /// The rendering context. ctx: CanvasRenderingContext2d, /// Which EscapeTime system is being animated. Boxed to encapsulate/avoid generics. etsystem: Box<dyn EscapeTime>, /// The current part of the fractal we're viewing. view_area: [geometry::Point; 2], } impl EscapeTimeAnimation { pub fn new( ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation { let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } } fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); log::debug!("View area: {:?}", self.view_area); log::debug!("pixel 0,0 maps to {}", vat.map_pixel_to_point([0.0, 0.0])); log::debug!( "pixel {},{} maps to {}", screen_width as u32, screen_height as u32, vat.map_pixel_to_point([screen_width.into(), screen_height.into()]) ); log::debug!("build color range"); let colors = color::color_range_linear( color::BLACK_U8, color::WHITE_U8, cmp::min(self.etsystem.max_iterations(), 50) as usize, ); log::debug!("build image pixels"); let mut image_pixels = (0..screen_height) .map(|y| { (0..screen_width) .map(|x| { let c: Complex64 = vat.map_pixel_to_point([f64::from(x), f64::from(y)]).into(); let (attracted, time) = self.etsystem.test_point(c); if attracted { color::AEBLUE_U8.0.iter() } else { colors[cmp::min(time, 50 - 1) as usize].0.iter() } }) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clamped(image_pixels.as_mut_slice()); // Create an ImageData from the array log::debug!("Create Image Data"); let image = ImageData::new_with_u8_clamped_array_and_sh( clamped_image_array, screen_width, screen_height, ) .unwrap(); log::debug!("Put Image Data"); self.ctx.put_image_data(&image, 0.0, 0.0).unwrap(); } } impl FractalAnimation for EscapeTimeAnimation { fn draw_one_frame(&mut self) -> bool { self.render(); false } fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); let pos_point = vat.map_pixel_to_point([x, y]); pos_point.into() } fn
(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); // compute the new view area in the fractal's coordinate system let tlp = vat.map_pixel_to_point([x1, y1]); let brp = vat.map_pixel_to_point([x2, y2]); // update self.view_area = [tlp, brp]; true } }
zoom
identifier_name
lib.rs
self.size.unwrap_or(0) } fn code_file(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn debug_file(&self) -> Option<Cow<str>> { self.debug_file.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn debug_identifier(&self) -> Option<Cow<str>> { self.debug_id.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn version(&self) -> Option<Cow<str>> { self.version.as_ref().map(|s| Cow::Borrowed(&s[..])) } } /// Like `PathBuf::file_name`, but try to work on Windows or POSIX-style paths. fn leafname(path: &str) -> &str { path.rsplit(|c| c == '/' || c == '\\') .next() .unwrap_or(path) } /// If `filename` ends with `match_extension`, remove it. Append `new_extension` to the result. fn replace_or_add_extension(filename: &str, match_extension: &str, new_extension: &str) -> String { let mut bits = filename.split('.').collect::<Vec<_>>(); if bits.len() > 1 && bits .last() .map_or(false, |e| e.to_lowercase() == match_extension) { bits.pop(); } bits.push(new_extension); bits.join(".") } /// Get a relative symbol path at which to locate symbols for `module`. /// /// Symbols are generally stored in the layout used by Microsoft's symbol /// server and associated tools: /// `<debug filename>/<debug identifier>/<debug filename>.sym`. If /// `debug filename` ends with *.pdb* the leaf filename will have that /// removed. /// `extension` is the expected extension for the symbol filename, generally /// *sym* if Breakpad text format symbols are expected. /// /// The debug filename and debug identifier can be found in the /// [first line][module_line] of the symbol file output by the dump_syms tool. /// You can use [this script][packagesymbols] to run dump_syms and put the /// resulting symbol files in the proper directory structure. /// /// [module_line]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md#MODULE-records /// [packagesymbols]: https://gist.github.com/luser/2ad32d290f224782fcfc#file-packagesymbols-py pub fn relative_symbol_path(module: &dyn Module, extension: &str) -> Option<String> { module.debug_file().and_then(|debug_file| { module.debug_identifier().map(|debug_id| { // Can't use PathBuf::file_name here, it doesn't handle // Windows file paths on non-Windows. let leaf = leafname(&debug_file); let filename = replace_or_add_extension(leaf, "pdb", extension); [leaf, &debug_id[..], &filename[..]].join("/") }) }) } /// Possible results of locating symbols. #[derive(Debug)] pub enum SymbolResult { /// Symbols loaded successfully. Ok(SymbolFile), /// Symbol file could not be found. NotFound, /// Error loading symbol file. LoadError(Error), } impl PartialEq for SymbolResult { fn eq(&self, other: &SymbolResult) -> bool
} impl fmt::Display for SymbolResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SymbolResult::Ok(_) => write!(f, "Ok"), SymbolResult::NotFound => write!(f, "Not found"), SymbolResult::LoadError(ref e) => write!(f, "Load error: {}", e), } } } /// A trait for things that can locate symbols for a given module. pub trait SymbolSupplier { /// Locate and load a symbol file for `module`. /// /// Implementations may use any strategy for locating and loading /// symbols. fn locate_symbols(&self, module: &dyn Module) -> SymbolResult; } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from local disk /// paths. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct SimpleSymbolSupplier { /// Local disk paths in which to search for symbols. paths: Vec<PathBuf>, } impl SimpleSymbolSupplier { /// Instantiate a new `SimpleSymbolSupplier` that will search in `paths`. pub fn new(paths: Vec<PathBuf>) -> SimpleSymbolSupplier { SimpleSymbolSupplier { paths } } } impl SymbolSupplier for SimpleSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref path in self.paths.iter() { let test_path = path.join(&rel_path); if fs::metadata(&test_path).ok().map_or(false, |m| m.is_file()) { return SymbolFile::from_file(&test_path) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } /// A SymbolSupplier that maps module names (code_files) to an in-memory string. /// /// Intended for mocking symbol files in tests. #[derive(Default, Debug, Clone)] pub struct StringSymbolSupplier { modules: HashMap<String, String>, } impl StringSymbolSupplier { /// Make a new StringSymbolSupplier with no modules. pub fn new(modules: HashMap<String, String>) -> Self { Self { modules } } } impl SymbolSupplier for StringSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(symbols) = self.modules.get(&*module.code_file()) { return SymbolFile::from_bytes(symbols.as_bytes()) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } SymbolResult::NotFound } } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from HTTP /// URLs. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct HttpSymbolSupplier { /// HTTP Client to use for fetching symbols. client: Client, /// URLs to search for symbols. urls: Vec<Url>, /// A `SimpleSymbolSupplier` to use for local symbol paths. local: SimpleSymbolSupplier, /// A path at which to cache downloaded symbols. cache: PathBuf, } impl HttpSymbolSupplier { /// Create a new `HttpSymbolSupplier`. /// /// Symbols will be searched for in each of `local_paths` and `cache` first, then via HTTP /// at each of `urls`. If a symbol file is found via HTTP it will be saved under `cache`. pub fn new( urls: Vec<String>, cache: PathBuf, mut local_paths: Vec<PathBuf>, ) -> HttpSymbolSupplier { let client = Client::new(); let urls = urls .into_iter() .filter_map(|mut u| { if!u.ends_with('/') { u.push('/'); } Url::parse(&u).ok() }) .collect(); local_paths.push(cache.clone()); let local = SimpleSymbolSupplier::new(local_paths); HttpSymbolSupplier { client, urls, local, cache, } } } /// Save the data in `contents` to `path`. fn save_contents(contents: &[u8], path: &Path) -> io::Result<()> { let base = path.parent().ok_or_else(|| { io::Error::new(io::ErrorKind::Other, format!("Bad cache path: {:?}", path)) })?; fs::create_dir_all(&base)?; let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) } /// Fetch a symbol file from the URL made by combining `base_url` and `rel_path` using `client`, /// save the file contents under `cache` + `rel_path` and also return them. fn fetch_symbol_file( client: &Client, base_url: &Url, rel_path: &str, cache: &Path, ) -> Result<Vec<u8>, Error> { let url = base_url.join(&rel_path)?; debug!("Trying {}", url); let mut res = client.get(url).send()?.error_for_status()?; let mut buf = vec![]; res.read_to_end(&mut buf)?; let local = cache.join(rel_path); match save_contents(&buf, &local) { Ok(_) => {} Err(e) => warn!("Failed to save symbol file in local disk cache: {}", e), } Ok(buf) } impl SymbolSupplier for HttpSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { // Check local paths first. match self.local.locate_symbols(module) { res @ SymbolResult::Ok(_) | res @ SymbolResult::LoadError(_) => res, SymbolResult::NotFound => { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref url in self.urls.iter() { if let Ok(buf) = fetch_symbol_file(&self.client, url, &rel_path, &self.cache) { return SymbolFile::from_bytes(&buf) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } } } /// A trait for setting symbol information on something like a stack frame. pub trait FrameSymbolizer { /// Get the program counter value for this frame. fn get_instruction(&self) -> u64; /// Set the name, base address, and paramter size of the function in // which this frame is executing. fn set_function(&mut self, name: &str, base: u64, parameter_size: u32); /// Set the source file and (1-based) line number this frame represents. fn set_source_file(&mut self, file: &str, line: u32, base: u64); } pub trait FrameWalker { /// Get the instruction address that we're trying to unwind from. fn get_instruction(&self) -> u64; /// Get the number of bytes the callee's callee's parameters take up /// on the stack (or 0 if unknown/invalid). This is needed for /// STACK WIN unwinding. fn get_grand_callee_parameter_size(&self) -> u32; /// Get a register-sized value stored at this address. fn get_register_at_address(&self, address: u64) -> Option<u64>; /// Get the value of a register from the callee's frame. fn get_callee_register(&self, name: &str) -> Option<u64>; /// Set the value of a register for the caller's frame. fn set_caller_register(&mut self, name: &str, val: u64) -> Option<()>; /// Explicitly mark one of the caller's registers as invalid. fn clear_caller_register(&mut self, name: &str); /// Set whatever registers in the caller should be set based on the cfa (e.g. rsp). fn set_cfa(&mut self, val: u64) -> Option<()>; /// Set whatever registers in the caller should be set based on the return address (e.g. rip). fn set_ra(&mut self, val: u64) -> Option<()>; } /// A simple implementation of `FrameSymbolizer` that just holds data. #[derive(Debug, Default)] pub struct SimpleFrame { /// The program counter value for this frame. pub instruction: u64, /// The name of the function in which the current instruction is executing. pub function: Option<String>, /// The offset of the start of `function` from the module base. pub function_base: Option<u64>, /// The size, in bytes, that this function's parameters take up on the stack. pub parameter_size: Option<u32>, /// The name of the source file in which the current instruction is executing. pub source_file: Option<String>, /// The 1-based index of the line number in `source_file` in which the current instruction is /// executing. pub source_line: Option<u32>, /// The offset of the start of `source_line` from the function base. pub source_line_base: Option<u64>, } impl SimpleFrame { /// Instantiate a `SimpleFrame` with instruction pointer `instruction`. pub fn with_instruction(instruction: u64) -> SimpleFrame { SimpleFrame { instruction, ..SimpleFrame::default() } } } impl FrameSymbolizer for SimpleFrame { fn get_instruction(&self) -> u64 { self.instruction } fn set_function(&mut self, name: &str, base: u64, parameter_size: u32) { self.function = Some(String::from(name)); self.function_base = Some(base); self.parameter_size = Some(parameter_size); } fn set_source_file(&mut self, file: &str, line: u32, base: u64) { self.source_file = Some(String::from(file)); self.source_line = Some(line); self.source_line_base = Some(base); } } // Can't make Module derive Hash, since then it can't be used as a trait // object (because the hash method is generic), so this is a hacky workaround. type ModuleKey = (String, String, Option<String>, Option<String>); /// Helper for deriving a hash key from a `Module` for `Symbolizer`. fn key(module: &dyn Module) -> ModuleKey { ( module.code_file().to_string(), module.code_identifier().to_string(), module.debug_file().map(|s| s.to_string()), module.debug_identifier().map(|s| s.to_string()), ) } /// Symbolicate stack frames. /// /// A `Symbolizer` manages loading symbols and looking up symbols in them /// including caching so that symbols for a given module are only loaded once. /// /// Call [`Symbolizer::new`][new] to instantiate a `Symbolizer`. A Symbolizer /// requires a [`SymbolSupplier`][supplier] to locate symbols. If you have /// symbols on disk in the [customary directory layout][dirlayout], a /// [`SimpleSymbolSupplier`][simple] will work. /// /// Use [`get_symbol_at_address`][get_symbol] or [`fill_symbol`][fill_symbol] to /// do symbol lookup. /// /// [new]: struct.Symbolizer.html#method.new /// [supplier]: trait.SymbolSupplier.html /// [dirlayout]: fn.relative_symbol_path.html /// [simple]: struct.SimpleSymbolSupplier.html /// [get_symbol]: struct.Symbolizer.html#method.get_symbol_at_address /// [fill_symbol]: struct.Symbolizer.html#method.fill_symbol pub struct Symbolizer { /// Symbol supplier for locating symbols. supplier: Box<dyn SymbolSupplier +'static>, /// Cache of symbol locating results. //TODO: use lru-cache: https://crates.io/crates/lru-cache/ symbols: RefCell<HashMap<ModuleKey, SymbolResult>>, } impl Symbolizer { /// Create a `Symbolizer` that uses `supplier` to locate symbols. pub fn new<T: SymbolSupplier +'static>(supplier: T) -> Symbolizer { Symbolizer { supplier: Box::new(supplier), symbols: RefCell::new(HashMap::new()), } } /// Helper method for non-minidump-using callers. /// /// Pass `debug_file` and `debug_id` describing a specific module, /// and `address`, a module-relative address, and get back /// a symbol in that module that covers that address, or `None`. /// /// See [the module-level documentation][module] for an example. /// /// [module]: index.html pub fn get_symbol_at_address( &self, debug_file: &str, debug_id: &str, address: u64, ) -> Option<String> { let k = (debug_file, debug_id); let mut frame = SimpleFrame::with_instruction(address); self.fill_symbol(&k, &mut frame); frame.function } /// Fill symbol information in `frame` using the instruction address /// from `frame`, and the module information from `module`. If you're not /// using a minidump module, you can use [`SimpleModule`][simplemodule] and /// [`SimpleFrame`][simpleframe]. /// /// # Examples /// /// ``` /// # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); /// use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; /// use std::path::PathBuf; /// let paths = vec!(PathBuf::from("../testdata/symbols/")); /// let supplier = SimpleSymbolSupplier::new(paths); /// let symbolizer = Symbolizer::new(supplier); /// let m = SimpleModule::new("test_app.pdb", "5A9832E5287241C1838ED98914E9B7FF1"); /// let mut f = SimpleFrame::with_instruction(0x1010); /// symbolizer.fill_symbol(&m, &mut f); /// assert_eq!(f.function.unwrap(), "vswprintf"); /// assert_eq!(f.source_file.unwrap(), r"c:\program files\microsoft visual studio 8\vc\include\swprintf.inl"); /// assert_eq!(f.source_line.unwrap(), 51); /// ``` /// /// [simplemodule]: struct.SimpleModule.html /// [simpleframe]: struct.SimpleFrame.html pub fn fill_symbol(&self, module: &dyn Module, frame: &mut dyn FrameSymbolizer) { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.fill_symbol(module, frame) } } pub fn walk_frame(&self, module: &dyn Module, walker: &mut dyn FrameWalker) -> Option<()> { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.walk_frame(module, walker) } else { None } } fn ensure_module(&self, module: &dyn Module, k: &ModuleKey) { if!self.symbols.borrow().contains_key(&k) { let res = self.supplier.locate_symbols(module); debug!("locate_symbols for {}: {}", module.code_file(), res); self.symbols.borrow_mut().insert(k.clone(), res); } } } #[test] fn test_leafname() { assert_eq!(leafname("c:\\foo\\bar\\test.pdb"), "test.pdb"); assert_eq!(leafname("c:/foo/bar/test.pdb"), "test.pdb"); assert_eq!(leafname("test.pdb"), "test.pdb"); assert_eq!(leafname("test"), "test"); assert_eq!(leafname("/path/to/test"), "test"); } #[test] fn test_replace_or_add_extension() { assert_eq!( replace_or_add_extension("test.pdb", "pdb", "sym"), "test.sym" ); assert_eq!( replace_or_add_extension("TEST.PDB", "pdb", "sym"), "TEST.sym" ); assert_eq!(replace_or_add_extension("test", "pdb", "sym"), "test.sym"); assert_eq!( replace_or_add_extension("test.x", "pdb", "sym"), "test.x.sym" ); assert_eq!(replace_or_add_extension("", "pdb", "sym"), ".sym"); assert_eq!(replace_or_add_extension("test.x", "x", "y"), "test.y"); } #[cfg(test)] mod test { use super::*; use std::fs; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use tempdir::TempDir; #[test] fn test_relative_symbol_path() { let m = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); let m2 = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m2, "bar").unwrap(), "foo.pdb/abcd1234/foo.bar" ); let m3 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m3, "sym").unwrap(), "foo.xyz/abcd1234/foo.xyz.sym" ); let m4 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m4, "bar").unwrap(), "foo.xyz/abcd1234/foo.xyz.bar" ); let bad = SimpleModule::default(); assert!(relative_symbol_path(&bad, "sym").is_none()); let bad2 = SimpleModule { debug_file: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad2, "sym").is_none()); let bad3 = SimpleModule { debug_id: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad3, "sym").is_none()); } #[test] fn test_relative_symbol_path_abs_paths() { { let m = SimpleModule::new("/path/to/foo.bin", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.bin/abcd1234/foo.bin.sym" ); } { let m = SimpleModule::new("c:/path/to
{ match (self, other) { (&SymbolResult::Ok(ref a), &SymbolResult::Ok(ref b)) => a == b, (&SymbolResult::NotFound, &SymbolResult::NotFound) => true, (&SymbolResult::LoadError(_), &SymbolResult::LoadError(_)) => true, _ => false, } }
identifier_body
lib.rs
self.size.unwrap_or(0) } fn code_file(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn debug_file(&self) -> Option<Cow<str>> { self.debug_file.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn debug_identifier(&self) -> Option<Cow<str>> { self.debug_id.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn version(&self) -> Option<Cow<str>> { self.version.as_ref().map(|s| Cow::Borrowed(&s[..])) } } /// Like `PathBuf::file_name`, but try to work on Windows or POSIX-style paths. fn leafname(path: &str) -> &str { path.rsplit(|c| c == '/' || c == '\\') .next() .unwrap_or(path) } /// If `filename` ends with `match_extension`, remove it. Append `new_extension` to the result. fn replace_or_add_extension(filename: &str, match_extension: &str, new_extension: &str) -> String { let mut bits = filename.split('.').collect::<Vec<_>>(); if bits.len() > 1 && bits .last() .map_or(false, |e| e.to_lowercase() == match_extension) { bits.pop(); } bits.push(new_extension); bits.join(".") } /// Get a relative symbol path at which to locate symbols for `module`. /// /// Symbols are generally stored in the layout used by Microsoft's symbol /// server and associated tools: /// `<debug filename>/<debug identifier>/<debug filename>.sym`. If /// `debug filename` ends with *.pdb* the leaf filename will have that /// removed. /// `extension` is the expected extension for the symbol filename, generally /// *sym* if Breakpad text format symbols are expected. /// /// The debug filename and debug identifier can be found in the /// [first line][module_line] of the symbol file output by the dump_syms tool. /// You can use [this script][packagesymbols] to run dump_syms and put the /// resulting symbol files in the proper directory structure. /// /// [module_line]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md#MODULE-records /// [packagesymbols]: https://gist.github.com/luser/2ad32d290f224782fcfc#file-packagesymbols-py pub fn relative_symbol_path(module: &dyn Module, extension: &str) -> Option<String> { module.debug_file().and_then(|debug_file| { module.debug_identifier().map(|debug_id| { // Can't use PathBuf::file_name here, it doesn't handle // Windows file paths on non-Windows. let leaf = leafname(&debug_file); let filename = replace_or_add_extension(leaf, "pdb", extension); [leaf, &debug_id[..], &filename[..]].join("/") }) }) } /// Possible results of locating symbols. #[derive(Debug)] pub enum SymbolResult { /// Symbols loaded successfully. Ok(SymbolFile), /// Symbol file could not be found. NotFound, /// Error loading symbol file. LoadError(Error), } impl PartialEq for SymbolResult { fn eq(&self, other: &SymbolResult) -> bool { match (self, other) { (&SymbolResult::Ok(ref a), &SymbolResult::Ok(ref b)) => a == b, (&SymbolResult::NotFound, &SymbolResult::NotFound) => true, (&SymbolResult::LoadError(_), &SymbolResult::LoadError(_)) => true, _ => false, } } } impl fmt::Display for SymbolResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SymbolResult::Ok(_) => write!(f, "Ok"), SymbolResult::NotFound => write!(f, "Not found"), SymbolResult::LoadError(ref e) => write!(f, "Load error: {}", e), } } } /// A trait for things that can locate symbols for a given module. pub trait SymbolSupplier { /// Locate and load a symbol file for `module`. /// /// Implementations may use any strategy for locating and loading /// symbols. fn locate_symbols(&self, module: &dyn Module) -> SymbolResult; } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from local disk /// paths. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct SimpleSymbolSupplier { /// Local disk paths in which to search for symbols. paths: Vec<PathBuf>, } impl SimpleSymbolSupplier { /// Instantiate a new `SimpleSymbolSupplier` that will search in `paths`. pub fn new(paths: Vec<PathBuf>) -> SimpleSymbolSupplier { SimpleSymbolSupplier { paths } } } impl SymbolSupplier for SimpleSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref path in self.paths.iter() { let test_path = path.join(&rel_path); if fs::metadata(&test_path).ok().map_or(false, |m| m.is_file()) { return SymbolFile::from_file(&test_path) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } /// A SymbolSupplier that maps module names (code_files) to an in-memory string. /// /// Intended for mocking symbol files in tests. #[derive(Default, Debug, Clone)] pub struct StringSymbolSupplier { modules: HashMap<String, String>, } impl StringSymbolSupplier { /// Make a new StringSymbolSupplier with no modules. pub fn new(modules: HashMap<String, String>) -> Self { Self { modules } } } impl SymbolSupplier for StringSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(symbols) = self.modules.get(&*module.code_file()) { return SymbolFile::from_bytes(symbols.as_bytes()) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } SymbolResult::NotFound } } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from HTTP /// URLs. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct HttpSymbolSupplier { /// HTTP Client to use for fetching symbols. client: Client, /// URLs to search for symbols. urls: Vec<Url>, /// A `SimpleSymbolSupplier` to use for local symbol paths. local: SimpleSymbolSupplier, /// A path at which to cache downloaded symbols. cache: PathBuf, } impl HttpSymbolSupplier { /// Create a new `HttpSymbolSupplier`. /// /// Symbols will be searched for in each of `local_paths` and `cache` first, then via HTTP /// at each of `urls`. If a symbol file is found via HTTP it will be saved under `cache`. pub fn new( urls: Vec<String>, cache: PathBuf, mut local_paths: Vec<PathBuf>, ) -> HttpSymbolSupplier { let client = Client::new(); let urls = urls .into_iter() .filter_map(|mut u| { if!u.ends_with('/') { u.push('/'); } Url::parse(&u).ok() }) .collect(); local_paths.push(cache.clone()); let local = SimpleSymbolSupplier::new(local_paths); HttpSymbolSupplier { client, urls, local, cache, } } } /// Save the data in `contents` to `path`. fn save_contents(contents: &[u8], path: &Path) -> io::Result<()> { let base = path.parent().ok_or_else(|| { io::Error::new(io::ErrorKind::Other, format!("Bad cache path: {:?}", path)) })?; fs::create_dir_all(&base)?; let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) } /// Fetch a symbol file from the URL made by combining `base_url` and `rel_path` using `client`, /// save the file contents under `cache` + `rel_path` and also return them. fn fetch_symbol_file( client: &Client, base_url: &Url, rel_path: &str, cache: &Path, ) -> Result<Vec<u8>, Error> { let url = base_url.join(&rel_path)?; debug!("Trying {}", url); let mut res = client.get(url).send()?.error_for_status()?; let mut buf = vec![]; res.read_to_end(&mut buf)?; let local = cache.join(rel_path); match save_contents(&buf, &local) { Ok(_) => {} Err(e) => warn!("Failed to save symbol file in local disk cache: {}", e), } Ok(buf) } impl SymbolSupplier for HttpSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { // Check local paths first. match self.local.locate_symbols(module) { res @ SymbolResult::Ok(_) | res @ SymbolResult::LoadError(_) => res, SymbolResult::NotFound => { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref url in self.urls.iter() { if let Ok(buf) = fetch_symbol_file(&self.client, url, &rel_path, &self.cache) { return SymbolFile::from_bytes(&buf) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } } } /// A trait for setting symbol information on something like a stack frame. pub trait FrameSymbolizer { /// Get the program counter value for this frame. fn get_instruction(&self) -> u64; /// Set the name, base address, and paramter size of the function in // which this frame is executing. fn set_function(&mut self, name: &str, base: u64, parameter_size: u32); /// Set the source file and (1-based) line number this frame represents. fn set_source_file(&mut self, file: &str, line: u32, base: u64); } pub trait FrameWalker { /// Get the instruction address that we're trying to unwind from. fn get_instruction(&self) -> u64; /// Get the number of bytes the callee's callee's parameters take up /// on the stack (or 0 if unknown/invalid). This is needed for /// STACK WIN unwinding. fn get_grand_callee_parameter_size(&self) -> u32; /// Get a register-sized value stored at this address. fn get_register_at_address(&self, address: u64) -> Option<u64>; /// Get the value of a register from the callee's frame. fn get_callee_register(&self, name: &str) -> Option<u64>; /// Set the value of a register for the caller's frame. fn set_caller_register(&mut self, name: &str, val: u64) -> Option<()>; /// Explicitly mark one of the caller's registers as invalid. fn clear_caller_register(&mut self, name: &str); /// Set whatever registers in the caller should be set based on the cfa (e.g. rsp). fn set_cfa(&mut self, val: u64) -> Option<()>; /// Set whatever registers in the caller should be set based on the return address (e.g. rip). fn set_ra(&mut self, val: u64) -> Option<()>; } /// A simple implementation of `FrameSymbolizer` that just holds data. #[derive(Debug, Default)] pub struct SimpleFrame { /// The program counter value for this frame. pub instruction: u64, /// The name of the function in which the current instruction is executing. pub function: Option<String>, /// The offset of the start of `function` from the module base. pub function_base: Option<u64>, /// The size, in bytes, that this function's parameters take up on the stack. pub parameter_size: Option<u32>, /// The name of the source file in which the current instruction is executing. pub source_file: Option<String>, /// The 1-based index of the line number in `source_file` in which the current instruction is /// executing. pub source_line: Option<u32>, /// The offset of the start of `source_line` from the function base. pub source_line_base: Option<u64>, } impl SimpleFrame { /// Instantiate a `SimpleFrame` with instruction pointer `instruction`. pub fn with_instruction(instruction: u64) -> SimpleFrame { SimpleFrame { instruction, ..SimpleFrame::default() } } } impl FrameSymbolizer for SimpleFrame { fn get_instruction(&self) -> u64 { self.instruction } fn set_function(&mut self, name: &str, base: u64, parameter_size: u32) { self.function = Some(String::from(name)); self.function_base = Some(base); self.parameter_size = Some(parameter_size); } fn set_source_file(&mut self, file: &str, line: u32, base: u64) { self.source_file = Some(String::from(file)); self.source_line = Some(line); self.source_line_base = Some(base); } } // Can't make Module derive Hash, since then it can't be used as a trait // object (because the hash method is generic), so this is a hacky workaround. type ModuleKey = (String, String, Option<String>, Option<String>); /// Helper for deriving a hash key from a `Module` for `Symbolizer`. fn key(module: &dyn Module) -> ModuleKey { ( module.code_file().to_string(), module.code_identifier().to_string(), module.debug_file().map(|s| s.to_string()), module.debug_identifier().map(|s| s.to_string()), ) } /// Symbolicate stack frames. /// /// A `Symbolizer` manages loading symbols and looking up symbols in them /// including caching so that symbols for a given module are only loaded once. /// /// Call [`Symbolizer::new`][new] to instantiate a `Symbolizer`. A Symbolizer /// requires a [`SymbolSupplier`][supplier] to locate symbols. If you have /// symbols on disk in the [customary directory layout][dirlayout], a /// [`SimpleSymbolSupplier`][simple] will work. /// /// Use [`get_symbol_at_address`][get_symbol] or [`fill_symbol`][fill_symbol] to /// do symbol lookup. /// /// [new]: struct.Symbolizer.html#method.new /// [supplier]: trait.SymbolSupplier.html /// [dirlayout]: fn.relative_symbol_path.html /// [simple]: struct.SimpleSymbolSupplier.html /// [get_symbol]: struct.Symbolizer.html#method.get_symbol_at_address /// [fill_symbol]: struct.Symbolizer.html#method.fill_symbol pub struct Symbolizer { /// Symbol supplier for locating symbols. supplier: Box<dyn SymbolSupplier +'static>, /// Cache of symbol locating results. //TODO: use lru-cache: https://crates.io/crates/lru-cache/ symbols: RefCell<HashMap<ModuleKey, SymbolResult>>, } impl Symbolizer { /// Create a `Symbolizer` that uses `supplier` to locate symbols. pub fn new<T: SymbolSupplier +'static>(supplier: T) -> Symbolizer { Symbolizer { supplier: Box::new(supplier), symbols: RefCell::new(HashMap::new()), } } /// Helper method for non-minidump-using callers. /// /// Pass `debug_file` and `debug_id` describing a specific module, /// and `address`, a module-relative address, and get back /// a symbol in that module that covers that address, or `None`. /// /// See [the module-level documentation][module] for an example. /// /// [module]: index.html pub fn get_symbol_at_address( &self, debug_file: &str, debug_id: &str, address: u64, ) -> Option<String> { let k = (debug_file, debug_id); let mut frame = SimpleFrame::with_instruction(address); self.fill_symbol(&k, &mut frame); frame.function } /// Fill symbol information in `frame` using the instruction address /// from `frame`, and the module information from `module`. If you're not /// using a minidump module, you can use [`SimpleModule`][simplemodule] and /// [`SimpleFrame`][simpleframe]. /// /// # Examples /// /// ``` /// # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); /// use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; /// use std::path::PathBuf; /// let paths = vec!(PathBuf::from("../testdata/symbols/")); /// let supplier = SimpleSymbolSupplier::new(paths); /// let symbolizer = Symbolizer::new(supplier); /// let m = SimpleModule::new("test_app.pdb", "5A9832E5287241C1838ED98914E9B7FF1"); /// let mut f = SimpleFrame::with_instruction(0x1010); /// symbolizer.fill_symbol(&m, &mut f); /// assert_eq!(f.function.unwrap(), "vswprintf");
/// /// [simplemodule]: struct.SimpleModule.html /// [simpleframe]: struct.SimpleFrame.html pub fn fill_symbol(&self, module: &dyn Module, frame: &mut dyn FrameSymbolizer) { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.fill_symbol(module, frame) } } pub fn walk_frame(&self, module: &dyn Module, walker: &mut dyn FrameWalker) -> Option<()> { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.walk_frame(module, walker) } else { None } } fn ensure_module(&self, module: &dyn Module, k: &ModuleKey) { if!self.symbols.borrow().contains_key(&k) { let res = self.supplier.locate_symbols(module); debug!("locate_symbols for {}: {}", module.code_file(), res); self.symbols.borrow_mut().insert(k.clone(), res); } } } #[test] fn test_leafname() { assert_eq!(leafname("c:\\foo\\bar\\test.pdb"), "test.pdb"); assert_eq!(leafname("c:/foo/bar/test.pdb"), "test.pdb"); assert_eq!(leafname("test.pdb"), "test.pdb"); assert_eq!(leafname("test"), "test"); assert_eq!(leafname("/path/to/test"), "test"); } #[test] fn test_replace_or_add_extension() { assert_eq!( replace_or_add_extension("test.pdb", "pdb", "sym"), "test.sym" ); assert_eq!( replace_or_add_extension("TEST.PDB", "pdb", "sym"), "TEST.sym" ); assert_eq!(replace_or_add_extension("test", "pdb", "sym"), "test.sym"); assert_eq!( replace_or_add_extension("test.x", "pdb", "sym"), "test.x.sym" ); assert_eq!(replace_or_add_extension("", "pdb", "sym"), ".sym"); assert_eq!(replace_or_add_extension("test.x", "x", "y"), "test.y"); } #[cfg(test)] mod test { use super::*; use std::fs; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use tempdir::TempDir; #[test] fn test_relative_symbol_path() { let m = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); let m2 = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m2, "bar").unwrap(), "foo.pdb/abcd1234/foo.bar" ); let m3 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m3, "sym").unwrap(), "foo.xyz/abcd1234/foo.xyz.sym" ); let m4 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m4, "bar").unwrap(), "foo.xyz/abcd1234/foo.xyz.bar" ); let bad = SimpleModule::default(); assert!(relative_symbol_path(&bad, "sym").is_none()); let bad2 = SimpleModule { debug_file: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad2, "sym").is_none()); let bad3 = SimpleModule { debug_id: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad3, "sym").is_none()); } #[test] fn test_relative_symbol_path_abs_paths() { { let m = SimpleModule::new("/path/to/foo.bin", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.bin/abcd1234/foo.bin.sym" ); } { let m = SimpleModule::new("c:/path/to/
/// assert_eq!(f.source_file.unwrap(), r"c:\program files\microsoft visual studio 8\vc\include\swprintf.inl"); /// assert_eq!(f.source_line.unwrap(), 51); /// ```
random_line_split
lib.rs
self.size.unwrap_or(0) } fn
(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn debug_file(&self) -> Option<Cow<str>> { self.debug_file.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn debug_identifier(&self) -> Option<Cow<str>> { self.debug_id.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn version(&self) -> Option<Cow<str>> { self.version.as_ref().map(|s| Cow::Borrowed(&s[..])) } } /// Like `PathBuf::file_name`, but try to work on Windows or POSIX-style paths. fn leafname(path: &str) -> &str { path.rsplit(|c| c == '/' || c == '\\') .next() .unwrap_or(path) } /// If `filename` ends with `match_extension`, remove it. Append `new_extension` to the result. fn replace_or_add_extension(filename: &str, match_extension: &str, new_extension: &str) -> String { let mut bits = filename.split('.').collect::<Vec<_>>(); if bits.len() > 1 && bits .last() .map_or(false, |e| e.to_lowercase() == match_extension) { bits.pop(); } bits.push(new_extension); bits.join(".") } /// Get a relative symbol path at which to locate symbols for `module`. /// /// Symbols are generally stored in the layout used by Microsoft's symbol /// server and associated tools: /// `<debug filename>/<debug identifier>/<debug filename>.sym`. If /// `debug filename` ends with *.pdb* the leaf filename will have that /// removed. /// `extension` is the expected extension for the symbol filename, generally /// *sym* if Breakpad text format symbols are expected. /// /// The debug filename and debug identifier can be found in the /// [first line][module_line] of the symbol file output by the dump_syms tool. /// You can use [this script][packagesymbols] to run dump_syms and put the /// resulting symbol files in the proper directory structure. /// /// [module_line]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md#MODULE-records /// [packagesymbols]: https://gist.github.com/luser/2ad32d290f224782fcfc#file-packagesymbols-py pub fn relative_symbol_path(module: &dyn Module, extension: &str) -> Option<String> { module.debug_file().and_then(|debug_file| { module.debug_identifier().map(|debug_id| { // Can't use PathBuf::file_name here, it doesn't handle // Windows file paths on non-Windows. let leaf = leafname(&debug_file); let filename = replace_or_add_extension(leaf, "pdb", extension); [leaf, &debug_id[..], &filename[..]].join("/") }) }) } /// Possible results of locating symbols. #[derive(Debug)] pub enum SymbolResult { /// Symbols loaded successfully. Ok(SymbolFile), /// Symbol file could not be found. NotFound, /// Error loading symbol file. LoadError(Error), } impl PartialEq for SymbolResult { fn eq(&self, other: &SymbolResult) -> bool { match (self, other) { (&SymbolResult::Ok(ref a), &SymbolResult::Ok(ref b)) => a == b, (&SymbolResult::NotFound, &SymbolResult::NotFound) => true, (&SymbolResult::LoadError(_), &SymbolResult::LoadError(_)) => true, _ => false, } } } impl fmt::Display for SymbolResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SymbolResult::Ok(_) => write!(f, "Ok"), SymbolResult::NotFound => write!(f, "Not found"), SymbolResult::LoadError(ref e) => write!(f, "Load error: {}", e), } } } /// A trait for things that can locate symbols for a given module. pub trait SymbolSupplier { /// Locate and load a symbol file for `module`. /// /// Implementations may use any strategy for locating and loading /// symbols. fn locate_symbols(&self, module: &dyn Module) -> SymbolResult; } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from local disk /// paths. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct SimpleSymbolSupplier { /// Local disk paths in which to search for symbols. paths: Vec<PathBuf>, } impl SimpleSymbolSupplier { /// Instantiate a new `SimpleSymbolSupplier` that will search in `paths`. pub fn new(paths: Vec<PathBuf>) -> SimpleSymbolSupplier { SimpleSymbolSupplier { paths } } } impl SymbolSupplier for SimpleSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref path in self.paths.iter() { let test_path = path.join(&rel_path); if fs::metadata(&test_path).ok().map_or(false, |m| m.is_file()) { return SymbolFile::from_file(&test_path) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } /// A SymbolSupplier that maps module names (code_files) to an in-memory string. /// /// Intended for mocking symbol files in tests. #[derive(Default, Debug, Clone)] pub struct StringSymbolSupplier { modules: HashMap<String, String>, } impl StringSymbolSupplier { /// Make a new StringSymbolSupplier with no modules. pub fn new(modules: HashMap<String, String>) -> Self { Self { modules } } } impl SymbolSupplier for StringSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(symbols) = self.modules.get(&*module.code_file()) { return SymbolFile::from_bytes(symbols.as_bytes()) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } SymbolResult::NotFound } } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from HTTP /// URLs. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct HttpSymbolSupplier { /// HTTP Client to use for fetching symbols. client: Client, /// URLs to search for symbols. urls: Vec<Url>, /// A `SimpleSymbolSupplier` to use for local symbol paths. local: SimpleSymbolSupplier, /// A path at which to cache downloaded symbols. cache: PathBuf, } impl HttpSymbolSupplier { /// Create a new `HttpSymbolSupplier`. /// /// Symbols will be searched for in each of `local_paths` and `cache` first, then via HTTP /// at each of `urls`. If a symbol file is found via HTTP it will be saved under `cache`. pub fn new( urls: Vec<String>, cache: PathBuf, mut local_paths: Vec<PathBuf>, ) -> HttpSymbolSupplier { let client = Client::new(); let urls = urls .into_iter() .filter_map(|mut u| { if!u.ends_with('/') { u.push('/'); } Url::parse(&u).ok() }) .collect(); local_paths.push(cache.clone()); let local = SimpleSymbolSupplier::new(local_paths); HttpSymbolSupplier { client, urls, local, cache, } } } /// Save the data in `contents` to `path`. fn save_contents(contents: &[u8], path: &Path) -> io::Result<()> { let base = path.parent().ok_or_else(|| { io::Error::new(io::ErrorKind::Other, format!("Bad cache path: {:?}", path)) })?; fs::create_dir_all(&base)?; let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) } /// Fetch a symbol file from the URL made by combining `base_url` and `rel_path` using `client`, /// save the file contents under `cache` + `rel_path` and also return them. fn fetch_symbol_file( client: &Client, base_url: &Url, rel_path: &str, cache: &Path, ) -> Result<Vec<u8>, Error> { let url = base_url.join(&rel_path)?; debug!("Trying {}", url); let mut res = client.get(url).send()?.error_for_status()?; let mut buf = vec![]; res.read_to_end(&mut buf)?; let local = cache.join(rel_path); match save_contents(&buf, &local) { Ok(_) => {} Err(e) => warn!("Failed to save symbol file in local disk cache: {}", e), } Ok(buf) } impl SymbolSupplier for HttpSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { // Check local paths first. match self.local.locate_symbols(module) { res @ SymbolResult::Ok(_) | res @ SymbolResult::LoadError(_) => res, SymbolResult::NotFound => { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref url in self.urls.iter() { if let Ok(buf) = fetch_symbol_file(&self.client, url, &rel_path, &self.cache) { return SymbolFile::from_bytes(&buf) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } } } /// A trait for setting symbol information on something like a stack frame. pub trait FrameSymbolizer { /// Get the program counter value for this frame. fn get_instruction(&self) -> u64; /// Set the name, base address, and paramter size of the function in // which this frame is executing. fn set_function(&mut self, name: &str, base: u64, parameter_size: u32); /// Set the source file and (1-based) line number this frame represents. fn set_source_file(&mut self, file: &str, line: u32, base: u64); } pub trait FrameWalker { /// Get the instruction address that we're trying to unwind from. fn get_instruction(&self) -> u64; /// Get the number of bytes the callee's callee's parameters take up /// on the stack (or 0 if unknown/invalid). This is needed for /// STACK WIN unwinding. fn get_grand_callee_parameter_size(&self) -> u32; /// Get a register-sized value stored at this address. fn get_register_at_address(&self, address: u64) -> Option<u64>; /// Get the value of a register from the callee's frame. fn get_callee_register(&self, name: &str) -> Option<u64>; /// Set the value of a register for the caller's frame. fn set_caller_register(&mut self, name: &str, val: u64) -> Option<()>; /// Explicitly mark one of the caller's registers as invalid. fn clear_caller_register(&mut self, name: &str); /// Set whatever registers in the caller should be set based on the cfa (e.g. rsp). fn set_cfa(&mut self, val: u64) -> Option<()>; /// Set whatever registers in the caller should be set based on the return address (e.g. rip). fn set_ra(&mut self, val: u64) -> Option<()>; } /// A simple implementation of `FrameSymbolizer` that just holds data. #[derive(Debug, Default)] pub struct SimpleFrame { /// The program counter value for this frame. pub instruction: u64, /// The name of the function in which the current instruction is executing. pub function: Option<String>, /// The offset of the start of `function` from the module base. pub function_base: Option<u64>, /// The size, in bytes, that this function's parameters take up on the stack. pub parameter_size: Option<u32>, /// The name of the source file in which the current instruction is executing. pub source_file: Option<String>, /// The 1-based index of the line number in `source_file` in which the current instruction is /// executing. pub source_line: Option<u32>, /// The offset of the start of `source_line` from the function base. pub source_line_base: Option<u64>, } impl SimpleFrame { /// Instantiate a `SimpleFrame` with instruction pointer `instruction`. pub fn with_instruction(instruction: u64) -> SimpleFrame { SimpleFrame { instruction, ..SimpleFrame::default() } } } impl FrameSymbolizer for SimpleFrame { fn get_instruction(&self) -> u64 { self.instruction } fn set_function(&mut self, name: &str, base: u64, parameter_size: u32) { self.function = Some(String::from(name)); self.function_base = Some(base); self.parameter_size = Some(parameter_size); } fn set_source_file(&mut self, file: &str, line: u32, base: u64) { self.source_file = Some(String::from(file)); self.source_line = Some(line); self.source_line_base = Some(base); } } // Can't make Module derive Hash, since then it can't be used as a trait // object (because the hash method is generic), so this is a hacky workaround. type ModuleKey = (String, String, Option<String>, Option<String>); /// Helper for deriving a hash key from a `Module` for `Symbolizer`. fn key(module: &dyn Module) -> ModuleKey { ( module.code_file().to_string(), module.code_identifier().to_string(), module.debug_file().map(|s| s.to_string()), module.debug_identifier().map(|s| s.to_string()), ) } /// Symbolicate stack frames. /// /// A `Symbolizer` manages loading symbols and looking up symbols in them /// including caching so that symbols for a given module are only loaded once. /// /// Call [`Symbolizer::new`][new] to instantiate a `Symbolizer`. A Symbolizer /// requires a [`SymbolSupplier`][supplier] to locate symbols. If you have /// symbols on disk in the [customary directory layout][dirlayout], a /// [`SimpleSymbolSupplier`][simple] will work. /// /// Use [`get_symbol_at_address`][get_symbol] or [`fill_symbol`][fill_symbol] to /// do symbol lookup. /// /// [new]: struct.Symbolizer.html#method.new /// [supplier]: trait.SymbolSupplier.html /// [dirlayout]: fn.relative_symbol_path.html /// [simple]: struct.SimpleSymbolSupplier.html /// [get_symbol]: struct.Symbolizer.html#method.get_symbol_at_address /// [fill_symbol]: struct.Symbolizer.html#method.fill_symbol pub struct Symbolizer { /// Symbol supplier for locating symbols. supplier: Box<dyn SymbolSupplier +'static>, /// Cache of symbol locating results. //TODO: use lru-cache: https://crates.io/crates/lru-cache/ symbols: RefCell<HashMap<ModuleKey, SymbolResult>>, } impl Symbolizer { /// Create a `Symbolizer` that uses `supplier` to locate symbols. pub fn new<T: SymbolSupplier +'static>(supplier: T) -> Symbolizer { Symbolizer { supplier: Box::new(supplier), symbols: RefCell::new(HashMap::new()), } } /// Helper method for non-minidump-using callers. /// /// Pass `debug_file` and `debug_id` describing a specific module, /// and `address`, a module-relative address, and get back /// a symbol in that module that covers that address, or `None`. /// /// See [the module-level documentation][module] for an example. /// /// [module]: index.html pub fn get_symbol_at_address( &self, debug_file: &str, debug_id: &str, address: u64, ) -> Option<String> { let k = (debug_file, debug_id); let mut frame = SimpleFrame::with_instruction(address); self.fill_symbol(&k, &mut frame); frame.function } /// Fill symbol information in `frame` using the instruction address /// from `frame`, and the module information from `module`. If you're not /// using a minidump module, you can use [`SimpleModule`][simplemodule] and /// [`SimpleFrame`][simpleframe]. /// /// # Examples /// /// ``` /// # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); /// use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; /// use std::path::PathBuf; /// let paths = vec!(PathBuf::from("../testdata/symbols/")); /// let supplier = SimpleSymbolSupplier::new(paths); /// let symbolizer = Symbolizer::new(supplier); /// let m = SimpleModule::new("test_app.pdb", "5A9832E5287241C1838ED98914E9B7FF1"); /// let mut f = SimpleFrame::with_instruction(0x1010); /// symbolizer.fill_symbol(&m, &mut f); /// assert_eq!(f.function.unwrap(), "vswprintf"); /// assert_eq!(f.source_file.unwrap(), r"c:\program files\microsoft visual studio 8\vc\include\swprintf.inl"); /// assert_eq!(f.source_line.unwrap(), 51); /// ``` /// /// [simplemodule]: struct.SimpleModule.html /// [simpleframe]: struct.SimpleFrame.html pub fn fill_symbol(&self, module: &dyn Module, frame: &mut dyn FrameSymbolizer) { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.fill_symbol(module, frame) } } pub fn walk_frame(&self, module: &dyn Module, walker: &mut dyn FrameWalker) -> Option<()> { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.walk_frame(module, walker) } else { None } } fn ensure_module(&self, module: &dyn Module, k: &ModuleKey) { if!self.symbols.borrow().contains_key(&k) { let res = self.supplier.locate_symbols(module); debug!("locate_symbols for {}: {}", module.code_file(), res); self.symbols.borrow_mut().insert(k.clone(), res); } } } #[test] fn test_leafname() { assert_eq!(leafname("c:\\foo\\bar\\test.pdb"), "test.pdb"); assert_eq!(leafname("c:/foo/bar/test.pdb"), "test.pdb"); assert_eq!(leafname("test.pdb"), "test.pdb"); assert_eq!(leafname("test"), "test"); assert_eq!(leafname("/path/to/test"), "test"); } #[test] fn test_replace_or_add_extension() { assert_eq!( replace_or_add_extension("test.pdb", "pdb", "sym"), "test.sym" ); assert_eq!( replace_or_add_extension("TEST.PDB", "pdb", "sym"), "TEST.sym" ); assert_eq!(replace_or_add_extension("test", "pdb", "sym"), "test.sym"); assert_eq!( replace_or_add_extension("test.x", "pdb", "sym"), "test.x.sym" ); assert_eq!(replace_or_add_extension("", "pdb", "sym"), ".sym"); assert_eq!(replace_or_add_extension("test.x", "x", "y"), "test.y"); } #[cfg(test)] mod test { use super::*; use std::fs; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use tempdir::TempDir; #[test] fn test_relative_symbol_path() { let m = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); let m2 = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m2, "bar").unwrap(), "foo.pdb/abcd1234/foo.bar" ); let m3 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m3, "sym").unwrap(), "foo.xyz/abcd1234/foo.xyz.sym" ); let m4 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m4, "bar").unwrap(), "foo.xyz/abcd1234/foo.xyz.bar" ); let bad = SimpleModule::default(); assert!(relative_symbol_path(&bad, "sym").is_none()); let bad2 = SimpleModule { debug_file: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad2, "sym").is_none()); let bad3 = SimpleModule { debug_id: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad3, "sym").is_none()); } #[test] fn test_relative_symbol_path_abs_paths() { { let m = SimpleModule::new("/path/to/foo.bin", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.bin/abcd1234/foo.bin.sym" ); } { let m = SimpleModule::new("c:/path/to
code_file
identifier_name
context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The context within which style is calculated. #![deny(missing_docs)] use animation::{Animation, PropertyAnimation}; use app_units::Au; use bloom::StyleBloom; use data::ElementData; use dom::{OpaqueNode, TNode, TElement, SendElement}; use error_reporting::ParseErrorReporter; use euclid::Size2D; #[cfg(feature = "gecko")] use gecko_bindings::structs; use matching::StyleSharingCandidateCache; use parking_lot::RwLock; #[cfg(feature = "gecko")] use selector_parser::PseudoElement; use selectors::matching::ElementSelectorFlags; use servo_config::opts; use shared_lock::StylesheetGuards; use std::collections::HashMap; use std::env; use std::fmt; use std::ops::Add; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Sender; use stylist::Stylist; use thread_state; use time; use timer::Timer; use traversal::DomTraversal; /// This structure is used to create a local style context from a shared one. pub struct ThreadLocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl ThreadLocalStyleContextCreationInfo { /// Trivially constructs a `ThreadLocalStyleContextCreationInfo`. pub fn new(animations_sender: Sender<Animation>) -> Self { ThreadLocalStyleContextCreationInfo { new_animations_sender: animations_sender, } } } /// Which quirks mode is this document in. /// /// See: https://quirks.spec.whatwg.org/ #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum QuirksMode { /// Quirks mode. Quirks, /// Limited quirks mode. LimitedQuirks, /// No quirks mode. NoQuirks, } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: Arc<Stylist>, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The animations that are currently running. pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, ///The CSS error reporter for all CSS loaded in this layout thread pub error_reporter: Box<ParseErrorReporter>, /// Data needed to create the thread-local style context from the shared one. pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// The QuirksMode state which the document needs to be rendered with pub quirks_mode: QuirksMode, /// True if the traversal is processing only animation restyles. pub animation_only_restyle: bool, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device.au_viewport_size() } } /// Information about the current element being processed. We group this together /// into a single struct within ThreadLocalStyleContext so that we can instantiate /// and destroy it easily at the beginning and end of element processing. pub struct CurrentElementInfo { /// The element being processed. Currently we use an OpaqueNode since we only /// use this for identity checks, but we could use SendElement if there were /// a good reason to. element: OpaqueNode, /// Whether the element is being styled for the first time. is_initial_style: bool, /// A Vec of possibly expired animations. Used only by Servo. #[allow(dead_code)] pub possibly_expired_animations: Vec<PropertyAnimation>, } /// Statistics gathered during the traversal. We gather statistics on each thread /// and then combine them after the threads join via the Add implementation below. #[derive(Default)] pub struct TraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: Option<bool>, } /// Implementation of Add to aggregate statistics across different threads. impl<'a> Add for &'a TraversalStatistics { type Output = TraversalStatistics; fn add(self, other: Self) -> TraversalStatistics { debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0, "traversal_time_ms should be set at the end by the caller"); TraversalStatistics { elements_traversed: self.elements_traversed + other.elements_traversed, elements_styled: self.elements_styled + other.elements_styled, elements_matched: self.elements_matched + other.elements_matched, styles_shared: self.styles_shared + other.styles_shared, traversal_time_ms: 0.0, is_parallel: None, } } } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time"); try!(writeln!(f, "[PERF] perf block start")); try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { "parallel" } else { "sequential" })); try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)); try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)); try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)); try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)); try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)); writeln!(f, "[PERF] perf block end") } } lazy_static! { /// Whether to dump style statistics, computed statically. We use an environmental /// variable so that this is easy to set for Gecko builds, and matches the /// mechanism we use to dump statistics on the Gecko style system. static ref DUMP_STYLE_STATISTICS: bool = { match env::var("DUMP_STYLE_STATISTICS") { Ok(s) =>!s.is_empty(), Err(_) => false, } }; } impl TraversalStatistics { /// Returns whether statistics dumping is enabled. pub fn should_dump() -> bool { *DUMP_STYLE_STATISTICS || opts::get().style_sharing_stats } /// Computes the traversal time given the start time in seconds. pub fn finish<E, D>(&mut self, traversal: &D, start: f64) where E: TElement, D: DomTraversal<E>, { self.is_parallel = Some(traversal.is_parallel()); self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of UpdateAnimations. pub flags UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations, /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions, /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties, /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults, } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Sets selector flags. This is used when we need to set flags on an /// element that we don't have exclusive access to (i.e. the parent). SetSelectorFlags(SendElement<E>, ElementSelectorFlags), #[cfg(feature = "gecko")] /// Marks that we need to update CSS animations, update effect properties of /// any type of animations after the normal traversal. UpdateAnimations(SendElement<E>, Option<PseudoElement>, UpdateAnimationsTasks), } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert!(thread_state::get() == thread_state::LAYOUT); match self { SetSelectorFlags(el, flags) => { unsafe { el.set_selector_flags(flags) }; } #[cfg(feature = "gecko")] UpdateAnimations(el, pseudo, tasks) => { unsafe { el.update_animations(pseudo.as_ref(), tasks) }; } } } /// Creates a task to set the selector flags on an element. pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self { use self::SequentialTask::*; SetSelectorFlags(unsafe { SendElement::new(el) }, flags) } #[cfg(feature = "gecko")] /// Creates a task to update various animation state on a given (pseudo-)element. pub fn update_animations(el: E, pseudo: Option<PseudoElement>, tasks: UpdateAnimationsTasks) -> Self { use self::SequentialTask::*; UpdateAnimations(unsafe { SendElement::new(el) }, pseudo, tasks) } } /// A thread-local style context. /// /// This context contains data that needs to be used during restyling, but is /// not required to be unique among worker threads, so we create one per worker /// thread in order to be able to mutate it without locking. pub struct ThreadLocalStyleContext<E: TElement> { /// A cache to share style among siblings. pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>, /// The bloom filter used to fast-reject selector-matching. pub bloom_filter: StyleBloom<E>, /// A channel on which new animations that have been triggered by style /// recalculation can be sent. pub new_animations_sender: Sender<Animation>, /// A set of tasks to be run (on the parent thread) in sequential mode after /// the rest of the styling is complete. This is useful for infrequently-needed /// non-threadsafe operations. pub tasks: Vec<SequentialTask<E>>, /// Statistics about the traversal. pub statistics: TraversalStatistics, /// Information related to the current element, non-None during processing. pub current_element_info: Option<CurrentElementInfo>, } impl<E: TElement> ThreadLocalStyleContext<E> { /// Creates a new `ThreadLocalStyleContext` from a shared one. pub fn
(shared: &SharedStyleContext) -> Self { ThreadLocalStyleContext { style_sharing_candidate_cache: StyleSharingCandidateCache::new(), bloom_filter: StyleBloom::new(), new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(), tasks: Vec::new(), statistics: TraversalStatistics::default(), current_element_info: None, } } /// Notes when the style system starts traversing an element. pub fn begin_element(&mut self, element: E, data: &ElementData) { debug_assert!(self.current_element_info.is_none()); self.current_element_info = Some(CurrentElementInfo { element: element.as_node().opaque(), is_initial_style:!data.has_styles(), possibly_expired_animations: Vec::new(), }); } /// Notes when the style system finishes traversing an element. pub fn end_element(&mut self, element: E) { debug_assert!(self.current_element_info.is_some()); debug_assert!(self.current_element_info.as_ref().unwrap().element == element.as_node().opaque()); self.current_element_info = None; } /// Returns true if the current element being traversed is being styled for /// the first time. /// /// Panics if called while no element is being traversed. pub fn is_initial_style(&self) -> bool { self.current_element_info.as_ref().unwrap().is_initial_style } } impl<E: TElement> Drop for ThreadLocalStyleContext<E> { fn drop(&mut self) { debug_assert!(self.current_element_info.is_none()); // Execute any enqueued sequential tasks. debug_assert!(thread_state::get() == thread_state::LAYOUT); for task in self.tasks.drain(..) { task.execute(); } } } /// A `StyleContext` is just a simple container for a immutable reference to a /// shared style context, and a mutable reference to a local one. pub struct StyleContext<'a, E: TElement + 'a> { /// The shared style context reference. pub shared: &'a SharedStyleContext<'a>, /// The thread-local style context (mutable) reference. pub thread_local: &'a mut ThreadLocalStyleContext<E>, } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, }
new
identifier_name
context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The context within which style is calculated. #![deny(missing_docs)] use animation::{Animation, PropertyAnimation}; use app_units::Au; use bloom::StyleBloom; use data::ElementData; use dom::{OpaqueNode, TNode, TElement, SendElement}; use error_reporting::ParseErrorReporter; use euclid::Size2D; #[cfg(feature = "gecko")] use gecko_bindings::structs; use matching::StyleSharingCandidateCache; use parking_lot::RwLock; #[cfg(feature = "gecko")] use selector_parser::PseudoElement; use selectors::matching::ElementSelectorFlags; use servo_config::opts; use shared_lock::StylesheetGuards; use std::collections::HashMap; use std::env; use std::fmt; use std::ops::Add; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Sender; use stylist::Stylist; use thread_state; use time; use timer::Timer; use traversal::DomTraversal; /// This structure is used to create a local style context from a shared one. pub struct ThreadLocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl ThreadLocalStyleContextCreationInfo { /// Trivially constructs a `ThreadLocalStyleContextCreationInfo`. pub fn new(animations_sender: Sender<Animation>) -> Self { ThreadLocalStyleContextCreationInfo { new_animations_sender: animations_sender, } } } /// Which quirks mode is this document in. /// /// See: https://quirks.spec.whatwg.org/ #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum QuirksMode { /// Quirks mode. Quirks, /// Limited quirks mode. LimitedQuirks, /// No quirks mode. NoQuirks, } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: Arc<Stylist>, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The animations that are currently running. pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, ///The CSS error reporter for all CSS loaded in this layout thread pub error_reporter: Box<ParseErrorReporter>, /// Data needed to create the thread-local style context from the shared one. pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// The QuirksMode state which the document needs to be rendered with pub quirks_mode: QuirksMode, /// True if the traversal is processing only animation restyles. pub animation_only_restyle: bool, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device.au_viewport_size() } } /// Information about the current element being processed. We group this together /// into a single struct within ThreadLocalStyleContext so that we can instantiate /// and destroy it easily at the beginning and end of element processing. pub struct CurrentElementInfo { /// The element being processed. Currently we use an OpaqueNode since we only /// use this for identity checks, but we could use SendElement if there were /// a good reason to. element: OpaqueNode, /// Whether the element is being styled for the first time. is_initial_style: bool, /// A Vec of possibly expired animations. Used only by Servo. #[allow(dead_code)] pub possibly_expired_animations: Vec<PropertyAnimation>, } /// Statistics gathered during the traversal. We gather statistics on each thread /// and then combine them after the threads join via the Add implementation below. #[derive(Default)] pub struct TraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: Option<bool>, } /// Implementation of Add to aggregate statistics across different threads. impl<'a> Add for &'a TraversalStatistics { type Output = TraversalStatistics; fn add(self, other: Self) -> TraversalStatistics { debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0, "traversal_time_ms should be set at the end by the caller"); TraversalStatistics { elements_traversed: self.elements_traversed + other.elements_traversed, elements_styled: self.elements_styled + other.elements_styled, elements_matched: self.elements_matched + other.elements_matched, styles_shared: self.styles_shared + other.styles_shared, traversal_time_ms: 0.0, is_parallel: None, } } } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time"); try!(writeln!(f, "[PERF] perf block start")); try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { "parallel" } else { "sequential" })); try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)); try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)); try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)); try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)); try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)); writeln!(f, "[PERF] perf block end") } } lazy_static! { /// Whether to dump style statistics, computed statically. We use an environmental /// variable so that this is easy to set for Gecko builds, and matches the /// mechanism we use to dump statistics on the Gecko style system. static ref DUMP_STYLE_STATISTICS: bool = { match env::var("DUMP_STYLE_STATISTICS") { Ok(s) =>!s.is_empty(), Err(_) => false, } }; } impl TraversalStatistics { /// Returns whether statistics dumping is enabled. pub fn should_dump() -> bool { *DUMP_STYLE_STATISTICS || opts::get().style_sharing_stats } /// Computes the traversal time given the start time in seconds. pub fn finish<E, D>(&mut self, traversal: &D, start: f64) where E: TElement, D: DomTraversal<E>, { self.is_parallel = Some(traversal.is_parallel()); self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of UpdateAnimations. pub flags UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations, /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions, /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties, /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults, } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Sets selector flags. This is used when we need to set flags on an /// element that we don't have exclusive access to (i.e. the parent). SetSelectorFlags(SendElement<E>, ElementSelectorFlags), #[cfg(feature = "gecko")] /// Marks that we need to update CSS animations, update effect properties of /// any type of animations after the normal traversal. UpdateAnimations(SendElement<E>, Option<PseudoElement>, UpdateAnimationsTasks), } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert!(thread_state::get() == thread_state::LAYOUT); match self { SetSelectorFlags(el, flags) => { unsafe { el.set_selector_flags(flags) }; } #[cfg(feature = "gecko")] UpdateAnimations(el, pseudo, tasks) => { unsafe { el.update_animations(pseudo.as_ref(), tasks) }; } } } /// Creates a task to set the selector flags on an element. pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self { use self::SequentialTask::*; SetSelectorFlags(unsafe { SendElement::new(el) }, flags) } #[cfg(feature = "gecko")] /// Creates a task to update various animation state on a given (pseudo-)element. pub fn update_animations(el: E, pseudo: Option<PseudoElement>, tasks: UpdateAnimationsTasks) -> Self { use self::SequentialTask::*; UpdateAnimations(unsafe { SendElement::new(el) }, pseudo, tasks) } } /// A thread-local style context. /// /// This context contains data that needs to be used during restyling, but is /// not required to be unique among worker threads, so we create one per worker /// thread in order to be able to mutate it without locking. pub struct ThreadLocalStyleContext<E: TElement> { /// A cache to share style among siblings.
/// recalculation can be sent. pub new_animations_sender: Sender<Animation>, /// A set of tasks to be run (on the parent thread) in sequential mode after /// the rest of the styling is complete. This is useful for infrequently-needed /// non-threadsafe operations. pub tasks: Vec<SequentialTask<E>>, /// Statistics about the traversal. pub statistics: TraversalStatistics, /// Information related to the current element, non-None during processing. pub current_element_info: Option<CurrentElementInfo>, } impl<E: TElement> ThreadLocalStyleContext<E> { /// Creates a new `ThreadLocalStyleContext` from a shared one. pub fn new(shared: &SharedStyleContext) -> Self { ThreadLocalStyleContext { style_sharing_candidate_cache: StyleSharingCandidateCache::new(), bloom_filter: StyleBloom::new(), new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(), tasks: Vec::new(), statistics: TraversalStatistics::default(), current_element_info: None, } } /// Notes when the style system starts traversing an element. pub fn begin_element(&mut self, element: E, data: &ElementData) { debug_assert!(self.current_element_info.is_none()); self.current_element_info = Some(CurrentElementInfo { element: element.as_node().opaque(), is_initial_style:!data.has_styles(), possibly_expired_animations: Vec::new(), }); } /// Notes when the style system finishes traversing an element. pub fn end_element(&mut self, element: E) { debug_assert!(self.current_element_info.is_some()); debug_assert!(self.current_element_info.as_ref().unwrap().element == element.as_node().opaque()); self.current_element_info = None; } /// Returns true if the current element being traversed is being styled for /// the first time. /// /// Panics if called while no element is being traversed. pub fn is_initial_style(&self) -> bool { self.current_element_info.as_ref().unwrap().is_initial_style } } impl<E: TElement> Drop for ThreadLocalStyleContext<E> { fn drop(&mut self) { debug_assert!(self.current_element_info.is_none()); // Execute any enqueued sequential tasks. debug_assert!(thread_state::get() == thread_state::LAYOUT); for task in self.tasks.drain(..) { task.execute(); } } } /// A `StyleContext` is just a simple container for a immutable reference to a /// shared style context, and a mutable reference to a local one. pub struct StyleContext<'a, E: TElement + 'a> { /// The shared style context reference. pub shared: &'a SharedStyleContext<'a>, /// The thread-local style context (mutable) reference. pub thread_local: &'a mut ThreadLocalStyleContext<E>, } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, }
pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>, /// The bloom filter used to fast-reject selector-matching. pub bloom_filter: StyleBloom<E>, /// A channel on which new animations that have been triggered by style
random_line_split
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, Debug)] pub struct CartesianJoint<N: RealField> { position: Vector<N>, } impl<N: RealField> CartesianJoint<N> { /// Create a cartesian joint with an initial position given by `position`. pub fn new(position: Vector<N>) -> Self { CartesianJoint { position } } } impl<N: RealField> Joint<N> for CartesianJoint<N> { #[inline] fn ndofs(&self) -> usize { DIM } fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N> { let t = Translation::from(parent_shift - body_shift + self.position); Isometry::from_parts(t, na::one()) } fn update_jacobians(&mut self, _: &Vector<N>, _: &[N]) {} fn jacobian(&self, _: &Isometry<N>, out: &mut JacobianSliceMut<N>) { out.fill_diagonal(N::one()) } fn jacobian_dot(&self, _: &Isometry<N>, _: &mut JacobianSliceMut<N>) {} fn jacobian_dot_veldiff_mul_coordinates( &self, _: &Isometry<N>, _: &[N], _: &mut JacobianSliceMut<N>, ) { } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { Velocity::from_vectors(Vector::from_row_slice(&vels[..DIM]), na::zero()) } fn jacobian_dot_mul_coordinates(&self, _: &[N]) -> Velocity<N> { Velocity::zero() } fn
(&self, _: &mut DVectorSliceMut<N>) {} fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.position += Vector::from_row_slice(&vels[..DIM]) * parameters.dt(); } fn apply_displacement(&mut self, disp: &[N]) { self.position += Vector::from_row_slice(&disp[..DIM]); } #[inline] fn clone(&self) -> Box<dyn Joint<N>> { Box::new(*self) } }
default_damping
identifier_name
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, Debug)] pub struct CartesianJoint<N: RealField> { position: Vector<N>, }
CartesianJoint { position } } } impl<N: RealField> Joint<N> for CartesianJoint<N> { #[inline] fn ndofs(&self) -> usize { DIM } fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N> { let t = Translation::from(parent_shift - body_shift + self.position); Isometry::from_parts(t, na::one()) } fn update_jacobians(&mut self, _: &Vector<N>, _: &[N]) {} fn jacobian(&self, _: &Isometry<N>, out: &mut JacobianSliceMut<N>) { out.fill_diagonal(N::one()) } fn jacobian_dot(&self, _: &Isometry<N>, _: &mut JacobianSliceMut<N>) {} fn jacobian_dot_veldiff_mul_coordinates( &self, _: &Isometry<N>, _: &[N], _: &mut JacobianSliceMut<N>, ) { } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { Velocity::from_vectors(Vector::from_row_slice(&vels[..DIM]), na::zero()) } fn jacobian_dot_mul_coordinates(&self, _: &[N]) -> Velocity<N> { Velocity::zero() } fn default_damping(&self, _: &mut DVectorSliceMut<N>) {} fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.position += Vector::from_row_slice(&vels[..DIM]) * parameters.dt(); } fn apply_displacement(&mut self, disp: &[N]) { self.position += Vector::from_row_slice(&disp[..DIM]); } #[inline] fn clone(&self) -> Box<dyn Joint<N>> { Box::new(*self) } }
impl<N: RealField> CartesianJoint<N> { /// Create a cartesian joint with an initial position given by `position`. pub fn new(position: Vector<N>) -> Self {
random_line_split
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, Debug)] pub struct CartesianJoint<N: RealField> { position: Vector<N>, } impl<N: RealField> CartesianJoint<N> { /// Create a cartesian joint with an initial position given by `position`. pub fn new(position: Vector<N>) -> Self { CartesianJoint { position } } } impl<N: RealField> Joint<N> for CartesianJoint<N> { #[inline] fn ndofs(&self) -> usize { DIM } fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N> { let t = Translation::from(parent_shift - body_shift + self.position); Isometry::from_parts(t, na::one()) } fn update_jacobians(&mut self, _: &Vector<N>, _: &[N]) {} fn jacobian(&self, _: &Isometry<N>, out: &mut JacobianSliceMut<N>) { out.fill_diagonal(N::one()) } fn jacobian_dot(&self, _: &Isometry<N>, _: &mut JacobianSliceMut<N>)
fn jacobian_dot_veldiff_mul_coordinates( &self, _: &Isometry<N>, _: &[N], _: &mut JacobianSliceMut<N>, ) { } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { Velocity::from_vectors(Vector::from_row_slice(&vels[..DIM]), na::zero()) } fn jacobian_dot_mul_coordinates(&self, _: &[N]) -> Velocity<N> { Velocity::zero() } fn default_damping(&self, _: &mut DVectorSliceMut<N>) {} fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.position += Vector::from_row_slice(&vels[..DIM]) * parameters.dt(); } fn apply_displacement(&mut self, disp: &[N]) { self.position += Vector::from_row_slice(&disp[..DIM]); } #[inline] fn clone(&self) -> Box<dyn Joint<N>> { Box::new(*self) } }
{}
identifier_body
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // 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. //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; use cita_types::Address; use logger::{error, warn}; use std::str; /// Implementation of the multiplexed line-based protocol. /// /// Frames begin with a 4 byte header, consisting of the numeric request ID /// encoded in network order, followed by the frame payload encoded as a UTF-8 /// string and terminated with a '\n' character: /// /// # An example frame: /// /// +------------------------+--------------------------+ /// | Type | Content | /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | /// | Version | u64 | /// | Address | u8;20 | /// | Length of Key | u8 | /// | TTL | u8 | /// | Reserved | u8;2 | /// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | /// +------------------------+--------------------------+ /// // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; /// According to CITA frame, defines its frame header length as: /// "Symbol for Start" + "Length of Full Payload" + "Version"+ /// "Address"+ "Length of Key"+"TTL"+"Reserved", /// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2;
pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMessageUnit { pub key: String, pub data: Vec<u8>, pub addr: Address, pub version: u64, pub ttl: u8, } impl NetMessageUnit { pub fn new(key: String, data: Vec<u8>, addr: Address, version: u64, ttl: u8) -> Self { NetMessageUnit { key, data, addr, version, ttl, } } } impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn pubsub_message_to_network_message(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); return None; } let length_full = length_key + info.data.len(); // Use 1 bytes to store the length for key, then store key, the last part is body. if length_full > u32::max_value() as usize { error!( "[CitaProtocol] The MQ message with key {} is too long {}.", info.key, info.data.len() ); return None; } let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); let request_id = NETMSG_START + length_full as u64; buf.put_u64_be(request_id); buf.put_u64_be(info.version); buf.put(info.addr.to_vec()); buf.put_u8(length_key as u8); buf.put_u8(info.ttl); buf.put_u16_be(0); buf.put(info.key.as_bytes()); buf.put_slice(&info.data); Some(buf.into()) } pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> { if buf.len() < CITA_FRAME_HEADER_LEN { return None; } let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start!= NETMSG_START { return None; } if length_full > buf.len() || length_full == 0 { return None; } let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, buf.len() ); return None; } let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( "[CitaProtocol] Network message parse key error {:?}.", key_buf ); return None; } let key = key_str_result.unwrap().to_string(); if length_full == length_key { warn!("[CitaProtocol] Network message is empty."); } Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_empty_message() { let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); assert!(buf.is_none()); } #[test] fn convert_messages() { let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); let data = vec![1, 3, 5, 7, 9]; msg.key = key.clone(); msg.data = data.clone(); let buf = pubsub_message_to_network_message(&msg).unwrap(); let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); let info = pub_msg_opt.unwrap(); assert_eq!(key, info.key); assert_eq!(data, info.data); } }
pub const HEAD_VERSION_OFFSET: usize = 4 + 4;
random_line_split
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // 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. //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; use cita_types::Address; use logger::{error, warn}; use std::str; /// Implementation of the multiplexed line-based protocol. /// /// Frames begin with a 4 byte header, consisting of the numeric request ID /// encoded in network order, followed by the frame payload encoded as a UTF-8 /// string and terminated with a '\n' character: /// /// # An example frame: /// /// +------------------------+--------------------------+ /// | Type | Content | /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | /// | Version | u64 | /// | Address | u8;20 | /// | Length of Key | u8 | /// | TTL | u8 | /// | Reserved | u8;2 | /// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | /// +------------------------+--------------------------+ /// // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; /// According to CITA frame, defines its frame header length as: /// "Symbol for Start" + "Length of Full Payload" + "Version"+ /// "Address"+ "Length of Key"+"TTL"+"Reserved", /// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2; pub const HEAD_VERSION_OFFSET: usize = 4 + 4; pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMessageUnit { pub key: String, pub data: Vec<u8>, pub addr: Address, pub version: u64, pub ttl: u8, } impl NetMessageUnit { pub fn new(key: String, data: Vec<u8>, addr: Address, version: u64, ttl: u8) -> Self
} impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn pubsub_message_to_network_message(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); return None; } let length_full = length_key + info.data.len(); // Use 1 bytes to store the length for key, then store key, the last part is body. if length_full > u32::max_value() as usize { error!( "[CitaProtocol] The MQ message with key {} is too long {}.", info.key, info.data.len() ); return None; } let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); let request_id = NETMSG_START + length_full as u64; buf.put_u64_be(request_id); buf.put_u64_be(info.version); buf.put(info.addr.to_vec()); buf.put_u8(length_key as u8); buf.put_u8(info.ttl); buf.put_u16_be(0); buf.put(info.key.as_bytes()); buf.put_slice(&info.data); Some(buf.into()) } pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> { if buf.len() < CITA_FRAME_HEADER_LEN { return None; } let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start!= NETMSG_START { return None; } if length_full > buf.len() || length_full == 0 { return None; } let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, buf.len() ); return None; } let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( "[CitaProtocol] Network message parse key error {:?}.", key_buf ); return None; } let key = key_str_result.unwrap().to_string(); if length_full == length_key { warn!("[CitaProtocol] Network message is empty."); } Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_empty_message() { let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); assert!(buf.is_none()); } #[test] fn convert_messages() { let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); let data = vec![1, 3, 5, 7, 9]; msg.key = key.clone(); msg.data = data.clone(); let buf = pubsub_message_to_network_message(&msg).unwrap(); let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); let info = pub_msg_opt.unwrap(); assert_eq!(key, info.key); assert_eq!(data, info.data); } }
{ NetMessageUnit { key, data, addr, version, ttl, } }
identifier_body
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // 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. //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; use cita_types::Address; use logger::{error, warn}; use std::str; /// Implementation of the multiplexed line-based protocol. /// /// Frames begin with a 4 byte header, consisting of the numeric request ID /// encoded in network order, followed by the frame payload encoded as a UTF-8 /// string and terminated with a '\n' character: /// /// # An example frame: /// /// +------------------------+--------------------------+ /// | Type | Content | /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | /// | Version | u64 | /// | Address | u8;20 | /// | Length of Key | u8 | /// | TTL | u8 | /// | Reserved | u8;2 | /// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | /// +------------------------+--------------------------+ /// // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; /// According to CITA frame, defines its frame header length as: /// "Symbol for Start" + "Length of Full Payload" + "Version"+ /// "Address"+ "Length of Key"+"TTL"+"Reserved", /// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2; pub const HEAD_VERSION_OFFSET: usize = 4 + 4; pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMessageUnit { pub key: String, pub data: Vec<u8>, pub addr: Address, pub version: u64, pub ttl: u8, } impl NetMessageUnit { pub fn new(key: String, data: Vec<u8>, addr: Address, version: u64, ttl: u8) -> Self { NetMessageUnit { key, data, addr, version, ttl, } } } impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn
(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); return None; } let length_full = length_key + info.data.len(); // Use 1 bytes to store the length for key, then store key, the last part is body. if length_full > u32::max_value() as usize { error!( "[CitaProtocol] The MQ message with key {} is too long {}.", info.key, info.data.len() ); return None; } let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); let request_id = NETMSG_START + length_full as u64; buf.put_u64_be(request_id); buf.put_u64_be(info.version); buf.put(info.addr.to_vec()); buf.put_u8(length_key as u8); buf.put_u8(info.ttl); buf.put_u16_be(0); buf.put(info.key.as_bytes()); buf.put_slice(&info.data); Some(buf.into()) } pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> { if buf.len() < CITA_FRAME_HEADER_LEN { return None; } let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start!= NETMSG_START { return None; } if length_full > buf.len() || length_full == 0 { return None; } let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, buf.len() ); return None; } let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( "[CitaProtocol] Network message parse key error {:?}.", key_buf ); return None; } let key = key_str_result.unwrap().to_string(); if length_full == length_key { warn!("[CitaProtocol] Network message is empty."); } Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_empty_message() { let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); assert!(buf.is_none()); } #[test] fn convert_messages() { let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); let data = vec![1, 3, 5, 7, 9]; msg.key = key.clone(); msg.data = data.clone(); let buf = pubsub_message_to_network_message(&msg).unwrap(); let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); let info = pub_msg_opt.unwrap(); assert_eq!(key, info.key); assert_eq!(data, info.data); } }
pubsub_message_to_network_message
identifier_name
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // 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. //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; use cita_types::Address; use logger::{error, warn}; use std::str; /// Implementation of the multiplexed line-based protocol. /// /// Frames begin with a 4 byte header, consisting of the numeric request ID /// encoded in network order, followed by the frame payload encoded as a UTF-8 /// string and terminated with a '\n' character: /// /// # An example frame: /// /// +------------------------+--------------------------+ /// | Type | Content | /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | /// | Version | u64 | /// | Address | u8;20 | /// | Length of Key | u8 | /// | TTL | u8 | /// | Reserved | u8;2 | /// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | /// +------------------------+--------------------------+ /// // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; /// According to CITA frame, defines its frame header length as: /// "Symbol for Start" + "Length of Full Payload" + "Version"+ /// "Address"+ "Length of Key"+"TTL"+"Reserved", /// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2; pub const HEAD_VERSION_OFFSET: usize = 4 + 4; pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMessageUnit { pub key: String, pub data: Vec<u8>, pub addr: Address, pub version: u64, pub ttl: u8, } impl NetMessageUnit { pub fn new(key: String, data: Vec<u8>, addr: Address, version: u64, ttl: u8) -> Self { NetMessageUnit { key, data, addr, version, ttl, } } } impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn pubsub_message_to_network_message(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); return None; } let length_full = length_key + info.data.len(); // Use 1 bytes to store the length for key, then store key, the last part is body. if length_full > u32::max_value() as usize { error!( "[CitaProtocol] The MQ message with key {} is too long {}.", info.key, info.data.len() ); return None; } let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); let request_id = NETMSG_START + length_full as u64; buf.put_u64_be(request_id); buf.put_u64_be(info.version); buf.put(info.addr.to_vec()); buf.put_u8(length_key as u8); buf.put_u8(info.ttl); buf.put_u16_be(0); buf.put(info.key.as_bytes()); buf.put_slice(&info.data); Some(buf.into()) } pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> { if buf.len() < CITA_FRAME_HEADER_LEN { return None; } let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start!= NETMSG_START { return None; } if length_full > buf.len() || length_full == 0 { return None; } let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, buf.len() ); return None; } let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( "[CitaProtocol] Network message parse key error {:?}.", key_buf ); return None; } let key = key_str_result.unwrap().to_string(); if length_full == length_key
Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_empty_message() { let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); assert!(buf.is_none()); } #[test] fn convert_messages() { let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); let data = vec![1, 3, 5, 7, 9]; msg.key = key.clone(); msg.data = data.clone(); let buf = pubsub_message_to_network_message(&msg).unwrap(); let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); let info = pub_msg_opt.unwrap(); assert_eq!(key, info.key); assert_eq!(data, info.data); } }
{ warn!("[CitaProtocol] Network message is empty."); }
conditional_block
unique-pinned-nocopy-2.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. struct r { i: @mut int, } #[unsafe_destructor] impl Drop for r { fn drop(&self) { unsafe { *(self.i) = *(self.i) + 1; } } } fn r(i: @mut int) -> r { r { i: i } } pub fn
() { let i = @mut 0; { let j = ~r(i); } assert_eq!(*i, 1); }
main
identifier_name
unique-pinned-nocopy-2.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. struct r { i: @mut int, } #[unsafe_destructor] impl Drop for r { fn drop(&self) { unsafe { *(self.i) = *(self.i) + 1; } }
fn r(i: @mut int) -> r { r { i: i } } pub fn main() { let i = @mut 0; { let j = ~r(i); } assert_eq!(*i, 1); }
}
random_line_split
unique-pinned-nocopy-2.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. struct r { i: @mut int, } #[unsafe_destructor] impl Drop for r { fn drop(&self)
} fn r(i: @mut int) -> r { r { i: i } } pub fn main() { let i = @mut 0; { let j = ~r(i); } assert_eq!(*i, 1); }
{ unsafe { *(self.i) = *(self.i) + 1; } }
identifier_body
type_infer.rs
/* 类型推导引擎不仅仅在初始化期间分析右值的类型, 还会通过分析变量在后面是 怎么使用的来推导该变量的类型 */ fn main() { // 借助类型标注,编译器知道 `elem` 具有 u8 类型 let elem = 5u8; // 创建一个空 vector(可增长数组)。 let m
ut vec = Vec::new(); // 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型 // 的 vector(`Vec<_>`)。 // 将 `elem` 插入 vector。 vec.push(elem); // Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`) // 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉 println!("{:?}", vec); }
identifier_body
type_infer.rs
/* 类型推导引擎不仅仅在初始化期间分析右值的类型, 还会通过分析变量在后面是 怎么使用的来推导该变量的类型 */ fn main() { // 借助类型标注,编译器知道 `elem` 具有 u8 类型 let elem = 5u8; // 创建一个空 vector(可增长数组)。
t mut vec = Vec::new(); // 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型 // 的 vector(`Vec<_>`)。 // 将 `elem` 插入 vector。 vec.push(elem); // Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`) // 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉 println!("{:?}", vec); }
le
identifier_name
type_infer.rs
/* 类型推导引擎不仅仅在初始化期间分析右值的类型, 还会通过分析变量在后面是 怎么使用的来推导该变量的类型
// 创建一个空 vector(可增长数组)。 let mut vec = Vec::new(); // 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型 // 的 vector(`Vec<_>`)。 // 将 `elem` 插入 vector。 vec.push(elem); // Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`) // 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉 println!("{:?}", vec); }
*/ fn main() { // 借助类型标注,编译器知道 `elem` 具有 u8 类型 let elem = 5u8;
random_line_split
a4.rs
fn main() { // Declaración de vectores o arrays let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector. let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, en este caso cadenas de texto y se deja mutable para poder agregar elementos.
println!("primer elemento vector 1: {} y tercer elemento vector 2: {}", vector1[0], vector2[2]); // También se puede consultar el índice de uno de los elementos del vector usando "[X]" junto al nombre del vecto, dónde X es el número de la posición del elemento. }
vector2 = vec!["Primero","Segundo"]; // Se agregan elementos al vector sobreescribiendolo gracias a "mut". vector2.push("Tercero"); // Agrega un elemento al final del vector. println!("primer vector 1: {:?} y segundo vector: {:?}", vector1, vector2); // Forma de ver en consola un vector no olvidar el ":?" entre los corchetes para que se imprima de lo contraria genera error.
random_line_split
a4.rs
fn main()
{ // Declaración de vectores o arrays let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector. let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, en este caso cadenas de texto y se deja mutable para poder agregar elementos. vector2 = vec!["Primero","Segundo"]; // Se agregan elementos al vector sobreescribiendolo gracias a "mut". vector2.push("Tercero"); // Agrega un elemento al final del vector. println!("primer vector 1: {:?} y segundo vector: {:?}", vector1, vector2); // Forma de ver en consola un vector no olvidar el ":?" entre los corchetes para que se imprima de lo contraria genera error. println!("primer elemento vector 1: {} y tercer elemento vector 2: {}", vector1[0], vector2[2]); // También se puede consultar el índice de uno de los elementos del vector usando "[X]" junto al nombre del vecto, dónde X es el número de la posición del elemento. }
identifier_body
a4.rs
fn
() { // Declaración de vectores o arrays let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector. let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, en este caso cadenas de texto y se deja mutable para poder agregar elementos. vector2 = vec!["Primero","Segundo"]; // Se agregan elementos al vector sobreescribiendolo gracias a "mut". vector2.push("Tercero"); // Agrega un elemento al final del vector. println!("primer vector 1: {:?} y segundo vector: {:?}", vector1, vector2); // Forma de ver en consola un vector no olvidar el ":?" entre los corchetes para que se imprima de lo contraria genera error. println!("primer elemento vector 1: {} y tercer elemento vector 2: {}", vector1[0], vector2[2]); // También se puede consultar el índice de uno de los elementos del vector usando "[X]" junto al nombre del vecto, dónde X es el número de la posición del elemento. }
main
identifier_name
unique-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-tidy-linelength // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *the_a // gdb-check:$1 = {{RUST$ENUM$DISR = TheA, x = 0, y = 8970181431921507452}, {RUST$ENUM$DISR = TheA, 0, 2088533116, 2088533116}} // gdb-command:print *the_b // gdb-check:$2 = {{RUST$ENUM$DISR = TheB, x = 0, y = 1229782938247303441}, {RUST$ENUM$DISR = TheB, 0, 286331153, 286331153}} // gdb-command:print *univariant // gdb-check:$3 = {{123234}} // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print *the_a // lldb-check:[...]$0 = TheA { x: 0, y: 8970181431921507452 } // lldb-command:print *the_b // lldb-check:[...]$1 = TheB(0, 286331153, 286331153) // lldb-command:print *univariant // lldb-check:[...]$2 = TheOnlyCase(123234) #![allow(unused_variables)] #![feature(box_syntax)] #![omit_gdb_pretty_printer_section] // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum
{ TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main() { // In order to avoid endianness trouble all of the following test values consist of a single // repeated byte. This way each interpretation of the union should look the same, no matter if // this is a big or little endian machine. // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a: Box<_> = box ABC::TheA { x: 0, y: 8970181431921507452 }; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b: Box<_> = box ABC::TheB (0, 286331153, 286331153); let univariant: Box<_> = box Univariant::TheOnlyCase(123234); zzz(); // #break } fn zzz() {()}
ABC
identifier_name
unique-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-tidy-linelength // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *the_a // gdb-check:$1 = {{RUST$ENUM$DISR = TheA, x = 0, y = 8970181431921507452}, {RUST$ENUM$DISR = TheA, 0, 2088533116, 2088533116}} // gdb-command:print *the_b // gdb-check:$2 = {{RUST$ENUM$DISR = TheB, x = 0, y = 1229782938247303441}, {RUST$ENUM$DISR = TheB, 0, 286331153, 286331153}} // gdb-command:print *univariant // gdb-check:$3 = {{123234}} // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print *the_a // lldb-check:[...]$0 = TheA { x: 0, y: 8970181431921507452 } // lldb-command:print *the_b // lldb-check:[...]$1 = TheB(0, 286331153, 286331153) // lldb-command:print *univariant // lldb-check:[...]$2 = TheOnlyCase(123234) #![allow(unused_variables)] #![feature(box_syntax)] #![omit_gdb_pretty_printer_section] // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main() { // In order to avoid endianness trouble all of the following test values consist of a single // repeated byte. This way each interpretation of the union should look the same, no matter if // this is a big or little endian machine. // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a: Box<_> = box ABC::TheA { x: 0, y: 8970181431921507452 }; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b: Box<_> = box ABC::TheB (0, 286331153, 286331153); let univariant: Box<_> = box Univariant::TheOnlyCase(123234); zzz(); // #break } fn zzz() {()}
// 0b00010001000100010001000100010001 = 286331153
random_line_split
vertex.rs
//! Vertex data structures. use cgmath::{Point2,Point3,Vector2}; #[cfg(test)] use std::mem; use common::color::Color4; #[derive(Debug, Clone, Copy, PartialEq)] /// An untextured rendering vertex, with position and color. pub struct ColoredVertex { /// The 3-d position of this vertex in world space. pub position: Point3<f32>, /// The color to apply to this vertex, in lieu of a texture. pub color: Color4<f32>, } #[test] fn check_vertex_size() { assert_eq!(mem::size_of::<ColoredVertex>(), 7*4); assert_eq!(mem::size_of::<TextureVertex>(), 5*4); } impl ColoredVertex {
}; [ vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y), vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y), ] } } #[derive(Debug, Clone, Copy, PartialEq)] /// A point in the world with corresponding texture data. /// /// The texture position is [0, 1]. pub struct TextureVertex { /// The position of this vertex in the world. pub world_position: Point3<f32>, /// The position of this vertex on a texture. The range of valid values /// in each dimension is [0, 1]. pub texture_position: Vector2<f32>, }
/// Generates two colored triangles, representing a square, at z=0. /// The bounds of the square is represented by `b`. pub fn square(min: Point2<f32>, max: Point2<f32>, color: Color4<f32>) -> [ColoredVertex; 6] { let vtx = |x, y| { ColoredVertex { position: Point3::new(x, y, 0.0), color: color }
random_line_split
vertex.rs
//! Vertex data structures. use cgmath::{Point2,Point3,Vector2}; #[cfg(test)] use std::mem; use common::color::Color4; #[derive(Debug, Clone, Copy, PartialEq)] /// An untextured rendering vertex, with position and color. pub struct ColoredVertex { /// The 3-d position of this vertex in world space. pub position: Point3<f32>, /// The color to apply to this vertex, in lieu of a texture. pub color: Color4<f32>, } #[test] fn check_vertex_size() { assert_eq!(mem::size_of::<ColoredVertex>(), 7*4); assert_eq!(mem::size_of::<TextureVertex>(), 5*4); } impl ColoredVertex { /// Generates two colored triangles, representing a square, at z=0. /// The bounds of the square is represented by `b`. pub fn square(min: Point2<f32>, max: Point2<f32>, color: Color4<f32>) -> [ColoredVertex; 6]
} #[derive(Debug, Clone, Copy, PartialEq)] /// A point in the world with corresponding texture data. /// /// The texture position is [0, 1]. pub struct TextureVertex { /// The position of this vertex in the world. pub world_position: Point3<f32>, /// The position of this vertex on a texture. The range of valid values /// in each dimension is [0, 1]. pub texture_position: Vector2<f32>, }
{ let vtx = |x, y| { ColoredVertex { position: Point3::new(x, y, 0.0), color: color } }; [ vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y), vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y), ] }
identifier_body
vertex.rs
//! Vertex data structures. use cgmath::{Point2,Point3,Vector2}; #[cfg(test)] use std::mem; use common::color::Color4; #[derive(Debug, Clone, Copy, PartialEq)] /// An untextured rendering vertex, with position and color. pub struct ColoredVertex { /// The 3-d position of this vertex in world space. pub position: Point3<f32>, /// The color to apply to this vertex, in lieu of a texture. pub color: Color4<f32>, } #[test] fn check_vertex_size() { assert_eq!(mem::size_of::<ColoredVertex>(), 7*4); assert_eq!(mem::size_of::<TextureVertex>(), 5*4); } impl ColoredVertex { /// Generates two colored triangles, representing a square, at z=0. /// The bounds of the square is represented by `b`. pub fn square(min: Point2<f32>, max: Point2<f32>, color: Color4<f32>) -> [ColoredVertex; 6] { let vtx = |x, y| { ColoredVertex { position: Point3::new(x, y, 0.0), color: color } }; [ vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y), vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y), ] } } #[derive(Debug, Clone, Copy, PartialEq)] /// A point in the world with corresponding texture data. /// /// The texture position is [0, 1]. pub struct
{ /// The position of this vertex in the world. pub world_position: Point3<f32>, /// The position of this vertex on a texture. The range of valid values /// in each dimension is [0, 1]. pub texture_position: Vector2<f32>, }
TextureVertex
identifier_name
distinct_clause.rs
use crate::backend::Backend; use crate::query_builder::*; use crate::query_dsl::order_dsl::ValidOrderingForDistinct; use crate::result::QueryResult;
#[derive(Debug, Clone, Copy, QueryId)] pub struct NoDistinctClause; #[derive(Debug, Clone, Copy, QueryId)] pub struct DistinctClause; impl<DB: Backend> QueryFragment<DB> for NoDistinctClause { fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> { Ok(()) } } impl<DB: Backend> QueryFragment<DB> for DistinctClause { fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> { out.push_sql("DISTINCT "); Ok(()) } } impl<O> ValidOrderingForDistinct<NoDistinctClause> for O {} impl<O> ValidOrderingForDistinct<DistinctClause> for O {} #[cfg(feature = "postgres")] pub use crate::pg::DistinctOnClause;
random_line_split
distinct_clause.rs
use crate::backend::Backend; use crate::query_builder::*; use crate::query_dsl::order_dsl::ValidOrderingForDistinct; use crate::result::QueryResult; #[derive(Debug, Clone, Copy, QueryId)] pub struct
; #[derive(Debug, Clone, Copy, QueryId)] pub struct DistinctClause; impl<DB: Backend> QueryFragment<DB> for NoDistinctClause { fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> { Ok(()) } } impl<DB: Backend> QueryFragment<DB> for DistinctClause { fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> { out.push_sql("DISTINCT "); Ok(()) } } impl<O> ValidOrderingForDistinct<NoDistinctClause> for O {} impl<O> ValidOrderingForDistinct<DistinctClause> for O {} #[cfg(feature = "postgres")] pub use crate::pg::DistinctOnClause;
NoDistinctClause
identifier_name
chunk.rs
use std::io; use std::fmt; use std::ops::{Deref, DerefMut}; use ::aux::ReadExt; static NAME_LENGTH: u32 = 8; pub struct Root<R> { pub name: String, input: R, buffer: Vec<u8>, position: u32, } impl<R: io::Seek> Root<R> { pub fn tell(&mut self) -> u32 { self.input.seek(io::SeekFrom::Current(0)).unwrap() as u32 } } impl<R: io::Read> Root<R> { pub fn new(name: String, input: R) -> Root<R> { Root { name: name, input: input, buffer: Vec::new(), position: 0, } } pub fn get_pos(&self) -> u32 { self.position } fn skip(&mut self, num: u32) { self.read_bytes(num); } pub fn read_bytes(&mut self, num: u32) -> &[u8] { self.position += num; self.buffer.clear(); for _ in (0.. num) { let b = self.input.read_u8().unwrap(); self.buffer.push(b); } &self.buffer } pub fn read_u8(&mut self) -> u8 { self.position += 1; self.input.read_u8().unwrap() } pub fn read_u32(&mut self) -> u32 { self.position += 4; self.input.read_u32().unwrap() } pub fn read_bool(&mut self) -> bool { self.position += 1; self.input.read_u8().unwrap()!= 0 } pub fn read_str(&mut self) -> &str { use std::str::from_utf8; let size = self.input.read_u8().unwrap() as u32; self.position += 1; let buf = self.read_bytes(size); from_utf8(buf).unwrap() } pub fn enter<'b>(&'b mut self) -> Chunk<'b, R> { let name = { let raw = self.read_bytes(NAME_LENGTH); let buf = match raw.iter().position(|b| *b == 0) { Some(p) => &raw[..p], None => raw, }; String::from_utf8_lossy(buf) .into_owned() }; debug!("Entering chunk {}", name); let size = self.read_u32(); Chunk { name: name, size: size, end_pos: self.position + size, root: self, } } } pub struct Chunk<'a, R: io::Read + 'a> { name: String, size: u32, end_pos: u32, root: &'a mut Root<R>, } impl<'a, R: io::Read> fmt::Display for Chunk<'a, R> { fn fmt(&self, fm: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fm, "Chunk({}, {} left)", self.name, self.size) } } impl<'a, R: io::Read> Chunk<'a, R> { pub fn get_name(&self) -> &str { &self.name } pub fn has_more(&self)-> bool
pub fn ignore(self) { let left = self.end_pos - self.root.get_pos(); self.root.skip(left) } } impl<'a, R: io::Read> Drop for Chunk<'a, R> { fn drop(&mut self) { debug!("Leaving chunk"); assert!(!self.has_more()) } } impl<'a, R: io::Read> Deref for Chunk<'a, R> { type Target = Root<R>; fn deref(&self) -> &Root<R> { self.root } } impl<'a, R: io::Read> DerefMut for Chunk<'a, R> { fn deref_mut(&mut self) -> &mut Root<R> { self.root } }
{ self.root.get_pos() < self.end_pos }
identifier_body
chunk.rs
use std::io; use std::fmt; use std::ops::{Deref, DerefMut}; use ::aux::ReadExt; static NAME_LENGTH: u32 = 8; pub struct Root<R> { pub name: String, input: R, buffer: Vec<u8>, position: u32, } impl<R: io::Seek> Root<R> { pub fn tell(&mut self) -> u32 { self.input.seek(io::SeekFrom::Current(0)).unwrap() as u32 } } impl<R: io::Read> Root<R> { pub fn new(name: String, input: R) -> Root<R> { Root { name: name, input: input, buffer: Vec::new(), position: 0, } } pub fn get_pos(&self) -> u32 { self.position } fn skip(&mut self, num: u32) { self.read_bytes(num); } pub fn read_bytes(&mut self, num: u32) -> &[u8] { self.position += num; self.buffer.clear(); for _ in (0.. num) { let b = self.input.read_u8().unwrap(); self.buffer.push(b); } &self.buffer } pub fn read_u8(&mut self) -> u8 { self.position += 1; self.input.read_u8().unwrap() } pub fn read_u32(&mut self) -> u32 { self.position += 4; self.input.read_u32().unwrap() } pub fn read_bool(&mut self) -> bool { self.position += 1; self.input.read_u8().unwrap()!= 0 } pub fn read_str(&mut self) -> &str { use std::str::from_utf8; let size = self.input.read_u8().unwrap() as u32; self.position += 1; let buf = self.read_bytes(size); from_utf8(buf).unwrap() } pub fn enter<'b>(&'b mut self) -> Chunk<'b, R> { let name = { let raw = self.read_bytes(NAME_LENGTH); let buf = match raw.iter().position(|b| *b == 0) { Some(p) => &raw[..p], None => raw, }; String::from_utf8_lossy(buf) .into_owned() }; debug!("Entering chunk {}", name); let size = self.read_u32(); Chunk { name: name, size: size, end_pos: self.position + size, root: self, } } } pub struct Chunk<'a, R: io::Read + 'a> { name: String, size: u32, end_pos: u32, root: &'a mut Root<R>, } impl<'a, R: io::Read> fmt::Display for Chunk<'a, R> { fn fmt(&self, fm: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fm, "Chunk({}, {} left)", self.name, self.size) } } impl<'a, R: io::Read> Chunk<'a, R> { pub fn get_name(&self) -> &str { &self.name } pub fn has_more(&self)-> bool { self.root.get_pos() < self.end_pos } pub fn ignore(self) { let left = self.end_pos - self.root.get_pos(); self.root.skip(left) } } impl<'a, R: io::Read> Drop for Chunk<'a, R> { fn drop(&mut self) { debug!("Leaving chunk"); assert!(!self.has_more()) } } impl<'a, R: io::Read> Deref for Chunk<'a, R> { type Target = Root<R>; fn deref(&self) -> &Root<R> { self.root }
} }
} impl<'a, R: io::Read> DerefMut for Chunk<'a, R> { fn deref_mut(&mut self) -> &mut Root<R> { self.root
random_line_split
chunk.rs
use std::io; use std::fmt; use std::ops::{Deref, DerefMut}; use ::aux::ReadExt; static NAME_LENGTH: u32 = 8; pub struct Root<R> { pub name: String, input: R, buffer: Vec<u8>, position: u32, } impl<R: io::Seek> Root<R> { pub fn tell(&mut self) -> u32 { self.input.seek(io::SeekFrom::Current(0)).unwrap() as u32 } } impl<R: io::Read> Root<R> { pub fn new(name: String, input: R) -> Root<R> { Root { name: name, input: input, buffer: Vec::new(), position: 0, } } pub fn get_pos(&self) -> u32 { self.position } fn skip(&mut self, num: u32) { self.read_bytes(num); } pub fn read_bytes(&mut self, num: u32) -> &[u8] { self.position += num; self.buffer.clear(); for _ in (0.. num) { let b = self.input.read_u8().unwrap(); self.buffer.push(b); } &self.buffer } pub fn
(&mut self) -> u8 { self.position += 1; self.input.read_u8().unwrap() } pub fn read_u32(&mut self) -> u32 { self.position += 4; self.input.read_u32().unwrap() } pub fn read_bool(&mut self) -> bool { self.position += 1; self.input.read_u8().unwrap()!= 0 } pub fn read_str(&mut self) -> &str { use std::str::from_utf8; let size = self.input.read_u8().unwrap() as u32; self.position += 1; let buf = self.read_bytes(size); from_utf8(buf).unwrap() } pub fn enter<'b>(&'b mut self) -> Chunk<'b, R> { let name = { let raw = self.read_bytes(NAME_LENGTH); let buf = match raw.iter().position(|b| *b == 0) { Some(p) => &raw[..p], None => raw, }; String::from_utf8_lossy(buf) .into_owned() }; debug!("Entering chunk {}", name); let size = self.read_u32(); Chunk { name: name, size: size, end_pos: self.position + size, root: self, } } } pub struct Chunk<'a, R: io::Read + 'a> { name: String, size: u32, end_pos: u32, root: &'a mut Root<R>, } impl<'a, R: io::Read> fmt::Display for Chunk<'a, R> { fn fmt(&self, fm: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fm, "Chunk({}, {} left)", self.name, self.size) } } impl<'a, R: io::Read> Chunk<'a, R> { pub fn get_name(&self) -> &str { &self.name } pub fn has_more(&self)-> bool { self.root.get_pos() < self.end_pos } pub fn ignore(self) { let left = self.end_pos - self.root.get_pos(); self.root.skip(left) } } impl<'a, R: io::Read> Drop for Chunk<'a, R> { fn drop(&mut self) { debug!("Leaving chunk"); assert!(!self.has_more()) } } impl<'a, R: io::Read> Deref for Chunk<'a, R> { type Target = Root<R>; fn deref(&self) -> &Root<R> { self.root } } impl<'a, R: io::Read> DerefMut for Chunk<'a, R> { fn deref_mut(&mut self) -> &mut Root<R> { self.root } }
read_u8
identifier_name
xwrapper.rs
use libc::*; use std::ffi::{CString, CStr}; use std::ptr; use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints }; use x11::xrender::{ XRenderCreatePicture, XRenderFindVisualFormat, XRenderPictureAttributes, XRenderQueryExtension }; use x11::xlib::{ _XDisplay, XDefaultVisual }; // // X Definitions // static XNone: c_ulong = 0; static CPSubWindowMode: c_ulong = 1 << 8; // // Xlib Types // #[repr(C)] pub struct struct__XWMHints { pub flags: c_long, pub input: c_int, pub initial_state: c_int, pub icon_pixmap: Pixmap, pub icon_window: Window, pub icon_x: c_int, pub icon_y: c_int, pub icon_mask: Pixmap, pub window_group: XID, } pub type XWMHints = struct__XWMHints; // // Xlib & X Extensions Linking // #[link(name = "X11")] extern { fn Xutf8SetWMProperties(display: *mut Display, window: Window, window_name: *mut c_char, icon_name: *mut c_char, argv: *mut *mut c_char, argc: i32, normal_hints: *mut XSizeHints, wm_hints: *mut XWMHints, class_hints: *mut XClassHint); } #[link(name = "Xcomposite")] extern { fn XCompositeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xdamage")] extern { fn XDamageQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xext")] extern { fn XShapeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xfixes")] extern { fn XFixesQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } // // XServer Struct // pub struct XServer { display: *mut Display, root: Window } impl XServer { pub fn new() -> XServer { unsafe { let display = XOpenDisplay(ptr::null_mut()); if display.is_null() { panic!("Could not open display!"); } let screen = XDefaultScreenOfDisplay(display); let root = XRootWindowOfScreen(screen); XServer { display: display, root: root } } } } pub fn query_extension(xserver: &XServer, name: &str) { let mut event_base = &mut 0; let mut error_base = &mut 0; unsafe { match name { "Xcomposite" => if XCompositeQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XComposite extension!"); }, "Xdamage" => if XDamageQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XDamage extension!"); }, "Xfixes" => if XFixesQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XFixes extension!"); }, "Xrender" => { let have_xrender = XRenderQueryExtension(xserver.display as *mut _XDisplay, event_base, error_base); if have_xrender == 0 { panic!("No XRender extension!"); } }, "Xshape" => if XShapeQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XShape extension!"); }, _ => panic!(format!("Don't know how to query for {} extension", name)), } } } pub struct WindowSettings { pub opacity: XID, pub type_atom: XID, pub is_desktop: XID, pub is_dock: XID, pub is_toolbar: XID, pub is_menu: XID, pub is_util: XID, pub is_splash: XID, pub is_dialog: XID, pub is_dropdown: XID, pub is_popup: XID, pub is_tooltip: XID, pub is_notification: XID, pub is_combo: XID, pub is_dnd: XID, pub is_normal: XID, } pub fn find_window_settings(xserver: &XServer) -> WindowSettings
} pub fn intern_atom(xserver: &XServer, name: &str) -> XID { return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) }; } pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes { return XRenderPictureAttributes { repeat: 0, alpha_map: XNone, alpha_x_origin: 0, alpha_y_origin: 0, clip_x_origin: 0, clip_y_origin: 0, clip_mask: XNone, graphics_exposures: 0, subwindow_mode: 0, poly_edge: 0, poly_mode: 0, dither: XNone, component_alpha: 0, } } // // Side-Effecting Stuff // pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool { let screen = unsafe { XDefaultScreen(xserver.display) }; let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap(); let reg_atom = unsafe { XInternAtom(xserver.display, reg_atom_name.as_ptr() as *mut c_char, 0) }; let extant_window = unsafe { XGetSelectionOwner(xserver.display, reg_atom) }; if extant_window!= XNone { return false; } unsafe { let our_window = XCreateSimpleWindow(xserver.display, xserver.root, 0, 0, 1, 1, 0, XNone, XNone); Xutf8SetWMProperties(xserver.display, our_window, wm_name.as_ptr() as *mut c_char, wm_name.as_ptr() as *mut c_char, ptr::null_mut(), 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut()); XSetSelectionOwner(xserver.display, reg_atom, our_window, 0); }; return true; } pub fn create_root_picture(xserver: &XServer, attributes: &mut XRenderPictureAttributes) -> c_ulong { let display = xserver.display; let xr_display = xserver.display as *mut _XDisplay; let format = unsafe { XRenderFindVisualFormat(xr_display, XDefaultVisual(xr_display, XDefaultScreen(display))) }; return unsafe { XRenderCreatePicture( xr_display , xserver.root , format , CPSubWindowMode , attributes ) }; }
{ WindowSettings { opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"), type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"), is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"), is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"), is_toolbar: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLBAR"), is_menu: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_MENU"), is_util: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_UTILITY"), is_splash: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_SPLASH"), is_dialog: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DIALOG"), is_dropdown: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DROPDOWN"), is_popup: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_POPUP"), is_tooltip: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLTIP"), is_notification: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NOTIFICATION"), is_combo: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_COMBO"), is_dnd: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DND"), is_normal: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NORMAL"), }
identifier_body
xwrapper.rs
use libc::*; use std::ffi::{CString, CStr}; use std::ptr; use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints }; use x11::xrender::{ XRenderCreatePicture, XRenderFindVisualFormat, XRenderPictureAttributes, XRenderQueryExtension }; use x11::xlib::{ _XDisplay, XDefaultVisual }; // // X Definitions // static XNone: c_ulong = 0; static CPSubWindowMode: c_ulong = 1 << 8; // // Xlib Types // #[repr(C)] pub struct struct__XWMHints { pub flags: c_long, pub input: c_int, pub initial_state: c_int, pub icon_pixmap: Pixmap, pub icon_window: Window, pub icon_x: c_int, pub icon_y: c_int, pub icon_mask: Pixmap, pub window_group: XID, } pub type XWMHints = struct__XWMHints; // // Xlib & X Extensions Linking // #[link(name = "X11")] extern { fn Xutf8SetWMProperties(display: *mut Display, window: Window, window_name: *mut c_char, icon_name: *mut c_char, argv: *mut *mut c_char, argc: i32, normal_hints: *mut XSizeHints, wm_hints: *mut XWMHints, class_hints: *mut XClassHint); } #[link(name = "Xcomposite")] extern { fn XCompositeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xdamage")] extern { fn XDamageQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xext")] extern { fn XShapeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xfixes")] extern { fn XFixesQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } // // XServer Struct // pub struct XServer { display: *mut Display, root: Window } impl XServer { pub fn new() -> XServer { unsafe { let display = XOpenDisplay(ptr::null_mut()); if display.is_null() { panic!("Could not open display!"); } let screen = XDefaultScreenOfDisplay(display); let root = XRootWindowOfScreen(screen); XServer { display: display, root: root } } } } pub fn query_extension(xserver: &XServer, name: &str) { let mut event_base = &mut 0; let mut error_base = &mut 0; unsafe { match name { "Xcomposite" => if XCompositeQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XComposite extension!"); }, "Xdamage" => if XDamageQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XDamage extension!"); }, "Xfixes" => if XFixesQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XFixes extension!"); }, "Xrender" => { let have_xrender = XRenderQueryExtension(xserver.display as *mut _XDisplay, event_base, error_base); if have_xrender == 0 { panic!("No XRender extension!"); } }, "Xshape" => if XShapeQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XShape extension!"); }, _ => panic!(format!("Don't know how to query for {} extension", name)), } } } pub struct WindowSettings { pub opacity: XID, pub type_atom: XID, pub is_desktop: XID, pub is_dock: XID, pub is_toolbar: XID, pub is_menu: XID, pub is_util: XID, pub is_splash: XID, pub is_dialog: XID, pub is_dropdown: XID, pub is_popup: XID, pub is_tooltip: XID, pub is_notification: XID, pub is_combo: XID, pub is_dnd: XID, pub is_normal: XID, } pub fn
(xserver: &XServer) -> WindowSettings { WindowSettings { opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"), type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"), is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"), is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"), is_toolbar: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLBAR"), is_menu: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_MENU"), is_util: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_UTILITY"), is_splash: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_SPLASH"), is_dialog: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DIALOG"), is_dropdown: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DROPDOWN"), is_popup: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_POPUP"), is_tooltip: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLTIP"), is_notification: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NOTIFICATION"), is_combo: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_COMBO"), is_dnd: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DND"), is_normal: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NORMAL"), } } pub fn intern_atom(xserver: &XServer, name: &str) -> XID { return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) }; } pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes { return XRenderPictureAttributes { repeat: 0, alpha_map: XNone, alpha_x_origin: 0, alpha_y_origin: 0, clip_x_origin: 0, clip_y_origin: 0, clip_mask: XNone, graphics_exposures: 0, subwindow_mode: 0, poly_edge: 0, poly_mode: 0, dither: XNone, component_alpha: 0, } } // // Side-Effecting Stuff // pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool { let screen = unsafe { XDefaultScreen(xserver.display) }; let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap(); let reg_atom = unsafe { XInternAtom(xserver.display, reg_atom_name.as_ptr() as *mut c_char, 0) }; let extant_window = unsafe { XGetSelectionOwner(xserver.display, reg_atom) }; if extant_window!= XNone { return false; } unsafe { let our_window = XCreateSimpleWindow(xserver.display, xserver.root, 0, 0, 1, 1, 0, XNone, XNone); Xutf8SetWMProperties(xserver.display, our_window, wm_name.as_ptr() as *mut c_char, wm_name.as_ptr() as *mut c_char, ptr::null_mut(), 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut()); XSetSelectionOwner(xserver.display, reg_atom, our_window, 0); }; return true; } pub fn create_root_picture(xserver: &XServer, attributes: &mut XRenderPictureAttributes) -> c_ulong { let display = xserver.display; let xr_display = xserver.display as *mut _XDisplay; let format = unsafe { XRenderFindVisualFormat(xr_display, XDefaultVisual(xr_display, XDefaultScreen(display))) }; return unsafe { XRenderCreatePicture( xr_display , xserver.root , format , CPSubWindowMode , attributes ) }; }
find_window_settings
identifier_name
xwrapper.rs
use libc::*; use std::ffi::{CString, CStr}; use std::ptr; use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints }; use x11::xrender::{ XRenderCreatePicture, XRenderFindVisualFormat, XRenderPictureAttributes, XRenderQueryExtension }; use x11::xlib::{ _XDisplay, XDefaultVisual }; // // X Definitions // static XNone: c_ulong = 0; static CPSubWindowMode: c_ulong = 1 << 8; // // Xlib Types // #[repr(C)] pub struct struct__XWMHints { pub flags: c_long, pub input: c_int, pub initial_state: c_int, pub icon_pixmap: Pixmap, pub icon_window: Window, pub icon_x: c_int, pub icon_y: c_int, pub icon_mask: Pixmap, pub window_group: XID, } pub type XWMHints = struct__XWMHints; // // Xlib & X Extensions Linking // #[link(name = "X11")] extern { fn Xutf8SetWMProperties(display: *mut Display, window: Window, window_name: *mut c_char, icon_name: *mut c_char, argv: *mut *mut c_char, argc: i32, normal_hints: *mut XSizeHints, wm_hints: *mut XWMHints, class_hints: *mut XClassHint); } #[link(name = "Xcomposite")] extern { fn XCompositeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xdamage")] extern { fn XDamageQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xext")] extern { fn XShapeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xfixes")] extern { fn XFixesQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } // // XServer Struct // pub struct XServer { display: *mut Display, root: Window } impl XServer { pub fn new() -> XServer { unsafe { let display = XOpenDisplay(ptr::null_mut()); if display.is_null() { panic!("Could not open display!"); } let screen = XDefaultScreenOfDisplay(display); let root = XRootWindowOfScreen(screen); XServer { display: display, root: root } } } } pub fn query_extension(xserver: &XServer, name: &str) { let mut event_base = &mut 0; let mut error_base = &mut 0; unsafe { match name { "Xcomposite" => if XCompositeQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XComposite extension!"); }, "Xdamage" => if XDamageQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XDamage extension!"); }, "Xfixes" => if XFixesQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XFixes extension!"); }, "Xrender" => { let have_xrender = XRenderQueryExtension(xserver.display as *mut _XDisplay, event_base, error_base); if have_xrender == 0 { panic!("No XRender extension!"); } }, "Xshape" => if XShapeQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XShape extension!"); }, _ => panic!(format!("Don't know how to query for {} extension", name)), } } } pub struct WindowSettings { pub opacity: XID, pub type_atom: XID, pub is_desktop: XID, pub is_dock: XID, pub is_toolbar: XID, pub is_menu: XID, pub is_util: XID, pub is_splash: XID, pub is_dialog: XID, pub is_dropdown: XID, pub is_popup: XID, pub is_tooltip: XID, pub is_notification: XID, pub is_combo: XID, pub is_dnd: XID, pub is_normal: XID, } pub fn find_window_settings(xserver: &XServer) -> WindowSettings { WindowSettings { opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"), type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"), is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"), is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"), is_toolbar: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLBAR"), is_menu: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_MENU"), is_util: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_UTILITY"), is_splash: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_SPLASH"), is_dialog: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DIALOG"), is_dropdown: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DROPDOWN"), is_popup: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_POPUP"), is_tooltip: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLTIP"), is_notification: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NOTIFICATION"), is_combo: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_COMBO"), is_dnd: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DND"), is_normal: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NORMAL"), } } pub fn intern_atom(xserver: &XServer, name: &str) -> XID { return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) }; } pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes { return XRenderPictureAttributes { repeat: 0, alpha_map: XNone, alpha_x_origin: 0, alpha_y_origin: 0, clip_x_origin: 0, clip_y_origin: 0, clip_mask: XNone,
dither: XNone, component_alpha: 0, } } // // Side-Effecting Stuff // pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool { let screen = unsafe { XDefaultScreen(xserver.display) }; let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap(); let reg_atom = unsafe { XInternAtom(xserver.display, reg_atom_name.as_ptr() as *mut c_char, 0) }; let extant_window = unsafe { XGetSelectionOwner(xserver.display, reg_atom) }; if extant_window!= XNone { return false; } unsafe { let our_window = XCreateSimpleWindow(xserver.display, xserver.root, 0, 0, 1, 1, 0, XNone, XNone); Xutf8SetWMProperties(xserver.display, our_window, wm_name.as_ptr() as *mut c_char, wm_name.as_ptr() as *mut c_char, ptr::null_mut(), 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut()); XSetSelectionOwner(xserver.display, reg_atom, our_window, 0); }; return true; } pub fn create_root_picture(xserver: &XServer, attributes: &mut XRenderPictureAttributes) -> c_ulong { let display = xserver.display; let xr_display = xserver.display as *mut _XDisplay; let format = unsafe { XRenderFindVisualFormat(xr_display, XDefaultVisual(xr_display, XDefaultScreen(display))) }; return unsafe { XRenderCreatePicture( xr_display , xserver.root , format , CPSubWindowMode , attributes ) }; }
graphics_exposures: 0, subwindow_mode: 0, poly_edge: 0, poly_mode: 0,
random_line_split
xwrapper.rs
use libc::*; use std::ffi::{CString, CStr}; use std::ptr; use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints }; use x11::xrender::{ XRenderCreatePicture, XRenderFindVisualFormat, XRenderPictureAttributes, XRenderQueryExtension }; use x11::xlib::{ _XDisplay, XDefaultVisual }; // // X Definitions // static XNone: c_ulong = 0; static CPSubWindowMode: c_ulong = 1 << 8; // // Xlib Types // #[repr(C)] pub struct struct__XWMHints { pub flags: c_long, pub input: c_int, pub initial_state: c_int, pub icon_pixmap: Pixmap, pub icon_window: Window, pub icon_x: c_int, pub icon_y: c_int, pub icon_mask: Pixmap, pub window_group: XID, } pub type XWMHints = struct__XWMHints; // // Xlib & X Extensions Linking // #[link(name = "X11")] extern { fn Xutf8SetWMProperties(display: *mut Display, window: Window, window_name: *mut c_char, icon_name: *mut c_char, argv: *mut *mut c_char, argc: i32, normal_hints: *mut XSizeHints, wm_hints: *mut XWMHints, class_hints: *mut XClassHint); } #[link(name = "Xcomposite")] extern { fn XCompositeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xdamage")] extern { fn XDamageQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xext")] extern { fn XShapeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } #[link(name = "Xfixes")] extern { fn XFixesQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32; } // // XServer Struct // pub struct XServer { display: *mut Display, root: Window } impl XServer { pub fn new() -> XServer { unsafe { let display = XOpenDisplay(ptr::null_mut()); if display.is_null() { panic!("Could not open display!"); } let screen = XDefaultScreenOfDisplay(display); let root = XRootWindowOfScreen(screen); XServer { display: display, root: root } } } } pub fn query_extension(xserver: &XServer, name: &str) { let mut event_base = &mut 0; let mut error_base = &mut 0; unsafe { match name { "Xcomposite" => if XCompositeQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XComposite extension!"); }, "Xdamage" => if XDamageQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XDamage extension!"); }, "Xfixes" => if XFixesQueryExtension(xserver.display, event_base, error_base) == 0 { panic!("No XFixes extension!"); }, "Xrender" => { let have_xrender = XRenderQueryExtension(xserver.display as *mut _XDisplay, event_base, error_base); if have_xrender == 0 { panic!("No XRender extension!"); } }, "Xshape" => if XShapeQueryExtension(xserver.display, event_base, error_base) == 0
, _ => panic!(format!("Don't know how to query for {} extension", name)), } } } pub struct WindowSettings { pub opacity: XID, pub type_atom: XID, pub is_desktop: XID, pub is_dock: XID, pub is_toolbar: XID, pub is_menu: XID, pub is_util: XID, pub is_splash: XID, pub is_dialog: XID, pub is_dropdown: XID, pub is_popup: XID, pub is_tooltip: XID, pub is_notification: XID, pub is_combo: XID, pub is_dnd: XID, pub is_normal: XID, } pub fn find_window_settings(xserver: &XServer) -> WindowSettings { WindowSettings { opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"), type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"), is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"), is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"), is_toolbar: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLBAR"), is_menu: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_MENU"), is_util: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_UTILITY"), is_splash: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_SPLASH"), is_dialog: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DIALOG"), is_dropdown: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DROPDOWN"), is_popup: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_POPUP"), is_tooltip: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLTIP"), is_notification: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NOTIFICATION"), is_combo: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_COMBO"), is_dnd: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DND"), is_normal: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NORMAL"), } } pub fn intern_atom(xserver: &XServer, name: &str) -> XID { return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) }; } pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes { return XRenderPictureAttributes { repeat: 0, alpha_map: XNone, alpha_x_origin: 0, alpha_y_origin: 0, clip_x_origin: 0, clip_y_origin: 0, clip_mask: XNone, graphics_exposures: 0, subwindow_mode: 0, poly_edge: 0, poly_mode: 0, dither: XNone, component_alpha: 0, } } // // Side-Effecting Stuff // pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool { let screen = unsafe { XDefaultScreen(xserver.display) }; let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap(); let reg_atom = unsafe { XInternAtom(xserver.display, reg_atom_name.as_ptr() as *mut c_char, 0) }; let extant_window = unsafe { XGetSelectionOwner(xserver.display, reg_atom) }; if extant_window!= XNone { return false; } unsafe { let our_window = XCreateSimpleWindow(xserver.display, xserver.root, 0, 0, 1, 1, 0, XNone, XNone); Xutf8SetWMProperties(xserver.display, our_window, wm_name.as_ptr() as *mut c_char, wm_name.as_ptr() as *mut c_char, ptr::null_mut(), 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut()); XSetSelectionOwner(xserver.display, reg_atom, our_window, 0); }; return true; } pub fn create_root_picture(xserver: &XServer, attributes: &mut XRenderPictureAttributes) -> c_ulong { let display = xserver.display; let xr_display = xserver.display as *mut _XDisplay; let format = unsafe { XRenderFindVisualFormat(xr_display, XDefaultVisual(xr_display, XDefaultScreen(display))) }; return unsafe { XRenderCreatePicture( xr_display , xserver.root , format , CPSubWindowMode , attributes ) }; }
{ panic!("No XShape extension!"); }
conditional_block
list.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)} // TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1: // // decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman, // upper-roman // // TODO(bholley): Missing quite a few gecko properties here as well. // // [1]: http://dev.w3.org/csswg/css-counter-styles/ ${helpers.single_keyword("list-style-type", """ disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed """, extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari gujarati gurmukhi kannada khmer lao malayalam mongolian myanmar oriya persian telugu thai tibetan cjk-earthly-branch cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana katakana-iroha""", gecko_constant_prefix="NS_STYLE_LIST_STYLE", animatable=False)} ${helpers.predefined_type("list-style-image", "UrlOrNone", "computed_value::T::None", animatable="False")} <%helpers:longhand name="quotes" animatable="False"> use cssparser::Token; use std::borrow::Cow; use std::fmt; use style_traits::ToCss; use values::computed::ComputedValueAsSpecified; use values::NoViewportPercentage; pub use self::computed_value::T as SpecifiedValue; pub mod computed_value { #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct T(pub Vec<(String,String)>); } impl ComputedValueAsSpecified for SpecifiedValue {} impl NoViewportPercentage for SpecifiedValue {} impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut first = true; for pair in &self.0 { if!first { try!(dest.write_str(" ")); } first = false; try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest)); try!(dest.write_str(" ")); try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest)); } Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(vec![ ("\u{201c}".to_owned(), "\u{201d}".to_owned()), ("\u{2018}".to_owned(), "\u{2019}".to_owned()), ]) } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue(Vec::new())) } let mut quotes = Vec::new(); loop { let first = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), Ok(_) => return Err(()), Err(()) => break, }; let second = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), _ => return Err(()), }; quotes.push((first, second)) } if!quotes.is_empty() { Ok(SpecifiedValue(quotes)) } else { Err(()) } } </%helpers:longhand>
<%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("List", inherited=True) %>
random_line_split
list.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("List", inherited=True) %> ${helpers.single_keyword("list-style-position", "outside inside", animatable=False)} // TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1: // // decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman, // upper-roman // // TODO(bholley): Missing quite a few gecko properties here as well. // // [1]: http://dev.w3.org/csswg/css-counter-styles/ ${helpers.single_keyword("list-style-type", """ disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed """, extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari gujarati gurmukhi kannada khmer lao malayalam mongolian myanmar oriya persian telugu thai tibetan cjk-earthly-branch cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana katakana-iroha""", gecko_constant_prefix="NS_STYLE_LIST_STYLE", animatable=False)} ${helpers.predefined_type("list-style-image", "UrlOrNone", "computed_value::T::None", animatable="False")} <%helpers:longhand name="quotes" animatable="False"> use cssparser::Token; use std::borrow::Cow; use std::fmt; use style_traits::ToCss; use values::computed::ComputedValueAsSpecified; use values::NoViewportPercentage; pub use self::computed_value::T as SpecifiedValue; pub mod computed_value { #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct T(pub Vec<(String,String)>); } impl ComputedValueAsSpecified for SpecifiedValue {} impl NoViewportPercentage for SpecifiedValue {} impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut first = true; for pair in &self.0 { if!first { try!(dest.write_str(" ")); } first = false; try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest)); try!(dest.write_str(" ")); try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest)); } Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(vec![ ("\u{201c}".to_owned(), "\u{201d}".to_owned()), ("\u{2018}".to_owned(), "\u{2019}".to_owned()), ]) } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()>
} else { Err(()) } } </%helpers:longhand>
{ if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue(Vec::new())) } let mut quotes = Vec::new(); loop { let first = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), Ok(_) => return Err(()), Err(()) => break, }; let second = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), _ => return Err(()), }; quotes.push((first, second)) } if !quotes.is_empty() { Ok(SpecifiedValue(quotes))
identifier_body
list.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("List", inherited=True) %> ${helpers.single_keyword("list-style-position", "outside inside", animatable=False)} // TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1: // // decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman, // upper-roman // // TODO(bholley): Missing quite a few gecko properties here as well. // // [1]: http://dev.w3.org/csswg/css-counter-styles/ ${helpers.single_keyword("list-style-type", """ disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed """, extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari gujarati gurmukhi kannada khmer lao malayalam mongolian myanmar oriya persian telugu thai tibetan cjk-earthly-branch cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana katakana-iroha""", gecko_constant_prefix="NS_STYLE_LIST_STYLE", animatable=False)} ${helpers.predefined_type("list-style-image", "UrlOrNone", "computed_value::T::None", animatable="False")} <%helpers:longhand name="quotes" animatable="False"> use cssparser::Token; use std::borrow::Cow; use std::fmt; use style_traits::ToCss; use values::computed::ComputedValueAsSpecified; use values::NoViewportPercentage; pub use self::computed_value::T as SpecifiedValue; pub mod computed_value { #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct
(pub Vec<(String,String)>); } impl ComputedValueAsSpecified for SpecifiedValue {} impl NoViewportPercentage for SpecifiedValue {} impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut first = true; for pair in &self.0 { if!first { try!(dest.write_str(" ")); } first = false; try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest)); try!(dest.write_str(" ")); try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest)); } Ok(()) } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(vec![ ("\u{201c}".to_owned(), "\u{201d}".to_owned()), ("\u{2018}".to_owned(), "\u{2019}".to_owned()), ]) } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue(Vec::new())) } let mut quotes = Vec::new(); loop { let first = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), Ok(_) => return Err(()), Err(()) => break, }; let second = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), _ => return Err(()), }; quotes.push((first, second)) } if!quotes.is_empty() { Ok(SpecifiedValue(quotes)) } else { Err(()) } } </%helpers:longhand>
T
identifier_name
template_installer.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. use crate::elastic::client::Client; use crate::prelude::*; use anyhow::anyhow; use anyhow::Result; pub async fn install_template(client: &Client, template: &str) -> Result<()>
)); } let template_string = { if version.major >= 7 { crate::resource::get_string("elasticsearch/template-es7x.json").ok_or_else(|| { anyhow!( "Failed to find template for Elasticsearch version {}", version.version ) })? } else { return Err(anyhow!( "Elasticsearch version {} not supported", version.version )); } }; info!("Installing template {}", &template); let mut templatejs: serde_json::Value = serde_json::from_str(&template_string)?; templatejs["index_patterns"] = format!("{}-*", template).into(); client .put_template(template, serde_json::to_string(&templatejs)?) .await?; Ok(()) }
{ debug!("Checking for template \"{}\"", template); match client.get_template(template).await { Err(err) => { warn!("Failed to check if template {} exists: {}", template, err); } Ok(None) => { debug!("Did not find template for \"{}\", will install", template); } Ok(Some(_)) => { debug!("Found template for \"{}\"", template); return Ok(()); } }; let version = client.get_version().await?; if version.major < 7 { return Err(anyhow!( "Elasticsearch version {} not supported", version.version
identifier_body
template_installer.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. use crate::elastic::client::Client; use crate::prelude::*; use anyhow::anyhow; use anyhow::Result; pub async fn
(client: &Client, template: &str) -> Result<()> { debug!("Checking for template \"{}\"", template); match client.get_template(template).await { Err(err) => { warn!("Failed to check if template {} exists: {}", template, err); } Ok(None) => { debug!("Did not find template for \"{}\", will install", template); } Ok(Some(_)) => { debug!("Found template for \"{}\"", template); return Ok(()); } }; let version = client.get_version().await?; if version.major < 7 { return Err(anyhow!( "Elasticsearch version {} not supported", version.version )); } let template_string = { if version.major >= 7 { crate::resource::get_string("elasticsearch/template-es7x.json").ok_or_else(|| { anyhow!( "Failed to find template for Elasticsearch version {}", version.version ) })? } else { return Err(anyhow!( "Elasticsearch version {} not supported", version.version )); } }; info!("Installing template {}", &template); let mut templatejs: serde_json::Value = serde_json::from_str(&template_string)?; templatejs["index_patterns"] = format!("{}-*", template).into(); client .put_template(template, serde_json::to_string(&templatejs)?) .await?; Ok(()) }
install_template
identifier_name
template_installer.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. use crate::elastic::client::Client; use crate::prelude::*;
debug!("Checking for template \"{}\"", template); match client.get_template(template).await { Err(err) => { warn!("Failed to check if template {} exists: {}", template, err); } Ok(None) => { debug!("Did not find template for \"{}\", will install", template); } Ok(Some(_)) => { debug!("Found template for \"{}\"", template); return Ok(()); } }; let version = client.get_version().await?; if version.major < 7 { return Err(anyhow!( "Elasticsearch version {} not supported", version.version )); } let template_string = { if version.major >= 7 { crate::resource::get_string("elasticsearch/template-es7x.json").ok_or_else(|| { anyhow!( "Failed to find template for Elasticsearch version {}", version.version ) })? } else { return Err(anyhow!( "Elasticsearch version {} not supported", version.version )); } }; info!("Installing template {}", &template); let mut templatejs: serde_json::Value = serde_json::from_str(&template_string)?; templatejs["index_patterns"] = format!("{}-*", template).into(); client .put_template(template, serde_json::to_string(&templatejs)?) .await?; Ok(()) }
use anyhow::anyhow; use anyhow::Result; pub async fn install_template(client: &Client, template: &str) -> Result<()> {
random_line_split
template_installer.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. use crate::elastic::client::Client; use crate::prelude::*; use anyhow::anyhow; use anyhow::Result; pub async fn install_template(client: &Client, template: &str) -> Result<()> { debug!("Checking for template \"{}\"", template); match client.get_template(template).await { Err(err) => { warn!("Failed to check if template {} exists: {}", template, err); } Ok(None) => { debug!("Did not find template for \"{}\", will install", template); } Ok(Some(_)) =>
}; let version = client.get_version().await?; if version.major < 7 { return Err(anyhow!( "Elasticsearch version {} not supported", version.version )); } let template_string = { if version.major >= 7 { crate::resource::get_string("elasticsearch/template-es7x.json").ok_or_else(|| { anyhow!( "Failed to find template for Elasticsearch version {}", version.version ) })? } else { return Err(anyhow!( "Elasticsearch version {} not supported", version.version )); } }; info!("Installing template {}", &template); let mut templatejs: serde_json::Value = serde_json::from_str(&template_string)?; templatejs["index_patterns"] = format!("{}-*", template).into(); client .put_template(template, serde_json::to_string(&templatejs)?) .await?; Ok(()) }
{ debug!("Found template for \"{}\"", template); return Ok(()); }
conditional_block
filter.rs
use crate::fns::FnMut1; use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`filter`](super::StreamExt::filter) method. #[must_use = "streams do nothing unless polled"] pub struct Filter<St, Fut, F> where St: Stream, { #[pin] stream: St, f: F, #[pin] pending_fut: Option<Fut>, pending_item: Option<St::Item>, } } impl<St, Fut, F> fmt::Debug for Filter<St, Fut, F> where St: Stream + fmt::Debug, St::Item: fmt::Debug, Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Filter") .field("stream", &self.stream) .field("pending_fut", &self.pending_fut) .field("pending_item", &self.pending_item) .finish() } } #[allow(single_use_lifetimes)] // https://github.com/rust-lang/rust/issues/55058 impl<St, Fut, F> Filter<St, Fut, F> where St: Stream, F: for<'a> FnMut1<&'a St::Item, Output = Fut>, Fut: Future<Output = bool>, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, f, pending_fut: None, pending_item: None } } delegate_access_inner!(stream, St, ()); } impl<St, Fut, F> FusedStream for Filter<St, Fut, F> where St: Stream + FusedStream, F: FnMut(&St::Item) -> Fut, Fut: Future<Output = bool>, { fn is_terminated(&self) -> bool { self.pending_fut.is_none() && self.stream.is_terminated() } } #[allow(single_use_lifetimes)] // https://github.com/rust-lang/rust/issues/55058 impl<St, Fut, F> Stream for Filter<St, Fut, F> where St: Stream, F: for<'a> FnMut1<&'a St::Item, Output = Fut>, Fut: Future<Output = bool>, { type Item = St::Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<St::Item>> { let mut this = self.project(); Poll::Ready(loop { if let Some(fut) = this.pending_fut.as_mut().as_pin_mut() { let res = ready!(fut.poll(cx)); this.pending_fut.set(None); if res { break this.pending_item.take(); } *this.pending_item = None; } else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) { this.pending_fut.set(Some(this.f.call_mut(&item))); *this.pending_item = Some(item); } else { break None; } }) } fn
(&self) -> (usize, Option<usize>) { let pending_len = if self.pending_item.is_some() { 1 } else { 0 }; let (_, upper) = self.stream.size_hint(); let upper = match upper { Some(x) => x.checked_add(pending_len), None => None, }; (0, upper) // can't know a lower bound, due to the predicate } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S, Fut, F, Item> Sink<Item> for Filter<S, Fut, F> where S: Stream + Sink<Item>, F: FnMut(&S::Item) -> Fut, Fut: Future<Output = bool>, { type Error = S::Error; delegate_sink!(stream, Item); }
size_hint
identifier_name
filter.rs
use crate::fns::FnMut1; use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`filter`](super::StreamExt::filter) method. #[must_use = "streams do nothing unless polled"] pub struct Filter<St, Fut, F> where St: Stream, { #[pin] stream: St, f: F, #[pin] pending_fut: Option<Fut>, pending_item: Option<St::Item>, } } impl<St, Fut, F> fmt::Debug for Filter<St, Fut, F> where St: Stream + fmt::Debug, St::Item: fmt::Debug, Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Filter") .field("stream", &self.stream) .field("pending_fut", &self.pending_fut) .field("pending_item", &self.pending_item) .finish() } } #[allow(single_use_lifetimes)] // https://github.com/rust-lang/rust/issues/55058 impl<St, Fut, F> Filter<St, Fut, F> where St: Stream, F: for<'a> FnMut1<&'a St::Item, Output = Fut>, Fut: Future<Output = bool>, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, f, pending_fut: None, pending_item: None } } delegate_access_inner!(stream, St, ()); } impl<St, Fut, F> FusedStream for Filter<St, Fut, F> where St: Stream + FusedStream, F: FnMut(&St::Item) -> Fut, Fut: Future<Output = bool>, { fn is_terminated(&self) -> bool { self.pending_fut.is_none() && self.stream.is_terminated() } } #[allow(single_use_lifetimes)] // https://github.com/rust-lang/rust/issues/55058 impl<St, Fut, F> Stream for Filter<St, Fut, F> where St: Stream, F: for<'a> FnMut1<&'a St::Item, Output = Fut>, Fut: Future<Output = bool>, { type Item = St::Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<St::Item>> { let mut this = self.project(); Poll::Ready(loop { if let Some(fut) = this.pending_fut.as_mut().as_pin_mut() { let res = ready!(fut.poll(cx)); this.pending_fut.set(None); if res { break this.pending_item.take(); } *this.pending_item = None; } else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) { this.pending_fut.set(Some(this.f.call_mut(&item))); *this.pending_item = Some(item); } else { break None; } }) } fn size_hint(&self) -> (usize, Option<usize>) { let pending_len = if self.pending_item.is_some() { 1 } else
; let (_, upper) = self.stream.size_hint(); let upper = match upper { Some(x) => x.checked_add(pending_len), None => None, }; (0, upper) // can't know a lower bound, due to the predicate } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S, Fut, F, Item> Sink<Item> for Filter<S, Fut, F> where S: Stream + Sink<Item>, F: FnMut(&S::Item) -> Fut, Fut: Future<Output = bool>, { type Error = S::Error; delegate_sink!(stream, Item); }
{ 0 }
conditional_block
filter.rs
use crate::fns::FnMut1; use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`filter`](super::StreamExt::filter) method. #[must_use = "streams do nothing unless polled"] pub struct Filter<St, Fut, F> where St: Stream, { #[pin] stream: St, f: F, #[pin] pending_fut: Option<Fut>, pending_item: Option<St::Item>, } } impl<St, Fut, F> fmt::Debug for Filter<St, Fut, F> where St: Stream + fmt::Debug, St::Item: fmt::Debug, Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Filter") .field("stream", &self.stream) .field("pending_fut", &self.pending_fut) .field("pending_item", &self.pending_item) .finish() } } #[allow(single_use_lifetimes)] // https://github.com/rust-lang/rust/issues/55058 impl<St, Fut, F> Filter<St, Fut, F> where St: Stream, F: for<'a> FnMut1<&'a St::Item, Output = Fut>, Fut: Future<Output = bool>, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, f, pending_fut: None, pending_item: None } } delegate_access_inner!(stream, St, ()); } impl<St, Fut, F> FusedStream for Filter<St, Fut, F> where St: Stream + FusedStream, F: FnMut(&St::Item) -> Fut, Fut: Future<Output = bool>, { fn is_terminated(&self) -> bool { self.pending_fut.is_none() && self.stream.is_terminated() } } #[allow(single_use_lifetimes)] // https://github.com/rust-lang/rust/issues/55058 impl<St, Fut, F> Stream for Filter<St, Fut, F> where St: Stream,
{ type Item = St::Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<St::Item>> { let mut this = self.project(); Poll::Ready(loop { if let Some(fut) = this.pending_fut.as_mut().as_pin_mut() { let res = ready!(fut.poll(cx)); this.pending_fut.set(None); if res { break this.pending_item.take(); } *this.pending_item = None; } else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) { this.pending_fut.set(Some(this.f.call_mut(&item))); *this.pending_item = Some(item); } else { break None; } }) } fn size_hint(&self) -> (usize, Option<usize>) { let pending_len = if self.pending_item.is_some() { 1 } else { 0 }; let (_, upper) = self.stream.size_hint(); let upper = match upper { Some(x) => x.checked_add(pending_len), None => None, }; (0, upper) // can't know a lower bound, due to the predicate } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S, Fut, F, Item> Sink<Item> for Filter<S, Fut, F> where S: Stream + Sink<Item>, F: FnMut(&S::Item) -> Fut, Fut: Future<Output = bool>, { type Error = S::Error; delegate_sink!(stream, Item); }
F: for<'a> FnMut1<&'a St::Item, Output = Fut>, Fut: Future<Output = bool>,
random_line_split