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
version.rs
use crate::internal::consts; // ========================================================================= // /// The CFB format version to use. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Version { /// Version 3, which uses 512-byte sectors. V3, /// Version 4, which uses 4096-byte sectors. V4, } impl Version { /// Returns the version enum for the given version number, or `None`. pub fn from_number(number: u16) -> Option<Version> { match number { 3 => Some(Version::V3), 4 => Some(Version::V4), _ => None, } } /// Returns the version number for this version. pub fn number(self) -> u16 { match self { Version::V3 => 3, Version::V4 => 4, } } /// Returns the sector shift used in this version. pub fn sector_shift(self) -> u16 { match self { Version::V3 => 9, // 512-byte sectors Version::V4 => 12, // 4096-byte sectors } } /// Returns the length of sectors used in this version. /// /// ``` /// use cfb::Version; /// assert_eq!(Version::V3.sector_len(), 512); /// assert_eq!(Version::V4.sector_len(), 4096); /// ``` pub fn sector_len(self) -> usize { 1 << (self.sector_shift() as usize) } /// Returns the bitmask used for reading stream lengths in this version. pub fn stream_len_mask(self) -> u64 { match self { Version::V3 => 0xffffffff, Version::V4 => 0xffffffffffffffff, } } /// Returns the number of directory entries per sector in this version. pub fn
(self) -> usize { self.sector_len() / consts::DIR_ENTRY_LEN } } // ========================================================================= // #[cfg(test)] mod tests { use super::Version; #[test] fn number_round_trip() { for &version in &[Version::V3, Version::V4] { assert_eq!(Version::from_number(version.number()), Some(version)); } } } // ========================================================================= //
dir_entries_per_sector
identifier_name
signals.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Tests related to signal handling by the nodes. // cspell:ignore unistd #![cfg(unix)] use futures::StreamExt; use nix::{ sys::signal::{kill, Signal}, unistd::Pid, }; use rusty_fork::{fork, rusty_fork_id, ChildWrapper}; use tokio::{ runtime::Runtime, signal::unix::{signal, SignalKind}, }; use tokio_stream::wrappers::SignalStream; use std::{ env, fs::File, io::{BufRead, BufReader, Seek, SeekFrom}, thread, time::Duration, }; pub mod common; use crate::common::{run_nodes, Options}; fn check_child_start(child: &mut ChildWrapper) { let maybe_status = child .wait_timeout(Duration::from_secs(5)) .expect("Failed to wait for node to function"); if let Some(status) = maybe_status { panic!( "Node exited unexpectedly with this exit status: {:?}", status ); } } fn check_child_exit(child: &mut ChildWrapper, output: &mut File) { // Check that the child has exited. let exit_status = child .wait_timeout(Duration::from_secs(2)) .expect("Failed to wait for node exit") .unwrap_or_else(|| { child.kill().ok(); panic!("Node did not exit in 2 secs after being sent the signal"); }); assert!( exit_status.success(), "Node exited with unexpected status: {:?}", exit_status ); output.seek(SeekFrom::Start(0)).unwrap(); let reader = BufReader::new(&*output); for line in reader.lines().flatten() { if line.contains("Shutting down node handler") { return; } } panic!("Node did not shut down properly"); } fn check_child(child: &mut ChildWrapper, output: &mut File, signal: Signal) { // Sleep several seconds in order for the node to launch. check_child_start(child); // Send a signal to the node. let pid = Pid::from_raw(child.id() as i32); kill(pid, signal).unwrap(); // Check that the child has exited. check_child_exit(child, output); } async fn start_node(start_port: u16, with_http: bool) { // Enable logs in order to check that the node shuts down properly. env::set_var("RUST_LOG", "exonum_node=info"); exonum::helpers::init_logger().ok(); let mut options = Options::default(); if with_http { options.http_start_port = Some(start_port + 1); } let (mut nodes, _) = run_nodes(1, start_port, options); let node = nodes.pop().unwrap(); node.run().await } fn check_child_with_custom_handler( child: &mut ChildWrapper, output: &mut File, http_port: Option<u16>, ) { // Sleep several seconds in order for the node to launch. check_child_start(child); // Send a signal to the node. let pid = Pid::from_raw(child.id() as i32); for _ in 0..2 { kill(pid, Signal::SIGTERM).unwrap(); thread::sleep(Duration::from_secs(1)); // Check that the node did not exit due to a custom handler. let maybe_status = child.try_wait().expect("Failed to query child exit status"); if let Some(status) = maybe_status { panic!( "Node exited unexpectedly with this exit status: {:?}", status ); } } if let Some(http_port) = http_port { // Check that the HTTP server is still functional by querying the Rust runtime. let url = format!( "http://127.0.0.1:{}/api/runtimes/rust/proto-sources?type=core", http_port ); let response = reqwest::blocking::get(&url).unwrap(); assert!(response.status().is_success(), "{:?}", response); } // Send the third signal. The node should now exit. kill(pid, Signal::SIGTERM).unwrap(); check_child_exit(child, output); } async fn start_node_without_signals(start_port: u16, with_http: bool) { let mut options = Options { disable_signals: true, ..Default::default() }; if with_http { options.http_start_port = Some(start_port + 1); } let (mut nodes, _) = run_nodes(1, start_port, options); let node = nodes.pop().unwrap(); // Register a SIGTERM handler that terminates the node after several signals are received. let mut signal = SignalStream::new(signal(SignalKind::terminate()).unwrap()).skip(2); let shutdown_handle = node.shutdown_handle(); tokio::spawn(async move { signal.next().await; println!("Shutting down node handler"); shutdown_handle.shutdown().await.unwrap(); }); node.run().await } #[test] fn interrupt_node_without_http()
#[test] fn interrupt_node_with_http() { fork( "interrupt_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGINT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_460, true)); }, ) .unwrap(); } #[test] fn terminate_node_without_http() { fork( "terminate_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGTERM), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_470, false)); }, ) .unwrap(); } #[test] fn terminate_node_with_http() { fork( "terminate_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGTERM), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_480, true)); }, ) .unwrap(); } #[test] fn quit_node_without_http() { fork( "quit_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGQUIT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_490, false)); }, ) .unwrap(); } #[test] fn quit_node_with_http() { fork( "quit_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGQUIT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_500, true)); }, ) .unwrap(); } #[test] fn term_node_with_custom_handling_and_http() { fork( "term_node_with_custom_handling_and_http", rusty_fork_id!(), |_| {}, |child, output| check_child_with_custom_handler(child, output, Some(16_511)), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node_without_signals(16_510, true)); }, ) .unwrap(); } #[test] fn term_node_with_custom_handling_and_no_http() { fork( "term_node_with_custom_handling_and_no_http", rusty_fork_id!(), |_| {}, |child, output| check_child_with_custom_handler(child, output, None), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node_without_signals(16_520, false)); }, ) .unwrap(); }
{ fork( "interrupt_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGINT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_450, false)); }, ) .unwrap(); }
identifier_body
signals.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Tests related to signal handling by the nodes. // cspell:ignore unistd #![cfg(unix)] use futures::StreamExt; use nix::{ sys::signal::{kill, Signal}, unistd::Pid, }; use rusty_fork::{fork, rusty_fork_id, ChildWrapper}; use tokio::{ runtime::Runtime, signal::unix::{signal, SignalKind}, }; use tokio_stream::wrappers::SignalStream; use std::{ env, fs::File, io::{BufRead, BufReader, Seek, SeekFrom}, thread, time::Duration, }; pub mod common; use crate::common::{run_nodes, Options}; fn check_child_start(child: &mut ChildWrapper) { let maybe_status = child .wait_timeout(Duration::from_secs(5)) .expect("Failed to wait for node to function"); if let Some(status) = maybe_status { panic!( "Node exited unexpectedly with this exit status: {:?}", status ); } } fn check_child_exit(child: &mut ChildWrapper, output: &mut File) { // Check that the child has exited. let exit_status = child .wait_timeout(Duration::from_secs(2)) .expect("Failed to wait for node exit") .unwrap_or_else(|| { child.kill().ok(); panic!("Node did not exit in 2 secs after being sent the signal"); }); assert!( exit_status.success(), "Node exited with unexpected status: {:?}", exit_status ); output.seek(SeekFrom::Start(0)).unwrap(); let reader = BufReader::new(&*output); for line in reader.lines().flatten() { if line.contains("Shutting down node handler") { return; } } panic!("Node did not shut down properly"); } fn check_child(child: &mut ChildWrapper, output: &mut File, signal: Signal) { // Sleep several seconds in order for the node to launch. check_child_start(child); // Send a signal to the node. let pid = Pid::from_raw(child.id() as i32); kill(pid, signal).unwrap(); // Check that the child has exited. check_child_exit(child, output); } async fn start_node(start_port: u16, with_http: bool) { // Enable logs in order to check that the node shuts down properly. env::set_var("RUST_LOG", "exonum_node=info"); exonum::helpers::init_logger().ok(); let mut options = Options::default(); if with_http
let (mut nodes, _) = run_nodes(1, start_port, options); let node = nodes.pop().unwrap(); node.run().await } fn check_child_with_custom_handler( child: &mut ChildWrapper, output: &mut File, http_port: Option<u16>, ) { // Sleep several seconds in order for the node to launch. check_child_start(child); // Send a signal to the node. let pid = Pid::from_raw(child.id() as i32); for _ in 0..2 { kill(pid, Signal::SIGTERM).unwrap(); thread::sleep(Duration::from_secs(1)); // Check that the node did not exit due to a custom handler. let maybe_status = child.try_wait().expect("Failed to query child exit status"); if let Some(status) = maybe_status { panic!( "Node exited unexpectedly with this exit status: {:?}", status ); } } if let Some(http_port) = http_port { // Check that the HTTP server is still functional by querying the Rust runtime. let url = format!( "http://127.0.0.1:{}/api/runtimes/rust/proto-sources?type=core", http_port ); let response = reqwest::blocking::get(&url).unwrap(); assert!(response.status().is_success(), "{:?}", response); } // Send the third signal. The node should now exit. kill(pid, Signal::SIGTERM).unwrap(); check_child_exit(child, output); } async fn start_node_without_signals(start_port: u16, with_http: bool) { let mut options = Options { disable_signals: true, ..Default::default() }; if with_http { options.http_start_port = Some(start_port + 1); } let (mut nodes, _) = run_nodes(1, start_port, options); let node = nodes.pop().unwrap(); // Register a SIGTERM handler that terminates the node after several signals are received. let mut signal = SignalStream::new(signal(SignalKind::terminate()).unwrap()).skip(2); let shutdown_handle = node.shutdown_handle(); tokio::spawn(async move { signal.next().await; println!("Shutting down node handler"); shutdown_handle.shutdown().await.unwrap(); }); node.run().await } #[test] fn interrupt_node_without_http() { fork( "interrupt_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGINT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_450, false)); }, ) .unwrap(); } #[test] fn interrupt_node_with_http() { fork( "interrupt_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGINT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_460, true)); }, ) .unwrap(); } #[test] fn terminate_node_without_http() { fork( "terminate_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGTERM), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_470, false)); }, ) .unwrap(); } #[test] fn terminate_node_with_http() { fork( "terminate_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGTERM), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_480, true)); }, ) .unwrap(); } #[test] fn quit_node_without_http() { fork( "quit_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGQUIT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_490, false)); }, ) .unwrap(); } #[test] fn quit_node_with_http() { fork( "quit_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGQUIT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_500, true)); }, ) .unwrap(); } #[test] fn term_node_with_custom_handling_and_http() { fork( "term_node_with_custom_handling_and_http", rusty_fork_id!(), |_| {}, |child, output| check_child_with_custom_handler(child, output, Some(16_511)), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node_without_signals(16_510, true)); }, ) .unwrap(); } #[test] fn term_node_with_custom_handling_and_no_http() { fork( "term_node_with_custom_handling_and_no_http", rusty_fork_id!(), |_| {}, |child, output| check_child_with_custom_handler(child, output, None), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node_without_signals(16_520, false)); }, ) .unwrap(); }
{ options.http_start_port = Some(start_port + 1); }
conditional_block
signals.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Tests related to signal handling by the nodes. // cspell:ignore unistd #![cfg(unix)] use futures::StreamExt; use nix::{ sys::signal::{kill, Signal}, unistd::Pid, }; use rusty_fork::{fork, rusty_fork_id, ChildWrapper}; use tokio::{ runtime::Runtime, signal::unix::{signal, SignalKind}, }; use tokio_stream::wrappers::SignalStream; use std::{ env, fs::File, io::{BufRead, BufReader, Seek, SeekFrom}, thread, time::Duration, }; pub mod common; use crate::common::{run_nodes, Options};
.wait_timeout(Duration::from_secs(5)) .expect("Failed to wait for node to function"); if let Some(status) = maybe_status { panic!( "Node exited unexpectedly with this exit status: {:?}", status ); } } fn check_child_exit(child: &mut ChildWrapper, output: &mut File) { // Check that the child has exited. let exit_status = child .wait_timeout(Duration::from_secs(2)) .expect("Failed to wait for node exit") .unwrap_or_else(|| { child.kill().ok(); panic!("Node did not exit in 2 secs after being sent the signal"); }); assert!( exit_status.success(), "Node exited with unexpected status: {:?}", exit_status ); output.seek(SeekFrom::Start(0)).unwrap(); let reader = BufReader::new(&*output); for line in reader.lines().flatten() { if line.contains("Shutting down node handler") { return; } } panic!("Node did not shut down properly"); } fn check_child(child: &mut ChildWrapper, output: &mut File, signal: Signal) { // Sleep several seconds in order for the node to launch. check_child_start(child); // Send a signal to the node. let pid = Pid::from_raw(child.id() as i32); kill(pid, signal).unwrap(); // Check that the child has exited. check_child_exit(child, output); } async fn start_node(start_port: u16, with_http: bool) { // Enable logs in order to check that the node shuts down properly. env::set_var("RUST_LOG", "exonum_node=info"); exonum::helpers::init_logger().ok(); let mut options = Options::default(); if with_http { options.http_start_port = Some(start_port + 1); } let (mut nodes, _) = run_nodes(1, start_port, options); let node = nodes.pop().unwrap(); node.run().await } fn check_child_with_custom_handler( child: &mut ChildWrapper, output: &mut File, http_port: Option<u16>, ) { // Sleep several seconds in order for the node to launch. check_child_start(child); // Send a signal to the node. let pid = Pid::from_raw(child.id() as i32); for _ in 0..2 { kill(pid, Signal::SIGTERM).unwrap(); thread::sleep(Duration::from_secs(1)); // Check that the node did not exit due to a custom handler. let maybe_status = child.try_wait().expect("Failed to query child exit status"); if let Some(status) = maybe_status { panic!( "Node exited unexpectedly with this exit status: {:?}", status ); } } if let Some(http_port) = http_port { // Check that the HTTP server is still functional by querying the Rust runtime. let url = format!( "http://127.0.0.1:{}/api/runtimes/rust/proto-sources?type=core", http_port ); let response = reqwest::blocking::get(&url).unwrap(); assert!(response.status().is_success(), "{:?}", response); } // Send the third signal. The node should now exit. kill(pid, Signal::SIGTERM).unwrap(); check_child_exit(child, output); } async fn start_node_without_signals(start_port: u16, with_http: bool) { let mut options = Options { disable_signals: true, ..Default::default() }; if with_http { options.http_start_port = Some(start_port + 1); } let (mut nodes, _) = run_nodes(1, start_port, options); let node = nodes.pop().unwrap(); // Register a SIGTERM handler that terminates the node after several signals are received. let mut signal = SignalStream::new(signal(SignalKind::terminate()).unwrap()).skip(2); let shutdown_handle = node.shutdown_handle(); tokio::spawn(async move { signal.next().await; println!("Shutting down node handler"); shutdown_handle.shutdown().await.unwrap(); }); node.run().await } #[test] fn interrupt_node_without_http() { fork( "interrupt_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGINT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_450, false)); }, ) .unwrap(); } #[test] fn interrupt_node_with_http() { fork( "interrupt_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGINT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_460, true)); }, ) .unwrap(); } #[test] fn terminate_node_without_http() { fork( "terminate_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGTERM), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_470, false)); }, ) .unwrap(); } #[test] fn terminate_node_with_http() { fork( "terminate_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGTERM), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_480, true)); }, ) .unwrap(); } #[test] fn quit_node_without_http() { fork( "quit_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGQUIT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_490, false)); }, ) .unwrap(); } #[test] fn quit_node_with_http() { fork( "quit_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGQUIT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_500, true)); }, ) .unwrap(); } #[test] fn term_node_with_custom_handling_and_http() { fork( "term_node_with_custom_handling_and_http", rusty_fork_id!(), |_| {}, |child, output| check_child_with_custom_handler(child, output, Some(16_511)), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node_without_signals(16_510, true)); }, ) .unwrap(); } #[test] fn term_node_with_custom_handling_and_no_http() { fork( "term_node_with_custom_handling_and_no_http", rusty_fork_id!(), |_| {}, |child, output| check_child_with_custom_handler(child, output, None), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node_without_signals(16_520, false)); }, ) .unwrap(); }
fn check_child_start(child: &mut ChildWrapper) { let maybe_status = child
random_line_split
signals.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Tests related to signal handling by the nodes. // cspell:ignore unistd #![cfg(unix)] use futures::StreamExt; use nix::{ sys::signal::{kill, Signal}, unistd::Pid, }; use rusty_fork::{fork, rusty_fork_id, ChildWrapper}; use tokio::{ runtime::Runtime, signal::unix::{signal, SignalKind}, }; use tokio_stream::wrappers::SignalStream; use std::{ env, fs::File, io::{BufRead, BufReader, Seek, SeekFrom}, thread, time::Duration, }; pub mod common; use crate::common::{run_nodes, Options}; fn check_child_start(child: &mut ChildWrapper) { let maybe_status = child .wait_timeout(Duration::from_secs(5)) .expect("Failed to wait for node to function"); if let Some(status) = maybe_status { panic!( "Node exited unexpectedly with this exit status: {:?}", status ); } } fn check_child_exit(child: &mut ChildWrapper, output: &mut File) { // Check that the child has exited. let exit_status = child .wait_timeout(Duration::from_secs(2)) .expect("Failed to wait for node exit") .unwrap_or_else(|| { child.kill().ok(); panic!("Node did not exit in 2 secs after being sent the signal"); }); assert!( exit_status.success(), "Node exited with unexpected status: {:?}", exit_status ); output.seek(SeekFrom::Start(0)).unwrap(); let reader = BufReader::new(&*output); for line in reader.lines().flatten() { if line.contains("Shutting down node handler") { return; } } panic!("Node did not shut down properly"); } fn check_child(child: &mut ChildWrapper, output: &mut File, signal: Signal) { // Sleep several seconds in order for the node to launch. check_child_start(child); // Send a signal to the node. let pid = Pid::from_raw(child.id() as i32); kill(pid, signal).unwrap(); // Check that the child has exited. check_child_exit(child, output); } async fn start_node(start_port: u16, with_http: bool) { // Enable logs in order to check that the node shuts down properly. env::set_var("RUST_LOG", "exonum_node=info"); exonum::helpers::init_logger().ok(); let mut options = Options::default(); if with_http { options.http_start_port = Some(start_port + 1); } let (mut nodes, _) = run_nodes(1, start_port, options); let node = nodes.pop().unwrap(); node.run().await } fn check_child_with_custom_handler( child: &mut ChildWrapper, output: &mut File, http_port: Option<u16>, ) { // Sleep several seconds in order for the node to launch. check_child_start(child); // Send a signal to the node. let pid = Pid::from_raw(child.id() as i32); for _ in 0..2 { kill(pid, Signal::SIGTERM).unwrap(); thread::sleep(Duration::from_secs(1)); // Check that the node did not exit due to a custom handler. let maybe_status = child.try_wait().expect("Failed to query child exit status"); if let Some(status) = maybe_status { panic!( "Node exited unexpectedly with this exit status: {:?}", status ); } } if let Some(http_port) = http_port { // Check that the HTTP server is still functional by querying the Rust runtime. let url = format!( "http://127.0.0.1:{}/api/runtimes/rust/proto-sources?type=core", http_port ); let response = reqwest::blocking::get(&url).unwrap(); assert!(response.status().is_success(), "{:?}", response); } // Send the third signal. The node should now exit. kill(pid, Signal::SIGTERM).unwrap(); check_child_exit(child, output); } async fn start_node_without_signals(start_port: u16, with_http: bool) { let mut options = Options { disable_signals: true, ..Default::default() }; if with_http { options.http_start_port = Some(start_port + 1); } let (mut nodes, _) = run_nodes(1, start_port, options); let node = nodes.pop().unwrap(); // Register a SIGTERM handler that terminates the node after several signals are received. let mut signal = SignalStream::new(signal(SignalKind::terminate()).unwrap()).skip(2); let shutdown_handle = node.shutdown_handle(); tokio::spawn(async move { signal.next().await; println!("Shutting down node handler"); shutdown_handle.shutdown().await.unwrap(); }); node.run().await } #[test] fn
() { fork( "interrupt_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGINT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_450, false)); }, ) .unwrap(); } #[test] fn interrupt_node_with_http() { fork( "interrupt_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGINT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_460, true)); }, ) .unwrap(); } #[test] fn terminate_node_without_http() { fork( "terminate_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGTERM), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_470, false)); }, ) .unwrap(); } #[test] fn terminate_node_with_http() { fork( "terminate_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGTERM), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_480, true)); }, ) .unwrap(); } #[test] fn quit_node_without_http() { fork( "quit_node_without_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGQUIT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_490, false)); }, ) .unwrap(); } #[test] fn quit_node_with_http() { fork( "quit_node_with_http", rusty_fork_id!(), |_| {}, |child, output| check_child(child, output, Signal::SIGQUIT), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node(16_500, true)); }, ) .unwrap(); } #[test] fn term_node_with_custom_handling_and_http() { fork( "term_node_with_custom_handling_and_http", rusty_fork_id!(), |_| {}, |child, output| check_child_with_custom_handler(child, output, Some(16_511)), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node_without_signals(16_510, true)); }, ) .unwrap(); } #[test] fn term_node_with_custom_handling_and_no_http() { fork( "term_node_with_custom_handling_and_no_http", rusty_fork_id!(), |_| {}, |child, output| check_child_with_custom_handler(child, output, None), || { let runtime = Runtime::new().unwrap(); runtime.block_on(start_node_without_signals(16_520, false)); }, ) .unwrap(); }
interrupt_node_without_http
identifier_name
borrowck-preserve-box-in-field.rs
// ignore-pretty // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// exec-env:RUST_POISON_ON_FREE=1 #![feature(managed_boxes)] fn borrow(x: &int, f: |x: &int|) { let before = *x; f(x); let after = *x; assert_eq!(before, after); } struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(&(*x.f) as *int, &(*b_x) as *int); x = @F {f: ~4}; println!("&*b_x = {:p}", &(*b_x)); assert_eq!(*b_x, 3); assert!(&(*x.f) as *int!= &(*b_x) as *int); }) }
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
borrowck-preserve-box-in-field.rs
// ignore-pretty // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_POISON_ON_FREE=1 #![feature(managed_boxes)] fn borrow(x: &int, f: |x: &int|)
struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(&(*x.f) as *int, &(*b_x) as *int); x = @F {f: ~4}; println!("&*b_x = {:p}", &(*b_x)); assert_eq!(*b_x, 3); assert!(&(*x.f) as *int!= &(*b_x) as *int); }) }
{ let before = *x; f(x); let after = *x; assert_eq!(before, after); }
identifier_body
borrowck-preserve-box-in-field.rs
// ignore-pretty // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_POISON_ON_FREE=1 #![feature(managed_boxes)] fn
(x: &int, f: |x: &int|) { let before = *x; f(x); let after = *x; assert_eq!(before, after); } struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(&(*x.f) as *int, &(*b_x) as *int); x = @F {f: ~4}; println!("&*b_x = {:p}", &(*b_x)); assert_eq!(*b_x, 3); assert!(&(*x.f) as *int!= &(*b_x) as *int); }) }
borrow
identifier_name
combine.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. /////////////////////////////////////////////////////////////////////////// // # Type combining // // There are four type combiners: equate, sub, lub, and glb. Each // implements the trait `Combine` and contains methods for combining // two instances of various things and yielding a new instance. These // combiner methods always yield a `Result<T>`. There is a lot of // common code for these operations, implemented as default methods on // the `Combine` trait. // // Each operation may have side-effects on the inference context, // though these can be unrolled using snapshots. On success, the // LUB/GLB operations return the appropriate bound. The Eq and Sub // operations generally return the first operand. // // ## Contravariance // // When you are relating two things which have a contravariant // relationship, you should use `contratys()` or `contraregions()`, // rather than inversing the order of arguments! This is necessary // because the order of arguments is not relevant for LUB and GLB. It // is also useful to track which value is the "expected" value in // terms of error reporting. use super::bivariate::Bivariate; use super::equate::Equate; use super::glb::Glb; use super::lub::Lub; use super::sub::Sub; use super::{InferCtxt}; use super::{MiscVariable, TypeTrace}; use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf}; use middle::ty::{TyVar}; use middle::ty::{IntType, UintType}; use middle::ty::{self, Ty, TypeError}; use middle::ty_fold; use middle::ty_fold::{TypeFolder, TypeFoldable}; use middle::ty_relate::{self, Relate, RelateResult, TypeRelation}; use syntax::ast; use syntax::codemap::Span; #[derive(Clone)] pub struct CombineFields<'a, 'tcx: 'a> { pub infcx: &'a InferCtxt<'a, 'tcx>, pub a_is_expected: bool, pub trace: TypeTrace<'tcx>, pub cause: Option<ty_relate::Cause>, } pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>, relation: &mut R, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> where R: TypeRelation<'a,'tcx> { let a_is_expected = relation.a_is_expected(); match (&a.sty, &b.sty) { // Relate integral variables to other types (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => { try!(infcx.int_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| int_unification_error(a_is_expected, e))); Ok(a) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, IntType(v)) } (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, IntType(v)) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, UintType(v)) } (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, UintType(v)) } // Relate floating-point variables to other types (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => { try!(infcx.float_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| float_unification_error(relation.a_is_expected(), e))); Ok(a) } (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => { unify_float_variable(infcx, a_is_expected, v_id, v) } (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => { unify_float_variable(infcx,!a_is_expected, v_id, v) } // All other cases of inference are errors (&ty::TyInfer(_), _) | (_, &ty::TyInfer(_)) => { Err(TypeError::Sorts(ty_relate::expected_found(relation, &a, &b))) } _ => { ty_relate::super_relate_tys(relation, a, b) } } } fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::IntVid, val: ty::IntVarValue) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .int_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| int_unification_error(vid_is_expected, e))); match val { IntType(v) => Ok(infcx.tcx.mk_mach_int(v)), UintType(v) => Ok(infcx.tcx.mk_mach_uint(v)), } } fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::FloatVid, val: ast::FloatTy) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .float_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| float_unification_error(vid_is_expected, e))); Ok(infcx.tcx.mk_mach_float(val)) } impl<'a, 'tcx> CombineFields<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.infcx.tcx } pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> { CombineFields { a_is_expected:!self.a_is_expected, ..(*self).clone() } } pub fn equate(&self) -> Equate<'a, 'tcx> { Equate::new(self.clone()) } pub fn bivariate(&self) -> Bivariate<'a, 'tcx> { Bivariate::new(self.clone()) } pub fn sub(&self) -> Sub<'a, 'tcx> { Sub::new(self.clone()) } pub fn lub(&self) -> Lub<'a, 'tcx> { Lub::new(self.clone()) } pub fn glb(&self) -> Glb<'a, 'tcx> { Glb::new(self.clone()) } pub fn instantiate(&self, a_ty: Ty<'tcx>, dir: RelationDir, b_vid: ty::TyVid) -> RelateResult<'tcx, ()> { let mut stack = Vec::new(); stack.push((a_ty, dir, b_vid)); loop { // For each turn of the loop, we extract a tuple // // (a_ty, dir, b_vid) // // to relate. Here dir is either SubtypeOf or // SupertypeOf. The idea is that we should ensure that // the type `a_ty` is a subtype or supertype (respectively) of the // type to which `b_vid` is bound. // // If `b_vid` has not yet been instantiated with a type // (which is always true on the first iteration, but not // necessarily true on later iterations), we will first // instantiate `b_vid` with a *generalized* version of // `a_ty`. Generalization introduces other inference // variables wherever subtyping could occur (at time of // this writing, this means replacing free regions with // region variables). let (a_ty, dir, b_vid) = match stack.pop() { None => break, Some(e) => e, }; debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid); // Check whether `vid` has been instantiated yet. If not, // make a generalized form of `ty` and instantiate with // that. let b_ty = self.infcx.type_variables.borrow().probe(b_vid); let b_ty = match b_ty { Some(t) => t, //...already instantiated. None => { //...not yet instantiated: // Generalize type if necessary. let generalized_ty = try!(match dir { EqTo => self.generalize(a_ty, b_vid, false), BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true), }); debug!("instantiate(a_ty={:?}, dir={:?}, \ b_vid={:?}, generalized_ty={:?})", a_ty, dir, b_vid, generalized_ty); self.infcx.type_variables .borrow_mut() .instantiate_and_push( b_vid, generalized_ty, &mut stack); generalized_ty } }; // The original triple was `(a_ty, dir, b_vid)` -- now we have // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`: // // FIXME(#16847): This code is non-ideal because all these subtype // relations wind up attributed to the same spans. We need // to associate causes/spans with each of the relations in // the stack to get this right. try!(match dir { BiTo => self.bivariate().relate(&a_ty, &b_ty), EqTo => self.equate().relate(&a_ty, &b_ty), SubtypeOf => self.sub().relate(&a_ty, &b_ty), SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty), }); } Ok(()) } /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok` /// otherwise. fn generalize(&self, ty: Ty<'tcx>, for_vid: ty::TyVid, make_region_vars: bool) -> RelateResult<'tcx, Ty<'tcx>> { let mut generalize = Generalizer { infcx: self.infcx, span: self.trace.origin.span(), for_vid: for_vid, make_region_vars: make_region_vars, cycle_detected: false }; let u = ty.fold_with(&mut generalize); if generalize.cycle_detected { Err(TypeError::CyclicTy) } else { Ok(u) } } } struct Generalizer<'cx, 'tcx:'cx> { infcx: &'cx InferCtxt<'cx, 'tcx>, span: Span, for_vid: ty::TyVid, make_region_vars: bool, cycle_detected: bool, } impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { // Check to see whether the type we are genealizing references // `vid`. At the same time, also update any type variables to // the values that they are bound to. This is needed to truly // check for cycles, but also just makes things readable. // // (In particular, you could have something like `$0 = Box<$1>` // where `$1` has already been instantiated with `Box<$0>`) match t.sty { ty::TyInfer(ty::TyVar(vid)) => { if vid == self.for_vid { self.cycle_detected = true; self.tcx().types.err } else { match self.infcx.type_variables.borrow().probe(vid) { Some(u) => self.fold_ty(u), None => t, } } } _ => { ty_fold::super_fold_ty(self, t) } } } fn
(&mut self, r: ty::Region) -> ty::Region { match r { // Never make variables for regions bound within the type itself. ty::ReLateBound(..) => { return r; } // Early-bound regions should really have been substituted away before // we get to this point. ty::ReEarlyBound(..) => { self.tcx().sess.span_bug( self.span, &format!("Encountered early bound region when generalizing: {:?}", r)); } // Always make a fresh region variable for skolemized regions; // the higher-ranked decision procedures rely on this. ty::ReInfer(ty::ReSkolemized(..)) => { } // For anything else, we make a region variable, unless we // are *equating*, in which case it's just wasteful. ty::ReEmpty | ty::ReStatic | ty::ReScope(..) | ty::ReInfer(ty::ReVar(..)) | ty::ReFree(..) => { if!self.make_region_vars { return r; } } } // FIXME: This is non-ideal because we don't give a // very descriptive origin for this region variable. self.infcx.next_region_var(MiscVariable(self.span)) } } pub trait RelateResultCompare<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::TypeError<'tcx>; } impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::TypeError<'tcx>, { self.clone().and_then(|s| { if s == t { self.clone() } else { Err(f()) } }) } } fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue)) -> ty::TypeError<'tcx> { let (a, b) = v; TypeError::IntMismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) } fn float_unification_error<'tcx>(a_is_expected: bool, v: (ast::FloatTy, ast::FloatTy)) -> ty::TypeError<'tcx> { let (a, b) = v; TypeError::FloatMismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) }
fold_region
identifier_name
combine.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. /////////////////////////////////////////////////////////////////////////// // # Type combining // // There are four type combiners: equate, sub, lub, and glb. Each // implements the trait `Combine` and contains methods for combining // two instances of various things and yielding a new instance. These // combiner methods always yield a `Result<T>`. There is a lot of // common code for these operations, implemented as default methods on // the `Combine` trait. // // Each operation may have side-effects on the inference context, // though these can be unrolled using snapshots. On success, the // LUB/GLB operations return the appropriate bound. The Eq and Sub // operations generally return the first operand. // // ## Contravariance // // When you are relating two things which have a contravariant // relationship, you should use `contratys()` or `contraregions()`, // rather than inversing the order of arguments! This is necessary // because the order of arguments is not relevant for LUB and GLB. It // is also useful to track which value is the "expected" value in // terms of error reporting. use super::bivariate::Bivariate; use super::equate::Equate; use super::glb::Glb; use super::lub::Lub; use super::sub::Sub; use super::{InferCtxt}; use super::{MiscVariable, TypeTrace}; use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf}; use middle::ty::{TyVar}; use middle::ty::{IntType, UintType}; use middle::ty::{self, Ty, TypeError}; use middle::ty_fold; use middle::ty_fold::{TypeFolder, TypeFoldable}; use middle::ty_relate::{self, Relate, RelateResult, TypeRelation}; use syntax::ast; use syntax::codemap::Span; #[derive(Clone)] pub struct CombineFields<'a, 'tcx: 'a> { pub infcx: &'a InferCtxt<'a, 'tcx>, pub a_is_expected: bool, pub trace: TypeTrace<'tcx>, pub cause: Option<ty_relate::Cause>, } pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>, relation: &mut R, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> where R: TypeRelation<'a,'tcx> { let a_is_expected = relation.a_is_expected(); match (&a.sty, &b.sty) { // Relate integral variables to other types (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => { try!(infcx.int_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| int_unification_error(a_is_expected, e))); Ok(a) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, IntType(v)) } (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, IntType(v)) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, UintType(v)) } (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, UintType(v)) } // Relate floating-point variables to other types (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => { try!(infcx.float_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| float_unification_error(relation.a_is_expected(), e))); Ok(a) } (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => { unify_float_variable(infcx, a_is_expected, v_id, v) } (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => { unify_float_variable(infcx,!a_is_expected, v_id, v) } // All other cases of inference are errors (&ty::TyInfer(_), _) | (_, &ty::TyInfer(_)) => { Err(TypeError::Sorts(ty_relate::expected_found(relation, &a, &b))) } _ => { ty_relate::super_relate_tys(relation, a, b) } } } fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::IntVid, val: ty::IntVarValue) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .int_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| int_unification_error(vid_is_expected, e))); match val { IntType(v) => Ok(infcx.tcx.mk_mach_int(v)), UintType(v) => Ok(infcx.tcx.mk_mach_uint(v)), } } fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::FloatVid, val: ast::FloatTy) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .float_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| float_unification_error(vid_is_expected, e))); Ok(infcx.tcx.mk_mach_float(val)) } impl<'a, 'tcx> CombineFields<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.infcx.tcx } pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> { CombineFields { a_is_expected:!self.a_is_expected, ..(*self).clone() } } pub fn equate(&self) -> Equate<'a, 'tcx> { Equate::new(self.clone()) } pub fn bivariate(&self) -> Bivariate<'a, 'tcx> { Bivariate::new(self.clone()) } pub fn sub(&self) -> Sub<'a, 'tcx> { Sub::new(self.clone()) } pub fn lub(&self) -> Lub<'a, 'tcx> { Lub::new(self.clone()) } pub fn glb(&self) -> Glb<'a, 'tcx> { Glb::new(self.clone()) } pub fn instantiate(&self, a_ty: Ty<'tcx>, dir: RelationDir, b_vid: ty::TyVid) -> RelateResult<'tcx, ()> { let mut stack = Vec::new(); stack.push((a_ty, dir, b_vid)); loop { // For each turn of the loop, we extract a tuple // // (a_ty, dir, b_vid) // // to relate. Here dir is either SubtypeOf or // SupertypeOf. The idea is that we should ensure that // the type `a_ty` is a subtype or supertype (respectively) of the // type to which `b_vid` is bound. // // If `b_vid` has not yet been instantiated with a type // (which is always true on the first iteration, but not // necessarily true on later iterations), we will first // instantiate `b_vid` with a *generalized* version of // `a_ty`. Generalization introduces other inference // variables wherever subtyping could occur (at time of // this writing, this means replacing free regions with // region variables). let (a_ty, dir, b_vid) = match stack.pop() { None => break, Some(e) => e, }; debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid); // Check whether `vid` has been instantiated yet. If not, // make a generalized form of `ty` and instantiate with // that. let b_ty = self.infcx.type_variables.borrow().probe(b_vid); let b_ty = match b_ty { Some(t) => t, //...already instantiated. None => { //...not yet instantiated: // Generalize type if necessary. let generalized_ty = try!(match dir { EqTo => self.generalize(a_ty, b_vid, false), BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true), }); debug!("instantiate(a_ty={:?}, dir={:?}, \ b_vid={:?}, generalized_ty={:?})", a_ty, dir, b_vid, generalized_ty); self.infcx.type_variables .borrow_mut() .instantiate_and_push( b_vid, generalized_ty, &mut stack); generalized_ty } }; // The original triple was `(a_ty, dir, b_vid)` -- now we have // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`: // // FIXME(#16847): This code is non-ideal because all these subtype // relations wind up attributed to the same spans. We need // to associate causes/spans with each of the relations in // the stack to get this right. try!(match dir { BiTo => self.bivariate().relate(&a_ty, &b_ty), EqTo => self.equate().relate(&a_ty, &b_ty), SubtypeOf => self.sub().relate(&a_ty, &b_ty), SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty), }); } Ok(()) } /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok` /// otherwise. fn generalize(&self, ty: Ty<'tcx>, for_vid: ty::TyVid, make_region_vars: bool) -> RelateResult<'tcx, Ty<'tcx>> { let mut generalize = Generalizer { infcx: self.infcx, span: self.trace.origin.span(), for_vid: for_vid, make_region_vars: make_region_vars, cycle_detected: false }; let u = ty.fold_with(&mut generalize); if generalize.cycle_detected { Err(TypeError::CyclicTy) } else { Ok(u) } } } struct Generalizer<'cx, 'tcx:'cx> { infcx: &'cx InferCtxt<'cx, 'tcx>, span: Span, for_vid: ty::TyVid, make_region_vars: bool, cycle_detected: bool, } impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx>
_ => { ty_fold::super_fold_ty(self, t) } } } fn fold_region(&mut self, r: ty::Region) -> ty::Region { match r { // Never make variables for regions bound within the type itself. ty::ReLateBound(..) => { return r; } // Early-bound regions should really have been substituted away before // we get to this point. ty::ReEarlyBound(..) => { self.tcx().sess.span_bug( self.span, &format!("Encountered early bound region when generalizing: {:?}", r)); } // Always make a fresh region variable for skolemized regions; // the higher-ranked decision procedures rely on this. ty::ReInfer(ty::ReSkolemized(..)) => { } // For anything else, we make a region variable, unless we // are *equating*, in which case it's just wasteful. ty::ReEmpty | ty::ReStatic | ty::ReScope(..) | ty::ReInfer(ty::ReVar(..)) | ty::ReFree(..) => { if!self.make_region_vars { return r; } } } // FIXME: This is non-ideal because we don't give a // very descriptive origin for this region variable. self.infcx.next_region_var(MiscVariable(self.span)) } } pub trait RelateResultCompare<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::TypeError<'tcx>; } impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::TypeError<'tcx>, { self.clone().and_then(|s| { if s == t { self.clone() } else { Err(f()) } }) } } fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue)) -> ty::TypeError<'tcx> { let (a, b) = v; TypeError::IntMismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) } fn float_unification_error<'tcx>(a_is_expected: bool, v: (ast::FloatTy, ast::FloatTy)) -> ty::TypeError<'tcx> { let (a, b) = v; TypeError::FloatMismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) }
{ // Check to see whether the type we are genealizing references // `vid`. At the same time, also update any type variables to // the values that they are bound to. This is needed to truly // check for cycles, but also just makes things readable. // // (In particular, you could have something like `$0 = Box<$1>` // where `$1` has already been instantiated with `Box<$0>`) match t.sty { ty::TyInfer(ty::TyVar(vid)) => { if vid == self.for_vid { self.cycle_detected = true; self.tcx().types.err } else { match self.infcx.type_variables.borrow().probe(vid) { Some(u) => self.fold_ty(u), None => t, } } }
identifier_body
combine.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. /////////////////////////////////////////////////////////////////////////// // # Type combining // // There are four type combiners: equate, sub, lub, and glb. Each // implements the trait `Combine` and contains methods for combining // two instances of various things and yielding a new instance. These // combiner methods always yield a `Result<T>`. There is a lot of // common code for these operations, implemented as default methods on // the `Combine` trait. // // Each operation may have side-effects on the inference context, // though these can be unrolled using snapshots. On success, the // LUB/GLB operations return the appropriate bound. The Eq and Sub // operations generally return the first operand. // // ## Contravariance // // When you are relating two things which have a contravariant // relationship, you should use `contratys()` or `contraregions()`, // rather than inversing the order of arguments! This is necessary // because the order of arguments is not relevant for LUB and GLB. It // is also useful to track which value is the "expected" value in // terms of error reporting. use super::bivariate::Bivariate; use super::equate::Equate; use super::glb::Glb; use super::lub::Lub; use super::sub::Sub; use super::{InferCtxt}; use super::{MiscVariable, TypeTrace}; use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf}; use middle::ty::{TyVar}; use middle::ty::{IntType, UintType}; use middle::ty::{self, Ty, TypeError}; use middle::ty_fold; use middle::ty_fold::{TypeFolder, TypeFoldable}; use middle::ty_relate::{self, Relate, RelateResult, TypeRelation}; use syntax::ast; use syntax::codemap::Span; #[derive(Clone)] pub struct CombineFields<'a, 'tcx: 'a> { pub infcx: &'a InferCtxt<'a, 'tcx>, pub a_is_expected: bool, pub trace: TypeTrace<'tcx>, pub cause: Option<ty_relate::Cause>, } pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>, relation: &mut R, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> where R: TypeRelation<'a,'tcx> { let a_is_expected = relation.a_is_expected(); match (&a.sty, &b.sty) { // Relate integral variables to other types (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => { try!(infcx.int_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| int_unification_error(a_is_expected, e))); Ok(a) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, IntType(v)) } (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, IntType(v)) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, UintType(v)) } (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, UintType(v)) } // Relate floating-point variables to other types (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => { try!(infcx.float_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| float_unification_error(relation.a_is_expected(), e))); Ok(a) } (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => { unify_float_variable(infcx, a_is_expected, v_id, v) } (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => { unify_float_variable(infcx,!a_is_expected, v_id, v) } // All other cases of inference are errors (&ty::TyInfer(_), _) | (_, &ty::TyInfer(_)) => { Err(TypeError::Sorts(ty_relate::expected_found(relation, &a, &b))) } _ => { ty_relate::super_relate_tys(relation, a, b) } } } fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::IntVid, val: ty::IntVarValue) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .int_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| int_unification_error(vid_is_expected, e))); match val { IntType(v) => Ok(infcx.tcx.mk_mach_int(v)), UintType(v) => Ok(infcx.tcx.mk_mach_uint(v)), } } fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::FloatVid, val: ast::FloatTy) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .float_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| float_unification_error(vid_is_expected, e))); Ok(infcx.tcx.mk_mach_float(val)) } impl<'a, 'tcx> CombineFields<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.infcx.tcx } pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> { CombineFields { a_is_expected:!self.a_is_expected, ..(*self).clone() } } pub fn equate(&self) -> Equate<'a, 'tcx> { Equate::new(self.clone()) } pub fn bivariate(&self) -> Bivariate<'a, 'tcx> { Bivariate::new(self.clone()) } pub fn sub(&self) -> Sub<'a, 'tcx> { Sub::new(self.clone()) } pub fn lub(&self) -> Lub<'a, 'tcx> { Lub::new(self.clone()) } pub fn glb(&self) -> Glb<'a, 'tcx> { Glb::new(self.clone()) } pub fn instantiate(&self, a_ty: Ty<'tcx>, dir: RelationDir, b_vid: ty::TyVid) -> RelateResult<'tcx, ()> { let mut stack = Vec::new(); stack.push((a_ty, dir, b_vid)); loop { // For each turn of the loop, we extract a tuple // // (a_ty, dir, b_vid) // // to relate. Here dir is either SubtypeOf or // SupertypeOf. The idea is that we should ensure that // the type `a_ty` is a subtype or supertype (respectively) of the // type to which `b_vid` is bound. // // If `b_vid` has not yet been instantiated with a type // (which is always true on the first iteration, but not // necessarily true on later iterations), we will first // instantiate `b_vid` with a *generalized* version of // `a_ty`. Generalization introduces other inference // variables wherever subtyping could occur (at time of // this writing, this means replacing free regions with // region variables). let (a_ty, dir, b_vid) = match stack.pop() { None => break, Some(e) => e, }; debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid); // Check whether `vid` has been instantiated yet. If not, // make a generalized form of `ty` and instantiate with // that. let b_ty = self.infcx.type_variables.borrow().probe(b_vid); let b_ty = match b_ty { Some(t) => t, //...already instantiated. None => { //...not yet instantiated: // Generalize type if necessary. let generalized_ty = try!(match dir { EqTo => self.generalize(a_ty, b_vid, false), BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true), }); debug!("instantiate(a_ty={:?}, dir={:?}, \ b_vid={:?}, generalized_ty={:?})", a_ty, dir, b_vid, generalized_ty); self.infcx.type_variables .borrow_mut() .instantiate_and_push( b_vid, generalized_ty, &mut stack); generalized_ty } }; // The original triple was `(a_ty, dir, b_vid)` -- now we have // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`: // // FIXME(#16847): This code is non-ideal because all these subtype // relations wind up attributed to the same spans. We need // to associate causes/spans with each of the relations in // the stack to get this right. try!(match dir { BiTo => self.bivariate().relate(&a_ty, &b_ty), EqTo => self.equate().relate(&a_ty, &b_ty), SubtypeOf => self.sub().relate(&a_ty, &b_ty), SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty), }); } Ok(()) } /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok` /// otherwise. fn generalize(&self, ty: Ty<'tcx>, for_vid: ty::TyVid, make_region_vars: bool) -> RelateResult<'tcx, Ty<'tcx>> { let mut generalize = Generalizer { infcx: self.infcx, span: self.trace.origin.span(), for_vid: for_vid, make_region_vars: make_region_vars, cycle_detected: false }; let u = ty.fold_with(&mut generalize); if generalize.cycle_detected { Err(TypeError::CyclicTy) } else { Ok(u) } } } struct Generalizer<'cx, 'tcx:'cx> { infcx: &'cx InferCtxt<'cx, 'tcx>, span: Span, for_vid: ty::TyVid, make_region_vars: bool, cycle_detected: bool, } impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { // Check to see whether the type we are genealizing references // `vid`. At the same time, also update any type variables to // the values that they are bound to. This is needed to truly // check for cycles, but also just makes things readable. // // (In particular, you could have something like `$0 = Box<$1>` // where `$1` has already been instantiated with `Box<$0>`) match t.sty { ty::TyInfer(ty::TyVar(vid)) => { if vid == self.for_vid { self.cycle_detected = true; self.tcx().types.err } else { match self.infcx.type_variables.borrow().probe(vid) { Some(u) => self.fold_ty(u), None => t, } } } _ => { ty_fold::super_fold_ty(self, t) } } } fn fold_region(&mut self, r: ty::Region) -> ty::Region { match r { // Never make variables for regions bound within the type itself. ty::ReLateBound(..) => { return r; } // Early-bound regions should really have been substituted away before // we get to this point. ty::ReEarlyBound(..) => { self.tcx().sess.span_bug( self.span, &format!("Encountered early bound region when generalizing: {:?}", r)); } // Always make a fresh region variable for skolemized regions; // the higher-ranked decision procedures rely on this. ty::ReInfer(ty::ReSkolemized(..)) => { } // For anything else, we make a region variable, unless we // are *equating*, in which case it's just wasteful. ty::ReEmpty | ty::ReStatic | ty::ReScope(..) | ty::ReInfer(ty::ReVar(..)) | ty::ReFree(..) => { if!self.make_region_vars { return r; } } } // FIXME: This is non-ideal because we don't give a // very descriptive origin for this region variable. self.infcx.next_region_var(MiscVariable(self.span)) } } pub trait RelateResultCompare<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::TypeError<'tcx>; } impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
self.clone().and_then(|s| { if s == t { self.clone() } else { Err(f()) } }) } } fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue)) -> ty::TypeError<'tcx> { let (a, b) = v; TypeError::IntMismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) } fn float_unification_error<'tcx>(a_is_expected: bool, v: (ast::FloatTy, ast::FloatTy)) -> ty::TypeError<'tcx> { let (a, b) = v; TypeError::FloatMismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) }
F: FnOnce() -> ty::TypeError<'tcx>, {
random_line_split
ui_helper.rs
use pbr::{MultiBar, Pipe, ProgressBar, Units}; use std::io::Stdout; use std::sync::Mutex; use std::thread; use std::time::Duration; lazy_static! { static ref TOTALS: Mutex<Vec<u64>> = Mutex::new(vec![]); static ref PBRS: Mutex<Vec<ProgressBar<Pipe>>> = Mutex::new(vec![]); } pub fn start_pbr(file_name: &str, lengths: Vec<u64>) { let mut mb = MultiBar::new(); mb.println(&format!("Downloading: {}", file_name)); let total_length = lengths.iter().sum(); build_global_bar(&mut mb, total_length); mb.println(""); for length in lengths { build_child_bar(&mut mb, length); } thread::spawn(move || mb.listen()); } pub fn setting_up_bar(bar_idx: usize) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); pbrs[bar_idx + 1].message("Starting... "); pbrs[bar_idx + 1].tick(); } pub fn start_bar(bar_idx: usize) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); pbrs[bar_idx + 1].message(""); pbrs[bar_idx + 1].show_message = false; pbrs[bar_idx + 1].tick(); } pub fn update_bar(bar_idx: usize, progress: u64) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); let mut totals = TOTALS .lock() .expect("Failed to acquire TOTALS lock, lock poisoned!"); pbrs[bar_idx + 1].set(progress); totals[bar_idx] = progress; let total_progress = totals.iter().sum(); pbrs[0].set(total_progress); } pub fn success_global_bar() { finish_bar_with_message(0, "Download Complete!"); } pub fn success_bar(bar_idx: usize) { finish_bar_with_message(bar_idx + 1, "Download Complete!"); } pub fn fail_bar(bar_idx: usize) { finish_bar_with_message(bar_idx + 1, "Download Failed!"); } fn finish_bar_with_message(act_bar: usize, message: &str) { PBRS.lock() .expect("Failed to acquire PBRS lock, lock poisoned!")[act_bar] .finish_print(message); } fn build_global_bar(mb: &mut MultiBar<Stdout>, size: u64) { build_bar(mb, size, None); } fn build_child_bar(mb: &mut MultiBar<Stdout>, size: u64) { build_bar(mb, size, Some("Pending... ".to_string())); let mut totals = TOTALS .lock() .expect("Failed to acquire TOTALS lock, lock poisoned!"); totals.push(0); } fn build_bar(mb: &mut MultiBar<Stdout>, size: u64, message: Option<String>)
{ let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); let mut pb = mb.create_bar(size); pb.set_max_refresh_rate(Some(Duration::from_millis(200))); pb.tick_format("▏▎▍▌▋▊▉██▉▊▋▌▍▎▏"); pb.set_units(Units::Bytes); if let Some(msg) = message { pb.show_message = true; pb.message(&msg); } else { pb.show_message = false; } pb.tick(); pbrs.push(pb); }
identifier_body
ui_helper.rs
use pbr::{MultiBar, Pipe, ProgressBar, Units}; use std::io::Stdout; use std::sync::Mutex; use std::thread; use std::time::Duration; lazy_static! { static ref TOTALS: Mutex<Vec<u64>> = Mutex::new(vec![]); static ref PBRS: Mutex<Vec<ProgressBar<Pipe>>> = Mutex::new(vec![]); } pub fn start_pbr(file_name: &str, lengths: Vec<u64>) { let mut mb = MultiBar::new(); mb.println(&format!("Downloading: {}", file_name)); let total_length = lengths.iter().sum(); build_global_bar(&mut mb, total_length); mb.println(""); for length in lengths { build_child_bar(&mut mb, length); } thread::spawn(move || mb.listen()); } pub fn setting_up_bar(bar_idx: usize) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); pbrs[bar_idx + 1].message("Starting... "); pbrs[bar_idx + 1].tick(); } pub fn start_bar(bar_idx: usize) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); pbrs[bar_idx + 1].message(""); pbrs[bar_idx + 1].show_message = false; pbrs[bar_idx + 1].tick(); } pub fn update_bar(bar_idx: usize, progress: u64) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); let mut totals = TOTALS .lock() .expect("Failed to acquire TOTALS lock, lock poisoned!"); pbrs[bar_idx + 1].set(progress); totals[bar_idx] = progress; let total_progress = totals.iter().sum(); pbrs[0].set(total_progress); } pub fn success_global_bar() { finish_bar_with_message(0, "Download Complete!"); } pub fn
(bar_idx: usize) { finish_bar_with_message(bar_idx + 1, "Download Complete!"); } pub fn fail_bar(bar_idx: usize) { finish_bar_with_message(bar_idx + 1, "Download Failed!"); } fn finish_bar_with_message(act_bar: usize, message: &str) { PBRS.lock() .expect("Failed to acquire PBRS lock, lock poisoned!")[act_bar] .finish_print(message); } fn build_global_bar(mb: &mut MultiBar<Stdout>, size: u64) { build_bar(mb, size, None); } fn build_child_bar(mb: &mut MultiBar<Stdout>, size: u64) { build_bar(mb, size, Some("Pending... ".to_string())); let mut totals = TOTALS .lock() .expect("Failed to acquire TOTALS lock, lock poisoned!"); totals.push(0); } fn build_bar(mb: &mut MultiBar<Stdout>, size: u64, message: Option<String>) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); let mut pb = mb.create_bar(size); pb.set_max_refresh_rate(Some(Duration::from_millis(200))); pb.tick_format("▏▎▍▌▋▊▉██▉▊▋▌▍▎▏"); pb.set_units(Units::Bytes); if let Some(msg) = message { pb.show_message = true; pb.message(&msg); } else { pb.show_message = false; } pb.tick(); pbrs.push(pb); }
success_bar
identifier_name
ui_helper.rs
use pbr::{MultiBar, Pipe, ProgressBar, Units}; use std::io::Stdout; use std::sync::Mutex; use std::thread; use std::time::Duration; lazy_static! { static ref TOTALS: Mutex<Vec<u64>> = Mutex::new(vec![]); static ref PBRS: Mutex<Vec<ProgressBar<Pipe>>> = Mutex::new(vec![]); } pub fn start_pbr(file_name: &str, lengths: Vec<u64>) { let mut mb = MultiBar::new(); mb.println(&format!("Downloading: {}", file_name)); let total_length = lengths.iter().sum(); build_global_bar(&mut mb, total_length); mb.println(""); for length in lengths { build_child_bar(&mut mb, length); } thread::spawn(move || mb.listen()); } pub fn setting_up_bar(bar_idx: usize) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); pbrs[bar_idx + 1].message("Starting... "); pbrs[bar_idx + 1].tick(); } pub fn start_bar(bar_idx: usize) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); pbrs[bar_idx + 1].message(""); pbrs[bar_idx + 1].show_message = false; pbrs[bar_idx + 1].tick(); } pub fn update_bar(bar_idx: usize, progress: u64) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); let mut totals = TOTALS .lock() .expect("Failed to acquire TOTALS lock, lock poisoned!"); pbrs[bar_idx + 1].set(progress); totals[bar_idx] = progress; let total_progress = totals.iter().sum(); pbrs[0].set(total_progress); } pub fn success_global_bar() { finish_bar_with_message(0, "Download Complete!"); } pub fn success_bar(bar_idx: usize) { finish_bar_with_message(bar_idx + 1, "Download Complete!"); } pub fn fail_bar(bar_idx: usize) { finish_bar_with_message(bar_idx + 1, "Download Failed!"); } fn finish_bar_with_message(act_bar: usize, message: &str) { PBRS.lock() .expect("Failed to acquire PBRS lock, lock poisoned!")[act_bar] .finish_print(message); } fn build_global_bar(mb: &mut MultiBar<Stdout>, size: u64) { build_bar(mb, size, None); } fn build_child_bar(mb: &mut MultiBar<Stdout>, size: u64) { build_bar(mb, size, Some("Pending... ".to_string())); let mut totals = TOTALS .lock() .expect("Failed to acquire TOTALS lock, lock poisoned!"); totals.push(0); } fn build_bar(mb: &mut MultiBar<Stdout>, size: u64, message: Option<String>) { let mut pbrs = PBRS .lock()
.expect("Failed to acquire PBRS lock, lock poisoned!"); let mut pb = mb.create_bar(size); pb.set_max_refresh_rate(Some(Duration::from_millis(200))); pb.tick_format("▏▎▍▌▋▊▉██▉▊▋▌▍▎▏"); pb.set_units(Units::Bytes); if let Some(msg) = message { pb.show_message = true; pb.message(&msg); } else { pb.show_message = false; } pb.tick(); pbrs.push(pb); }
random_line_split
ui_helper.rs
use pbr::{MultiBar, Pipe, ProgressBar, Units}; use std::io::Stdout; use std::sync::Mutex; use std::thread; use std::time::Duration; lazy_static! { static ref TOTALS: Mutex<Vec<u64>> = Mutex::new(vec![]); static ref PBRS: Mutex<Vec<ProgressBar<Pipe>>> = Mutex::new(vec![]); } pub fn start_pbr(file_name: &str, lengths: Vec<u64>) { let mut mb = MultiBar::new(); mb.println(&format!("Downloading: {}", file_name)); let total_length = lengths.iter().sum(); build_global_bar(&mut mb, total_length); mb.println(""); for length in lengths { build_child_bar(&mut mb, length); } thread::spawn(move || mb.listen()); } pub fn setting_up_bar(bar_idx: usize) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); pbrs[bar_idx + 1].message("Starting... "); pbrs[bar_idx + 1].tick(); } pub fn start_bar(bar_idx: usize) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); pbrs[bar_idx + 1].message(""); pbrs[bar_idx + 1].show_message = false; pbrs[bar_idx + 1].tick(); } pub fn update_bar(bar_idx: usize, progress: u64) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); let mut totals = TOTALS .lock() .expect("Failed to acquire TOTALS lock, lock poisoned!"); pbrs[bar_idx + 1].set(progress); totals[bar_idx] = progress; let total_progress = totals.iter().sum(); pbrs[0].set(total_progress); } pub fn success_global_bar() { finish_bar_with_message(0, "Download Complete!"); } pub fn success_bar(bar_idx: usize) { finish_bar_with_message(bar_idx + 1, "Download Complete!"); } pub fn fail_bar(bar_idx: usize) { finish_bar_with_message(bar_idx + 1, "Download Failed!"); } fn finish_bar_with_message(act_bar: usize, message: &str) { PBRS.lock() .expect("Failed to acquire PBRS lock, lock poisoned!")[act_bar] .finish_print(message); } fn build_global_bar(mb: &mut MultiBar<Stdout>, size: u64) { build_bar(mb, size, None); } fn build_child_bar(mb: &mut MultiBar<Stdout>, size: u64) { build_bar(mb, size, Some("Pending... ".to_string())); let mut totals = TOTALS .lock() .expect("Failed to acquire TOTALS lock, lock poisoned!"); totals.push(0); } fn build_bar(mb: &mut MultiBar<Stdout>, size: u64, message: Option<String>) { let mut pbrs = PBRS .lock() .expect("Failed to acquire PBRS lock, lock poisoned!"); let mut pb = mb.create_bar(size); pb.set_max_refresh_rate(Some(Duration::from_millis(200))); pb.tick_format("▏▎▍▌▋▊▉██▉▊▋▌▍▎▏"); pb.set_units(Units::Bytes); if let Some(msg) = message { pb.show_message = true
= false; } pb.tick(); pbrs.push(pb); }
; pb.message(&msg); } else { pb.show_message
conditional_block
static.rs
// Copyright 2018 Kyle Mayes // // 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. extern crate glob; use std::path::{Path, PathBuf}; use glob::Pattern; use common; /// Returns the name of an LLVM or Clang library from a path to such a library. fn get_library_name(path: &Path) -> Option<String> { path.file_stem().map(|p| { let string = p.to_string_lossy(); if let Some(name) = string.strip_prefix("lib") { name.to_owned() } else { string.to_string() } }) } /// Returns the LLVM libraries required to link to `libclang` statically. fn get_llvm_libraries() -> Vec<String> { common::run_llvm_config(&["--libs"]) .unwrap() .split_whitespace() .filter_map(|p| { // Depending on the version of `llvm-config` in use, listed // libraries may be in one of two forms, a full path to the library // or simply prefixed with `-l`. if let Some(path) = p.strip_prefix("-l") { Some(path.into()) } else { get_library_name(Path::new(p)) } }) .collect() } /// Clang libraries required to link to `libclang` 3.5 and later statically. const CLANG_LIBRARIES: &[&str] = &[ "clang", "clangAST", "clangAnalysis", "clangBasic", "clangDriver", "clangEdit", "clangFrontend", "clangIndex", "clangLex", "clangParse", "clangRewrite", "clangSema", "clangSerialization", ]; /// Returns the Clang libraries required to link to `libclang` statically. fn get_clang_libraries<P: AsRef<Path>>(directory: P) -> Vec<String> { // Escape the directory in case it contains characters that have special // meaning in glob patterns (e.g., `[` or `]`). let directory = Pattern::escape(directory.as_ref().to_str().unwrap()); let directory = Path::new(&directory); let pattern = directory.join("libclang*.a").to_str().unwrap().to_owned(); if let Ok(libraries) = glob::glob(&pattern) { libraries .filter_map(|l| l.ok().and_then(|l| get_library_name(&l))) .collect() } else { CLANG_LIBRARIES.iter().map(|l| (*l).to_string()).collect() } } /// Returns a directory containing `libclang` static libraries. fn find() -> PathBuf { let name = if cfg!(target_os = "windows") { "libclang.lib" } else { "libclang.a" }; let files = common::search_libclang_directories(&[name.into()], "LIBCLANG_STATIC_PATH"); if let Some((directory, _)) = files.into_iter().next() { directory } else { panic!("could not find any static libraries"); } } /// Find and link to `libclang` statically. pub fn link()
println!( "cargo:rustc-link-search=native={}", common::run_llvm_config(&["--libdir"]).unwrap().trim_end() ); for library in get_llvm_libraries() { println!("cargo:rustc-link-lib={}{}", prefix, library); } // Specify required system libraries. // MSVC doesn't need this, as it tracks dependencies inside `.lib` files. if cfg!(target_os = "freebsd") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l c++ -l z"); } else if cfg!(target_os = "linux") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l stdc++ -l z"); } else if cfg!(target_os = "macos") { println!("cargo:rustc-flags=-l ffi -l ncurses -l c++ -l z"); } else if cfg!(target_os = "haiku") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l stdc++ -l z"); } cep.discard(); }
{ let cep = common::CommandErrorPrinter::default(); let directory = find(); // Specify required Clang static libraries. println!("cargo:rustc-link-search=native={}", directory.display()); for library in get_clang_libraries(directory) { println!("cargo:rustc-link-lib=static={}", library); } // Determine the shared mode used by LLVM. let mode = common::run_llvm_config(&["--shared-mode"]).map(|m| m.trim().to_owned()); let prefix = if mode.map_or(false, |m| m == "static") { "static=" } else { "" }; // Specify required LLVM static libraries.
identifier_body
static.rs
// Copyright 2018 Kyle Mayes // // 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. extern crate glob; use std::path::{Path, PathBuf}; use glob::Pattern; use common; /// Returns the name of an LLVM or Clang library from a path to such a library. fn get_library_name(path: &Path) -> Option<String> { path.file_stem().map(|p| { let string = p.to_string_lossy(); if let Some(name) = string.strip_prefix("lib") { name.to_owned() } else { string.to_string() } }) } /// Returns the LLVM libraries required to link to `libclang` statically. fn get_llvm_libraries() -> Vec<String> { common::run_llvm_config(&["--libs"]) .unwrap() .split_whitespace() .filter_map(|p| { // Depending on the version of `llvm-config` in use, listed // libraries may be in one of two forms, a full path to the library // or simply prefixed with `-l`. if let Some(path) = p.strip_prefix("-l") { Some(path.into()) } else { get_library_name(Path::new(p)) } }) .collect() } /// Clang libraries required to link to `libclang` 3.5 and later statically. const CLANG_LIBRARIES: &[&str] = &[ "clang", "clangAST", "clangAnalysis", "clangBasic", "clangDriver", "clangEdit", "clangFrontend", "clangIndex", "clangLex", "clangParse", "clangRewrite", "clangSema", "clangSerialization", ]; /// Returns the Clang libraries required to link to `libclang` statically. fn
<P: AsRef<Path>>(directory: P) -> Vec<String> { // Escape the directory in case it contains characters that have special // meaning in glob patterns (e.g., `[` or `]`). let directory = Pattern::escape(directory.as_ref().to_str().unwrap()); let directory = Path::new(&directory); let pattern = directory.join("libclang*.a").to_str().unwrap().to_owned(); if let Ok(libraries) = glob::glob(&pattern) { libraries .filter_map(|l| l.ok().and_then(|l| get_library_name(&l))) .collect() } else { CLANG_LIBRARIES.iter().map(|l| (*l).to_string()).collect() } } /// Returns a directory containing `libclang` static libraries. fn find() -> PathBuf { let name = if cfg!(target_os = "windows") { "libclang.lib" } else { "libclang.a" }; let files = common::search_libclang_directories(&[name.into()], "LIBCLANG_STATIC_PATH"); if let Some((directory, _)) = files.into_iter().next() { directory } else { panic!("could not find any static libraries"); } } /// Find and link to `libclang` statically. pub fn link() { let cep = common::CommandErrorPrinter::default(); let directory = find(); // Specify required Clang static libraries. println!("cargo:rustc-link-search=native={}", directory.display()); for library in get_clang_libraries(directory) { println!("cargo:rustc-link-lib=static={}", library); } // Determine the shared mode used by LLVM. let mode = common::run_llvm_config(&["--shared-mode"]).map(|m| m.trim().to_owned()); let prefix = if mode.map_or(false, |m| m == "static") { "static=" } else { "" }; // Specify required LLVM static libraries. println!( "cargo:rustc-link-search=native={}", common::run_llvm_config(&["--libdir"]).unwrap().trim_end() ); for library in get_llvm_libraries() { println!("cargo:rustc-link-lib={}{}", prefix, library); } // Specify required system libraries. // MSVC doesn't need this, as it tracks dependencies inside `.lib` files. if cfg!(target_os = "freebsd") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l c++ -l z"); } else if cfg!(target_os = "linux") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l stdc++ -l z"); } else if cfg!(target_os = "macos") { println!("cargo:rustc-flags=-l ffi -l ncurses -l c++ -l z"); } else if cfg!(target_os = "haiku") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l stdc++ -l z"); } cep.discard(); }
get_clang_libraries
identifier_name
static.rs
// Copyright 2018 Kyle Mayes // // 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. extern crate glob; use std::path::{Path, PathBuf}; use glob::Pattern; use common; /// Returns the name of an LLVM or Clang library from a path to such a library. fn get_library_name(path: &Path) -> Option<String> { path.file_stem().map(|p| { let string = p.to_string_lossy(); if let Some(name) = string.strip_prefix("lib") { name.to_owned() } else { string.to_string() } }) } /// Returns the LLVM libraries required to link to `libclang` statically. fn get_llvm_libraries() -> Vec<String> { common::run_llvm_config(&["--libs"]) .unwrap() .split_whitespace() .filter_map(|p| { // Depending on the version of `llvm-config` in use, listed // libraries may be in one of two forms, a full path to the library // or simply prefixed with `-l`. if let Some(path) = p.strip_prefix("-l") { Some(path.into()) } else { get_library_name(Path::new(p)) } }) .collect() } /// Clang libraries required to link to `libclang` 3.5 and later statically. const CLANG_LIBRARIES: &[&str] = &[ "clang", "clangAST", "clangAnalysis", "clangBasic", "clangDriver", "clangEdit", "clangFrontend", "clangIndex", "clangLex", "clangParse", "clangRewrite", "clangSema", "clangSerialization", ]; /// Returns the Clang libraries required to link to `libclang` statically. fn get_clang_libraries<P: AsRef<Path>>(directory: P) -> Vec<String> { // Escape the directory in case it contains characters that have special // meaning in glob patterns (e.g., `[` or `]`). let directory = Pattern::escape(directory.as_ref().to_str().unwrap()); let directory = Path::new(&directory); let pattern = directory.join("libclang*.a").to_str().unwrap().to_owned(); if let Ok(libraries) = glob::glob(&pattern) { libraries .filter_map(|l| l.ok().and_then(|l| get_library_name(&l))) .collect() } else
} /// Returns a directory containing `libclang` static libraries. fn find() -> PathBuf { let name = if cfg!(target_os = "windows") { "libclang.lib" } else { "libclang.a" }; let files = common::search_libclang_directories(&[name.into()], "LIBCLANG_STATIC_PATH"); if let Some((directory, _)) = files.into_iter().next() { directory } else { panic!("could not find any static libraries"); } } /// Find and link to `libclang` statically. pub fn link() { let cep = common::CommandErrorPrinter::default(); let directory = find(); // Specify required Clang static libraries. println!("cargo:rustc-link-search=native={}", directory.display()); for library in get_clang_libraries(directory) { println!("cargo:rustc-link-lib=static={}", library); } // Determine the shared mode used by LLVM. let mode = common::run_llvm_config(&["--shared-mode"]).map(|m| m.trim().to_owned()); let prefix = if mode.map_or(false, |m| m == "static") { "static=" } else { "" }; // Specify required LLVM static libraries. println!( "cargo:rustc-link-search=native={}", common::run_llvm_config(&["--libdir"]).unwrap().trim_end() ); for library in get_llvm_libraries() { println!("cargo:rustc-link-lib={}{}", prefix, library); } // Specify required system libraries. // MSVC doesn't need this, as it tracks dependencies inside `.lib` files. if cfg!(target_os = "freebsd") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l c++ -l z"); } else if cfg!(target_os = "linux") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l stdc++ -l z"); } else if cfg!(target_os = "macos") { println!("cargo:rustc-flags=-l ffi -l ncurses -l c++ -l z"); } else if cfg!(target_os = "haiku") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l stdc++ -l z"); } cep.discard(); }
{ CLANG_LIBRARIES.iter().map(|l| (*l).to_string()).collect() }
conditional_block
static.rs
// Copyright 2018 Kyle Mayes // // 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. extern crate glob; use std::path::{Path, PathBuf}; use glob::Pattern; use common; /// Returns the name of an LLVM or Clang library from a path to such a library. fn get_library_name(path: &Path) -> Option<String> { path.file_stem().map(|p| { let string = p.to_string_lossy(); if let Some(name) = string.strip_prefix("lib") { name.to_owned() } else { string.to_string() } }) } /// Returns the LLVM libraries required to link to `libclang` statically. fn get_llvm_libraries() -> Vec<String> { common::run_llvm_config(&["--libs"]) .unwrap() .split_whitespace() .filter_map(|p| { // Depending on the version of `llvm-config` in use, listed // libraries may be in one of two forms, a full path to the library // or simply prefixed with `-l`. if let Some(path) = p.strip_prefix("-l") { Some(path.into()) } else { get_library_name(Path::new(p)) } }) .collect() } /// Clang libraries required to link to `libclang` 3.5 and later statically. const CLANG_LIBRARIES: &[&str] = &[ "clang", "clangAST", "clangAnalysis", "clangBasic", "clangDriver", "clangEdit", "clangFrontend", "clangIndex", "clangLex", "clangParse", "clangRewrite", "clangSema", "clangSerialization", ]; /// Returns the Clang libraries required to link to `libclang` statically. fn get_clang_libraries<P: AsRef<Path>>(directory: P) -> Vec<String> { // Escape the directory in case it contains characters that have special // meaning in glob patterns (e.g., `[` or `]`). let directory = Pattern::escape(directory.as_ref().to_str().unwrap()); let directory = Path::new(&directory); let pattern = directory.join("libclang*.a").to_str().unwrap().to_owned(); if let Ok(libraries) = glob::glob(&pattern) { libraries .filter_map(|l| l.ok().and_then(|l| get_library_name(&l))) .collect() } else { CLANG_LIBRARIES.iter().map(|l| (*l).to_string()).collect() } } /// Returns a directory containing `libclang` static libraries. fn find() -> PathBuf { let name = if cfg!(target_os = "windows") { "libclang.lib" } else { "libclang.a" }; let files = common::search_libclang_directories(&[name.into()], "LIBCLANG_STATIC_PATH"); if let Some((directory, _)) = files.into_iter().next() { directory } else { panic!("could not find any static libraries"); } } /// Find and link to `libclang` statically. pub fn link() { let cep = common::CommandErrorPrinter::default(); let directory = find(); // Specify required Clang static libraries. println!("cargo:rustc-link-search=native={}", directory.display()); for library in get_clang_libraries(directory) { println!("cargo:rustc-link-lib=static={}", library); }
} else { "" }; // Specify required LLVM static libraries. println!( "cargo:rustc-link-search=native={}", common::run_llvm_config(&["--libdir"]).unwrap().trim_end() ); for library in get_llvm_libraries() { println!("cargo:rustc-link-lib={}{}", prefix, library); } // Specify required system libraries. // MSVC doesn't need this, as it tracks dependencies inside `.lib` files. if cfg!(target_os = "freebsd") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l c++ -l z"); } else if cfg!(target_os = "linux") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l stdc++ -l z"); } else if cfg!(target_os = "macos") { println!("cargo:rustc-flags=-l ffi -l ncurses -l c++ -l z"); } else if cfg!(target_os = "haiku") { println!("cargo:rustc-flags=-l ffi -l ncursesw -l stdc++ -l z"); } cep.discard(); }
// Determine the shared mode used by LLVM. let mode = common::run_llvm_config(&["--shared-mode"]).map(|m| m.trim().to_owned()); let prefix = if mode.map_or(false, |m| m == "static") { "static="
random_line_split
main.rs
use std::env; use std::process; use std::time::{Instant, Duration}; fn fibonacci_naive(n: u64) -> u64 { if n < 2 { n } else { fibonacci_naive(n-1) + fibonacci_naive(n-2) } } fn fibonacci_tailrec(n: u64, a: u64, b: u64) -> u64 { if n == 0 { a } else { fibonacci_tailrec(n-1, b, a+b) } } fn fibonacci_iterative(n_orig: u64) -> u64 { let mut a: u64 = 0; let mut b: u64 = 1; let mut n = n_orig; while n > 0 { // unclear if Rust supports syntax like this (https://github.com/rust-lang/rust/issues/10174): // (a, b) = (b, a + b); let tmp = a; a = b; b = a + tmp; n -= 1; } a } fn duration_in_sec(d: Duration) -> f64 { (d.as_secs() as f64) + ((d.subsec_nanos() as f64) / 1_000_000_000 as f64) } fn main()
println!("{}", duration_in_sec(time2.elapsed())); let time3 = Instant::now(); let mut checksum_f3 = 0; for _ in 0..m { checksum_f3 += fibonacci_iterative(n); checksum_f3 %= 2147483647 } println!("{}", duration_in_sec(time3.elapsed())); println!("{}", f1); println!("{}", checksum_f2); println!("{}", checksum_f3); }
{ let args: Vec<_> = env::args().collect(); if args.len() != 3 { println!("Unexpected number of arguments."); process::exit(1); } let n = args[1].parse::<u64>().unwrap(); let m = args[2].parse::<u64>().unwrap(); let time1 = Instant::now(); let f1 = fibonacci_naive(n); println!("{}", duration_in_sec(time1.elapsed())); let time2 = Instant::now(); let mut checksum_f2 = 0; for _ in 0..m { checksum_f2 += fibonacci_tailrec(n, 0, 1); checksum_f2 %= 2147483647 }
identifier_body
main.rs
use std::env; use std::process; use std::time::{Instant, Duration}; fn fibonacci_naive(n: u64) -> u64 { if n < 2 { n } else { fibonacci_naive(n-1) + fibonacci_naive(n-2) } } fn fibonacci_tailrec(n: u64, a: u64, b: u64) -> u64 { if n == 0 { a } else { fibonacci_tailrec(n-1, b, a+b) } } fn fibonacci_iterative(n_orig: u64) -> u64 { let mut a: u64 = 0; let mut b: u64 = 1; let mut n = n_orig; while n > 0 { // unclear if Rust supports syntax like this (https://github.com/rust-lang/rust/issues/10174): // (a, b) = (b, a + b); let tmp = a; a = b; b = a + tmp; n -= 1; } a } fn
(d: Duration) -> f64 { (d.as_secs() as f64) + ((d.subsec_nanos() as f64) / 1_000_000_000 as f64) } fn main() { let args: Vec<_> = env::args().collect(); if args.len()!= 3 { println!("Unexpected number of arguments."); process::exit(1); } let n = args[1].parse::<u64>().unwrap(); let m = args[2].parse::<u64>().unwrap(); let time1 = Instant::now(); let f1 = fibonacci_naive(n); println!("{}", duration_in_sec(time1.elapsed())); let time2 = Instant::now(); let mut checksum_f2 = 0; for _ in 0..m { checksum_f2 += fibonacci_tailrec(n, 0, 1); checksum_f2 %= 2147483647 } println!("{}", duration_in_sec(time2.elapsed())); let time3 = Instant::now(); let mut checksum_f3 = 0; for _ in 0..m { checksum_f3 += fibonacci_iterative(n); checksum_f3 %= 2147483647 } println!("{}", duration_in_sec(time3.elapsed())); println!("{}", f1); println!("{}", checksum_f2); println!("{}", checksum_f3); }
duration_in_sec
identifier_name
main.rs
use std::env; use std::process; use std::time::{Instant, Duration}; fn fibonacci_naive(n: u64) -> u64 { if n < 2 { n } else { fibonacci_naive(n-1) + fibonacci_naive(n-2) } } fn fibonacci_tailrec(n: u64, a: u64, b: u64) -> u64 { if n == 0 { a } else { fibonacci_tailrec(n-1, b, a+b) } } fn fibonacci_iterative(n_orig: u64) -> u64 { let mut a: u64 = 0; let mut b: u64 = 1; let mut n = n_orig; while n > 0 { // unclear if Rust supports syntax like this (https://github.com/rust-lang/rust/issues/10174): // (a, b) = (b, a + b); let tmp = a; a = b; b = a + tmp; n -= 1; } a } fn duration_in_sec(d: Duration) -> f64 { (d.as_secs() as f64) + ((d.subsec_nanos() as f64) / 1_000_000_000 as f64) }
let args: Vec<_> = env::args().collect(); if args.len()!= 3 { println!("Unexpected number of arguments."); process::exit(1); } let n = args[1].parse::<u64>().unwrap(); let m = args[2].parse::<u64>().unwrap(); let time1 = Instant::now(); let f1 = fibonacci_naive(n); println!("{}", duration_in_sec(time1.elapsed())); let time2 = Instant::now(); let mut checksum_f2 = 0; for _ in 0..m { checksum_f2 += fibonacci_tailrec(n, 0, 1); checksum_f2 %= 2147483647 } println!("{}", duration_in_sec(time2.elapsed())); let time3 = Instant::now(); let mut checksum_f3 = 0; for _ in 0..m { checksum_f3 += fibonacci_iterative(n); checksum_f3 %= 2147483647 } println!("{}", duration_in_sec(time3.elapsed())); println!("{}", f1); println!("{}", checksum_f2); println!("{}", checksum_f3); }
fn main() {
random_line_split
main.rs
use std::env; use std::process; use std::time::{Instant, Duration}; fn fibonacci_naive(n: u64) -> u64 { if n < 2 { n } else
} fn fibonacci_tailrec(n: u64, a: u64, b: u64) -> u64 { if n == 0 { a } else { fibonacci_tailrec(n-1, b, a+b) } } fn fibonacci_iterative(n_orig: u64) -> u64 { let mut a: u64 = 0; let mut b: u64 = 1; let mut n = n_orig; while n > 0 { // unclear if Rust supports syntax like this (https://github.com/rust-lang/rust/issues/10174): // (a, b) = (b, a + b); let tmp = a; a = b; b = a + tmp; n -= 1; } a } fn duration_in_sec(d: Duration) -> f64 { (d.as_secs() as f64) + ((d.subsec_nanos() as f64) / 1_000_000_000 as f64) } fn main() { let args: Vec<_> = env::args().collect(); if args.len()!= 3 { println!("Unexpected number of arguments."); process::exit(1); } let n = args[1].parse::<u64>().unwrap(); let m = args[2].parse::<u64>().unwrap(); let time1 = Instant::now(); let f1 = fibonacci_naive(n); println!("{}", duration_in_sec(time1.elapsed())); let time2 = Instant::now(); let mut checksum_f2 = 0; for _ in 0..m { checksum_f2 += fibonacci_tailrec(n, 0, 1); checksum_f2 %= 2147483647 } println!("{}", duration_in_sec(time2.elapsed())); let time3 = Instant::now(); let mut checksum_f3 = 0; for _ in 0..m { checksum_f3 += fibonacci_iterative(n); checksum_f3 %= 2147483647 } println!("{}", duration_in_sec(time3.elapsed())); println!("{}", f1); println!("{}", checksum_f2); println!("{}", checksum_f3); }
{ fibonacci_naive(n-1) + fibonacci_naive(n-2) }
conditional_block
node.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency between layout and //! style. use cssparser::RGBA; use legacy::{IntegerAttribute, LengthAttribute, SimpleColorAttribute, UnsignedIntegerAttribute}; use selectors::AttrSelector; use servo_util::str::LengthOrPercentageOrAuto; use string_cache::{Atom, Namespace}; pub trait TNode<'a, E: TElement<'a>> : Clone + Copy { fn parent_node(self) -> Option<Self>; fn first_child(self) -> Option<Self>;
fn prev_sibling(self) -> Option<Self>; fn next_sibling(self) -> Option<Self>; fn is_document(self) -> bool; fn is_element(self) -> bool; fn as_element(self) -> E; fn match_attr(self, attr: &AttrSelector, test: |&str| -> bool) -> bool; fn is_html_element_in_html_document(self) -> bool; fn has_changed(self) -> bool; unsafe fn set_changed(self, value: bool); fn is_dirty(self) -> bool; unsafe fn set_dirty(self, value: bool); fn has_dirty_siblings(self) -> bool; unsafe fn set_dirty_siblings(self, value: bool); fn has_dirty_descendants(self) -> bool; unsafe fn set_dirty_descendants(self, value: bool); } pub trait TElement<'a> : Copy { fn get_attr(self, namespace: &Namespace, attr: &Atom) -> Option<&'a str>; fn get_attrs(self, attr: &Atom) -> Vec<&'a str>; fn get_link(self) -> Option<&'a str>; fn get_local_name(self) -> &'a Atom; fn get_namespace(self) -> &'a Namespace; fn get_hover_state(self) -> bool; fn get_id(self) -> Option<Atom>; fn get_disabled_state(self) -> bool; fn get_enabled_state(self) -> bool; fn get_checked_state(self) -> bool; fn get_indeterminate_state(self) -> bool; fn has_class(self, name: &Atom) -> bool; fn has_nonzero_border(self) -> bool; // Ordinarily I wouldn't use callbacks like this, but the alternative is // really messy, since there is a `JSRef` and a `RefCell` involved. Maybe // in the future when we have associated types and/or a more convenient // JS GC story... --pcwalton fn each_class(self, callback: |&Atom|); } pub trait TElementAttributes : Copy { fn get_length_attribute(self, attribute: LengthAttribute) -> LengthOrPercentageOrAuto; fn get_integer_attribute(self, attribute: IntegerAttribute) -> Option<i32>; fn get_unsigned_integer_attribute(self, attribute: UnsignedIntegerAttribute) -> Option<u32>; fn get_simple_color_attribute(self, attribute: SimpleColorAttribute) -> Option<RGBA>; }
fn last_child(self) -> Option<Self>;
random_line_split
lfo.rs
use audiobuffer::*; use processblock::ProcessBlock; use synthconfig::SynthConfig; use port::Port; #[derive(Debug)] pub struct LFO{ phase: f32, sample_rate: f32, } pub const FREQ:Port = Port{nr:0}; pub const OUT:Port = Port{nr:0}; const MAX_FREQ:f32 = 5.0; impl LFO{ pub fn new() -> Box<LFO>{ Box::new(LFO{ phase: 0.0, sample_rate: 44100.0 }) } } impl ProcessBlock for LFO { fn setup(&mut self, config: &SynthConfig){ self.sample_rate = config.sample_rate as f32 } fn process(&mut self, input: &mut AudioBufferVector, output: &mut AudioBufferVector){ let mut out = output.get(0).unwrap(); let freq = input.get(0).unwrap(); for (o, f) in izip!(&mut out, &freq){ *o = f32::sin(self.phase * 2.0 * ::std::f32::consts::PI); self.phase+=MAX_FREQ*f*2.0/self.sample_rate; } self.phase = self.phase % 1.0; output.put(0, out); input.put(0, freq); } fn typename(&self) -> &str{ "LFO" } fn input_count(&self) -> usize { 1 } fn
(&self) -> usize { 1 } fn port(&self, name: &str) -> Port{ match name { "output" => OUT, "freq" => FREQ, _ => panic!("Unknown port {}/{}", self.typename(), name) } } }
output_count
identifier_name
lfo.rs
use audiobuffer::*; use processblock::ProcessBlock; use synthconfig::SynthConfig; use port::Port; #[derive(Debug)] pub struct LFO{ phase: f32, sample_rate: f32, } pub const FREQ:Port = Port{nr:0}; pub const OUT:Port = Port{nr:0}; const MAX_FREQ:f32 = 5.0; impl LFO{ pub fn new() -> Box<LFO>{ Box::new(LFO{ phase: 0.0, sample_rate: 44100.0 }) } } impl ProcessBlock for LFO { fn setup(&mut self, config: &SynthConfig){ self.sample_rate = config.sample_rate as f32 } fn process(&mut self, input: &mut AudioBufferVector, output: &mut AudioBufferVector){ let mut out = output.get(0).unwrap(); let freq = input.get(0).unwrap(); for (o, f) in izip!(&mut out, &freq){ *o = f32::sin(self.phase * 2.0 * ::std::f32::consts::PI); self.phase+=MAX_FREQ*f*2.0/self.sample_rate; } self.phase = self.phase % 1.0; output.put(0, out); input.put(0, freq); } fn typename(&self) -> &str{ "LFO" } fn input_count(&self) -> usize { 1 } fn output_count(&self) -> usize { 1 } fn port(&self, name: &str) -> Port{ match name { "output" => OUT,
"freq" => FREQ, _ => panic!("Unknown port {}/{}", self.typename(), name) } } }
random_line_split
lib.rs
// Copyright (c) 2013-2017 Sandstorm Development Group, Inc. and contributors // // 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. //! An implementation of the [Cap'n Proto remote procedure call](https://capnproto.org/rpc.html) //! protocol. Includes all [Level 1](https://capnproto.org/rpc.html#protocol-features) features. //! //! # Example //! //! ```capnp //! # Cap'n Proto schema //! interface Foo { //! identity @0 (x: UInt32) -> (y: UInt32); //! } //! ``` //! //! ```ignore //! // Rust server defining an implementation of Foo. //! struct FooImpl; //! impl foo::Server for FooImpl { //! fn identity(&mut self, //! params: foo::IdentityParams, //! mut results: foo::IdentityResults) //! -> Promise<(), ::capnp::Error> //! { //! let x = pry!(params.get()).get_x(); //! results.get().set_y(x); //! Promise::ok(()) //! } //! } //! ``` //! //! ```ignore //! // Rust client calling a remote implementation of Foo. //! let mut request = foo_client.identity_request(); //! request.get().set_x(123); //! let promise = request.send().promise.and_then(|response| { //! println!("results = {}", response.get()?.get_y()); //! Ok(()) //! }); //! ``` //! //! For a more complete example, see https://github.com/capnproto/capnproto-rust/tree/master/capnp-rpc/examples/calculator extern crate capnp; extern crate capnp_futures; extern crate futures; use futures::{Future}; use futures::sync::oneshot; use capnp::Error; use capnp::capability::Promise; use capnp::private::capability::{ClientHook, ServerHook}; use std::cell::{RefCell}; use std::rc::{Rc}; use crate::task_set::TaskSet; pub use crate::rpc::Disconnector; /// Code generated from [rpc.capnp] /// (https://github.com/sandstorm-io/capnproto/blob/master/c%2B%2B/src/capnp/rpc.capnp). pub mod rpc_capnp { include!(concat!(env!("OUT_DIR"), "/rpc_capnp.rs")); } /// Code generated from [rpc-twoparty.capnp] /// (https://github.com/sandstorm-io/capnproto/blob/master/c%2B%2B/src/capnp/rpc-twoparty.capnp). pub mod rpc_twoparty_capnp { include!(concat!(env!("OUT_DIR"), "/rpc_twoparty_capnp.rs")); } /// Like `try!()`, but for functions that return a `Promise<T, E>` rather than a `Result<T, E>`. /// /// Unwraps a `Result<T, E>`. In the case of an error `Err(e)`, immediately returns from the /// enclosing function with `Promise::err(e)`. #[macro_export] macro_rules! pry { ($expr:expr) => ( match $expr { ::std::result::Result::Ok(val) => val, ::std::result::Result::Err(err) => { return ::capnp::capability::Promise::err(::std::convert::From::from(err)) } }) } mod broken; mod local; mod queued; mod rpc; mod attach; mod forked_promise; mod sender_queue; mod split; mod task_set; pub mod twoparty; pub trait OutgoingMessage { fn get_body<'a>(&'a mut self) -> ::capnp::Result<::capnp::any_pointer::Builder<'a>>; fn get_body_as_reader<'a>(&'a self) -> ::capnp::Result<::capnp::any_pointer::Reader<'a>>; /// Sends the message. Returns a promise for the message that resolves once the send has completed. /// Dropping the returned promise does *not* cancel the send. fn send(self: Box<Self>) -> (Promise<Rc<::capnp::message::Builder<::capnp::message::HeapAllocator>>, ::capnp::Error>, Rc<::capnp::message::Builder<::capnp::message::HeapAllocator>>); fn take(self: Box<Self>) -> ::capnp::message::Builder<::capnp::message::HeapAllocator>; } pub trait IncomingMessage { fn get_body<'a>(&'a self) -> ::capnp::Result<::capnp::any_pointer::Reader<'a>>; } pub trait Connection<VatId> { fn get_peer_vat_id(&self) -> VatId; fn new_outgoing_message(&mut self, first_segment_word_size: u32) -> Box<dyn OutgoingMessage>; /// Waits for a message to be received and returns it. If the read stream cleanly terminates, /// returns None. If any other problem occurs, returns an Error. fn receive_incoming_message(&mut self) -> Promise<Option<Box<dyn IncomingMessage>>, Error>; // Waits until all outgoing messages have been sent, then shuts down the outgoing stream. The // returned promise resolves after shutdown is complete. fn shutdown(&mut self, result: ::capnp::Result<()>) -> Promise<(), Error>; } pub trait VatNetwork<VatId> { /// Returns None if `hostId` refers to the local vat. fn connect(&mut self, host_id: VatId) -> Option<Box<dyn Connection<VatId>>>; /// Waits for the next incoming connection and return it. fn accept(&mut self) -> Promise<Box<dyn Connection<VatId>>, ::capnp::Error>; fn drive_until_shutdown(&mut self) -> Promise<(), Error>; } /// A portal to objects available on the network. /// /// The RPC implemententation sits on top of an implementation of `VatNetwork`, which /// determines how to form connections between vats. The RPC implementation determines /// how to use such connections to manage object references and make method calls. /// /// At the moment, this is all rather more general than it needs to be, because the only /// implementation of `VatNetwork` is `twoparty::VatNetwork`. However, eventually we /// will need to have more sophisticated `VatNetwork` implementations, in order to support /// [level 3](https://capnproto.org/rpc.html#protocol-features) features. /// /// An `RpcSystem` is a `Future` and needs to be driven by a task executor. A common way /// accomplish that is to pass the `RpcSystem` to `tokio_core::reactor::Handle::spawn()`. #[must_use = "futures do nothing unless polled"] pub struct RpcSystem<VatId> where VatId:'static { network: Box<dyn crate::VatNetwork<VatId>>, bootstrap_cap: Box<dyn ClientHook>, // XXX To handle three or more party networks, this should be a map from connection pointers // to connection states. connection_state: Rc<RefCell<Option<Rc<rpc::ConnectionState<VatId>>>>>, tasks: TaskSet<(), Error>, handle: crate::task_set::TaskSetHandle<(), Error> } impl <VatId> RpcSystem <VatId> { /// Constructs a new `RpcSystem` with the given network and bootstrap capability. pub fn new( mut network: Box<dyn crate::VatNetwork<VatId>>, bootstrap: Option<::capnp::capability::Client>) -> RpcSystem<VatId> { let bootstrap_cap = match bootstrap { Some(cap) => cap.hook, None => broken::new_cap(Error::failed("no bootstrap capabiity".to_string())), }; let (mut handle, tasks) = TaskSet::new(Box::new(SystemTaskReaper)); let mut handle1 = handle.clone(); handle.add(network.drive_until_shutdown().then(move |r| { let r = match r { Ok(()) => Ok(()), Err(e) => { if e.kind!= ::capnp::ErrorKind::Disconnected { // Don't report disconnects as an error. Err(e) } else { Ok(()) } } }; handle1.terminate(r); Ok(()) })); let mut result = RpcSystem { network: network, bootstrap_cap: bootstrap_cap, connection_state: Rc::new(RefCell::new(None)), tasks: tasks, handle: handle.clone(), }; let accept_loop = result.accept_loop(); handle.add(accept_loop); result } /// Connects to the given vat and returns its bootstrap interface. pub fn bootstrap<T>(&mut self, vat_id: VatId) -> T where T: ::capnp::capability::FromClientHook { let connection = match self.network.connect(vat_id) { Some(connection) => connection, None => { return T::new(self.bootstrap_cap.clone()); } }; let connection_state = RpcSystem::get_connection_state(self.connection_state.clone(), self.bootstrap_cap.clone(), connection, self.handle.clone()); let hook = rpc::ConnectionState::bootstrap(connection_state.clone()); T::new(hook) } // not really a loop, because it doesn't need to be for the two party case fn accept_loop(&mut self) -> Promise<(), Error> { let connection_state_ref = self.connection_state.clone(); let bootstrap_cap = self.bootstrap_cap.clone(); let handle = self.handle.clone(); Promise::from_future(self.network.accept().map(move |connection| { RpcSystem::get_connection_state(connection_state_ref, bootstrap_cap, connection, handle); })) } fn get_connection_state(connection_state_ref: Rc<RefCell<Option<Rc<rpc::ConnectionState<VatId>>>>>, bootstrap_cap: Box<dyn ClientHook>, connection: Box<dyn crate::Connection<VatId>>, mut handle: crate::task_set::TaskSetHandle<(), Error>) -> Rc<rpc::ConnectionState<VatId>> { // TODO this needs to be updated once we allow more general VatNetworks. let (tasks, result) = match *connection_state_ref.borrow() { Some(ref connection_state) => { // return early. return connection_state.clone() } None => { let (on_disconnect_fulfiller, on_disconnect_promise) = oneshot::channel::<Promise<(), Error>>(); let connection_state_ref1 = connection_state_ref.clone(); handle.add(on_disconnect_promise.then(move |shutdown_promise| { *connection_state_ref1.borrow_mut() = None; match shutdown_promise { Ok(s) => s, Err(e) => Promise::err(Error::failed(format!("{}", e))), } })); rpc::ConnectionState::new(bootstrap_cap, connection, on_disconnect_fulfiller) } }; *connection_state_ref.borrow_mut() = Some(result.clone()); handle.add(tasks); result } /// Returns a `Disconnector` future that can be run to cleanly close the connection to this `RpcSystem`'s network. /// You should get the `Disconnector` before you spawn the `RpcSystem`. pub fn get_disconnector(&self) -> rpc::Disconnector<VatId> { rpc::Disconnector::new(self.connection_state.clone()) } } impl <VatId> Future for RpcSystem<VatId> where VatId:'static { type Item = (); type Error = Error; fn poll(&mut self) -> ::futures::Poll<Self::Item, Self::Error> { self.tasks.poll() } } /// Hook that allows local implementations of interfaces to be passed to the RPC system /// so that they can be called remotely. /// /// To use this, you need to do the following dance: /// /// ```ignore /// let client = foo::ToClient::new(FooImpl).into_client::<::capnp_rpc::Server>()); /// ``` pub struct Server; impl ServerHook for Server { fn new_client(server: Box<dyn (::capnp::capability::Server)>) -> ::capnp::capability::Client { ::capnp::capability::Client::new(Box::new(local::Client::new(server))) } } /// Converts a promise for a client into a client that queues up any calls that arrive /// before the promise resolves. // TODO: figure out a better way to allow construction of promise clients. pub fn new_promise_client<T, F>(client_promise: F) -> T where T: ::capnp::capability::FromClientHook, F: ::futures::Future<Item=::capnp::capability::Client,Error=Error>, F:'static { let mut queued_client = crate::queued::Client::new(None); let weak_client = Rc::downgrade(&queued_client.inner); queued_client.drive(client_promise.then(move |r| { if let Some(queued_inner) = weak_client.upgrade() { crate::queued::ClientInner::resolve(&queued_inner, r.map(|c| c.hook)); } Ok(()) })); T::new(Box::new(queued_client)) } struct SystemTaskReaper; impl crate::task_set::TaskReaper<(), Error> for SystemTaskReaper { fn task_failed(&mut self, error: Error) { println!("ERROR: {}", error); } } pub struct ImbuedMessageBuilder<A> where A: ::capnp::message::Allocator { builder: ::capnp::message::Builder<A>, cap_table: Vec<Option<Box<dyn (::capnp::private::capability::ClientHook)>>>, } impl <A> ImbuedMessageBuilder<A> where A: ::capnp::message::Allocator { pub fn new(allocator: A) -> Self { ImbuedMessageBuilder { builder: ::capnp::message::Builder::new(allocator), cap_table: Vec::new(), } } pub fn get_root<'a, T>(&'a mut self) -> ::capnp::Result<T> where T: ::capnp::traits::FromPointerBuilder<'a> { use capnp::traits::ImbueMut; let mut root: ::capnp::any_pointer::Builder = self.builder.get_root()?; root.imbue_mut(&mut self.cap_table); root.get_as() } pub fn set_root<To, From>(&mut self, value: From) -> ::capnp::Result<()> where From: ::capnp::traits::SetPointerBuilder<To>
}
{ use capnp::traits::ImbueMut; let mut root: ::capnp::any_pointer::Builder = self.builder.get_root()?; root.imbue_mut(&mut self.cap_table); root.set_as(value) }
identifier_body
lib.rs
// Copyright (c) 2013-2017 Sandstorm Development Group, Inc. and contributors // // 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. //! An implementation of the [Cap'n Proto remote procedure call](https://capnproto.org/rpc.html) //! protocol. Includes all [Level 1](https://capnproto.org/rpc.html#protocol-features) features. //! //! # Example //! //! ```capnp //! # Cap'n Proto schema //! interface Foo { //! identity @0 (x: UInt32) -> (y: UInt32); //! } //! ``` //! //! ```ignore //! // Rust server defining an implementation of Foo. //! struct FooImpl; //! impl foo::Server for FooImpl { //! fn identity(&mut self, //! params: foo::IdentityParams, //! mut results: foo::IdentityResults) //! -> Promise<(), ::capnp::Error> //! { //! let x = pry!(params.get()).get_x(); //! results.get().set_y(x); //! Promise::ok(()) //! } //! } //! ``` //! //! ```ignore //! // Rust client calling a remote implementation of Foo. //! let mut request = foo_client.identity_request(); //! request.get().set_x(123); //! let promise = request.send().promise.and_then(|response| { //! println!("results = {}", response.get()?.get_y()); //! Ok(()) //! }); //! ``` //! //! For a more complete example, see https://github.com/capnproto/capnproto-rust/tree/master/capnp-rpc/examples/calculator extern crate capnp; extern crate capnp_futures; extern crate futures; use futures::{Future}; use futures::sync::oneshot; use capnp::Error; use capnp::capability::Promise; use capnp::private::capability::{ClientHook, ServerHook}; use std::cell::{RefCell}; use std::rc::{Rc}; use crate::task_set::TaskSet; pub use crate::rpc::Disconnector; /// Code generated from [rpc.capnp] /// (https://github.com/sandstorm-io/capnproto/blob/master/c%2B%2B/src/capnp/rpc.capnp). pub mod rpc_capnp { include!(concat!(env!("OUT_DIR"), "/rpc_capnp.rs")); } /// Code generated from [rpc-twoparty.capnp] /// (https://github.com/sandstorm-io/capnproto/blob/master/c%2B%2B/src/capnp/rpc-twoparty.capnp). pub mod rpc_twoparty_capnp { include!(concat!(env!("OUT_DIR"), "/rpc_twoparty_capnp.rs")); } /// Like `try!()`, but for functions that return a `Promise<T, E>` rather than a `Result<T, E>`. /// /// Unwraps a `Result<T, E>`. In the case of an error `Err(e)`, immediately returns from the /// enclosing function with `Promise::err(e)`. #[macro_export] macro_rules! pry { ($expr:expr) => ( match $expr { ::std::result::Result::Ok(val) => val, ::std::result::Result::Err(err) => { return ::capnp::capability::Promise::err(::std::convert::From::from(err)) } }) } mod broken; mod local; mod queued; mod rpc; mod attach; mod forked_promise; mod sender_queue; mod split; mod task_set; pub mod twoparty; pub trait OutgoingMessage { fn get_body<'a>(&'a mut self) -> ::capnp::Result<::capnp::any_pointer::Builder<'a>>; fn get_body_as_reader<'a>(&'a self) -> ::capnp::Result<::capnp::any_pointer::Reader<'a>>; /// Sends the message. Returns a promise for the message that resolves once the send has completed. /// Dropping the returned promise does *not* cancel the send. fn send(self: Box<Self>) -> (Promise<Rc<::capnp::message::Builder<::capnp::message::HeapAllocator>>, ::capnp::Error>, Rc<::capnp::message::Builder<::capnp::message::HeapAllocator>>); fn take(self: Box<Self>) -> ::capnp::message::Builder<::capnp::message::HeapAllocator>; } pub trait IncomingMessage { fn get_body<'a>(&'a self) -> ::capnp::Result<::capnp::any_pointer::Reader<'a>>; } pub trait Connection<VatId> { fn get_peer_vat_id(&self) -> VatId; fn new_outgoing_message(&mut self, first_segment_word_size: u32) -> Box<dyn OutgoingMessage>; /// Waits for a message to be received and returns it. If the read stream cleanly terminates, /// returns None. If any other problem occurs, returns an Error. fn receive_incoming_message(&mut self) -> Promise<Option<Box<dyn IncomingMessage>>, Error>; // Waits until all outgoing messages have been sent, then shuts down the outgoing stream. The // returned promise resolves after shutdown is complete. fn shutdown(&mut self, result: ::capnp::Result<()>) -> Promise<(), Error>; } pub trait VatNetwork<VatId> { /// Returns None if `hostId` refers to the local vat. fn connect(&mut self, host_id: VatId) -> Option<Box<dyn Connection<VatId>>>; /// Waits for the next incoming connection and return it. fn accept(&mut self) -> Promise<Box<dyn Connection<VatId>>, ::capnp::Error>; fn drive_until_shutdown(&mut self) -> Promise<(), Error>; } /// A portal to objects available on the network. /// /// The RPC implemententation sits on top of an implementation of `VatNetwork`, which /// determines how to form connections between vats. The RPC implementation determines /// how to use such connections to manage object references and make method calls. /// /// At the moment, this is all rather more general than it needs to be, because the only /// implementation of `VatNetwork` is `twoparty::VatNetwork`. However, eventually we /// will need to have more sophisticated `VatNetwork` implementations, in order to support /// [level 3](https://capnproto.org/rpc.html#protocol-features) features. /// /// An `RpcSystem` is a `Future` and needs to be driven by a task executor. A common way /// accomplish that is to pass the `RpcSystem` to `tokio_core::reactor::Handle::spawn()`. #[must_use = "futures do nothing unless polled"] pub struct RpcSystem<VatId> where VatId:'static { network: Box<dyn crate::VatNetwork<VatId>>, bootstrap_cap: Box<dyn ClientHook>, // XXX To handle three or more party networks, this should be a map from connection pointers // to connection states. connection_state: Rc<RefCell<Option<Rc<rpc::ConnectionState<VatId>>>>>, tasks: TaskSet<(), Error>, handle: crate::task_set::TaskSetHandle<(), Error> } impl <VatId> RpcSystem <VatId> { /// Constructs a new `RpcSystem` with the given network and bootstrap capability. pub fn new( mut network: Box<dyn crate::VatNetwork<VatId>>, bootstrap: Option<::capnp::capability::Client>) -> RpcSystem<VatId> { let bootstrap_cap = match bootstrap { Some(cap) => cap.hook, None => broken::new_cap(Error::failed("no bootstrap capabiity".to_string())), }; let (mut handle, tasks) = TaskSet::new(Box::new(SystemTaskReaper)); let mut handle1 = handle.clone(); handle.add(network.drive_until_shutdown().then(move |r| { let r = match r { Ok(()) => Ok(()), Err(e) => { if e.kind!= ::capnp::ErrorKind::Disconnected { // Don't report disconnects as an error. Err(e) } else { Ok(()) } } }; handle1.terminate(r); Ok(()) })); let mut result = RpcSystem { network: network, bootstrap_cap: bootstrap_cap, connection_state: Rc::new(RefCell::new(None)), tasks: tasks, handle: handle.clone(), }; let accept_loop = result.accept_loop(); handle.add(accept_loop); result } /// Connects to the given vat and returns its bootstrap interface. pub fn bootstrap<T>(&mut self, vat_id: VatId) -> T where T: ::capnp::capability::FromClientHook { let connection = match self.network.connect(vat_id) { Some(connection) => connection, None => { return T::new(self.bootstrap_cap.clone()); } }; let connection_state = RpcSystem::get_connection_state(self.connection_state.clone(), self.bootstrap_cap.clone(), connection, self.handle.clone()); let hook = rpc::ConnectionState::bootstrap(connection_state.clone()); T::new(hook) } // not really a loop, because it doesn't need to be for the two party case fn accept_loop(&mut self) -> Promise<(), Error> { let connection_state_ref = self.connection_state.clone(); let bootstrap_cap = self.bootstrap_cap.clone(); let handle = self.handle.clone(); Promise::from_future(self.network.accept().map(move |connection| { RpcSystem::get_connection_state(connection_state_ref, bootstrap_cap, connection, handle); })) } fn get_connection_state(connection_state_ref: Rc<RefCell<Option<Rc<rpc::ConnectionState<VatId>>>>>, bootstrap_cap: Box<dyn ClientHook>, connection: Box<dyn crate::Connection<VatId>>, mut handle: crate::task_set::TaskSetHandle<(), Error>) -> Rc<rpc::ConnectionState<VatId>> { // TODO this needs to be updated once we allow more general VatNetworks. let (tasks, result) = match *connection_state_ref.borrow() { Some(ref connection_state) => { // return early. return connection_state.clone() } None => { let (on_disconnect_fulfiller, on_disconnect_promise) = oneshot::channel::<Promise<(), Error>>(); let connection_state_ref1 = connection_state_ref.clone(); handle.add(on_disconnect_promise.then(move |shutdown_promise| { *connection_state_ref1.borrow_mut() = None; match shutdown_promise { Ok(s) => s, Err(e) => Promise::err(Error::failed(format!("{}", e))), } })); rpc::ConnectionState::new(bootstrap_cap, connection, on_disconnect_fulfiller) } }; *connection_state_ref.borrow_mut() = Some(result.clone()); handle.add(tasks); result } /// Returns a `Disconnector` future that can be run to cleanly close the connection to this `RpcSystem`'s network. /// You should get the `Disconnector` before you spawn the `RpcSystem`. pub fn
(&self) -> rpc::Disconnector<VatId> { rpc::Disconnector::new(self.connection_state.clone()) } } impl <VatId> Future for RpcSystem<VatId> where VatId:'static { type Item = (); type Error = Error; fn poll(&mut self) -> ::futures::Poll<Self::Item, Self::Error> { self.tasks.poll() } } /// Hook that allows local implementations of interfaces to be passed to the RPC system /// so that they can be called remotely. /// /// To use this, you need to do the following dance: /// /// ```ignore /// let client = foo::ToClient::new(FooImpl).into_client::<::capnp_rpc::Server>()); /// ``` pub struct Server; impl ServerHook for Server { fn new_client(server: Box<dyn (::capnp::capability::Server)>) -> ::capnp::capability::Client { ::capnp::capability::Client::new(Box::new(local::Client::new(server))) } } /// Converts a promise for a client into a client that queues up any calls that arrive /// before the promise resolves. // TODO: figure out a better way to allow construction of promise clients. pub fn new_promise_client<T, F>(client_promise: F) -> T where T: ::capnp::capability::FromClientHook, F: ::futures::Future<Item=::capnp::capability::Client,Error=Error>, F:'static { let mut queued_client = crate::queued::Client::new(None); let weak_client = Rc::downgrade(&queued_client.inner); queued_client.drive(client_promise.then(move |r| { if let Some(queued_inner) = weak_client.upgrade() { crate::queued::ClientInner::resolve(&queued_inner, r.map(|c| c.hook)); } Ok(()) })); T::new(Box::new(queued_client)) } struct SystemTaskReaper; impl crate::task_set::TaskReaper<(), Error> for SystemTaskReaper { fn task_failed(&mut self, error: Error) { println!("ERROR: {}", error); } } pub struct ImbuedMessageBuilder<A> where A: ::capnp::message::Allocator { builder: ::capnp::message::Builder<A>, cap_table: Vec<Option<Box<dyn (::capnp::private::capability::ClientHook)>>>, } impl <A> ImbuedMessageBuilder<A> where A: ::capnp::message::Allocator { pub fn new(allocator: A) -> Self { ImbuedMessageBuilder { builder: ::capnp::message::Builder::new(allocator), cap_table: Vec::new(), } } pub fn get_root<'a, T>(&'a mut self) -> ::capnp::Result<T> where T: ::capnp::traits::FromPointerBuilder<'a> { use capnp::traits::ImbueMut; let mut root: ::capnp::any_pointer::Builder = self.builder.get_root()?; root.imbue_mut(&mut self.cap_table); root.get_as() } pub fn set_root<To, From>(&mut self, value: From) -> ::capnp::Result<()> where From: ::capnp::traits::SetPointerBuilder<To> { use capnp::traits::ImbueMut; let mut root: ::capnp::any_pointer::Builder = self.builder.get_root()?; root.imbue_mut(&mut self.cap_table); root.set_as(value) } }
get_disconnector
identifier_name
lib.rs
// Copyright (c) 2013-2017 Sandstorm Development Group, Inc. and contributors // // 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.
//! //! ```capnp //! # Cap'n Proto schema //! interface Foo { //! identity @0 (x: UInt32) -> (y: UInt32); //! } //! ``` //! //! ```ignore //! // Rust server defining an implementation of Foo. //! struct FooImpl; //! impl foo::Server for FooImpl { //! fn identity(&mut self, //! params: foo::IdentityParams, //! mut results: foo::IdentityResults) //! -> Promise<(), ::capnp::Error> //! { //! let x = pry!(params.get()).get_x(); //! results.get().set_y(x); //! Promise::ok(()) //! } //! } //! ``` //! //! ```ignore //! // Rust client calling a remote implementation of Foo. //! let mut request = foo_client.identity_request(); //! request.get().set_x(123); //! let promise = request.send().promise.and_then(|response| { //! println!("results = {}", response.get()?.get_y()); //! Ok(()) //! }); //! ``` //! //! For a more complete example, see https://github.com/capnproto/capnproto-rust/tree/master/capnp-rpc/examples/calculator extern crate capnp; extern crate capnp_futures; extern crate futures; use futures::{Future}; use futures::sync::oneshot; use capnp::Error; use capnp::capability::Promise; use capnp::private::capability::{ClientHook, ServerHook}; use std::cell::{RefCell}; use std::rc::{Rc}; use crate::task_set::TaskSet; pub use crate::rpc::Disconnector; /// Code generated from [rpc.capnp] /// (https://github.com/sandstorm-io/capnproto/blob/master/c%2B%2B/src/capnp/rpc.capnp). pub mod rpc_capnp { include!(concat!(env!("OUT_DIR"), "/rpc_capnp.rs")); } /// Code generated from [rpc-twoparty.capnp] /// (https://github.com/sandstorm-io/capnproto/blob/master/c%2B%2B/src/capnp/rpc-twoparty.capnp). pub mod rpc_twoparty_capnp { include!(concat!(env!("OUT_DIR"), "/rpc_twoparty_capnp.rs")); } /// Like `try!()`, but for functions that return a `Promise<T, E>` rather than a `Result<T, E>`. /// /// Unwraps a `Result<T, E>`. In the case of an error `Err(e)`, immediately returns from the /// enclosing function with `Promise::err(e)`. #[macro_export] macro_rules! pry { ($expr:expr) => ( match $expr { ::std::result::Result::Ok(val) => val, ::std::result::Result::Err(err) => { return ::capnp::capability::Promise::err(::std::convert::From::from(err)) } }) } mod broken; mod local; mod queued; mod rpc; mod attach; mod forked_promise; mod sender_queue; mod split; mod task_set; pub mod twoparty; pub trait OutgoingMessage { fn get_body<'a>(&'a mut self) -> ::capnp::Result<::capnp::any_pointer::Builder<'a>>; fn get_body_as_reader<'a>(&'a self) -> ::capnp::Result<::capnp::any_pointer::Reader<'a>>; /// Sends the message. Returns a promise for the message that resolves once the send has completed. /// Dropping the returned promise does *not* cancel the send. fn send(self: Box<Self>) -> (Promise<Rc<::capnp::message::Builder<::capnp::message::HeapAllocator>>, ::capnp::Error>, Rc<::capnp::message::Builder<::capnp::message::HeapAllocator>>); fn take(self: Box<Self>) -> ::capnp::message::Builder<::capnp::message::HeapAllocator>; } pub trait IncomingMessage { fn get_body<'a>(&'a self) -> ::capnp::Result<::capnp::any_pointer::Reader<'a>>; } pub trait Connection<VatId> { fn get_peer_vat_id(&self) -> VatId; fn new_outgoing_message(&mut self, first_segment_word_size: u32) -> Box<dyn OutgoingMessage>; /// Waits for a message to be received and returns it. If the read stream cleanly terminates, /// returns None. If any other problem occurs, returns an Error. fn receive_incoming_message(&mut self) -> Promise<Option<Box<dyn IncomingMessage>>, Error>; // Waits until all outgoing messages have been sent, then shuts down the outgoing stream. The // returned promise resolves after shutdown is complete. fn shutdown(&mut self, result: ::capnp::Result<()>) -> Promise<(), Error>; } pub trait VatNetwork<VatId> { /// Returns None if `hostId` refers to the local vat. fn connect(&mut self, host_id: VatId) -> Option<Box<dyn Connection<VatId>>>; /// Waits for the next incoming connection and return it. fn accept(&mut self) -> Promise<Box<dyn Connection<VatId>>, ::capnp::Error>; fn drive_until_shutdown(&mut self) -> Promise<(), Error>; } /// A portal to objects available on the network. /// /// The RPC implemententation sits on top of an implementation of `VatNetwork`, which /// determines how to form connections between vats. The RPC implementation determines /// how to use such connections to manage object references and make method calls. /// /// At the moment, this is all rather more general than it needs to be, because the only /// implementation of `VatNetwork` is `twoparty::VatNetwork`. However, eventually we /// will need to have more sophisticated `VatNetwork` implementations, in order to support /// [level 3](https://capnproto.org/rpc.html#protocol-features) features. /// /// An `RpcSystem` is a `Future` and needs to be driven by a task executor. A common way /// accomplish that is to pass the `RpcSystem` to `tokio_core::reactor::Handle::spawn()`. #[must_use = "futures do nothing unless polled"] pub struct RpcSystem<VatId> where VatId:'static { network: Box<dyn crate::VatNetwork<VatId>>, bootstrap_cap: Box<dyn ClientHook>, // XXX To handle three or more party networks, this should be a map from connection pointers // to connection states. connection_state: Rc<RefCell<Option<Rc<rpc::ConnectionState<VatId>>>>>, tasks: TaskSet<(), Error>, handle: crate::task_set::TaskSetHandle<(), Error> } impl <VatId> RpcSystem <VatId> { /// Constructs a new `RpcSystem` with the given network and bootstrap capability. pub fn new( mut network: Box<dyn crate::VatNetwork<VatId>>, bootstrap: Option<::capnp::capability::Client>) -> RpcSystem<VatId> { let bootstrap_cap = match bootstrap { Some(cap) => cap.hook, None => broken::new_cap(Error::failed("no bootstrap capabiity".to_string())), }; let (mut handle, tasks) = TaskSet::new(Box::new(SystemTaskReaper)); let mut handle1 = handle.clone(); handle.add(network.drive_until_shutdown().then(move |r| { let r = match r { Ok(()) => Ok(()), Err(e) => { if e.kind!= ::capnp::ErrorKind::Disconnected { // Don't report disconnects as an error. Err(e) } else { Ok(()) } } }; handle1.terminate(r); Ok(()) })); let mut result = RpcSystem { network: network, bootstrap_cap: bootstrap_cap, connection_state: Rc::new(RefCell::new(None)), tasks: tasks, handle: handle.clone(), }; let accept_loop = result.accept_loop(); handle.add(accept_loop); result } /// Connects to the given vat and returns its bootstrap interface. pub fn bootstrap<T>(&mut self, vat_id: VatId) -> T where T: ::capnp::capability::FromClientHook { let connection = match self.network.connect(vat_id) { Some(connection) => connection, None => { return T::new(self.bootstrap_cap.clone()); } }; let connection_state = RpcSystem::get_connection_state(self.connection_state.clone(), self.bootstrap_cap.clone(), connection, self.handle.clone()); let hook = rpc::ConnectionState::bootstrap(connection_state.clone()); T::new(hook) } // not really a loop, because it doesn't need to be for the two party case fn accept_loop(&mut self) -> Promise<(), Error> { let connection_state_ref = self.connection_state.clone(); let bootstrap_cap = self.bootstrap_cap.clone(); let handle = self.handle.clone(); Promise::from_future(self.network.accept().map(move |connection| { RpcSystem::get_connection_state(connection_state_ref, bootstrap_cap, connection, handle); })) } fn get_connection_state(connection_state_ref: Rc<RefCell<Option<Rc<rpc::ConnectionState<VatId>>>>>, bootstrap_cap: Box<dyn ClientHook>, connection: Box<dyn crate::Connection<VatId>>, mut handle: crate::task_set::TaskSetHandle<(), Error>) -> Rc<rpc::ConnectionState<VatId>> { // TODO this needs to be updated once we allow more general VatNetworks. let (tasks, result) = match *connection_state_ref.borrow() { Some(ref connection_state) => { // return early. return connection_state.clone() } None => { let (on_disconnect_fulfiller, on_disconnect_promise) = oneshot::channel::<Promise<(), Error>>(); let connection_state_ref1 = connection_state_ref.clone(); handle.add(on_disconnect_promise.then(move |shutdown_promise| { *connection_state_ref1.borrow_mut() = None; match shutdown_promise { Ok(s) => s, Err(e) => Promise::err(Error::failed(format!("{}", e))), } })); rpc::ConnectionState::new(bootstrap_cap, connection, on_disconnect_fulfiller) } }; *connection_state_ref.borrow_mut() = Some(result.clone()); handle.add(tasks); result } /// Returns a `Disconnector` future that can be run to cleanly close the connection to this `RpcSystem`'s network. /// You should get the `Disconnector` before you spawn the `RpcSystem`. pub fn get_disconnector(&self) -> rpc::Disconnector<VatId> { rpc::Disconnector::new(self.connection_state.clone()) } } impl <VatId> Future for RpcSystem<VatId> where VatId:'static { type Item = (); type Error = Error; fn poll(&mut self) -> ::futures::Poll<Self::Item, Self::Error> { self.tasks.poll() } } /// Hook that allows local implementations of interfaces to be passed to the RPC system /// so that they can be called remotely. /// /// To use this, you need to do the following dance: /// /// ```ignore /// let client = foo::ToClient::new(FooImpl).into_client::<::capnp_rpc::Server>()); /// ``` pub struct Server; impl ServerHook for Server { fn new_client(server: Box<dyn (::capnp::capability::Server)>) -> ::capnp::capability::Client { ::capnp::capability::Client::new(Box::new(local::Client::new(server))) } } /// Converts a promise for a client into a client that queues up any calls that arrive /// before the promise resolves. // TODO: figure out a better way to allow construction of promise clients. pub fn new_promise_client<T, F>(client_promise: F) -> T where T: ::capnp::capability::FromClientHook, F: ::futures::Future<Item=::capnp::capability::Client,Error=Error>, F:'static { let mut queued_client = crate::queued::Client::new(None); let weak_client = Rc::downgrade(&queued_client.inner); queued_client.drive(client_promise.then(move |r| { if let Some(queued_inner) = weak_client.upgrade() { crate::queued::ClientInner::resolve(&queued_inner, r.map(|c| c.hook)); } Ok(()) })); T::new(Box::new(queued_client)) } struct SystemTaskReaper; impl crate::task_set::TaskReaper<(), Error> for SystemTaskReaper { fn task_failed(&mut self, error: Error) { println!("ERROR: {}", error); } } pub struct ImbuedMessageBuilder<A> where A: ::capnp::message::Allocator { builder: ::capnp::message::Builder<A>, cap_table: Vec<Option<Box<dyn (::capnp::private::capability::ClientHook)>>>, } impl <A> ImbuedMessageBuilder<A> where A: ::capnp::message::Allocator { pub fn new(allocator: A) -> Self { ImbuedMessageBuilder { builder: ::capnp::message::Builder::new(allocator), cap_table: Vec::new(), } } pub fn get_root<'a, T>(&'a mut self) -> ::capnp::Result<T> where T: ::capnp::traits::FromPointerBuilder<'a> { use capnp::traits::ImbueMut; let mut root: ::capnp::any_pointer::Builder = self.builder.get_root()?; root.imbue_mut(&mut self.cap_table); root.get_as() } pub fn set_root<To, From>(&mut self, value: From) -> ::capnp::Result<()> where From: ::capnp::traits::SetPointerBuilder<To> { use capnp::traits::ImbueMut; let mut root: ::capnp::any_pointer::Builder = self.builder.get_root()?; root.imbue_mut(&mut self.cap_table); root.set_as(value) } }
//! An implementation of the [Cap'n Proto remote procedure call](https://capnproto.org/rpc.html) //! protocol. Includes all [Level 1](https://capnproto.org/rpc.html#protocol-features) features. //! //! # Example
random_line_split
isbn.rs
//! isbnid-rs //! Rust ISBN identifier library //! //! isbnid is a simple crate to handle ISBN identification numbers. //! isbnid will store, check and convert ISBNs in ISBN10, and ISBN13 //! formats and it will transform between them and output in URN form. //! isbnid can also output ISBN numbers with the correct hyphens //! corresponding to the actual issuance authorities. The information //! is retrieved from https://www.isbn-international.org/. ISBN numbers //! have a complex internal structure which roughly represents the country, //! the language and the publisher. See also https://en.wikipedia.org/wiki/ISBN. //! //! # Install //! You can find this crate on crates.io and it can be used by adding isbnid to the //! dependencies in your project's Cargo.toml and root file. //! //! ```text //! [dependencies] //! isbnid = "0.1.0" //! ``` //! //! # Usage //! //! ```text //! extern crate isbnid; //! //! use isbnid::isbn; //! //! let id = isbn::ISBN("9780553109535").unwrap(); //! println!("{}", id.isbn10()); //! println!("{}", id.isbn13()); //! ``` //! //! ```text //! 0553109537 //! 9780553109535 //! ``` use std::result; use std::ascii::AsciiExt; use std::str::FromStr; use regex::Regex; use hyphen; #[derive(Debug)] pub enum ISBNError { /// String doesn't form a valid ISBN10 or ISBN13 number encoding Format, /// ISBN Check digit is not valid CheckDigit, /// ISBN13 Bookland encoding (EAN-13) is different form 978 or 979, /// or it is 979 when converting to ISBN10 Bookland, /// ISBN doesn't belong to the ISBN International official range Range } fn digit10(id: &str) -> u64 { let mut n = u64::from_str(&id[0..9]).unwrap(); let mut d = 0u64; for i in 1..10 { d = d + (10 - i) * (n % 10); n = n / 10; } d % 11 } fn digit13(id: &str) -> u64 { let mut n = u64::from_str(&id[0..12]).unwrap(); let mut d = 0u64; for i in 1..13 { d = d + (1 + 2 * (i % 2)) * (n % 10); n = n / 10; } // Kludge for unsigned negative module (100000000000000000u64 - d) % 10 // 10^17 } pub struct ISBN { id: String, } impl ISBN { /// Creates a new ISBN number object. /// It will fail if the encoding is incorrect or if the Bookland is not 978, 979 pub fn new(id: &str) -> result::Result<ISBN, ISBNError> { let reif = Regex::new(r"^(\d(-| )?){9}(x|X|\d|(\d(-| )?){3}\d)$").unwrap(); let reis = Regex::new(r"[^0-9X]").unwrap(); if! id.is_ascii() ||! reif.is_match(id)
let nid: String = reis.replace_all(&id.to_uppercase(), "").into(); if nid.len() == 13 { if &nid[0..3]!= "978" && &nid[0..3]!= "979" { // Invalid Bookland code return Err(ISBNError::Bookland); } if u64::from_str(&nid[12..13]).unwrap()!= digit13(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } return Ok(ISBN{id: nid}); } if nid.len() == 10 { let id13 = "978".to_string() + &nid[0..9]; if &nid[9..10] == "X" && 10!= digit10(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } if &nid[9..10] == "X" && 10 == digit10(&nid) { return Ok(ISBN{id: format!("{}{}", &id13, digit13(&id13))}); } if u64::from_str(&nid[9..10]).unwrap()!= digit10(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } return Ok(ISBN{id: format!("{}{}", &id13, digit13(&id13))}); } // Invalid ISBN format, dead code by regex assert!(false); Err(ISBNError::Format) } /// Returns the ISBN10 encoding. It will fail if the ISBN13 Bookland is 979 /// as ISBN10 is only defined for 978 pub fn isbn10(&self) -> Result<String, ISBNError> { if &self.id[0..3]!= "978" { // Invalid Bookland code return Err(ISBNError::Bookland) } let check10 = digit10(&self.id[3..12]); if check10 == 10 { Ok(format!("{}X", &self.id[3..12] )) } else { Ok(format!("{}{}", &self.id[3..12], check10)) } } /// Returns the ISBN13 encoding. The internal encoding is ISBN13 so this will never fail pub fn isbn13(&self) -> String { format!("{}", &self.id) } /// Returns a hyphenated ISBN13 number. It will fail if the ISBN number is not registered pub fn hyphen(&self) -> Result<String, ISBNError> { let (grp, reg, pbl) = hyphen::segments(&self.id); if grp == 0 { return Err(ISBNError::Range); } Ok([&self.id[0..3], &self.id[3..3 + grp], &self.id[3 + grp.. 3 + grp + reg], &self.id[12 - pbl..12], &self.id[12..13]].join("-")) } /// RFC 2888, URN Encoding of ISBN. https://www.ietf.org/rfc/rfc2288 pub fn urn(&self) -> String { format!("URN:ISBN:{}", &self.id) } /// Returns doi formated ISBN. It fail if the ISBN number is not registered pub fn doi(&self) -> Result<String, ISBNError> { let (grp, reg, pbl) = hyphen::segments(&self.id); if grp == 0 { return Err(ISBNError::Range); } Ok(format!("10.{}.{}/{}", &self.id[0..3], &self.id[3..3 + grp + reg], &self.id[12 - pbl..13])) } /// Static ISBN format validation pub fn is_valid(id: &str) -> bool { match ISBN::new(id) { Ok(_) => true, Err(_) => false } } }
{ // Invalid ISBN format return Err(ISBNError::Format) }
conditional_block
isbn.rs
//! isbnid-rs //! Rust ISBN identifier library //! //! isbnid is a simple crate to handle ISBN identification numbers. //! isbnid will store, check and convert ISBNs in ISBN10, and ISBN13 //! formats and it will transform between them and output in URN form. //! isbnid can also output ISBN numbers with the correct hyphens //! corresponding to the actual issuance authorities. The information //! is retrieved from https://www.isbn-international.org/. ISBN numbers //! have a complex internal structure which roughly represents the country, //! the language and the publisher. See also https://en.wikipedia.org/wiki/ISBN. //! //! # Install //! You can find this crate on crates.io and it can be used by adding isbnid to the //! dependencies in your project's Cargo.toml and root file. //! //! ```text //! [dependencies] //! isbnid = "0.1.0" //! ``` //! //! # Usage //! //! ```text //! extern crate isbnid; //! //! use isbnid::isbn; //! //! let id = isbn::ISBN("9780553109535").unwrap(); //! println!("{}", id.isbn10()); //! println!("{}", id.isbn13()); //! ``` //! //! ```text //! 0553109537 //! 9780553109535 //! ``` use std::result; use std::ascii::AsciiExt; use std::str::FromStr; use regex::Regex; use hyphen; #[derive(Debug)] pub enum
{ /// String doesn't form a valid ISBN10 or ISBN13 number encoding Format, /// ISBN Check digit is not valid CheckDigit, /// ISBN13 Bookland encoding (EAN-13) is different form 978 or 979, /// or it is 979 when converting to ISBN10 Bookland, /// ISBN doesn't belong to the ISBN International official range Range } fn digit10(id: &str) -> u64 { let mut n = u64::from_str(&id[0..9]).unwrap(); let mut d = 0u64; for i in 1..10 { d = d + (10 - i) * (n % 10); n = n / 10; } d % 11 } fn digit13(id: &str) -> u64 { let mut n = u64::from_str(&id[0..12]).unwrap(); let mut d = 0u64; for i in 1..13 { d = d + (1 + 2 * (i % 2)) * (n % 10); n = n / 10; } // Kludge for unsigned negative module (100000000000000000u64 - d) % 10 // 10^17 } pub struct ISBN { id: String, } impl ISBN { /// Creates a new ISBN number object. /// It will fail if the encoding is incorrect or if the Bookland is not 978, 979 pub fn new(id: &str) -> result::Result<ISBN, ISBNError> { let reif = Regex::new(r"^(\d(-| )?){9}(x|X|\d|(\d(-| )?){3}\d)$").unwrap(); let reis = Regex::new(r"[^0-9X]").unwrap(); if! id.is_ascii() ||! reif.is_match(id) { // Invalid ISBN format return Err(ISBNError::Format) } let nid: String = reis.replace_all(&id.to_uppercase(), "").into(); if nid.len() == 13 { if &nid[0..3]!= "978" && &nid[0..3]!= "979" { // Invalid Bookland code return Err(ISBNError::Bookland); } if u64::from_str(&nid[12..13]).unwrap()!= digit13(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } return Ok(ISBN{id: nid}); } if nid.len() == 10 { let id13 = "978".to_string() + &nid[0..9]; if &nid[9..10] == "X" && 10!= digit10(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } if &nid[9..10] == "X" && 10 == digit10(&nid) { return Ok(ISBN{id: format!("{}{}", &id13, digit13(&id13))}); } if u64::from_str(&nid[9..10]).unwrap()!= digit10(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } return Ok(ISBN{id: format!("{}{}", &id13, digit13(&id13))}); } // Invalid ISBN format, dead code by regex assert!(false); Err(ISBNError::Format) } /// Returns the ISBN10 encoding. It will fail if the ISBN13 Bookland is 979 /// as ISBN10 is only defined for 978 pub fn isbn10(&self) -> Result<String, ISBNError> { if &self.id[0..3]!= "978" { // Invalid Bookland code return Err(ISBNError::Bookland) } let check10 = digit10(&self.id[3..12]); if check10 == 10 { Ok(format!("{}X", &self.id[3..12] )) } else { Ok(format!("{}{}", &self.id[3..12], check10)) } } /// Returns the ISBN13 encoding. The internal encoding is ISBN13 so this will never fail pub fn isbn13(&self) -> String { format!("{}", &self.id) } /// Returns a hyphenated ISBN13 number. It will fail if the ISBN number is not registered pub fn hyphen(&self) -> Result<String, ISBNError> { let (grp, reg, pbl) = hyphen::segments(&self.id); if grp == 0 { return Err(ISBNError::Range); } Ok([&self.id[0..3], &self.id[3..3 + grp], &self.id[3 + grp.. 3 + grp + reg], &self.id[12 - pbl..12], &self.id[12..13]].join("-")) } /// RFC 2888, URN Encoding of ISBN. https://www.ietf.org/rfc/rfc2288 pub fn urn(&self) -> String { format!("URN:ISBN:{}", &self.id) } /// Returns doi formated ISBN. It fail if the ISBN number is not registered pub fn doi(&self) -> Result<String, ISBNError> { let (grp, reg, pbl) = hyphen::segments(&self.id); if grp == 0 { return Err(ISBNError::Range); } Ok(format!("10.{}.{}/{}", &self.id[0..3], &self.id[3..3 + grp + reg], &self.id[12 - pbl..13])) } /// Static ISBN format validation pub fn is_valid(id: &str) -> bool { match ISBN::new(id) { Ok(_) => true, Err(_) => false } } }
ISBNError
identifier_name
isbn.rs
//! isbnid-rs //! Rust ISBN identifier library //! //! isbnid is a simple crate to handle ISBN identification numbers. //! isbnid will store, check and convert ISBNs in ISBN10, and ISBN13 //! formats and it will transform between them and output in URN form. //! isbnid can also output ISBN numbers with the correct hyphens //! corresponding to the actual issuance authorities. The information //! is retrieved from https://www.isbn-international.org/. ISBN numbers //! have a complex internal structure which roughly represents the country, //! the language and the publisher. See also https://en.wikipedia.org/wiki/ISBN. //! //! # Install //! You can find this crate on crates.io and it can be used by adding isbnid to the //! dependencies in your project's Cargo.toml and root file. //! //! ```text //! [dependencies] //! isbnid = "0.1.0" //! ``` //! //! # Usage //! //! ```text //! extern crate isbnid; //! //! use isbnid::isbn; //! //! let id = isbn::ISBN("9780553109535").unwrap(); //! println!("{}", id.isbn10()); //! println!("{}", id.isbn13()); //! ``` //! //! ```text //! 0553109537 //! 9780553109535 //! ``` use std::result; use std::ascii::AsciiExt; use std::str::FromStr; use regex::Regex; use hyphen; #[derive(Debug)] pub enum ISBNError { /// String doesn't form a valid ISBN10 or ISBN13 number encoding Format, /// ISBN Check digit is not valid CheckDigit, /// ISBN13 Bookland encoding (EAN-13) is different form 978 or 979, /// or it is 979 when converting to ISBN10 Bookland, /// ISBN doesn't belong to the ISBN International official range Range
let mut d = 0u64; for i in 1..10 { d = d + (10 - i) * (n % 10); n = n / 10; } d % 11 } fn digit13(id: &str) -> u64 { let mut n = u64::from_str(&id[0..12]).unwrap(); let mut d = 0u64; for i in 1..13 { d = d + (1 + 2 * (i % 2)) * (n % 10); n = n / 10; } // Kludge for unsigned negative module (100000000000000000u64 - d) % 10 // 10^17 } pub struct ISBN { id: String, } impl ISBN { /// Creates a new ISBN number object. /// It will fail if the encoding is incorrect or if the Bookland is not 978, 979 pub fn new(id: &str) -> result::Result<ISBN, ISBNError> { let reif = Regex::new(r"^(\d(-| )?){9}(x|X|\d|(\d(-| )?){3}\d)$").unwrap(); let reis = Regex::new(r"[^0-9X]").unwrap(); if! id.is_ascii() ||! reif.is_match(id) { // Invalid ISBN format return Err(ISBNError::Format) } let nid: String = reis.replace_all(&id.to_uppercase(), "").into(); if nid.len() == 13 { if &nid[0..3]!= "978" && &nid[0..3]!= "979" { // Invalid Bookland code return Err(ISBNError::Bookland); } if u64::from_str(&nid[12..13]).unwrap()!= digit13(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } return Ok(ISBN{id: nid}); } if nid.len() == 10 { let id13 = "978".to_string() + &nid[0..9]; if &nid[9..10] == "X" && 10!= digit10(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } if &nid[9..10] == "X" && 10 == digit10(&nid) { return Ok(ISBN{id: format!("{}{}", &id13, digit13(&id13))}); } if u64::from_str(&nid[9..10]).unwrap()!= digit10(&nid) { // Invalid ISBN check digit return Err(ISBNError::CheckDigit); } return Ok(ISBN{id: format!("{}{}", &id13, digit13(&id13))}); } // Invalid ISBN format, dead code by regex assert!(false); Err(ISBNError::Format) } /// Returns the ISBN10 encoding. It will fail if the ISBN13 Bookland is 979 /// as ISBN10 is only defined for 978 pub fn isbn10(&self) -> Result<String, ISBNError> { if &self.id[0..3]!= "978" { // Invalid Bookland code return Err(ISBNError::Bookland) } let check10 = digit10(&self.id[3..12]); if check10 == 10 { Ok(format!("{}X", &self.id[3..12] )) } else { Ok(format!("{}{}", &self.id[3..12], check10)) } } /// Returns the ISBN13 encoding. The internal encoding is ISBN13 so this will never fail pub fn isbn13(&self) -> String { format!("{}", &self.id) } /// Returns a hyphenated ISBN13 number. It will fail if the ISBN number is not registered pub fn hyphen(&self) -> Result<String, ISBNError> { let (grp, reg, pbl) = hyphen::segments(&self.id); if grp == 0 { return Err(ISBNError::Range); } Ok([&self.id[0..3], &self.id[3..3 + grp], &self.id[3 + grp.. 3 + grp + reg], &self.id[12 - pbl..12], &self.id[12..13]].join("-")) } /// RFC 2888, URN Encoding of ISBN. https://www.ietf.org/rfc/rfc2288 pub fn urn(&self) -> String { format!("URN:ISBN:{}", &self.id) } /// Returns doi formated ISBN. It fail if the ISBN number is not registered pub fn doi(&self) -> Result<String, ISBNError> { let (grp, reg, pbl) = hyphen::segments(&self.id); if grp == 0 { return Err(ISBNError::Range); } Ok(format!("10.{}.{}/{}", &self.id[0..3], &self.id[3..3 + grp + reg], &self.id[12 - pbl..13])) } /// Static ISBN format validation pub fn is_valid(id: &str) -> bool { match ISBN::new(id) { Ok(_) => true, Err(_) => false } } }
} fn digit10(id: &str) -> u64 { let mut n = u64::from_str(&id[0..9]).unwrap();
random_line_split
image.rs
/// According to glibc: /// ```c /// /* The x86-64 never uses Elf64_Rel/Elf32_Rel relocations. */ /// #define ELF_MACHINE_NO_REL 1 /// #define ELF_MACHINE_NO_RELA 0 /// ``` use std::fmt; use elf::header::Header; use elf::program_header::{self, ProgramHeader}; use elf::dyn::{self, Dyn}; use elf::sym::{self, Sym}; use goblin::strtab::Strtab; use elf::reloc; use elf::gnu_hash::GnuHash; use tls; /// Computes the "load bias", which is normally the base. However, in older Linux kernel's, 3.13, and whatever runs on travis, I have discovered that the kernel incorrectly maps the vdso with "bad" values. /// /// Specifically, I'm seeing the `p_vaddr` value and `d_val` in the dynamic array showing up with overflow biased values, e.g.: /// ``` /// p/x phdr.p_vaddr /// $1 = 0xffffffffff700000 /// (gdb) p/x bias /// $2 = 0x00007fff873f1000 /// ``` /// In newer kernels the `phdr.p_vaddr` (correctly) reports `0x468` (it's a `ET_DYN` after all), which is then safely added to the original bias/load address to recover the desired address in memory, in this case: 0x7ffff7ff7468. /// Unfortunately, life is not so easy in 3.13, as we're told the `p_vaddr` (and the `d_val` in the dynamic entry entries) is a crazy value like above. Luckily, after looking at what several dynamic linkers do, I noticed that they all seem to implement a version of the following, in that we can recover the correct address by relying on insane overflow arithmetic _regardless_ of whether we received this crazy address, or a normal address: /// ``` /// load_bias = base - p_vaddr + p_offset /// ``` /// In the 3.13 case: /// ``` /// let load_bias = 0x7fff873f1000u64.wrapping_sub(0xffffffffff700000u64.wrapping_add(0)); /// println!("load_bias: 0x{:x}", load_bias); /// let dynamic = load_bias.wrapping_add(0xffffffffff700468); /// println!("dynamic: 0x{:x}", dynamic); /// ``` /// On my machine with `4.4.5-1-ARCH`, the computed load bias will equal itself, and subsequent additions of sane `p_vaddr` values will work as expected. /// As for why the above is the case on older kernels (or perhaps VMs only, I haven't tested extensively), I have no idea. #[inline(always)] pub unsafe fn compute_load_bias_wrapping(base: usize, phdrs:&[ProgramHeader]) -> usize { for phdr in phdrs { if phdr.p_type == program_header::PT_LOAD { return base.wrapping_sub(phdr.p_vaddr.wrapping_add(phdr.p_offset) as usize); } } 0 } /// A `SharedObject` is either: /// 1. an mmap'd dynamic library which is explicitly loaded by `dryad` /// 2. the vdso provided by the kernel /// 3. the executable we're interpreting pub struct SharedObject<'process> { pub load_bias: usize, pub map_begin: usize, // probably remove these? pub map_end: usize, pub libs: Vec<&'process str>, pub phdrs: &'process[ProgramHeader], pub dynamic: &'process [Dyn], pub strtab: Strtab<'process>, pub symtab: &'process[Sym], // yes this is hacks, and yes i hate compile time switches, but // number of relocs can be in 10k+ and not realistic to allocate a buffer // of Reloc structs #[cfg(target_pointer_width = "32")] pub relocations: &'process[reloc::Rel], #[cfg(target_pointer_width = "64")] pub relocations: &'process[reloc::Rela], #[cfg(target_pointer_width = "32")] pub pltrelocations: &'process[reloc::Rel], #[cfg(target_pointer_width = "64")] pub pltrelocations: &'process[reloc::Rela], pub pltgot: *const usize, pub gnu_hash: Option<GnuHash<'process>>, pub load_path: Option<String>, pub flags: usize, pub state_flags: usize, pub tls: Option<tls::TlsInfo>, pub link_info: dyn::DynamicInfo, } impl<'process> fmt::Debug for SharedObject<'process> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "name: {} load_bias: {:x} DT_FLAGS: 0x{:x} DT_FLAGS_1 0x{:x}\n ProgramHeaders: {:#?}\n _DYNAMIC: {:#?}\n String Table: {:#?}\n Symbol Table: {:#?}\n Reloc Table: {:#?}\n Plt Reloc Table: {:#?}\n Libraries: {:#?}\n", self.name(), self.load_bias, self.flags, self.state_flags, self.phdrs, self.dynamic, self.strtab, self.symtab, self.relocations, self.pltrelocations, self.libs) } } macro_rules! gnu_hash { ($link_info:ident, $symtab:ident) => { if let Some(addr) = $link_info.gnu_hash { Some (GnuHash::new(addr as *const u32, $symtab.len(), $symtab)) } else { None } } } impl<'process> SharedObject<'process> { pub fn name (&self) -> &str { &self.strtab[self.link_info.soname] } /// Assumes the object referenced by the ptr has already been mmap'd or loaded into memory some way pub unsafe fn from_raw (ptr: usize) -> SharedObject<'process> { let header = &*(ptr as *const Header); let phdrs = ProgramHeader::from_raw_parts((header.e_phoff as usize + ptr) as *const ProgramHeader, header.e_phnum as usize); let load_bias = compute_load_bias_wrapping(ptr, &phdrs); let dynamic = dyn::from_phdrs(load_bias, phdrs).unwrap(); let link_info = dyn::DynamicInfo::new(&dynamic, load_bias); let num_syms = (link_info.strtab - link_info.symtab) / sym::SIZEOF_SYM; let symtab = sym::from_raw(link_info.symtab as *const sym::Sym, num_syms); let strtab = Strtab::from_raw(link_info.strtab as *const u8, link_info.strsz as usize, 0x0); let libs = dyn::get_needed(dynamic, &strtab, link_info.needed_count); #[cfg(target_pointer_width = "32")] let relocations = reloc::from_raw_rel(link_info.rel as *const reloc::Rel, link_info.relsz); #[cfg(target_pointer_width = "32")] let pltrelocations = reloc::from_raw_rel(link_info.jmprel as *const reloc::Rel, link_info.pltrelsz); #[cfg(target_pointer_width = "64")] let relocations = reloc::from_raw_rela(link_info.rela as *const reloc::Rela, link_info.relasz); #[cfg(target_pointer_width = "64")] let pltrelocations = reloc::from_raw_rela(link_info.jmprel as *const reloc::Rela, link_info.pltrelsz); let pltgot = if let Some(addr) = link_info.pltgot { addr } else { 0 }; SharedObject { load_bias: ptr, map_begin: 0, map_end: 0, libs: libs, phdrs: phdrs, dynamic: dynamic, symtab: symtab, strtab: strtab, relocations: relocations, pltrelocations: pltrelocations, pltgot: pltgot as *const usize, gnu_hash: gnu_hash!(link_info, symtab), load_path: None, flags: link_info.flags as usize, state_flags: link_info.flags_1 as usize, tls: None, // TODO: should probably check for tls, even tho this currently only used for linux gate link_info: link_info, } } pub fn from_executable (name: &'static str, phdr_addr: usize, phnum: usize, lachesis: &mut tls::Lachesis) -> Result<SharedObject<'process>, String> { unsafe { let addr = phdr_addr as *const ProgramHeader; let phdrs = ProgramHeader::from_raw_parts(addr, phnum); let mut load_bias = 0usize; let mut dynamic_vaddr = None; let mut tls_phdr = None; for phdr in phdrs { match phdr.p_type { program_header::PT_PHDR => { load_bias = phdr_addr - phdr.p_vaddr as usize; }, program_header::PT_DYNAMIC => { dynamic_vaddr = Some(phdr.p_vaddr as usize); }, program_header::PT_TLS =>
, _ => () } } let tls = if let Some(phdr) = tls_phdr { Some(lachesis.push_module(name, load_bias, phdr)) } else { None }; if let Some(vaddr) = dynamic_vaddr { let dynamic = dyn::from_raw(load_bias, vaddr); let link_info = dyn::DynamicInfo::new(dynamic, load_bias); // TODO: swap out the link_info syment with compile time constant SIZEOF_SYM? let num_syms = (link_info.strtab - link_info.symtab) / link_info.syment; // this _CAN'T_ generally be valid; but rdr has been doing it and scans every linux shared object binary without issue... so it must be right! let symtab = sym::from_raw(link_info.symtab as *const sym::Sym, num_syms); let strtab = Strtab::from_raw(link_info.strtab as *const u8, link_info.strsz, 0x0); let libs = dyn::get_needed(dynamic, &strtab, link_info.needed_count); #[cfg(target_pointer_width = "32")] let relocations = reloc::from_raw_rel(link_info.rel as *const reloc::Rel, link_info.relsz); #[cfg(target_pointer_width = "32")] let pltrelocations = reloc::from_raw_rel(link_info.jmprel as *const reloc::Rel, link_info.pltrelsz); #[cfg(target_pointer_width = "64")] let relocations = reloc::from_raw_rela(link_info.rela as *const reloc::Rela, link_info.relasz); #[cfg(target_pointer_width = "64")] let pltrelocations = reloc::from_raw_rela(link_info.jmprel as *const reloc::Rela, link_info.pltrelsz); // TODO: fail with Err, not panic let pltgot = link_info.pltgot.expect("Error executable has no pltgot, aborting") as *const usize; Ok (SharedObject { load_bias: load_bias, map_begin: 0, map_end: 0, libs: libs, phdrs: phdrs, dynamic: dynamic, symtab: symtab, strtab: strtab, relocations: relocations, pltrelocations: pltrelocations, pltgot: pltgot, gnu_hash: gnu_hash!(link_info, symtab), load_path: Some (name.to_string()), // TODO: make absolute?, flags: link_info.flags as usize, state_flags: link_info.flags_1 as usize, tls: tls, link_info: link_info, }) } else { Err (format!("Error: executable {} has no _DYNAMIC array", name)) } } } /// This is used by dryad's runtime symbol resolution pub fn find (&self, name: &str, hash: u32) -> Option<&sym::Sym> { // println!("<{}.find> finding symbol: {}", self.name, symbol); match self.gnu_hash { Some (ref gnu_hash) => gnu_hash.find(name, hash, &self.strtab), None => None } } } //unsafe impl<'a> Send for SharedObject<'a> {} //unsafe impl<'a> Sync for SharedObject<'a> {}
{ tls_phdr = Some(phdr); }
conditional_block
image.rs
/// According to glibc: /// ```c /// /* The x86-64 never uses Elf64_Rel/Elf32_Rel relocations. */ /// #define ELF_MACHINE_NO_REL 1 /// #define ELF_MACHINE_NO_RELA 0 /// ``` use std::fmt; use elf::header::Header; use elf::program_header::{self, ProgramHeader}; use elf::dyn::{self, Dyn}; use elf::sym::{self, Sym}; use goblin::strtab::Strtab; use elf::reloc; use elf::gnu_hash::GnuHash; use tls; /// Computes the "load bias", which is normally the base. However, in older Linux kernel's, 3.13, and whatever runs on travis, I have discovered that the kernel incorrectly maps the vdso with "bad" values. /// /// Specifically, I'm seeing the `p_vaddr` value and `d_val` in the dynamic array showing up with overflow biased values, e.g.: /// ``` /// p/x phdr.p_vaddr /// $1 = 0xffffffffff700000 /// (gdb) p/x bias /// $2 = 0x00007fff873f1000 /// ``` /// In newer kernels the `phdr.p_vaddr` (correctly) reports `0x468` (it's a `ET_DYN` after all), which is then safely added to the original bias/load address to recover the desired address in memory, in this case: 0x7ffff7ff7468. /// Unfortunately, life is not so easy in 3.13, as we're told the `p_vaddr` (and the `d_val` in the dynamic entry entries) is a crazy value like above. Luckily, after looking at what several dynamic linkers do, I noticed that they all seem to implement a version of the following, in that we can recover the correct address by relying on insane overflow arithmetic _regardless_ of whether we received this crazy address, or a normal address: /// ``` /// load_bias = base - p_vaddr + p_offset /// ``` /// In the 3.13 case: /// ``` /// let load_bias = 0x7fff873f1000u64.wrapping_sub(0xffffffffff700000u64.wrapping_add(0)); /// println!("load_bias: 0x{:x}", load_bias); /// let dynamic = load_bias.wrapping_add(0xffffffffff700468); /// println!("dynamic: 0x{:x}", dynamic); /// ``` /// On my machine with `4.4.5-1-ARCH`, the computed load bias will equal itself, and subsequent additions of sane `p_vaddr` values will work as expected. /// As for why the above is the case on older kernels (or perhaps VMs only, I haven't tested extensively), I have no idea. #[inline(always)] pub unsafe fn compute_load_bias_wrapping(base: usize, phdrs:&[ProgramHeader]) -> usize { for phdr in phdrs { if phdr.p_type == program_header::PT_LOAD { return base.wrapping_sub(phdr.p_vaddr.wrapping_add(phdr.p_offset) as usize); } } 0 } /// A `SharedObject` is either: /// 1. an mmap'd dynamic library which is explicitly loaded by `dryad` /// 2. the vdso provided by the kernel /// 3. the executable we're interpreting pub struct SharedObject<'process> { pub load_bias: usize, pub map_begin: usize, // probably remove these? pub map_end: usize, pub libs: Vec<&'process str>, pub phdrs: &'process[ProgramHeader], pub dynamic: &'process [Dyn], pub strtab: Strtab<'process>, pub symtab: &'process[Sym], // yes this is hacks, and yes i hate compile time switches, but // number of relocs can be in 10k+ and not realistic to allocate a buffer // of Reloc structs #[cfg(target_pointer_width = "32")] pub relocations: &'process[reloc::Rel], #[cfg(target_pointer_width = "64")] pub relocations: &'process[reloc::Rela], #[cfg(target_pointer_width = "32")] pub pltrelocations: &'process[reloc::Rel], #[cfg(target_pointer_width = "64")] pub pltrelocations: &'process[reloc::Rela], pub pltgot: *const usize, pub gnu_hash: Option<GnuHash<'process>>, pub load_path: Option<String>, pub flags: usize, pub state_flags: usize, pub tls: Option<tls::TlsInfo>, pub link_info: dyn::DynamicInfo, } impl<'process> fmt::Debug for SharedObject<'process> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "name: {} load_bias: {:x} DT_FLAGS: 0x{:x} DT_FLAGS_1 0x{:x}\n ProgramHeaders: {:#?}\n _DYNAMIC: {:#?}\n String Table: {:#?}\n Symbol Table: {:#?}\n Reloc Table: {:#?}\n Plt Reloc Table: {:#?}\n Libraries: {:#?}\n", self.name(), self.load_bias, self.flags, self.state_flags, self.phdrs, self.dynamic, self.strtab, self.symtab, self.relocations, self.pltrelocations, self.libs) } } macro_rules! gnu_hash { ($link_info:ident, $symtab:ident) => { if let Some(addr) = $link_info.gnu_hash { Some (GnuHash::new(addr as *const u32, $symtab.len(), $symtab)) } else { None } } } impl<'process> SharedObject<'process> { pub fn name (&self) -> &str { &self.strtab[self.link_info.soname] } /// Assumes the object referenced by the ptr has already been mmap'd or loaded into memory some way pub unsafe fn from_raw (ptr: usize) -> SharedObject<'process> { let header = &*(ptr as *const Header); let phdrs = ProgramHeader::from_raw_parts((header.e_phoff as usize + ptr) as *const ProgramHeader, header.e_phnum as usize); let load_bias = compute_load_bias_wrapping(ptr, &phdrs); let dynamic = dyn::from_phdrs(load_bias, phdrs).unwrap(); let link_info = dyn::DynamicInfo::new(&dynamic, load_bias); let num_syms = (link_info.strtab - link_info.symtab) / sym::SIZEOF_SYM; let symtab = sym::from_raw(link_info.symtab as *const sym::Sym, num_syms); let strtab = Strtab::from_raw(link_info.strtab as *const u8, link_info.strsz as usize, 0x0); let libs = dyn::get_needed(dynamic, &strtab, link_info.needed_count); #[cfg(target_pointer_width = "32")] let relocations = reloc::from_raw_rel(link_info.rel as *const reloc::Rel, link_info.relsz); #[cfg(target_pointer_width = "32")] let pltrelocations = reloc::from_raw_rel(link_info.jmprel as *const reloc::Rel, link_info.pltrelsz); #[cfg(target_pointer_width = "64")] let relocations = reloc::from_raw_rela(link_info.rela as *const reloc::Rela, link_info.relasz); #[cfg(target_pointer_width = "64")] let pltrelocations = reloc::from_raw_rela(link_info.jmprel as *const reloc::Rela, link_info.pltrelsz); let pltgot = if let Some(addr) = link_info.pltgot { addr } else { 0 }; SharedObject { load_bias: ptr, map_begin: 0, map_end: 0, libs: libs, phdrs: phdrs, dynamic: dynamic, symtab: symtab, strtab: strtab, relocations: relocations, pltrelocations: pltrelocations, pltgot: pltgot as *const usize, gnu_hash: gnu_hash!(link_info, symtab), load_path: None, flags: link_info.flags as usize, state_flags: link_info.flags_1 as usize, tls: None, // TODO: should probably check for tls, even tho this currently only used for linux gate link_info: link_info, } } pub fn from_executable (name: &'static str, phdr_addr: usize, phnum: usize, lachesis: &mut tls::Lachesis) -> Result<SharedObject<'process>, String> { unsafe { let addr = phdr_addr as *const ProgramHeader; let phdrs = ProgramHeader::from_raw_parts(addr, phnum); let mut load_bias = 0usize; let mut dynamic_vaddr = None; let mut tls_phdr = None; for phdr in phdrs { match phdr.p_type { program_header::PT_PHDR => { load_bias = phdr_addr - phdr.p_vaddr as usize; }, program_header::PT_DYNAMIC => { dynamic_vaddr = Some(phdr.p_vaddr as usize); }, program_header::PT_TLS => { tls_phdr = Some(phdr); }, _ => () } }
if let Some(vaddr) = dynamic_vaddr { let dynamic = dyn::from_raw(load_bias, vaddr); let link_info = dyn::DynamicInfo::new(dynamic, load_bias); // TODO: swap out the link_info syment with compile time constant SIZEOF_SYM? let num_syms = (link_info.strtab - link_info.symtab) / link_info.syment; // this _CAN'T_ generally be valid; but rdr has been doing it and scans every linux shared object binary without issue... so it must be right! let symtab = sym::from_raw(link_info.symtab as *const sym::Sym, num_syms); let strtab = Strtab::from_raw(link_info.strtab as *const u8, link_info.strsz, 0x0); let libs = dyn::get_needed(dynamic, &strtab, link_info.needed_count); #[cfg(target_pointer_width = "32")] let relocations = reloc::from_raw_rel(link_info.rel as *const reloc::Rel, link_info.relsz); #[cfg(target_pointer_width = "32")] let pltrelocations = reloc::from_raw_rel(link_info.jmprel as *const reloc::Rel, link_info.pltrelsz); #[cfg(target_pointer_width = "64")] let relocations = reloc::from_raw_rela(link_info.rela as *const reloc::Rela, link_info.relasz); #[cfg(target_pointer_width = "64")] let pltrelocations = reloc::from_raw_rela(link_info.jmprel as *const reloc::Rela, link_info.pltrelsz); // TODO: fail with Err, not panic let pltgot = link_info.pltgot.expect("Error executable has no pltgot, aborting") as *const usize; Ok (SharedObject { load_bias: load_bias, map_begin: 0, map_end: 0, libs: libs, phdrs: phdrs, dynamic: dynamic, symtab: symtab, strtab: strtab, relocations: relocations, pltrelocations: pltrelocations, pltgot: pltgot, gnu_hash: gnu_hash!(link_info, symtab), load_path: Some (name.to_string()), // TODO: make absolute?, flags: link_info.flags as usize, state_flags: link_info.flags_1 as usize, tls: tls, link_info: link_info, }) } else { Err (format!("Error: executable {} has no _DYNAMIC array", name)) } } } /// This is used by dryad's runtime symbol resolution pub fn find (&self, name: &str, hash: u32) -> Option<&sym::Sym> { // println!("<{}.find> finding symbol: {}", self.name, symbol); match self.gnu_hash { Some (ref gnu_hash) => gnu_hash.find(name, hash, &self.strtab), None => None } } } //unsafe impl<'a> Send for SharedObject<'a> {} //unsafe impl<'a> Sync for SharedObject<'a> {}
let tls = if let Some(phdr) = tls_phdr { Some(lachesis.push_module(name, load_bias, phdr)) } else { None };
random_line_split
image.rs
/// According to glibc: /// ```c /// /* The x86-64 never uses Elf64_Rel/Elf32_Rel relocations. */ /// #define ELF_MACHINE_NO_REL 1 /// #define ELF_MACHINE_NO_RELA 0 /// ``` use std::fmt; use elf::header::Header; use elf::program_header::{self, ProgramHeader}; use elf::dyn::{self, Dyn}; use elf::sym::{self, Sym}; use goblin::strtab::Strtab; use elf::reloc; use elf::gnu_hash::GnuHash; use tls; /// Computes the "load bias", which is normally the base. However, in older Linux kernel's, 3.13, and whatever runs on travis, I have discovered that the kernel incorrectly maps the vdso with "bad" values. /// /// Specifically, I'm seeing the `p_vaddr` value and `d_val` in the dynamic array showing up with overflow biased values, e.g.: /// ``` /// p/x phdr.p_vaddr /// $1 = 0xffffffffff700000 /// (gdb) p/x bias /// $2 = 0x00007fff873f1000 /// ``` /// In newer kernels the `phdr.p_vaddr` (correctly) reports `0x468` (it's a `ET_DYN` after all), which is then safely added to the original bias/load address to recover the desired address in memory, in this case: 0x7ffff7ff7468. /// Unfortunately, life is not so easy in 3.13, as we're told the `p_vaddr` (and the `d_val` in the dynamic entry entries) is a crazy value like above. Luckily, after looking at what several dynamic linkers do, I noticed that they all seem to implement a version of the following, in that we can recover the correct address by relying on insane overflow arithmetic _regardless_ of whether we received this crazy address, or a normal address: /// ``` /// load_bias = base - p_vaddr + p_offset /// ``` /// In the 3.13 case: /// ``` /// let load_bias = 0x7fff873f1000u64.wrapping_sub(0xffffffffff700000u64.wrapping_add(0)); /// println!("load_bias: 0x{:x}", load_bias); /// let dynamic = load_bias.wrapping_add(0xffffffffff700468); /// println!("dynamic: 0x{:x}", dynamic); /// ``` /// On my machine with `4.4.5-1-ARCH`, the computed load bias will equal itself, and subsequent additions of sane `p_vaddr` values will work as expected. /// As for why the above is the case on older kernels (or perhaps VMs only, I haven't tested extensively), I have no idea. #[inline(always)] pub unsafe fn compute_load_bias_wrapping(base: usize, phdrs:&[ProgramHeader]) -> usize { for phdr in phdrs { if phdr.p_type == program_header::PT_LOAD { return base.wrapping_sub(phdr.p_vaddr.wrapping_add(phdr.p_offset) as usize); } } 0 } /// A `SharedObject` is either: /// 1. an mmap'd dynamic library which is explicitly loaded by `dryad` /// 2. the vdso provided by the kernel /// 3. the executable we're interpreting pub struct SharedObject<'process> { pub load_bias: usize, pub map_begin: usize, // probably remove these? pub map_end: usize, pub libs: Vec<&'process str>, pub phdrs: &'process[ProgramHeader], pub dynamic: &'process [Dyn], pub strtab: Strtab<'process>, pub symtab: &'process[Sym], // yes this is hacks, and yes i hate compile time switches, but // number of relocs can be in 10k+ and not realistic to allocate a buffer // of Reloc structs #[cfg(target_pointer_width = "32")] pub relocations: &'process[reloc::Rel], #[cfg(target_pointer_width = "64")] pub relocations: &'process[reloc::Rela], #[cfg(target_pointer_width = "32")] pub pltrelocations: &'process[reloc::Rel], #[cfg(target_pointer_width = "64")] pub pltrelocations: &'process[reloc::Rela], pub pltgot: *const usize, pub gnu_hash: Option<GnuHash<'process>>, pub load_path: Option<String>, pub flags: usize, pub state_flags: usize, pub tls: Option<tls::TlsInfo>, pub link_info: dyn::DynamicInfo, } impl<'process> fmt::Debug for SharedObject<'process> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "name: {} load_bias: {:x} DT_FLAGS: 0x{:x} DT_FLAGS_1 0x{:x}\n ProgramHeaders: {:#?}\n _DYNAMIC: {:#?}\n String Table: {:#?}\n Symbol Table: {:#?}\n Reloc Table: {:#?}\n Plt Reloc Table: {:#?}\n Libraries: {:#?}\n", self.name(), self.load_bias, self.flags, self.state_flags, self.phdrs, self.dynamic, self.strtab, self.symtab, self.relocations, self.pltrelocations, self.libs) } } macro_rules! gnu_hash { ($link_info:ident, $symtab:ident) => { if let Some(addr) = $link_info.gnu_hash { Some (GnuHash::new(addr as *const u32, $symtab.len(), $symtab)) } else { None } } } impl<'process> SharedObject<'process> { pub fn name (&self) -> &str { &self.strtab[self.link_info.soname] } /// Assumes the object referenced by the ptr has already been mmap'd or loaded into memory some way pub unsafe fn from_raw (ptr: usize) -> SharedObject<'process>
load_bias: ptr, map_begin: 0, map_end: 0, libs: libs, phdrs: phdrs, dynamic: dynamic, symtab: symtab, strtab: strtab, relocations: relocations, pltrelocations: pltrelocations, pltgot: pltgot as *const usize, gnu_hash: gnu_hash!(link_info, symtab), load_path: None, flags: link_info.flags as usize, state_flags: link_info.flags_1 as usize, tls: None, // TODO: should probably check for tls, even tho this currently only used for linux gate link_info: link_info, } } pub fn from_executable (name: &'static str, phdr_addr: usize, phnum: usize, lachesis: &mut tls::Lachesis) -> Result<SharedObject<'process>, String> { unsafe { let addr = phdr_addr as *const ProgramHeader; let phdrs = ProgramHeader::from_raw_parts(addr, phnum); let mut load_bias = 0usize; let mut dynamic_vaddr = None; let mut tls_phdr = None; for phdr in phdrs { match phdr.p_type { program_header::PT_PHDR => { load_bias = phdr_addr - phdr.p_vaddr as usize; }, program_header::PT_DYNAMIC => { dynamic_vaddr = Some(phdr.p_vaddr as usize); }, program_header::PT_TLS => { tls_phdr = Some(phdr); }, _ => () } } let tls = if let Some(phdr) = tls_phdr { Some(lachesis.push_module(name, load_bias, phdr)) } else { None }; if let Some(vaddr) = dynamic_vaddr { let dynamic = dyn::from_raw(load_bias, vaddr); let link_info = dyn::DynamicInfo::new(dynamic, load_bias); // TODO: swap out the link_info syment with compile time constant SIZEOF_SYM? let num_syms = (link_info.strtab - link_info.symtab) / link_info.syment; // this _CAN'T_ generally be valid; but rdr has been doing it and scans every linux shared object binary without issue... so it must be right! let symtab = sym::from_raw(link_info.symtab as *const sym::Sym, num_syms); let strtab = Strtab::from_raw(link_info.strtab as *const u8, link_info.strsz, 0x0); let libs = dyn::get_needed(dynamic, &strtab, link_info.needed_count); #[cfg(target_pointer_width = "32")] let relocations = reloc::from_raw_rel(link_info.rel as *const reloc::Rel, link_info.relsz); #[cfg(target_pointer_width = "32")] let pltrelocations = reloc::from_raw_rel(link_info.jmprel as *const reloc::Rel, link_info.pltrelsz); #[cfg(target_pointer_width = "64")] let relocations = reloc::from_raw_rela(link_info.rela as *const reloc::Rela, link_info.relasz); #[cfg(target_pointer_width = "64")] let pltrelocations = reloc::from_raw_rela(link_info.jmprel as *const reloc::Rela, link_info.pltrelsz); // TODO: fail with Err, not panic let pltgot = link_info.pltgot.expect("Error executable has no pltgot, aborting") as *const usize; Ok (SharedObject { load_bias: load_bias, map_begin: 0, map_end: 0, libs: libs, phdrs: phdrs, dynamic: dynamic, symtab: symtab, strtab: strtab, relocations: relocations, pltrelocations: pltrelocations, pltgot: pltgot, gnu_hash: gnu_hash!(link_info, symtab), load_path: Some (name.to_string()), // TODO: make absolute?, flags: link_info.flags as usize, state_flags: link_info.flags_1 as usize, tls: tls, link_info: link_info, }) } else { Err (format!("Error: executable {} has no _DYNAMIC array", name)) } } } /// This is used by dryad's runtime symbol resolution pub fn find (&self, name: &str, hash: u32) -> Option<&sym::Sym> { // println!("<{}.find> finding symbol: {}", self.name, symbol); match self.gnu_hash { Some (ref gnu_hash) => gnu_hash.find(name, hash, &self.strtab), None => None } } } //unsafe impl<'a> Send for SharedObject<'a> {} //unsafe impl<'a> Sync for SharedObject<'a> {}
{ let header = &*(ptr as *const Header); let phdrs = ProgramHeader::from_raw_parts((header.e_phoff as usize + ptr) as *const ProgramHeader, header.e_phnum as usize); let load_bias = compute_load_bias_wrapping(ptr, &phdrs); let dynamic = dyn::from_phdrs(load_bias, phdrs).unwrap(); let link_info = dyn::DynamicInfo::new(&dynamic, load_bias); let num_syms = (link_info.strtab - link_info.symtab) / sym::SIZEOF_SYM; let symtab = sym::from_raw(link_info.symtab as *const sym::Sym, num_syms); let strtab = Strtab::from_raw(link_info.strtab as *const u8, link_info.strsz as usize, 0x0); let libs = dyn::get_needed(dynamic, &strtab, link_info.needed_count); #[cfg(target_pointer_width = "32")] let relocations = reloc::from_raw_rel(link_info.rel as *const reloc::Rel, link_info.relsz); #[cfg(target_pointer_width = "32")] let pltrelocations = reloc::from_raw_rel(link_info.jmprel as *const reloc::Rel, link_info.pltrelsz); #[cfg(target_pointer_width = "64")] let relocations = reloc::from_raw_rela(link_info.rela as *const reloc::Rela, link_info.relasz); #[cfg(target_pointer_width = "64")] let pltrelocations = reloc::from_raw_rela(link_info.jmprel as *const reloc::Rela, link_info.pltrelsz); let pltgot = if let Some(addr) = link_info.pltgot { addr } else { 0 }; SharedObject {
identifier_body
image.rs
/// According to glibc: /// ```c /// /* The x86-64 never uses Elf64_Rel/Elf32_Rel relocations. */ /// #define ELF_MACHINE_NO_REL 1 /// #define ELF_MACHINE_NO_RELA 0 /// ``` use std::fmt; use elf::header::Header; use elf::program_header::{self, ProgramHeader}; use elf::dyn::{self, Dyn}; use elf::sym::{self, Sym}; use goblin::strtab::Strtab; use elf::reloc; use elf::gnu_hash::GnuHash; use tls; /// Computes the "load bias", which is normally the base. However, in older Linux kernel's, 3.13, and whatever runs on travis, I have discovered that the kernel incorrectly maps the vdso with "bad" values. /// /// Specifically, I'm seeing the `p_vaddr` value and `d_val` in the dynamic array showing up with overflow biased values, e.g.: /// ``` /// p/x phdr.p_vaddr /// $1 = 0xffffffffff700000 /// (gdb) p/x bias /// $2 = 0x00007fff873f1000 /// ``` /// In newer kernels the `phdr.p_vaddr` (correctly) reports `0x468` (it's a `ET_DYN` after all), which is then safely added to the original bias/load address to recover the desired address in memory, in this case: 0x7ffff7ff7468. /// Unfortunately, life is not so easy in 3.13, as we're told the `p_vaddr` (and the `d_val` in the dynamic entry entries) is a crazy value like above. Luckily, after looking at what several dynamic linkers do, I noticed that they all seem to implement a version of the following, in that we can recover the correct address by relying on insane overflow arithmetic _regardless_ of whether we received this crazy address, or a normal address: /// ``` /// load_bias = base - p_vaddr + p_offset /// ``` /// In the 3.13 case: /// ``` /// let load_bias = 0x7fff873f1000u64.wrapping_sub(0xffffffffff700000u64.wrapping_add(0)); /// println!("load_bias: 0x{:x}", load_bias); /// let dynamic = load_bias.wrapping_add(0xffffffffff700468); /// println!("dynamic: 0x{:x}", dynamic); /// ``` /// On my machine with `4.4.5-1-ARCH`, the computed load bias will equal itself, and subsequent additions of sane `p_vaddr` values will work as expected. /// As for why the above is the case on older kernels (or perhaps VMs only, I haven't tested extensively), I have no idea. #[inline(always)] pub unsafe fn
(base: usize, phdrs:&[ProgramHeader]) -> usize { for phdr in phdrs { if phdr.p_type == program_header::PT_LOAD { return base.wrapping_sub(phdr.p_vaddr.wrapping_add(phdr.p_offset) as usize); } } 0 } /// A `SharedObject` is either: /// 1. an mmap'd dynamic library which is explicitly loaded by `dryad` /// 2. the vdso provided by the kernel /// 3. the executable we're interpreting pub struct SharedObject<'process> { pub load_bias: usize, pub map_begin: usize, // probably remove these? pub map_end: usize, pub libs: Vec<&'process str>, pub phdrs: &'process[ProgramHeader], pub dynamic: &'process [Dyn], pub strtab: Strtab<'process>, pub symtab: &'process[Sym], // yes this is hacks, and yes i hate compile time switches, but // number of relocs can be in 10k+ and not realistic to allocate a buffer // of Reloc structs #[cfg(target_pointer_width = "32")] pub relocations: &'process[reloc::Rel], #[cfg(target_pointer_width = "64")] pub relocations: &'process[reloc::Rela], #[cfg(target_pointer_width = "32")] pub pltrelocations: &'process[reloc::Rel], #[cfg(target_pointer_width = "64")] pub pltrelocations: &'process[reloc::Rela], pub pltgot: *const usize, pub gnu_hash: Option<GnuHash<'process>>, pub load_path: Option<String>, pub flags: usize, pub state_flags: usize, pub tls: Option<tls::TlsInfo>, pub link_info: dyn::DynamicInfo, } impl<'process> fmt::Debug for SharedObject<'process> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "name: {} load_bias: {:x} DT_FLAGS: 0x{:x} DT_FLAGS_1 0x{:x}\n ProgramHeaders: {:#?}\n _DYNAMIC: {:#?}\n String Table: {:#?}\n Symbol Table: {:#?}\n Reloc Table: {:#?}\n Plt Reloc Table: {:#?}\n Libraries: {:#?}\n", self.name(), self.load_bias, self.flags, self.state_flags, self.phdrs, self.dynamic, self.strtab, self.symtab, self.relocations, self.pltrelocations, self.libs) } } macro_rules! gnu_hash { ($link_info:ident, $symtab:ident) => { if let Some(addr) = $link_info.gnu_hash { Some (GnuHash::new(addr as *const u32, $symtab.len(), $symtab)) } else { None } } } impl<'process> SharedObject<'process> { pub fn name (&self) -> &str { &self.strtab[self.link_info.soname] } /// Assumes the object referenced by the ptr has already been mmap'd or loaded into memory some way pub unsafe fn from_raw (ptr: usize) -> SharedObject<'process> { let header = &*(ptr as *const Header); let phdrs = ProgramHeader::from_raw_parts((header.e_phoff as usize + ptr) as *const ProgramHeader, header.e_phnum as usize); let load_bias = compute_load_bias_wrapping(ptr, &phdrs); let dynamic = dyn::from_phdrs(load_bias, phdrs).unwrap(); let link_info = dyn::DynamicInfo::new(&dynamic, load_bias); let num_syms = (link_info.strtab - link_info.symtab) / sym::SIZEOF_SYM; let symtab = sym::from_raw(link_info.symtab as *const sym::Sym, num_syms); let strtab = Strtab::from_raw(link_info.strtab as *const u8, link_info.strsz as usize, 0x0); let libs = dyn::get_needed(dynamic, &strtab, link_info.needed_count); #[cfg(target_pointer_width = "32")] let relocations = reloc::from_raw_rel(link_info.rel as *const reloc::Rel, link_info.relsz); #[cfg(target_pointer_width = "32")] let pltrelocations = reloc::from_raw_rel(link_info.jmprel as *const reloc::Rel, link_info.pltrelsz); #[cfg(target_pointer_width = "64")] let relocations = reloc::from_raw_rela(link_info.rela as *const reloc::Rela, link_info.relasz); #[cfg(target_pointer_width = "64")] let pltrelocations = reloc::from_raw_rela(link_info.jmprel as *const reloc::Rela, link_info.pltrelsz); let pltgot = if let Some(addr) = link_info.pltgot { addr } else { 0 }; SharedObject { load_bias: ptr, map_begin: 0, map_end: 0, libs: libs, phdrs: phdrs, dynamic: dynamic, symtab: symtab, strtab: strtab, relocations: relocations, pltrelocations: pltrelocations, pltgot: pltgot as *const usize, gnu_hash: gnu_hash!(link_info, symtab), load_path: None, flags: link_info.flags as usize, state_flags: link_info.flags_1 as usize, tls: None, // TODO: should probably check for tls, even tho this currently only used for linux gate link_info: link_info, } } pub fn from_executable (name: &'static str, phdr_addr: usize, phnum: usize, lachesis: &mut tls::Lachesis) -> Result<SharedObject<'process>, String> { unsafe { let addr = phdr_addr as *const ProgramHeader; let phdrs = ProgramHeader::from_raw_parts(addr, phnum); let mut load_bias = 0usize; let mut dynamic_vaddr = None; let mut tls_phdr = None; for phdr in phdrs { match phdr.p_type { program_header::PT_PHDR => { load_bias = phdr_addr - phdr.p_vaddr as usize; }, program_header::PT_DYNAMIC => { dynamic_vaddr = Some(phdr.p_vaddr as usize); }, program_header::PT_TLS => { tls_phdr = Some(phdr); }, _ => () } } let tls = if let Some(phdr) = tls_phdr { Some(lachesis.push_module(name, load_bias, phdr)) } else { None }; if let Some(vaddr) = dynamic_vaddr { let dynamic = dyn::from_raw(load_bias, vaddr); let link_info = dyn::DynamicInfo::new(dynamic, load_bias); // TODO: swap out the link_info syment with compile time constant SIZEOF_SYM? let num_syms = (link_info.strtab - link_info.symtab) / link_info.syment; // this _CAN'T_ generally be valid; but rdr has been doing it and scans every linux shared object binary without issue... so it must be right! let symtab = sym::from_raw(link_info.symtab as *const sym::Sym, num_syms); let strtab = Strtab::from_raw(link_info.strtab as *const u8, link_info.strsz, 0x0); let libs = dyn::get_needed(dynamic, &strtab, link_info.needed_count); #[cfg(target_pointer_width = "32")] let relocations = reloc::from_raw_rel(link_info.rel as *const reloc::Rel, link_info.relsz); #[cfg(target_pointer_width = "32")] let pltrelocations = reloc::from_raw_rel(link_info.jmprel as *const reloc::Rel, link_info.pltrelsz); #[cfg(target_pointer_width = "64")] let relocations = reloc::from_raw_rela(link_info.rela as *const reloc::Rela, link_info.relasz); #[cfg(target_pointer_width = "64")] let pltrelocations = reloc::from_raw_rela(link_info.jmprel as *const reloc::Rela, link_info.pltrelsz); // TODO: fail with Err, not panic let pltgot = link_info.pltgot.expect("Error executable has no pltgot, aborting") as *const usize; Ok (SharedObject { load_bias: load_bias, map_begin: 0, map_end: 0, libs: libs, phdrs: phdrs, dynamic: dynamic, symtab: symtab, strtab: strtab, relocations: relocations, pltrelocations: pltrelocations, pltgot: pltgot, gnu_hash: gnu_hash!(link_info, symtab), load_path: Some (name.to_string()), // TODO: make absolute?, flags: link_info.flags as usize, state_flags: link_info.flags_1 as usize, tls: tls, link_info: link_info, }) } else { Err (format!("Error: executable {} has no _DYNAMIC array", name)) } } } /// This is used by dryad's runtime symbol resolution pub fn find (&self, name: &str, hash: u32) -> Option<&sym::Sym> { // println!("<{}.find> finding symbol: {}", self.name, symbol); match self.gnu_hash { Some (ref gnu_hash) => gnu_hash.find(name, hash, &self.strtab), None => None } } } //unsafe impl<'a> Send for SharedObject<'a> {} //unsafe impl<'a> Sync for SharedObject<'a> {}
compute_load_bias_wrapping
identifier_name
log-knows-the-names-of-variants-in-std.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(Clone, Show)] enum foo { a(uint), b(String), } fn check_log<T: std::fmt::Show>(exp: String, v: T) { assert_eq!(exp, format!("{:?}", v)); } pub fn main() { let mut x = Some(foo::a(22u)); let exp = "Some(a(22u))".to_string(); let act = format!("{:?}", x); assert_eq!(act, exp); check_log(exp, x); x = None; let exp = "None".to_string(); let act = format!("{:?}", x); assert_eq!(act, exp);
}
check_log(exp, x);
random_line_split
log-knows-the-names-of-variants-in-std.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(Clone, Show)] enum
{ a(uint), b(String), } fn check_log<T: std::fmt::Show>(exp: String, v: T) { assert_eq!(exp, format!("{:?}", v)); } pub fn main() { let mut x = Some(foo::a(22u)); let exp = "Some(a(22u))".to_string(); let act = format!("{:?}", x); assert_eq!(act, exp); check_log(exp, x); x = None; let exp = "None".to_string(); let act = format!("{:?}", x); assert_eq!(act, exp); check_log(exp, x); }
foo
identifier_name
log-knows-the-names-of-variants-in-std.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(Clone, Show)] enum foo { a(uint), b(String), } fn check_log<T: std::fmt::Show>(exp: String, v: T) { assert_eq!(exp, format!("{:?}", v)); } pub fn main()
{ let mut x = Some(foo::a(22u)); let exp = "Some(a(22u))".to_string(); let act = format!("{:?}", x); assert_eq!(act, exp); check_log(exp, x); x = None; let exp = "None".to_string(); let act = format!("{:?}", x); assert_eq!(act, exp); check_log(exp, x); }
identifier_body
parser_testing.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. use ast; use parse::new_parse_sess; use parse::{ParseSess,string_to_filemap,filemap_to_tts}; use parse::new_parser_from_source_str; use parse::parser::Parser; use parse::token; use ptr::P; /// Map a string to tts, using a made-up filename: pub fn string_to_tts(source_str: String) -> Vec<ast::TokenTree> { let ps = new_parse_sess(); filemap_to_tts(&ps, string_to_filemap(&ps, source_str, "bogofile".to_string())) } /// Map string to parser (via tts) pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> { new_parser_from_source_str(ps, Vec::new(), "bogofile".to_string(), source_str) } fn with_error_checking_parse<T, F>(s: String, f: F) -> T where F: FnOnce(&mut Parser) -> T, { let ps = new_parse_sess(); let mut p = string_to_parser(&ps, s); let x = f(&mut p); p.abort_if_errors(); x } /// Parse a string, return a crate. pub fn string_to_crate (source_str : String) -> ast::Crate { with_error_checking_parse(source_str, |p| { panictry!(p.parse_crate_mod()) }) } /// Parse a string, return an expr pub fn string_to_expr (source_str : String) -> P<ast::Expr> { with_error_checking_parse(source_str, |p| { p.parse_expr() }) } /// Parse a string, return an item pub fn
(source_str : String) -> Option<P<ast::Item>> { with_error_checking_parse(source_str, |p| { p.parse_item() }) } /// Parse a string, return a stmt pub fn string_to_stmt(source_str : String) -> P<ast::Stmt> { with_error_checking_parse(source_str, |p| { p.parse_stmt().unwrap() }) } /// Parse a string, return a pat. Uses "irrefutable"... which doesn't /// (currently) affect parsing. pub fn string_to_pat(source_str: String) -> P<ast::Pat> { string_to_parser(&new_parse_sess(), source_str).parse_pat() } /// Convert a vector of strings to a vector of ast::Ident's pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<ast::Ident> { ids.iter().map(|u| token::str_to_ident(*u)).collect() } /// Does the given string match the pattern? whitespace in the first string /// may be deleted or replaced with other whitespace to match the pattern. /// this function is Unicode-ignorant; fortunately, the careful design of /// UTF-8 mitigates this ignorance. In particular, this function only collapses /// sequences of \n, \r,'', and \t, but it should otherwise tolerate Unicode /// chars. Unsurprisingly, it doesn't do NKF-normalization(?). pub fn matches_codepattern(a : &str, b : &str) -> bool { let mut idx_a = 0; let mut idx_b = 0; loop { if idx_a == a.len() && idx_b == b.len() { return true; } else if idx_a == a.len() {return false;} else if idx_b == b.len() { // maybe the stuff left in a is all ws? if is_whitespace(a.char_at(idx_a)) { return scan_for_non_ws_or_end(a,idx_a) == a.len(); } else { return false; } } // ws in both given and pattern: else if is_whitespace(a.char_at(idx_a)) && is_whitespace(b.char_at(idx_b)) { idx_a = scan_for_non_ws_or_end(a,idx_a); idx_b = scan_for_non_ws_or_end(b,idx_b); } // ws in given only: else if is_whitespace(a.char_at(idx_a)) { idx_a = scan_for_non_ws_or_end(a,idx_a); } // *don't* silently eat ws in expected only. else if a.char_at(idx_a) == b.char_at(idx_b) { idx_a += 1; idx_b += 1; } else { return false; } } } /// Given a string and an index, return the first usize >= idx /// that is a non-ws-char or is outside of the legal range of /// the string. fn scan_for_non_ws_or_end(a : &str, idx: usize) -> usize { let mut i = idx; let len = a.len(); while (i < len) && (is_whitespace(a.char_at(i))) { i += 1; } i } /// Copied from lexer. pub fn is_whitespace(c: char) -> bool { return c =='' || c == '\t' || c == '\r' || c == '\n'; } #[cfg(test)] mod test { use super::*; #[test] fn eqmodws() { assert_eq!(matches_codepattern("",""),true); assert_eq!(matches_codepattern("","a"),false); assert_eq!(matches_codepattern("a",""),false); assert_eq!(matches_codepattern("a","a"),true); assert_eq!(matches_codepattern("a b","a \n\t\r b"),true); assert_eq!(matches_codepattern("a b ","a \n\t\r b"),true); assert_eq!(matches_codepattern("a b","a \n\t\r b "),false); assert_eq!(matches_codepattern("a b","a b"),true); assert_eq!(matches_codepattern("ab","a b"),false); assert_eq!(matches_codepattern("a b","ab"),true); } }
string_to_item
identifier_name
parser_testing.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. //
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast; use parse::new_parse_sess; use parse::{ParseSess,string_to_filemap,filemap_to_tts}; use parse::new_parser_from_source_str; use parse::parser::Parser; use parse::token; use ptr::P; /// Map a string to tts, using a made-up filename: pub fn string_to_tts(source_str: String) -> Vec<ast::TokenTree> { let ps = new_parse_sess(); filemap_to_tts(&ps, string_to_filemap(&ps, source_str, "bogofile".to_string())) } /// Map string to parser (via tts) pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> { new_parser_from_source_str(ps, Vec::new(), "bogofile".to_string(), source_str) } fn with_error_checking_parse<T, F>(s: String, f: F) -> T where F: FnOnce(&mut Parser) -> T, { let ps = new_parse_sess(); let mut p = string_to_parser(&ps, s); let x = f(&mut p); p.abort_if_errors(); x } /// Parse a string, return a crate. pub fn string_to_crate (source_str : String) -> ast::Crate { with_error_checking_parse(source_str, |p| { panictry!(p.parse_crate_mod()) }) } /// Parse a string, return an expr pub fn string_to_expr (source_str : String) -> P<ast::Expr> { with_error_checking_parse(source_str, |p| { p.parse_expr() }) } /// Parse a string, return an item pub fn string_to_item (source_str : String) -> Option<P<ast::Item>> { with_error_checking_parse(source_str, |p| { p.parse_item() }) } /// Parse a string, return a stmt pub fn string_to_stmt(source_str : String) -> P<ast::Stmt> { with_error_checking_parse(source_str, |p| { p.parse_stmt().unwrap() }) } /// Parse a string, return a pat. Uses "irrefutable"... which doesn't /// (currently) affect parsing. pub fn string_to_pat(source_str: String) -> P<ast::Pat> { string_to_parser(&new_parse_sess(), source_str).parse_pat() } /// Convert a vector of strings to a vector of ast::Ident's pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<ast::Ident> { ids.iter().map(|u| token::str_to_ident(*u)).collect() } /// Does the given string match the pattern? whitespace in the first string /// may be deleted or replaced with other whitespace to match the pattern. /// this function is Unicode-ignorant; fortunately, the careful design of /// UTF-8 mitigates this ignorance. In particular, this function only collapses /// sequences of \n, \r,'', and \t, but it should otherwise tolerate Unicode /// chars. Unsurprisingly, it doesn't do NKF-normalization(?). pub fn matches_codepattern(a : &str, b : &str) -> bool { let mut idx_a = 0; let mut idx_b = 0; loop { if idx_a == a.len() && idx_b == b.len() { return true; } else if idx_a == a.len() {return false;} else if idx_b == b.len() { // maybe the stuff left in a is all ws? if is_whitespace(a.char_at(idx_a)) { return scan_for_non_ws_or_end(a,idx_a) == a.len(); } else { return false; } } // ws in both given and pattern: else if is_whitespace(a.char_at(idx_a)) && is_whitespace(b.char_at(idx_b)) { idx_a = scan_for_non_ws_or_end(a,idx_a); idx_b = scan_for_non_ws_or_end(b,idx_b); } // ws in given only: else if is_whitespace(a.char_at(idx_a)) { idx_a = scan_for_non_ws_or_end(a,idx_a); } // *don't* silently eat ws in expected only. else if a.char_at(idx_a) == b.char_at(idx_b) { idx_a += 1; idx_b += 1; } else { return false; } } } /// Given a string and an index, return the first usize >= idx /// that is a non-ws-char or is outside of the legal range of /// the string. fn scan_for_non_ws_or_end(a : &str, idx: usize) -> usize { let mut i = idx; let len = a.len(); while (i < len) && (is_whitespace(a.char_at(i))) { i += 1; } i } /// Copied from lexer. pub fn is_whitespace(c: char) -> bool { return c =='' || c == '\t' || c == '\r' || c == '\n'; } #[cfg(test)] mod test { use super::*; #[test] fn eqmodws() { assert_eq!(matches_codepattern("",""),true); assert_eq!(matches_codepattern("","a"),false); assert_eq!(matches_codepattern("a",""),false); assert_eq!(matches_codepattern("a","a"),true); assert_eq!(matches_codepattern("a b","a \n\t\r b"),true); assert_eq!(matches_codepattern("a b ","a \n\t\r b"),true); assert_eq!(matches_codepattern("a b","a \n\t\r b "),false); assert_eq!(matches_codepattern("a b","a b"),true); assert_eq!(matches_codepattern("ab","a b"),false); assert_eq!(matches_codepattern("a b","ab"),true); } }
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
parser_testing.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. use ast; use parse::new_parse_sess; use parse::{ParseSess,string_to_filemap,filemap_to_tts}; use parse::new_parser_from_source_str; use parse::parser::Parser; use parse::token; use ptr::P; /// Map a string to tts, using a made-up filename: pub fn string_to_tts(source_str: String) -> Vec<ast::TokenTree> { let ps = new_parse_sess(); filemap_to_tts(&ps, string_to_filemap(&ps, source_str, "bogofile".to_string())) } /// Map string to parser (via tts) pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> { new_parser_from_source_str(ps, Vec::new(), "bogofile".to_string(), source_str) } fn with_error_checking_parse<T, F>(s: String, f: F) -> T where F: FnOnce(&mut Parser) -> T, { let ps = new_parse_sess(); let mut p = string_to_parser(&ps, s); let x = f(&mut p); p.abort_if_errors(); x } /// Parse a string, return a crate. pub fn string_to_crate (source_str : String) -> ast::Crate { with_error_checking_parse(source_str, |p| { panictry!(p.parse_crate_mod()) }) } /// Parse a string, return an expr pub fn string_to_expr (source_str : String) -> P<ast::Expr>
/// Parse a string, return an item pub fn string_to_item (source_str : String) -> Option<P<ast::Item>> { with_error_checking_parse(source_str, |p| { p.parse_item() }) } /// Parse a string, return a stmt pub fn string_to_stmt(source_str : String) -> P<ast::Stmt> { with_error_checking_parse(source_str, |p| { p.parse_stmt().unwrap() }) } /// Parse a string, return a pat. Uses "irrefutable"... which doesn't /// (currently) affect parsing. pub fn string_to_pat(source_str: String) -> P<ast::Pat> { string_to_parser(&new_parse_sess(), source_str).parse_pat() } /// Convert a vector of strings to a vector of ast::Ident's pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<ast::Ident> { ids.iter().map(|u| token::str_to_ident(*u)).collect() } /// Does the given string match the pattern? whitespace in the first string /// may be deleted or replaced with other whitespace to match the pattern. /// this function is Unicode-ignorant; fortunately, the careful design of /// UTF-8 mitigates this ignorance. In particular, this function only collapses /// sequences of \n, \r,'', and \t, but it should otherwise tolerate Unicode /// chars. Unsurprisingly, it doesn't do NKF-normalization(?). pub fn matches_codepattern(a : &str, b : &str) -> bool { let mut idx_a = 0; let mut idx_b = 0; loop { if idx_a == a.len() && idx_b == b.len() { return true; } else if idx_a == a.len() {return false;} else if idx_b == b.len() { // maybe the stuff left in a is all ws? if is_whitespace(a.char_at(idx_a)) { return scan_for_non_ws_or_end(a,idx_a) == a.len(); } else { return false; } } // ws in both given and pattern: else if is_whitespace(a.char_at(idx_a)) && is_whitespace(b.char_at(idx_b)) { idx_a = scan_for_non_ws_or_end(a,idx_a); idx_b = scan_for_non_ws_or_end(b,idx_b); } // ws in given only: else if is_whitespace(a.char_at(idx_a)) { idx_a = scan_for_non_ws_or_end(a,idx_a); } // *don't* silently eat ws in expected only. else if a.char_at(idx_a) == b.char_at(idx_b) { idx_a += 1; idx_b += 1; } else { return false; } } } /// Given a string and an index, return the first usize >= idx /// that is a non-ws-char or is outside of the legal range of /// the string. fn scan_for_non_ws_or_end(a : &str, idx: usize) -> usize { let mut i = idx; let len = a.len(); while (i < len) && (is_whitespace(a.char_at(i))) { i += 1; } i } /// Copied from lexer. pub fn is_whitespace(c: char) -> bool { return c =='' || c == '\t' || c == '\r' || c == '\n'; } #[cfg(test)] mod test { use super::*; #[test] fn eqmodws() { assert_eq!(matches_codepattern("",""),true); assert_eq!(matches_codepattern("","a"),false); assert_eq!(matches_codepattern("a",""),false); assert_eq!(matches_codepattern("a","a"),true); assert_eq!(matches_codepattern("a b","a \n\t\r b"),true); assert_eq!(matches_codepattern("a b ","a \n\t\r b"),true); assert_eq!(matches_codepattern("a b","a \n\t\r b "),false); assert_eq!(matches_codepattern("a b","a b"),true); assert_eq!(matches_codepattern("ab","a b"),false); assert_eq!(matches_codepattern("a b","ab"),true); } }
{ with_error_checking_parse(source_str, |p| { p.parse_expr() }) }
identifier_body
main.rs
extern crate getopts; extern crate image; use getopts::{optopt,getopts}; use std::default::Default; use std::io::fs::File; use std::os::args; mod css; mod dom; mod html; mod layout; mod style; mod painting; #[allow(unstable)] fn
() { // Parse command-line options: let opts = [ optopt("h", "html", "HTML document", "FILENAME"), optopt("c", "css", "CSS stylesheet", "FILENAME"), optopt("o", "output", "Output file", "FILENAME"), ]; let matches = match getopts(args().tail(), &opts) { Ok(m) => m, Err(f) => panic!(f.to_string()) }; // Read input files: let read_source = |&: arg_filename: Option<String>, default_filename: &str| { let path = match arg_filename { Some(ref filename) => &**filename, None => default_filename, }; File::open(&Path::new(path)).read_to_string().unwrap() }; let html = read_source(matches.opt_str("h"), "examples/test.html"); let css = read_source(matches.opt_str("c"), "examples/test.css"); // Since we don't have an actual window, hard-code the "viewport" size. let initial_containing_block = layout::Dimensions { content: layout::Rect { x: 0.0, y: 0.0, width: 800.0, height: 600.0 }, padding: Default::default(), border: Default::default(), margin: Default::default(), }; // Parsing and rendering: let root_node = html::parse(html); let stylesheet = css::parse(css); let style_root = style::style_tree(&root_node, &stylesheet); let layout_root = layout::layout_tree(&style_root, initial_containing_block); let canvas = painting::paint(&layout_root, initial_containing_block.content); // Create the output file: let filename = matches.opt_str("o").unwrap_or("output.png".to_string()); let file = File::create(&Path::new(&*filename)).unwrap(); // Save an image: let (w, h) = (canvas.width as u32, canvas.height as u32); let buffer: Vec<image::Rgba<u8>> = unsafe { std::mem::transmute(canvas.pixels) }; let img = image::ImageBuffer::from_fn(w, h, Box::new(|&: x: u32, y: u32| buffer[(y * w + x) as usize])); let result = image::ImageRgba8(img).save(file, image::PNG); match result { Ok(_) => println!("Saved output as {}", filename), Err(_) => println!("Error saving output as {}", filename) } // Debug output: // println!("{}", layout_root.dimensions); // println!("{}", display_list); }
main
identifier_name
main.rs
extern crate getopts; extern crate image; use getopts::{optopt,getopts}; use std::default::Default; use std::io::fs::File; use std::os::args; mod css; mod dom; mod html; mod layout; mod style; mod painting; #[allow(unstable)] fn main()
let html = read_source(matches.opt_str("h"), "examples/test.html"); let css = read_source(matches.opt_str("c"), "examples/test.css"); // Since we don't have an actual window, hard-code the "viewport" size. let initial_containing_block = layout::Dimensions { content: layout::Rect { x: 0.0, y: 0.0, width: 800.0, height: 600.0 }, padding: Default::default(), border: Default::default(), margin: Default::default(), }; // Parsing and rendering: let root_node = html::parse(html); let stylesheet = css::parse(css); let style_root = style::style_tree(&root_node, &stylesheet); let layout_root = layout::layout_tree(&style_root, initial_containing_block); let canvas = painting::paint(&layout_root, initial_containing_block.content); // Create the output file: let filename = matches.opt_str("o").unwrap_or("output.png".to_string()); let file = File::create(&Path::new(&*filename)).unwrap(); // Save an image: let (w, h) = (canvas.width as u32, canvas.height as u32); let buffer: Vec<image::Rgba<u8>> = unsafe { std::mem::transmute(canvas.pixels) }; let img = image::ImageBuffer::from_fn(w, h, Box::new(|&: x: u32, y: u32| buffer[(y * w + x) as usize])); let result = image::ImageRgba8(img).save(file, image::PNG); match result { Ok(_) => println!("Saved output as {}", filename), Err(_) => println!("Error saving output as {}", filename) } // Debug output: // println!("{}", layout_root.dimensions); // println!("{}", display_list); }
{ // Parse command-line options: let opts = [ optopt("h", "html", "HTML document", "FILENAME"), optopt("c", "css", "CSS stylesheet", "FILENAME"), optopt("o", "output", "Output file", "FILENAME"), ]; let matches = match getopts(args().tail(), &opts) { Ok(m) => m, Err(f) => panic!(f.to_string()) }; // Read input files: let read_source = |&: arg_filename: Option<String>, default_filename: &str| { let path = match arg_filename { Some(ref filename) => &**filename, None => default_filename, }; File::open(&Path::new(path)).read_to_string().unwrap() };
identifier_body
main.rs
extern crate getopts; extern crate image; use getopts::{optopt,getopts}; use std::default::Default; use std::io::fs::File; use std::os::args; mod css; mod dom; mod html; mod layout; mod style; mod painting; #[allow(unstable)] fn main() { // Parse command-line options: let opts = [ optopt("h", "html", "HTML document", "FILENAME"), optopt("c", "css", "CSS stylesheet", "FILENAME"), optopt("o", "output", "Output file", "FILENAME"), ]; let matches = match getopts(args().tail(), &opts) { Ok(m) => m, Err(f) => panic!(f.to_string()) }; // Read input files: let read_source = |&: arg_filename: Option<String>, default_filename: &str| { let path = match arg_filename { Some(ref filename) => &**filename, None => default_filename, }; File::open(&Path::new(path)).read_to_string().unwrap() }; let html = read_source(matches.opt_str("h"), "examples/test.html"); let css = read_source(matches.opt_str("c"), "examples/test.css"); // Since we don't have an actual window, hard-code the "viewport" size. let initial_containing_block = layout::Dimensions { content: layout::Rect { x: 0.0, y: 0.0, width: 800.0, height: 600.0 }, padding: Default::default(), border: Default::default(), margin: Default::default(), };
let root_node = html::parse(html); let stylesheet = css::parse(css); let style_root = style::style_tree(&root_node, &stylesheet); let layout_root = layout::layout_tree(&style_root, initial_containing_block); let canvas = painting::paint(&layout_root, initial_containing_block.content); // Create the output file: let filename = matches.opt_str("o").unwrap_or("output.png".to_string()); let file = File::create(&Path::new(&*filename)).unwrap(); // Save an image: let (w, h) = (canvas.width as u32, canvas.height as u32); let buffer: Vec<image::Rgba<u8>> = unsafe { std::mem::transmute(canvas.pixels) }; let img = image::ImageBuffer::from_fn(w, h, Box::new(|&: x: u32, y: u32| buffer[(y * w + x) as usize])); let result = image::ImageRgba8(img).save(file, image::PNG); match result { Ok(_) => println!("Saved output as {}", filename), Err(_) => println!("Error saving output as {}", filename) } // Debug output: // println!("{}", layout_root.dimensions); // println!("{}", display_list); }
// Parsing and rendering:
random_line_split
set.rs
use std::io::BufReader; use std::fs; use std::rc; use sym; use exec::Arg; use exec::Redir; use shell::Shell; fn rd_set(_rd: Redir) -> i32 { println!("Redirection set is unimplemented"); 0 } fn set_spec(av: &mut Vec<Arg>) -> sym::ScopeSpec { let mut ret = sym::ScopeSpec::Default; while av.len() > 0 { if av[0].is_str() { if!av[0].as_str().starts_with("-") { break; } let s = av.remove(0).unwrap_str(); // FIXME: graphemes()? for c in s.chars().skip(1) { ret = match c { 'l' => sym::ScopeSpec::Local, 'g' => sym::ScopeSpec::Global, 'e' => sym::ScopeSpec::Environment, _ => { warn!("set: Unrecognized argument '{}' found.", c); ret } } } } else { break; } } ret } fn set_keys(av: &mut Vec<Arg>) -> Vec<String> { let mut ret = Vec::new(); while av.len() > 0 { let arg = av.remove(0); // check for '=' if let Arg::Str(ref s) = arg { if s == "=" { break; } } for k in arg.into_vec() { ret.push(k); } } ret } fn fn_set(sh: &mut Shell, kv: Vec<String>, mut av: Vec<Arg>, spec: sym::ScopeSpec) -> i32 { if av.len() == 0 ||!av.last().unwrap().is_bl() { warn!("fn declaration must contain a block as its last arg."); return 2; } let exec_bl = av.pop().unwrap().unwrap_bl(); // TODO: patterns in function args! let mut args = Vec::new(); let mut vararg = None; let mut postargs = None; let mut flat_args = av.drain(..).flat_map(|x| x.into_vec()).collect::<Vec<_>>(); let inline = if flat_args.len() > 0 && flat_args[0] == "--inline" { flat_args.remove(0); true } else { false }; for sl in flat_args.windows(2) { let ref elt = sl[0]; let ref lookahead = sl[1]; if lookahead == "..." { if vararg.is_some() { warn!("set: fn can have at most one vararg"); return 2; } vararg = Some(elt.to_owned()); postargs = Some(Vec::new()); } else if elt!= "..." { if let Some(ref mut x) = postargs { x.push(elt.to_owned()); } else { args.push(elt.to_owned()); } } } // last arg if let Some(last) = flat_args.last() { if last!= "..." { if let Some(ref mut x) = postargs { x.push(last.to_owned()); } else { args.push(last.to_owned()); } } } for k in &kv { sh.st.set_fn(k, sym::Fn { name: k.clone(), inline: inline, args: args.clone(), vararg: vararg.clone(), postargs: postargs.clone(), lines: exec_bl.clone(), }, spec); } 0 } pub fn set_main() -> rc::Rc<Fn(Vec<Arg>, &mut Shell, Option<BufReader<fs::File>>) -> i32> { rc::Rc::new(|mut args: Vec<Arg>, sh: &mut Shell, _in: Option<BufReader<fs::File>>| -> i32 { // rd-set if args.len() == 1
// get args and keys let spec = set_spec(&mut args); let mut keyv = set_keys(&mut args); // filter out invalid keys let keyv = keyv.drain(..) .filter(|a| { a.find(|x| { if "?! {}()".contains(x) { // TODO: more invalid chars warn!("set: Key '{}' contains invalid characters", a); true } else { false } }) .is_none() }) .collect::<Vec<String>>(); // if we just said'set a b c', we want to set them to empty if args.is_empty() { args.push(Arg::Str(String::new())); } if args[0].is_str() && args[0].as_str() == "fn" { args.remove(0); return fn_set(sh, keyv, args, spec); } let val = args.drain(..).flat_map(|x| x.into_vec()).collect::<Vec<String>>().join(" "); let mut r = 0; for k in keyv { if sh.st.set_scope(&k, val.clone(), spec).is_err() { r = 2; } } r }) }
{ if args[0].is_rd() { let rd = args.remove(0).unwrap_rd(); return rd_set(rd); } }
conditional_block
set.rs
use std::io::BufReader; use std::fs; use std::rc; use sym; use exec::Arg; use exec::Redir; use shell::Shell; fn rd_set(_rd: Redir) -> i32 { println!("Redirection set is unimplemented"); 0 } fn set_spec(av: &mut Vec<Arg>) -> sym::ScopeSpec { let mut ret = sym::ScopeSpec::Default; while av.len() > 0 { if av[0].is_str() { if!av[0].as_str().starts_with("-") { break; } let s = av.remove(0).unwrap_str(); // FIXME: graphemes()? for c in s.chars().skip(1) { ret = match c { 'l' => sym::ScopeSpec::Local, 'g' => sym::ScopeSpec::Global, 'e' => sym::ScopeSpec::Environment, _ => { warn!("set: Unrecognized argument '{}' found.", c); ret } } } } else { break; } } ret } fn set_keys(av: &mut Vec<Arg>) -> Vec<String> { let mut ret = Vec::new(); while av.len() > 0 { let arg = av.remove(0); // check for '=' if let Arg::Str(ref s) = arg { if s == "=" { break; } } for k in arg.into_vec() { ret.push(k); } } ret } fn fn_set(sh: &mut Shell, kv: Vec<String>, mut av: Vec<Arg>, spec: sym::ScopeSpec) -> i32
for sl in flat_args.windows(2) { let ref elt = sl[0]; let ref lookahead = sl[1]; if lookahead == "..." { if vararg.is_some() { warn!("set: fn can have at most one vararg"); return 2; } vararg = Some(elt.to_owned()); postargs = Some(Vec::new()); } else if elt!= "..." { if let Some(ref mut x) = postargs { x.push(elt.to_owned()); } else { args.push(elt.to_owned()); } } } // last arg if let Some(last) = flat_args.last() { if last!= "..." { if let Some(ref mut x) = postargs { x.push(last.to_owned()); } else { args.push(last.to_owned()); } } } for k in &kv { sh.st.set_fn(k, sym::Fn { name: k.clone(), inline: inline, args: args.clone(), vararg: vararg.clone(), postargs: postargs.clone(), lines: exec_bl.clone(), }, spec); } 0 } pub fn set_main() -> rc::Rc<Fn(Vec<Arg>, &mut Shell, Option<BufReader<fs::File>>) -> i32> { rc::Rc::new(|mut args: Vec<Arg>, sh: &mut Shell, _in: Option<BufReader<fs::File>>| -> i32 { // rd-set if args.len() == 1 { if args[0].is_rd() { let rd = args.remove(0).unwrap_rd(); return rd_set(rd); } } // get args and keys let spec = set_spec(&mut args); let mut keyv = set_keys(&mut args); // filter out invalid keys let keyv = keyv.drain(..) .filter(|a| { a.find(|x| { if "?! {}()".contains(x) { // TODO: more invalid chars warn!("set: Key '{}' contains invalid characters", a); true } else { false } }) .is_none() }) .collect::<Vec<String>>(); // if we just said'set a b c', we want to set them to empty if args.is_empty() { args.push(Arg::Str(String::new())); } if args[0].is_str() && args[0].as_str() == "fn" { args.remove(0); return fn_set(sh, keyv, args, spec); } let val = args.drain(..).flat_map(|x| x.into_vec()).collect::<Vec<String>>().join(" "); let mut r = 0; for k in keyv { if sh.st.set_scope(&k, val.clone(), spec).is_err() { r = 2; } } r }) }
{ if av.len() == 0 || !av.last().unwrap().is_bl() { warn!("fn declaration must contain a block as its last arg."); return 2; } let exec_bl = av.pop().unwrap().unwrap_bl(); // TODO: patterns in function args! let mut args = Vec::new(); let mut vararg = None; let mut postargs = None; let mut flat_args = av.drain(..).flat_map(|x| x.into_vec()).collect::<Vec<_>>(); let inline = if flat_args.len() > 0 && flat_args[0] == "--inline" { flat_args.remove(0); true } else { false };
identifier_body
set.rs
use std::io::BufReader; use std::fs; use std::rc; use sym; use exec::Arg; use exec::Redir; use shell::Shell; fn rd_set(_rd: Redir) -> i32 { println!("Redirection set is unimplemented"); 0 } fn set_spec(av: &mut Vec<Arg>) -> sym::ScopeSpec { let mut ret = sym::ScopeSpec::Default; while av.len() > 0 { if av[0].is_str() { if!av[0].as_str().starts_with("-") { break; } let s = av.remove(0).unwrap_str(); // FIXME: graphemes()? for c in s.chars().skip(1) { ret = match c { 'l' => sym::ScopeSpec::Local, 'g' => sym::ScopeSpec::Global, 'e' => sym::ScopeSpec::Environment, _ => { warn!("set: Unrecognized argument '{}' found.", c); ret } } } } else { break; } } ret } fn set_keys(av: &mut Vec<Arg>) -> Vec<String> { let mut ret = Vec::new(); while av.len() > 0 { let arg = av.remove(0); // check for '=' if let Arg::Str(ref s) = arg { if s == "=" { break; } } for k in arg.into_vec() { ret.push(k); } } ret } fn fn_set(sh: &mut Shell, kv: Vec<String>, mut av: Vec<Arg>, spec: sym::ScopeSpec) -> i32 { if av.len() == 0 ||!av.last().unwrap().is_bl() { warn!("fn declaration must contain a block as its last arg."); return 2; } let exec_bl = av.pop().unwrap().unwrap_bl(); // TODO: patterns in function args! let mut args = Vec::new(); let mut vararg = None; let mut postargs = None; let mut flat_args = av.drain(..).flat_map(|x| x.into_vec()).collect::<Vec<_>>(); let inline = if flat_args.len() > 0 && flat_args[0] == "--inline" { flat_args.remove(0); true } else { false }; for sl in flat_args.windows(2) { let ref elt = sl[0]; let ref lookahead = sl[1]; if lookahead == "..." { if vararg.is_some() { warn!("set: fn can have at most one vararg"); return 2; } vararg = Some(elt.to_owned()); postargs = Some(Vec::new()); } else if elt!= "..." { if let Some(ref mut x) = postargs { x.push(elt.to_owned());
// last arg if let Some(last) = flat_args.last() { if last!= "..." { if let Some(ref mut x) = postargs { x.push(last.to_owned()); } else { args.push(last.to_owned()); } } } for k in &kv { sh.st.set_fn(k, sym::Fn { name: k.clone(), inline: inline, args: args.clone(), vararg: vararg.clone(), postargs: postargs.clone(), lines: exec_bl.clone(), }, spec); } 0 } pub fn set_main() -> rc::Rc<Fn(Vec<Arg>, &mut Shell, Option<BufReader<fs::File>>) -> i32> { rc::Rc::new(|mut args: Vec<Arg>, sh: &mut Shell, _in: Option<BufReader<fs::File>>| -> i32 { // rd-set if args.len() == 1 { if args[0].is_rd() { let rd = args.remove(0).unwrap_rd(); return rd_set(rd); } } // get args and keys let spec = set_spec(&mut args); let mut keyv = set_keys(&mut args); // filter out invalid keys let keyv = keyv.drain(..) .filter(|a| { a.find(|x| { if "?! {}()".contains(x) { // TODO: more invalid chars warn!("set: Key '{}' contains invalid characters", a); true } else { false } }) .is_none() }) .collect::<Vec<String>>(); // if we just said'set a b c', we want to set them to empty if args.is_empty() { args.push(Arg::Str(String::new())); } if args[0].is_str() && args[0].as_str() == "fn" { args.remove(0); return fn_set(sh, keyv, args, spec); } let val = args.drain(..).flat_map(|x| x.into_vec()).collect::<Vec<String>>().join(" "); let mut r = 0; for k in keyv { if sh.st.set_scope(&k, val.clone(), spec).is_err() { r = 2; } } r }) }
} else { args.push(elt.to_owned()); } } }
random_line_split
set.rs
use std::io::BufReader; use std::fs; use std::rc; use sym; use exec::Arg; use exec::Redir; use shell::Shell; fn rd_set(_rd: Redir) -> i32 { println!("Redirection set is unimplemented"); 0 } fn set_spec(av: &mut Vec<Arg>) -> sym::ScopeSpec { let mut ret = sym::ScopeSpec::Default; while av.len() > 0 { if av[0].is_str() { if!av[0].as_str().starts_with("-") { break; } let s = av.remove(0).unwrap_str(); // FIXME: graphemes()? for c in s.chars().skip(1) { ret = match c { 'l' => sym::ScopeSpec::Local, 'g' => sym::ScopeSpec::Global, 'e' => sym::ScopeSpec::Environment, _ => { warn!("set: Unrecognized argument '{}' found.", c); ret } } } } else { break; } } ret } fn set_keys(av: &mut Vec<Arg>) -> Vec<String> { let mut ret = Vec::new(); while av.len() > 0 { let arg = av.remove(0); // check for '=' if let Arg::Str(ref s) = arg { if s == "=" { break; } } for k in arg.into_vec() { ret.push(k); } } ret } fn fn_set(sh: &mut Shell, kv: Vec<String>, mut av: Vec<Arg>, spec: sym::ScopeSpec) -> i32 { if av.len() == 0 ||!av.last().unwrap().is_bl() { warn!("fn declaration must contain a block as its last arg."); return 2; } let exec_bl = av.pop().unwrap().unwrap_bl(); // TODO: patterns in function args! let mut args = Vec::new(); let mut vararg = None; let mut postargs = None; let mut flat_args = av.drain(..).flat_map(|x| x.into_vec()).collect::<Vec<_>>(); let inline = if flat_args.len() > 0 && flat_args[0] == "--inline" { flat_args.remove(0); true } else { false }; for sl in flat_args.windows(2) { let ref elt = sl[0]; let ref lookahead = sl[1]; if lookahead == "..." { if vararg.is_some() { warn!("set: fn can have at most one vararg"); return 2; } vararg = Some(elt.to_owned()); postargs = Some(Vec::new()); } else if elt!= "..." { if let Some(ref mut x) = postargs { x.push(elt.to_owned()); } else { args.push(elt.to_owned()); } } } // last arg if let Some(last) = flat_args.last() { if last!= "..." { if let Some(ref mut x) = postargs { x.push(last.to_owned()); } else { args.push(last.to_owned()); } } } for k in &kv { sh.st.set_fn(k, sym::Fn { name: k.clone(), inline: inline, args: args.clone(), vararg: vararg.clone(), postargs: postargs.clone(), lines: exec_bl.clone(), }, spec); } 0 } pub fn
() -> rc::Rc<Fn(Vec<Arg>, &mut Shell, Option<BufReader<fs::File>>) -> i32> { rc::Rc::new(|mut args: Vec<Arg>, sh: &mut Shell, _in: Option<BufReader<fs::File>>| -> i32 { // rd-set if args.len() == 1 { if args[0].is_rd() { let rd = args.remove(0).unwrap_rd(); return rd_set(rd); } } // get args and keys let spec = set_spec(&mut args); let mut keyv = set_keys(&mut args); // filter out invalid keys let keyv = keyv.drain(..) .filter(|a| { a.find(|x| { if "?! {}()".contains(x) { // TODO: more invalid chars warn!("set: Key '{}' contains invalid characters", a); true } else { false } }) .is_none() }) .collect::<Vec<String>>(); // if we just said'set a b c', we want to set them to empty if args.is_empty() { args.push(Arg::Str(String::new())); } if args[0].is_str() && args[0].as_str() == "fn" { args.remove(0); return fn_set(sh, keyv, args, spec); } let val = args.drain(..).flat_map(|x| x.into_vec()).collect::<Vec<String>>().join(" "); let mut r = 0; for k in keyv { if sh.st.set_scope(&k, val.clone(), spec).is_err() { r = 2; } } r }) }
set_main
identifier_name
one_or_many.rs
//use serde::de::Deserialize; use super::super::link::HalLink; use super::super::resource::OneOrMany; use serde_json::{from_str, to_string}; use serde::*; #[derive(Serialize, Deserialize)] struct Boh { oom: OneOrMany<String> } #[test] fn ensure_one_object_gets_serialized_as_one() { let boh = Boh { oom: OneOrMany::new().with(&"test".to_owned()) }; assert_eq!(to_string(&boh).unwrap(), r#"{"oom":"test"}"#); } #[test] fn ensure_two_objects_get_serialized_as_array() { let boh = Boh { oom: OneOrMany::new().with(&"test".to_owned()).with(&"test2".to_owned()) }; assert_eq!(to_string(&boh).unwrap(), r#"{"oom":["test","test2"]}"#); } #[test] fn ensure_array_gets_deserialized()
{ let s = r#"{"oom":["test","test2"]}"#; let boh: Boh = from_str(s).unwrap(); assert_eq!(2, boh.oom.len()); assert_eq!("test", boh.oom.many()[0]); assert_eq!("test2", boh.oom.many()[1]); }
identifier_body
one_or_many.rs
//use serde::de::Deserialize; use super::super::link::HalLink; use super::super::resource::OneOrMany; use serde_json::{from_str, to_string}; use serde::*; #[derive(Serialize, Deserialize)] struct Boh { oom: OneOrMany<String> } #[test] fn ensure_one_object_gets_serialized_as_one() { let boh = Boh { oom: OneOrMany::new().with(&"test".to_owned()) }; assert_eq!(to_string(&boh).unwrap(), r#"{"oom":"test"}"#); } #[test] fn ensure_two_objects_get_serialized_as_array() { let boh = Boh { oom: OneOrMany::new().with(&"test".to_owned()).with(&"test2".to_owned()) }; assert_eq!(to_string(&boh).unwrap(), r#"{"oom":["test","test2"]}"#); } #[test] fn
() { let s = r#"{"oom":["test","test2"]}"#; let boh: Boh = from_str(s).unwrap(); assert_eq!(2, boh.oom.len()); assert_eq!("test", boh.oom.many()[0]); assert_eq!("test2", boh.oom.many()[1]); }
ensure_array_gets_deserialized
identifier_name
one_or_many.rs
//use serde::de::Deserialize; use super::super::link::HalLink; use super::super::resource::OneOrMany; use serde_json::{from_str, to_string}; use serde::*;
{ oom: OneOrMany<String> } #[test] fn ensure_one_object_gets_serialized_as_one() { let boh = Boh { oom: OneOrMany::new().with(&"test".to_owned()) }; assert_eq!(to_string(&boh).unwrap(), r#"{"oom":"test"}"#); } #[test] fn ensure_two_objects_get_serialized_as_array() { let boh = Boh { oom: OneOrMany::new().with(&"test".to_owned()).with(&"test2".to_owned()) }; assert_eq!(to_string(&boh).unwrap(), r#"{"oom":["test","test2"]}"#); } #[test] fn ensure_array_gets_deserialized() { let s = r#"{"oom":["test","test2"]}"#; let boh: Boh = from_str(s).unwrap(); assert_eq!(2, boh.oom.len()); assert_eq!("test", boh.oom.many()[0]); assert_eq!("test2", boh.oom.many()[1]); }
#[derive(Serialize, Deserialize)] struct Boh
random_line_split
dead.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. // This implements the dead-code warning pass. It follows middle::reachable // closely. The idea is that all reachable symbols are live, codes called // from live codes are live, and everything else is dead. use middle::lint::{Allow, contains_lint, DeadCode}; use middle::privacy; use middle::ty; use middle::typeck; use util::nodemap::NodeSet; use collections::HashSet; use syntax::ast; use syntax::ast_map; use syntax::ast_util::{local_def, def_id_of_def, is_local}; use syntax::attr; use syntax::codemap; use syntax::parse::token; use syntax::visit::Visitor; use syntax::visit; pub static DEAD_CODE_LINT_STR: &'static str = "dead_code"; // Any local node that may call something in its body block should be // explored. For example, if it's a live NodeItem that is a // function, then we should explore its block to check for codes that // may need to be marked as live. fn should_explore(tcx: &ty::ctxt, def_id: ast::DefId) -> bool { if!is_local(def_id) { return false; } match tcx.map.find(def_id.node) { Some(ast_map::NodeItem(..)) | Some(ast_map::NodeMethod(..)) | Some(ast_map::NodeForeignItem(..)) | Some(ast_map::NodeTraitMethod(..)) => true, _ => false } } struct MarkSymbolVisitor<'a> { worklist: Vec<ast::NodeId>, tcx: &'a ty::ctxt, live_symbols: Box<HashSet<ast::NodeId>>, } impl<'a> MarkSymbolVisitor<'a> { fn new(tcx: &'a ty::ctxt, worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a> { MarkSymbolVisitor { worklist: worklist, tcx: tcx, live_symbols: box HashSet::new(), } } fn check_def_id(&mut self, def_id: ast::DefId) { if should_explore(self.tcx, def_id) { self.worklist.push(def_id.node); } self.live_symbols.insert(def_id.node); } fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) { let def = match self.tcx.def_map.borrow().find(id) { Some(&def) => def, None => return }; let def_id = match def { ast::DefVariant(enum_id, _, _) => Some(enum_id), ast::DefPrimTy(_) => None, _ => Some(def_id_of_def(def)), }; match def_id { Some(def_id) => self.check_def_id(def_id), None => (), } } fn lookup_and_handle_method(&mut self, id: ast::NodeId, span: codemap::Span) { let method_call = typeck::MethodCall::expr(id); match self.tcx.method_map.borrow().find(&method_call) {
typeck::MethodStatic(def_id) => { match ty::provided_source(self.tcx, def_id) { Some(p_did) => self.check_def_id(p_did), None => self.check_def_id(def_id) } } typeck::MethodParam(typeck::MethodParam { trait_id: trait_id, method_num: index, .. }) | typeck::MethodObject(typeck::MethodObject { trait_id: trait_id, method_num: index, .. }) => { let def_id = ty::trait_method(self.tcx, trait_id, index).def_id; self.check_def_id(def_id); } } } None => { self.tcx.sess.span_bug(span, "method call expression not \ in method map?!") } } } fn mark_live_symbols(&mut self) { let mut scanned = HashSet::new(); while self.worklist.len() > 0 { let id = self.worklist.pop().unwrap(); if scanned.contains(&id) { continue } scanned.insert(id); match self.tcx.map.find(id) { Some(ref node) => { self.live_symbols.insert(id); self.visit_node(node); } None => (), } } } fn visit_node(&mut self, node: &ast_map::Node) { match *node { ast_map::NodeItem(item) => { match item.node { ast::ItemFn(..) | ast::ItemTy(..) | ast::ItemEnum(..) | ast::ItemStruct(..) | ast::ItemStatic(..) => { visit::walk_item(self, item, ()); } _ => () } } ast_map::NodeTraitMethod(trait_method) => { visit::walk_trait_method(self, trait_method, ()); } ast_map::NodeMethod(method) => { visit::walk_block(self, method.body, ()); } ast_map::NodeForeignItem(foreign_item) => { visit::walk_foreign_item(self, foreign_item, ()); } _ => () } } } impl<'a> Visitor<()> for MarkSymbolVisitor<'a> { fn visit_expr(&mut self, expr: &ast::Expr, _: ()) { match expr.node { ast::ExprMethodCall(..) => { self.lookup_and_handle_method(expr.id, expr.span); } _ => () } visit::walk_expr(self, expr, ()) } fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, _: ()) { self.lookup_and_handle_definition(&id); visit::walk_path(self, path, ()); } fn visit_item(&mut self, _item: &ast::Item, _: ()) { // Do not recurse into items. These items will be added to the // worklist and recursed into manually if necessary. } } fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool { contains_lint(attrs, Allow, DEAD_CODE_LINT_STR) || attr::contains_name(attrs.as_slice(), "lang") } // This visitor seeds items that // 1) We want to explicitly consider as live: // * Item annotated with #[allow(dead_code)] // - This is done so that if we want to suppress warnings for a // group of dead functions, we only have to annotate the "root". // For example, if both `f` and `g` are dead and `f` calls `g`, // then annotating `f` with `#[allow(dead_code)]` will suppress // warning for both `f` and `g`. // * Item annotated with #[lang=".."] // - This is because lang items are always callable from elsewhere. // or // 2) We are not sure to be live or not // * Implementation of a trait method struct LifeSeeder { worklist: Vec<ast::NodeId>, } impl Visitor<()> for LifeSeeder { fn visit_item(&mut self, item: &ast::Item, _: ()) { if has_allow_dead_code_or_lang_attr(item.attrs.as_slice()) { self.worklist.push(item.id); } match item.node { ast::ItemImpl(_, Some(ref _trait_ref), _, ref methods) => { for method in methods.iter() { self.worklist.push(method.id); } } _ => () } visit::walk_item(self, item, ()); } fn visit_fn(&mut self, fk: &visit::FnKind, _: &ast::FnDecl, block: &ast::Block, _: codemap::Span, id: ast::NodeId, _: ()) { // Check for method here because methods are not ast::Item match *fk { visit::FkMethod(_, _, method) => { if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) { self.worklist.push(id); } } _ => () } visit::walk_block(self, block, ()); } } fn create_and_seed_worklist(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) -> Vec<ast::NodeId> { let mut worklist = Vec::new(); // Preferably, we would only need to seed the worklist with reachable // symbols. However, since the set of reachable symbols differs // depending on whether a crate is built as bin or lib, and we want // the warning to be consistent, we also seed the worklist with // exported symbols. for &id in exported_items.iter() { worklist.push(id); } for &id in reachable_symbols.iter() { worklist.push(id); } // Seed entry point match *tcx.sess.entry_fn.borrow() { Some((id, _)) => worklist.push(id), None => () } // Seed implemented trait methods let mut life_seeder = LifeSeeder { worklist: worklist }; visit::walk_crate(&mut life_seeder, krate, ()); return life_seeder.worklist; } fn find_live(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) -> Box<HashSet<ast::NodeId>> { let worklist = create_and_seed_worklist(tcx, exported_items, reachable_symbols, krate); let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist); symbol_visitor.mark_live_symbols(); symbol_visitor.live_symbols } fn should_warn(item: &ast::Item) -> bool { match item.node { ast::ItemStatic(..) | ast::ItemFn(..) | ast::ItemEnum(..) | ast::ItemStruct(..) => true, _ => false } } fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> { match item.node { ast::ItemStruct(struct_def, _) => struct_def.ctor_id, _ => None } } struct DeadVisitor<'a> { tcx: &'a ty::ctxt, live_symbols: Box<HashSet<ast::NodeId>>, } impl<'a> DeadVisitor<'a> { // id := node id of an item's definition. // ctor_id := `Some` if the item is a struct_ctor (tuple struct), // `None` otherwise. // If the item is a struct_ctor, then either its `id` or // `ctor_id` (unwrapped) is in the live_symbols set. More specifically, // DefMap maps the ExprPath of a struct_ctor to the node referred by // `ctor_id`. On the other hand, in a statement like // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor, // DefMap maps <ty> to `id` instead. fn symbol_is_live(&mut self, id: ast::NodeId, ctor_id: Option<ast::NodeId>) -> bool { if self.live_symbols.contains(&id) || ctor_id.map_or(false, |ctor| self.live_symbols.contains(&ctor)) { return true; } // If it's a type whose methods are live, then it's live, too. // This is done to handle the case where, for example, the static // method of a private type is used, but the type itself is never // called directly. let impl_methods = self.tcx.impl_methods.borrow(); match self.tcx.inherent_impls.borrow().find(&local_def(id)) { None => (), Some(impl_list) => { for impl_did in impl_list.borrow().iter() { for method_did in impl_methods.get(impl_did).iter() { if self.live_symbols.contains(&method_did.node) { return true; } } } } } false } fn warn_dead_code(&mut self, id: ast::NodeId, span: codemap::Span, ident: ast::Ident) { self.tcx .sess .add_lint(DeadCode, id, span, format!("code is never used: `{}`", token::get_ident(ident))); } } impl<'a> Visitor<()> for DeadVisitor<'a> { fn visit_item(&mut self, item: &ast::Item, _: ()) { let ctor_id = get_struct_ctor_id(item); if!self.symbol_is_live(item.id, ctor_id) && should_warn(item) { self.warn_dead_code(item.id, item.span, item.ident); } visit::walk_item(self, item, ()); } fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) { if!self.symbol_is_live(fi.id, None) { self.warn_dead_code(fi.id, fi.span, fi.ident); } visit::walk_foreign_item(self, fi, ()); } fn visit_fn(&mut self, fk: &visit::FnKind, _: &ast::FnDecl, block: &ast::Block, span: codemap::Span, id: ast::NodeId, _: ()) { // Have to warn method here because methods are not ast::Item match *fk { visit::FkMethod(..) => { let ident = visit::name_of_fn(fk); if!self.symbol_is_live(id, None) { self.warn_dead_code(id, span, ident); } } _ => () } visit::walk_block(self, block, ()); } // Overwrite so that we don't warn the trait method itself. fn visit_trait_method(&mut self, trait_method: &ast::TraitMethod, _: ()) { match *trait_method { ast::Provided(method) => visit::walk_block(self, method.body, ()), ast::Required(_) => () } } } pub fn check_crate(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) { let live_symbols = find_live(tcx, exported_items, reachable_symbols, krate); let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols }; visit::walk_crate(&mut visitor, krate, ()); }
Some(method) => { match method.origin {
random_line_split
dead.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. // This implements the dead-code warning pass. It follows middle::reachable // closely. The idea is that all reachable symbols are live, codes called // from live codes are live, and everything else is dead. use middle::lint::{Allow, contains_lint, DeadCode}; use middle::privacy; use middle::ty; use middle::typeck; use util::nodemap::NodeSet; use collections::HashSet; use syntax::ast; use syntax::ast_map; use syntax::ast_util::{local_def, def_id_of_def, is_local}; use syntax::attr; use syntax::codemap; use syntax::parse::token; use syntax::visit::Visitor; use syntax::visit; pub static DEAD_CODE_LINT_STR: &'static str = "dead_code"; // Any local node that may call something in its body block should be // explored. For example, if it's a live NodeItem that is a // function, then we should explore its block to check for codes that // may need to be marked as live. fn should_explore(tcx: &ty::ctxt, def_id: ast::DefId) -> bool { if!is_local(def_id) { return false; } match tcx.map.find(def_id.node) { Some(ast_map::NodeItem(..)) | Some(ast_map::NodeMethod(..)) | Some(ast_map::NodeForeignItem(..)) | Some(ast_map::NodeTraitMethod(..)) => true, _ => false } } struct MarkSymbolVisitor<'a> { worklist: Vec<ast::NodeId>, tcx: &'a ty::ctxt, live_symbols: Box<HashSet<ast::NodeId>>, } impl<'a> MarkSymbolVisitor<'a> { fn new(tcx: &'a ty::ctxt, worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a> { MarkSymbolVisitor { worklist: worklist, tcx: tcx, live_symbols: box HashSet::new(), } } fn check_def_id(&mut self, def_id: ast::DefId) { if should_explore(self.tcx, def_id) { self.worklist.push(def_id.node); } self.live_symbols.insert(def_id.node); } fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) { let def = match self.tcx.def_map.borrow().find(id) { Some(&def) => def, None => return }; let def_id = match def { ast::DefVariant(enum_id, _, _) => Some(enum_id), ast::DefPrimTy(_) => None, _ => Some(def_id_of_def(def)), }; match def_id { Some(def_id) => self.check_def_id(def_id), None => (), } } fn lookup_and_handle_method(&mut self, id: ast::NodeId, span: codemap::Span) { let method_call = typeck::MethodCall::expr(id); match self.tcx.method_map.borrow().find(&method_call) { Some(method) => { match method.origin { typeck::MethodStatic(def_id) => { match ty::provided_source(self.tcx, def_id) { Some(p_did) => self.check_def_id(p_did), None => self.check_def_id(def_id) } } typeck::MethodParam(typeck::MethodParam { trait_id: trait_id, method_num: index, .. }) | typeck::MethodObject(typeck::MethodObject { trait_id: trait_id, method_num: index, .. }) => { let def_id = ty::trait_method(self.tcx, trait_id, index).def_id; self.check_def_id(def_id); } } } None => { self.tcx.sess.span_bug(span, "method call expression not \ in method map?!") } } } fn mark_live_symbols(&mut self)
fn visit_node(&mut self, node: &ast_map::Node) { match *node { ast_map::NodeItem(item) => { match item.node { ast::ItemFn(..) | ast::ItemTy(..) | ast::ItemEnum(..) | ast::ItemStruct(..) | ast::ItemStatic(..) => { visit::walk_item(self, item, ()); } _ => () } } ast_map::NodeTraitMethod(trait_method) => { visit::walk_trait_method(self, trait_method, ()); } ast_map::NodeMethod(method) => { visit::walk_block(self, method.body, ()); } ast_map::NodeForeignItem(foreign_item) => { visit::walk_foreign_item(self, foreign_item, ()); } _ => () } } } impl<'a> Visitor<()> for MarkSymbolVisitor<'a> { fn visit_expr(&mut self, expr: &ast::Expr, _: ()) { match expr.node { ast::ExprMethodCall(..) => { self.lookup_and_handle_method(expr.id, expr.span); } _ => () } visit::walk_expr(self, expr, ()) } fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, _: ()) { self.lookup_and_handle_definition(&id); visit::walk_path(self, path, ()); } fn visit_item(&mut self, _item: &ast::Item, _: ()) { // Do not recurse into items. These items will be added to the // worklist and recursed into manually if necessary. } } fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool { contains_lint(attrs, Allow, DEAD_CODE_LINT_STR) || attr::contains_name(attrs.as_slice(), "lang") } // This visitor seeds items that // 1) We want to explicitly consider as live: // * Item annotated with #[allow(dead_code)] // - This is done so that if we want to suppress warnings for a // group of dead functions, we only have to annotate the "root". // For example, if both `f` and `g` are dead and `f` calls `g`, // then annotating `f` with `#[allow(dead_code)]` will suppress // warning for both `f` and `g`. // * Item annotated with #[lang=".."] // - This is because lang items are always callable from elsewhere. // or // 2) We are not sure to be live or not // * Implementation of a trait method struct LifeSeeder { worklist: Vec<ast::NodeId>, } impl Visitor<()> for LifeSeeder { fn visit_item(&mut self, item: &ast::Item, _: ()) { if has_allow_dead_code_or_lang_attr(item.attrs.as_slice()) { self.worklist.push(item.id); } match item.node { ast::ItemImpl(_, Some(ref _trait_ref), _, ref methods) => { for method in methods.iter() { self.worklist.push(method.id); } } _ => () } visit::walk_item(self, item, ()); } fn visit_fn(&mut self, fk: &visit::FnKind, _: &ast::FnDecl, block: &ast::Block, _: codemap::Span, id: ast::NodeId, _: ()) { // Check for method here because methods are not ast::Item match *fk { visit::FkMethod(_, _, method) => { if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) { self.worklist.push(id); } } _ => () } visit::walk_block(self, block, ()); } } fn create_and_seed_worklist(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) -> Vec<ast::NodeId> { let mut worklist = Vec::new(); // Preferably, we would only need to seed the worklist with reachable // symbols. However, since the set of reachable symbols differs // depending on whether a crate is built as bin or lib, and we want // the warning to be consistent, we also seed the worklist with // exported symbols. for &id in exported_items.iter() { worklist.push(id); } for &id in reachable_symbols.iter() { worklist.push(id); } // Seed entry point match *tcx.sess.entry_fn.borrow() { Some((id, _)) => worklist.push(id), None => () } // Seed implemented trait methods let mut life_seeder = LifeSeeder { worklist: worklist }; visit::walk_crate(&mut life_seeder, krate, ()); return life_seeder.worklist; } fn find_live(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) -> Box<HashSet<ast::NodeId>> { let worklist = create_and_seed_worklist(tcx, exported_items, reachable_symbols, krate); let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist); symbol_visitor.mark_live_symbols(); symbol_visitor.live_symbols } fn should_warn(item: &ast::Item) -> bool { match item.node { ast::ItemStatic(..) | ast::ItemFn(..) | ast::ItemEnum(..) | ast::ItemStruct(..) => true, _ => false } } fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> { match item.node { ast::ItemStruct(struct_def, _) => struct_def.ctor_id, _ => None } } struct DeadVisitor<'a> { tcx: &'a ty::ctxt, live_symbols: Box<HashSet<ast::NodeId>>, } impl<'a> DeadVisitor<'a> { // id := node id of an item's definition. // ctor_id := `Some` if the item is a struct_ctor (tuple struct), // `None` otherwise. // If the item is a struct_ctor, then either its `id` or // `ctor_id` (unwrapped) is in the live_symbols set. More specifically, // DefMap maps the ExprPath of a struct_ctor to the node referred by // `ctor_id`. On the other hand, in a statement like // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor, // DefMap maps <ty> to `id` instead. fn symbol_is_live(&mut self, id: ast::NodeId, ctor_id: Option<ast::NodeId>) -> bool { if self.live_symbols.contains(&id) || ctor_id.map_or(false, |ctor| self.live_symbols.contains(&ctor)) { return true; } // If it's a type whose methods are live, then it's live, too. // This is done to handle the case where, for example, the static // method of a private type is used, but the type itself is never // called directly. let impl_methods = self.tcx.impl_methods.borrow(); match self.tcx.inherent_impls.borrow().find(&local_def(id)) { None => (), Some(impl_list) => { for impl_did in impl_list.borrow().iter() { for method_did in impl_methods.get(impl_did).iter() { if self.live_symbols.contains(&method_did.node) { return true; } } } } } false } fn warn_dead_code(&mut self, id: ast::NodeId, span: codemap::Span, ident: ast::Ident) { self.tcx .sess .add_lint(DeadCode, id, span, format!("code is never used: `{}`", token::get_ident(ident))); } } impl<'a> Visitor<()> for DeadVisitor<'a> { fn visit_item(&mut self, item: &ast::Item, _: ()) { let ctor_id = get_struct_ctor_id(item); if!self.symbol_is_live(item.id, ctor_id) && should_warn(item) { self.warn_dead_code(item.id, item.span, item.ident); } visit::walk_item(self, item, ()); } fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) { if!self.symbol_is_live(fi.id, None) { self.warn_dead_code(fi.id, fi.span, fi.ident); } visit::walk_foreign_item(self, fi, ()); } fn visit_fn(&mut self, fk: &visit::FnKind, _: &ast::FnDecl, block: &ast::Block, span: codemap::Span, id: ast::NodeId, _: ()) { // Have to warn method here because methods are not ast::Item match *fk { visit::FkMethod(..) => { let ident = visit::name_of_fn(fk); if!self.symbol_is_live(id, None) { self.warn_dead_code(id, span, ident); } } _ => () } visit::walk_block(self, block, ()); } // Overwrite so that we don't warn the trait method itself. fn visit_trait_method(&mut self, trait_method: &ast::TraitMethod, _: ()) { match *trait_method { ast::Provided(method) => visit::walk_block(self, method.body, ()), ast::Required(_) => () } } } pub fn check_crate(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) { let live_symbols = find_live(tcx, exported_items, reachable_symbols, krate); let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols }; visit::walk_crate(&mut visitor, krate, ()); }
{ let mut scanned = HashSet::new(); while self.worklist.len() > 0 { let id = self.worklist.pop().unwrap(); if scanned.contains(&id) { continue } scanned.insert(id); match self.tcx.map.find(id) { Some(ref node) => { self.live_symbols.insert(id); self.visit_node(node); } None => (), } } }
identifier_body
dead.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. // This implements the dead-code warning pass. It follows middle::reachable // closely. The idea is that all reachable symbols are live, codes called // from live codes are live, and everything else is dead. use middle::lint::{Allow, contains_lint, DeadCode}; use middle::privacy; use middle::ty; use middle::typeck; use util::nodemap::NodeSet; use collections::HashSet; use syntax::ast; use syntax::ast_map; use syntax::ast_util::{local_def, def_id_of_def, is_local}; use syntax::attr; use syntax::codemap; use syntax::parse::token; use syntax::visit::Visitor; use syntax::visit; pub static DEAD_CODE_LINT_STR: &'static str = "dead_code"; // Any local node that may call something in its body block should be // explored. For example, if it's a live NodeItem that is a // function, then we should explore its block to check for codes that // may need to be marked as live. fn should_explore(tcx: &ty::ctxt, def_id: ast::DefId) -> bool { if!is_local(def_id) { return false; } match tcx.map.find(def_id.node) { Some(ast_map::NodeItem(..)) | Some(ast_map::NodeMethod(..)) | Some(ast_map::NodeForeignItem(..)) | Some(ast_map::NodeTraitMethod(..)) => true, _ => false } } struct MarkSymbolVisitor<'a> { worklist: Vec<ast::NodeId>, tcx: &'a ty::ctxt, live_symbols: Box<HashSet<ast::NodeId>>, } impl<'a> MarkSymbolVisitor<'a> { fn new(tcx: &'a ty::ctxt, worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a> { MarkSymbolVisitor { worklist: worklist, tcx: tcx, live_symbols: box HashSet::new(), } } fn check_def_id(&mut self, def_id: ast::DefId) { if should_explore(self.tcx, def_id) { self.worklist.push(def_id.node); } self.live_symbols.insert(def_id.node); } fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) { let def = match self.tcx.def_map.borrow().find(id) { Some(&def) => def, None => return }; let def_id = match def { ast::DefVariant(enum_id, _, _) => Some(enum_id), ast::DefPrimTy(_) => None, _ => Some(def_id_of_def(def)), }; match def_id { Some(def_id) => self.check_def_id(def_id), None => (), } } fn lookup_and_handle_method(&mut self, id: ast::NodeId, span: codemap::Span) { let method_call = typeck::MethodCall::expr(id); match self.tcx.method_map.borrow().find(&method_call) { Some(method) => { match method.origin { typeck::MethodStatic(def_id) => { match ty::provided_source(self.tcx, def_id) { Some(p_did) => self.check_def_id(p_did), None => self.check_def_id(def_id) } } typeck::MethodParam(typeck::MethodParam { trait_id: trait_id, method_num: index, .. }) | typeck::MethodObject(typeck::MethodObject { trait_id: trait_id, method_num: index, .. }) => { let def_id = ty::trait_method(self.tcx, trait_id, index).def_id; self.check_def_id(def_id); } } } None => { self.tcx.sess.span_bug(span, "method call expression not \ in method map?!") } } } fn mark_live_symbols(&mut self) { let mut scanned = HashSet::new(); while self.worklist.len() > 0 { let id = self.worklist.pop().unwrap(); if scanned.contains(&id) { continue } scanned.insert(id); match self.tcx.map.find(id) { Some(ref node) => { self.live_symbols.insert(id); self.visit_node(node); } None => (), } } } fn visit_node(&mut self, node: &ast_map::Node) { match *node { ast_map::NodeItem(item) => { match item.node { ast::ItemFn(..) | ast::ItemTy(..) | ast::ItemEnum(..) | ast::ItemStruct(..) | ast::ItemStatic(..) => { visit::walk_item(self, item, ()); } _ => () } } ast_map::NodeTraitMethod(trait_method) => { visit::walk_trait_method(self, trait_method, ()); } ast_map::NodeMethod(method) => { visit::walk_block(self, method.body, ()); } ast_map::NodeForeignItem(foreign_item) => { visit::walk_foreign_item(self, foreign_item, ()); } _ => () } } } impl<'a> Visitor<()> for MarkSymbolVisitor<'a> { fn visit_expr(&mut self, expr: &ast::Expr, _: ()) { match expr.node { ast::ExprMethodCall(..) => { self.lookup_and_handle_method(expr.id, expr.span); } _ => () } visit::walk_expr(self, expr, ()) } fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, _: ()) { self.lookup_and_handle_definition(&id); visit::walk_path(self, path, ()); } fn visit_item(&mut self, _item: &ast::Item, _: ()) { // Do not recurse into items. These items will be added to the // worklist and recursed into manually if necessary. } } fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool { contains_lint(attrs, Allow, DEAD_CODE_LINT_STR) || attr::contains_name(attrs.as_slice(), "lang") } // This visitor seeds items that // 1) We want to explicitly consider as live: // * Item annotated with #[allow(dead_code)] // - This is done so that if we want to suppress warnings for a // group of dead functions, we only have to annotate the "root". // For example, if both `f` and `g` are dead and `f` calls `g`, // then annotating `f` with `#[allow(dead_code)]` will suppress // warning for both `f` and `g`. // * Item annotated with #[lang=".."] // - This is because lang items are always callable from elsewhere. // or // 2) We are not sure to be live or not // * Implementation of a trait method struct LifeSeeder { worklist: Vec<ast::NodeId>, } impl Visitor<()> for LifeSeeder { fn visit_item(&mut self, item: &ast::Item, _: ()) { if has_allow_dead_code_or_lang_attr(item.attrs.as_slice()) { self.worklist.push(item.id); } match item.node { ast::ItemImpl(_, Some(ref _trait_ref), _, ref methods) => { for method in methods.iter() { self.worklist.push(method.id); } } _ => () } visit::walk_item(self, item, ()); } fn visit_fn(&mut self, fk: &visit::FnKind, _: &ast::FnDecl, block: &ast::Block, _: codemap::Span, id: ast::NodeId, _: ()) { // Check for method here because methods are not ast::Item match *fk { visit::FkMethod(_, _, method) => { if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) { self.worklist.push(id); } } _ => () } visit::walk_block(self, block, ()); } } fn create_and_seed_worklist(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) -> Vec<ast::NodeId> { let mut worklist = Vec::new(); // Preferably, we would only need to seed the worklist with reachable // symbols. However, since the set of reachable symbols differs // depending on whether a crate is built as bin or lib, and we want // the warning to be consistent, we also seed the worklist with // exported symbols. for &id in exported_items.iter() { worklist.push(id); } for &id in reachable_symbols.iter() { worklist.push(id); } // Seed entry point match *tcx.sess.entry_fn.borrow() { Some((id, _)) => worklist.push(id), None => () } // Seed implemented trait methods let mut life_seeder = LifeSeeder { worklist: worklist }; visit::walk_crate(&mut life_seeder, krate, ()); return life_seeder.worklist; } fn find_live(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) -> Box<HashSet<ast::NodeId>> { let worklist = create_and_seed_worklist(tcx, exported_items, reachable_symbols, krate); let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist); symbol_visitor.mark_live_symbols(); symbol_visitor.live_symbols } fn should_warn(item: &ast::Item) -> bool { match item.node { ast::ItemStatic(..) | ast::ItemFn(..) | ast::ItemEnum(..) | ast::ItemStruct(..) => true, _ => false } } fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> { match item.node { ast::ItemStruct(struct_def, _) => struct_def.ctor_id, _ => None } } struct
<'a> { tcx: &'a ty::ctxt, live_symbols: Box<HashSet<ast::NodeId>>, } impl<'a> DeadVisitor<'a> { // id := node id of an item's definition. // ctor_id := `Some` if the item is a struct_ctor (tuple struct), // `None` otherwise. // If the item is a struct_ctor, then either its `id` or // `ctor_id` (unwrapped) is in the live_symbols set. More specifically, // DefMap maps the ExprPath of a struct_ctor to the node referred by // `ctor_id`. On the other hand, in a statement like // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor, // DefMap maps <ty> to `id` instead. fn symbol_is_live(&mut self, id: ast::NodeId, ctor_id: Option<ast::NodeId>) -> bool { if self.live_symbols.contains(&id) || ctor_id.map_or(false, |ctor| self.live_symbols.contains(&ctor)) { return true; } // If it's a type whose methods are live, then it's live, too. // This is done to handle the case where, for example, the static // method of a private type is used, but the type itself is never // called directly. let impl_methods = self.tcx.impl_methods.borrow(); match self.tcx.inherent_impls.borrow().find(&local_def(id)) { None => (), Some(impl_list) => { for impl_did in impl_list.borrow().iter() { for method_did in impl_methods.get(impl_did).iter() { if self.live_symbols.contains(&method_did.node) { return true; } } } } } false } fn warn_dead_code(&mut self, id: ast::NodeId, span: codemap::Span, ident: ast::Ident) { self.tcx .sess .add_lint(DeadCode, id, span, format!("code is never used: `{}`", token::get_ident(ident))); } } impl<'a> Visitor<()> for DeadVisitor<'a> { fn visit_item(&mut self, item: &ast::Item, _: ()) { let ctor_id = get_struct_ctor_id(item); if!self.symbol_is_live(item.id, ctor_id) && should_warn(item) { self.warn_dead_code(item.id, item.span, item.ident); } visit::walk_item(self, item, ()); } fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) { if!self.symbol_is_live(fi.id, None) { self.warn_dead_code(fi.id, fi.span, fi.ident); } visit::walk_foreign_item(self, fi, ()); } fn visit_fn(&mut self, fk: &visit::FnKind, _: &ast::FnDecl, block: &ast::Block, span: codemap::Span, id: ast::NodeId, _: ()) { // Have to warn method here because methods are not ast::Item match *fk { visit::FkMethod(..) => { let ident = visit::name_of_fn(fk); if!self.symbol_is_live(id, None) { self.warn_dead_code(id, span, ident); } } _ => () } visit::walk_block(self, block, ()); } // Overwrite so that we don't warn the trait method itself. fn visit_trait_method(&mut self, trait_method: &ast::TraitMethod, _: ()) { match *trait_method { ast::Provided(method) => visit::walk_block(self, method.body, ()), ast::Required(_) => () } } } pub fn check_crate(tcx: &ty::ctxt, exported_items: &privacy::ExportedItems, reachable_symbols: &NodeSet, krate: &ast::Crate) { let live_symbols = find_live(tcx, exported_items, reachable_symbols, krate); let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols }; visit::walk_crate(&mut visitor, krate, ()); }
DeadVisitor
identifier_name
def.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub use self::Def::*; pub use self::MethodProvenance::*; pub use self::TraitItemKind::*; use middle::subst::ParamSpace; use middle::ty::{ExplicitSelfCategory, StaticExplicitSelfCategory}; use util::nodemap::NodeMap; use syntax::ast; use syntax::ast_util::local_def; use std::cell::RefCell; #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum Def { DefFn(ast::DefId, bool /* is_ctor */), DefStaticMethod(/* method */ ast::DefId, MethodProvenance), DefSelfTy(/* trait id */ ast::NodeId), DefMod(ast::DefId), DefForeignMod(ast::DefId), DefStatic(ast::DefId, bool /* is_mutbl */), DefConst(ast::DefId), DefLocal(ast::NodeId), DefVariant(ast::DefId /* enum */, ast::DefId /* variant */, bool /* is_structure */), DefTy(ast::DefId, bool /* is_enum */), DefAssociatedTy(ast::DefId), // A partially resolved path to an associated type `T::U` where `T` is a concrete // type (indicated by the DefId) which implements a trait which has an associated // type `U` (indicated by the Ident). // FIXME(#20301) -- should use Name DefAssociatedPath(TyParamProvenance, ast::Ident), DefTrait(ast::DefId), DefPrimTy(ast::PrimTy), DefTyParam(ParamSpace, u32, ast::DefId, ast::Name), DefUse(ast::DefId), DefUpvar(ast::NodeId, // id of closed over local ast::NodeId, // expr node that creates the closure ast::NodeId), // block node for the closest enclosing proc // or unboxed closure, DUMMY_NODE_ID otherwise /// Note that if it's a tuple struct's definition, the node id of the ast::DefId /// may either refer to the item definition's id or the StructDef.ctor_id. /// /// The cases that I have encountered so far are (this is not exhaustive): /// - If it's a ty_path referring to some tuple struct, then DefMap maps /// it to a def whose id is the item definition's id. /// - If it's an ExprPath referring to some tuple struct, then DefMap maps /// it to a def whose id is the StructDef.ctor_id. DefStruct(ast::DefId), DefTyParamBinder(ast::NodeId), /* struct, impl or trait with ty params */ DefRegion(ast::NodeId), DefLabel(ast::NodeId), DefMethod(ast::DefId /* method */, Option<ast::DefId> /* trait */, MethodProvenance), } // Definition mapping pub type DefMap = RefCell<NodeMap<Def>>; // This is the replacement export map. It maps a module to all of the exports // within. pub type ExportMap = NodeMap<Vec<Export>>; #[derive(Copy)] pub struct
{ pub name: ast::Name, // The name of the target. pub def_id: ast::DefId, // The definition of the target. } #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum MethodProvenance { FromTrait(ast::DefId), FromImpl(ast::DefId), } #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum TyParamProvenance { FromSelf(ast::DefId), FromParam(ast::DefId), } impl MethodProvenance { pub fn map<F>(self, f: F) -> MethodProvenance where F: FnOnce(ast::DefId) -> ast::DefId, { match self { FromTrait(did) => FromTrait(f(did)), FromImpl(did) => FromImpl(f(did)) } } } impl TyParamProvenance { pub fn def_id(&self) -> ast::DefId { match *self { TyParamProvenance::FromSelf(ref did) => did.clone(), TyParamProvenance::FromParam(ref did) => did.clone(), } } } #[derive(Clone, Copy, Eq, PartialEq)] pub enum TraitItemKind { NonstaticMethodTraitItemKind, StaticMethodTraitItemKind, TypeTraitItemKind, } impl TraitItemKind { pub fn from_explicit_self_category(explicit_self_category: ExplicitSelfCategory) -> TraitItemKind { if explicit_self_category == StaticExplicitSelfCategory { StaticMethodTraitItemKind } else { NonstaticMethodTraitItemKind } } } impl Def { pub fn local_node_id(&self) -> ast::NodeId { let def_id = self.def_id(); assert_eq!(def_id.krate, ast::LOCAL_CRATE); def_id.node } pub fn def_id(&self) -> ast::DefId { match *self { DefFn(id, _) | DefStaticMethod(id, _) | DefMod(id) | DefForeignMod(id) | DefStatic(id, _) | DefVariant(_, id, _) | DefTy(id, _) | DefAssociatedTy(id) | DefTyParam(_, _, id, _) | DefUse(id) | DefStruct(id) | DefTrait(id) | DefMethod(id, _, _) | DefConst(id) | DefAssociatedPath(TyParamProvenance::FromSelf(id), _) | DefAssociatedPath(TyParamProvenance::FromParam(id), _) => { id } DefLocal(id) | DefSelfTy(id) | DefUpvar(id, _, _) | DefRegion(id) | DefTyParamBinder(id) | DefLabel(id) => { local_def(id) } DefPrimTy(_) => panic!() } } pub fn variant_def_ids(&self) -> Option<(ast::DefId, ast::DefId)> { match *self { DefVariant(enum_id, var_id, _) => { Some((enum_id, var_id)) } _ => None } } }
Export
identifier_name
def.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub use self::Def::*; pub use self::MethodProvenance::*; pub use self::TraitItemKind::*; use middle::subst::ParamSpace; use middle::ty::{ExplicitSelfCategory, StaticExplicitSelfCategory}; use util::nodemap::NodeMap; use syntax::ast; use syntax::ast_util::local_def; use std::cell::RefCell; #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum Def { DefFn(ast::DefId, bool /* is_ctor */), DefStaticMethod(/* method */ ast::DefId, MethodProvenance), DefSelfTy(/* trait id */ ast::NodeId), DefMod(ast::DefId), DefForeignMod(ast::DefId), DefStatic(ast::DefId, bool /* is_mutbl */), DefConst(ast::DefId), DefLocal(ast::NodeId), DefVariant(ast::DefId /* enum */, ast::DefId /* variant */, bool /* is_structure */), DefTy(ast::DefId, bool /* is_enum */), DefAssociatedTy(ast::DefId), // A partially resolved path to an associated type `T::U` where `T` is a concrete // type (indicated by the DefId) which implements a trait which has an associated // type `U` (indicated by the Ident). // FIXME(#20301) -- should use Name DefAssociatedPath(TyParamProvenance, ast::Ident), DefTrait(ast::DefId), DefPrimTy(ast::PrimTy), DefTyParam(ParamSpace, u32, ast::DefId, ast::Name), DefUse(ast::DefId), DefUpvar(ast::NodeId, // id of closed over local ast::NodeId, // expr node that creates the closure ast::NodeId), // block node for the closest enclosing proc // or unboxed closure, DUMMY_NODE_ID otherwise /// Note that if it's a tuple struct's definition, the node id of the ast::DefId /// may either refer to the item definition's id or the StructDef.ctor_id. /// /// The cases that I have encountered so far are (this is not exhaustive): /// - If it's a ty_path referring to some tuple struct, then DefMap maps /// it to a def whose id is the item definition's id. /// - If it's an ExprPath referring to some tuple struct, then DefMap maps /// it to a def whose id is the StructDef.ctor_id. DefStruct(ast::DefId), DefTyParamBinder(ast::NodeId), /* struct, impl or trait with ty params */ DefRegion(ast::NodeId), DefLabel(ast::NodeId), DefMethod(ast::DefId /* method */, Option<ast::DefId> /* trait */, MethodProvenance), } // Definition mapping pub type DefMap = RefCell<NodeMap<Def>>; // This is the replacement export map. It maps a module to all of the exports // within. pub type ExportMap = NodeMap<Vec<Export>>; #[derive(Copy)]
pub def_id: ast::DefId, // The definition of the target. } #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum MethodProvenance { FromTrait(ast::DefId), FromImpl(ast::DefId), } #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum TyParamProvenance { FromSelf(ast::DefId), FromParam(ast::DefId), } impl MethodProvenance { pub fn map<F>(self, f: F) -> MethodProvenance where F: FnOnce(ast::DefId) -> ast::DefId, { match self { FromTrait(did) => FromTrait(f(did)), FromImpl(did) => FromImpl(f(did)) } } } impl TyParamProvenance { pub fn def_id(&self) -> ast::DefId { match *self { TyParamProvenance::FromSelf(ref did) => did.clone(), TyParamProvenance::FromParam(ref did) => did.clone(), } } } #[derive(Clone, Copy, Eq, PartialEq)] pub enum TraitItemKind { NonstaticMethodTraitItemKind, StaticMethodTraitItemKind, TypeTraitItemKind, } impl TraitItemKind { pub fn from_explicit_self_category(explicit_self_category: ExplicitSelfCategory) -> TraitItemKind { if explicit_self_category == StaticExplicitSelfCategory { StaticMethodTraitItemKind } else { NonstaticMethodTraitItemKind } } } impl Def { pub fn local_node_id(&self) -> ast::NodeId { let def_id = self.def_id(); assert_eq!(def_id.krate, ast::LOCAL_CRATE); def_id.node } pub fn def_id(&self) -> ast::DefId { match *self { DefFn(id, _) | DefStaticMethod(id, _) | DefMod(id) | DefForeignMod(id) | DefStatic(id, _) | DefVariant(_, id, _) | DefTy(id, _) | DefAssociatedTy(id) | DefTyParam(_, _, id, _) | DefUse(id) | DefStruct(id) | DefTrait(id) | DefMethod(id, _, _) | DefConst(id) | DefAssociatedPath(TyParamProvenance::FromSelf(id), _) | DefAssociatedPath(TyParamProvenance::FromParam(id), _) => { id } DefLocal(id) | DefSelfTy(id) | DefUpvar(id, _, _) | DefRegion(id) | DefTyParamBinder(id) | DefLabel(id) => { local_def(id) } DefPrimTy(_) => panic!() } } pub fn variant_def_ids(&self) -> Option<(ast::DefId, ast::DefId)> { match *self { DefVariant(enum_id, var_id, _) => { Some((enum_id, var_id)) } _ => None } } }
pub struct Export { pub name: ast::Name, // The name of the target.
random_line_split
server_query.rs
use async_graphql::{Context, FieldResult}; use chrono::prelude::*; use eyre::{ // eyre, Result,
}; use printspool_json_store::{JsonRow, Record}; // use async_graphql::{ // // ID, // // Context, // FieldResult, // }; // use printspool_json_store::Record as _; use crate::{built_info, server::Server}; #[derive(Default)] pub struct ServerQuery; #[derive(async_graphql::InputObject, Default, Debug)] pub struct FeatureFlagsInput { filter: Option<Vec<String>>, } #[async_graphql::Object] impl ServerQuery { async fn server_version(&self) -> String { // See https://docs.rs/built/0.4.4/built/ let version_number = built_info::GIT_VERSION.unwrap_or("DEV"); let dirty_string = if built_info::GIT_DIRTY.unwrap_or(false) { " + Uncommitted Changes" } else { "" }; // eg. Teg 0.1.0 for linux/x86_64 format!( "Teg {version_number}{dirty_string}", version_number = version_number, dirty_string = dirty_string, ) } /// Returns the current date time from the server. Useful for determining the connection /// latency. async fn ping(&self) -> DateTime<Utc> { Utc::now() } // TODO: Do we need pending updates still in the new architecture? // hasPendingUpdates #[instrument(skip(self, ctx))] async fn server_name<'ctx>( &self, ctx: &'ctx Context<'_>, ) -> FieldResult<Option<String>> { let db: &crate::Db = ctx.data()?; async move { let servers = sqlx::query_as!( JsonRow, r#" SELECT servers.props FROM servers WHERE (servers.props->'is_self')::boolean IS TRUE "#, ) .fetch_all(db) .await?; let servers = Server::from_rows(servers)?; let name = servers.into_iter().next().map(|server| server.name); Result::<_>::Ok(name) } // log the backtrace which is otherwise lost by FieldResult .await .map_err(|err| { warn!("{:?}", err); err.into() }) } #[instrument(skip(self))] async fn feature_flags( &self, #[graphql(default)] input: FeatureFlagsInput, ) -> FieldResult<Vec<String>> { let mut flags: Vec<String> = vec![ // Feature Flags Go Here! // "slicer".to_string(), ]; if std::env::var("ENABLE_SLICER") == Ok("1".to_string()) { flags.push("slicer".to_string()); } if let Some(filter) = input.filter { flags = flags .into_iter() .filter(|flag| filter.contains(flag)) .collect(); } Ok(flags) } }
// Context as _,
random_line_split
server_query.rs
use async_graphql::{Context, FieldResult}; use chrono::prelude::*; use eyre::{ // eyre, Result, // Context as _, }; use printspool_json_store::{JsonRow, Record}; // use async_graphql::{ // // ID, // // Context, // FieldResult, // }; // use printspool_json_store::Record as _; use crate::{built_info, server::Server}; #[derive(Default)] pub struct ServerQuery; #[derive(async_graphql::InputObject, Default, Debug)] pub struct FeatureFlagsInput { filter: Option<Vec<String>>, } #[async_graphql::Object] impl ServerQuery { async fn server_version(&self) -> String { // See https://docs.rs/built/0.4.4/built/ let version_number = built_info::GIT_VERSION.unwrap_or("DEV"); let dirty_string = if built_info::GIT_DIRTY.unwrap_or(false) { " + Uncommitted Changes" } else { "" }; // eg. Teg 0.1.0 for linux/x86_64 format!( "Teg {version_number}{dirty_string}", version_number = version_number, dirty_string = dirty_string, ) } /// Returns the current date time from the server. Useful for determining the connection /// latency. async fn ping(&self) -> DateTime<Utc> { Utc::now() } // TODO: Do we need pending updates still in the new architecture? // hasPendingUpdates #[instrument(skip(self, ctx))] async fn
<'ctx>( &self, ctx: &'ctx Context<'_>, ) -> FieldResult<Option<String>> { let db: &crate::Db = ctx.data()?; async move { let servers = sqlx::query_as!( JsonRow, r#" SELECT servers.props FROM servers WHERE (servers.props->'is_self')::boolean IS TRUE "#, ) .fetch_all(db) .await?; let servers = Server::from_rows(servers)?; let name = servers.into_iter().next().map(|server| server.name); Result::<_>::Ok(name) } // log the backtrace which is otherwise lost by FieldResult .await .map_err(|err| { warn!("{:?}", err); err.into() }) } #[instrument(skip(self))] async fn feature_flags( &self, #[graphql(default)] input: FeatureFlagsInput, ) -> FieldResult<Vec<String>> { let mut flags: Vec<String> = vec![ // Feature Flags Go Here! // "slicer".to_string(), ]; if std::env::var("ENABLE_SLICER") == Ok("1".to_string()) { flags.push("slicer".to_string()); } if let Some(filter) = input.filter { flags = flags .into_iter() .filter(|flag| filter.contains(flag)) .collect(); } Ok(flags) } }
server_name
identifier_name
server_query.rs
use async_graphql::{Context, FieldResult}; use chrono::prelude::*; use eyre::{ // eyre, Result, // Context as _, }; use printspool_json_store::{JsonRow, Record}; // use async_graphql::{ // // ID, // // Context, // FieldResult, // }; // use printspool_json_store::Record as _; use crate::{built_info, server::Server}; #[derive(Default)] pub struct ServerQuery; #[derive(async_graphql::InputObject, Default, Debug)] pub struct FeatureFlagsInput { filter: Option<Vec<String>>, } #[async_graphql::Object] impl ServerQuery { async fn server_version(&self) -> String { // See https://docs.rs/built/0.4.4/built/ let version_number = built_info::GIT_VERSION.unwrap_or("DEV"); let dirty_string = if built_info::GIT_DIRTY.unwrap_or(false) { " + Uncommitted Changes" } else
; // eg. Teg 0.1.0 for linux/x86_64 format!( "Teg {version_number}{dirty_string}", version_number = version_number, dirty_string = dirty_string, ) } /// Returns the current date time from the server. Useful for determining the connection /// latency. async fn ping(&self) -> DateTime<Utc> { Utc::now() } // TODO: Do we need pending updates still in the new architecture? // hasPendingUpdates #[instrument(skip(self, ctx))] async fn server_name<'ctx>( &self, ctx: &'ctx Context<'_>, ) -> FieldResult<Option<String>> { let db: &crate::Db = ctx.data()?; async move { let servers = sqlx::query_as!( JsonRow, r#" SELECT servers.props FROM servers WHERE (servers.props->'is_self')::boolean IS TRUE "#, ) .fetch_all(db) .await?; let servers = Server::from_rows(servers)?; let name = servers.into_iter().next().map(|server| server.name); Result::<_>::Ok(name) } // log the backtrace which is otherwise lost by FieldResult .await .map_err(|err| { warn!("{:?}", err); err.into() }) } #[instrument(skip(self))] async fn feature_flags( &self, #[graphql(default)] input: FeatureFlagsInput, ) -> FieldResult<Vec<String>> { let mut flags: Vec<String> = vec![ // Feature Flags Go Here! // "slicer".to_string(), ]; if std::env::var("ENABLE_SLICER") == Ok("1".to_string()) { flags.push("slicer".to_string()); } if let Some(filter) = input.filter { flags = flags .into_iter() .filter(|flag| filter.contains(flag)) .collect(); } Ok(flags) } }
{ "" }
conditional_block
server_query.rs
use async_graphql::{Context, FieldResult}; use chrono::prelude::*; use eyre::{ // eyre, Result, // Context as _, }; use printspool_json_store::{JsonRow, Record}; // use async_graphql::{ // // ID, // // Context, // FieldResult, // }; // use printspool_json_store::Record as _; use crate::{built_info, server::Server}; #[derive(Default)] pub struct ServerQuery; #[derive(async_graphql::InputObject, Default, Debug)] pub struct FeatureFlagsInput { filter: Option<Vec<String>>, } #[async_graphql::Object] impl ServerQuery { async fn server_version(&self) -> String { // See https://docs.rs/built/0.4.4/built/ let version_number = built_info::GIT_VERSION.unwrap_or("DEV"); let dirty_string = if built_info::GIT_DIRTY.unwrap_or(false) { " + Uncommitted Changes" } else { "" }; // eg. Teg 0.1.0 for linux/x86_64 format!( "Teg {version_number}{dirty_string}", version_number = version_number, dirty_string = dirty_string, ) } /// Returns the current date time from the server. Useful for determining the connection /// latency. async fn ping(&self) -> DateTime<Utc>
// TODO: Do we need pending updates still in the new architecture? // hasPendingUpdates #[instrument(skip(self, ctx))] async fn server_name<'ctx>( &self, ctx: &'ctx Context<'_>, ) -> FieldResult<Option<String>> { let db: &crate::Db = ctx.data()?; async move { let servers = sqlx::query_as!( JsonRow, r#" SELECT servers.props FROM servers WHERE (servers.props->'is_self')::boolean IS TRUE "#, ) .fetch_all(db) .await?; let servers = Server::from_rows(servers)?; let name = servers.into_iter().next().map(|server| server.name); Result::<_>::Ok(name) } // log the backtrace which is otherwise lost by FieldResult .await .map_err(|err| { warn!("{:?}", err); err.into() }) } #[instrument(skip(self))] async fn feature_flags( &self, #[graphql(default)] input: FeatureFlagsInput, ) -> FieldResult<Vec<String>> { let mut flags: Vec<String> = vec![ // Feature Flags Go Here! // "slicer".to_string(), ]; if std::env::var("ENABLE_SLICER") == Ok("1".to_string()) { flags.push("slicer".to_string()); } if let Some(filter) = input.filter { flags = flags .into_iter() .filter(|flag| filter.contains(flag)) .collect(); } Ok(flags) } }
{ Utc::now() }
identifier_body
config.rs
use std::{io, fmt, os, result, mem}; use std::collections::HashMap; use serialize::{Encodable,Encoder}; use toml; use core::MultiShell; use util::{CargoResult, ChainError, Require, internal, human}; use util::toml as cargo_toml; pub struct Config<'a> { home_path: Path, shell: &'a mut MultiShell<'a>, jobs: uint, target: Option<String>, linker: Option<String>, ar: Option<String>, } impl<'a> Config<'a> { pub fn new<'a>(shell: &'a mut MultiShell, jobs: Option<uint>, target: Option<String>) -> CargoResult<Config<'a>> { if jobs == Some(0) { return Err(human("jobs must be at least 1")) } Ok(Config { home_path: try!(os::homedir().require(|| { human("Cargo couldn't find your home directory. \ This probably means that $HOME was not set.") })), shell: shell, jobs: jobs.unwrap_or(os::num_cpus()), target: target, ar: None, linker: None, }) } pub fn home(&self) -> &Path { &self.home_path } pub fn git_db_path(&self) -> Path { self.home_path.join(".cargo").join("git").join("db") } pub fn git_checkout_path(&self) -> Path { self.home_path.join(".cargo").join("git").join("checkouts") } pub fn shell(&mut self) -> &mut MultiShell { &mut *self.shell } pub fn jobs(&self) -> uint { self.jobs } pub fn target(&self) -> Option<&str> { self.target.as_ref().map(|t| t.as_slice()) } pub fn set_ar(&mut self, ar: String) { self.ar = Some(ar); } pub fn set_linker(&mut self, linker: String) { self.linker = Some(linker); } pub fn linker(&self) -> Option<&str> { self.linker.as_ref().map(|t| t.as_slice()) } pub fn ar(&self) -> Option<&str> { self.ar.as_ref().map(|t| t.as_slice()) } } #[deriving(Eq,PartialEq,Clone,Encodable,Decodable)] pub enum Location { Project, Global } #[deriving(Eq,PartialEq,Clone,Decodable)] pub enum ConfigValue { String(String, Path), List(Vec<(String, Path)>), Table(HashMap<String, ConfigValue>), Boolean(bool, Path), } impl fmt::Show for ConfigValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { String(ref string, ref path) => { write!(f, "{} (from {})", string, path.display()) } List(ref list) => { try!(write!(f, "[")); for (i, &(ref s, ref path)) in list.iter().enumerate() { if i > 0 { try!(write!(f, ", ")); } try!(write!(f, "{} (from {})", s, path.display())); } write!(f, "]") } Table(ref table) => write!(f, "{}", table), Boolean(b, ref path) => write!(f, "{} (from {})", b, path.display()), } } } impl<E, S: Encoder<E>> Encodable<S, E> for ConfigValue { fn encode(&self, s: &mut S) -> Result<(), E> { match *self { String(ref string, _) => string.encode(s), List(ref list) => { let list: Vec<&String> = list.iter().map(|s| s.ref0()).collect(); list.encode(s) } Table(ref table) => table.encode(s), Boolean(b, _) => b.encode(s), } } } impl ConfigValue { fn from_toml(path: &Path, toml: toml::Value) -> CargoResult<ConfigValue> { match toml { toml::String(val) => Ok(String(val, path.clone())), toml::Boolean(b) => Ok(Boolean(b, path.clone())), toml::Array(val) => { Ok(List(try!(result::collect(val.move_iter().map(|toml| { match toml { toml::String(val) => Ok((val, path.clone())), _ => Err(internal("")), } }))))) } toml::Table(val) => { Ok(Table(try!(result::collect(val.move_iter().map(|(key, value)| { let value = raw_try!(ConfigValue::from_toml(path, value)); Ok((key, value)) }))))) } _ => return Err(internal("")) } } fn merge(&mut self, from: ConfigValue) -> CargoResult<()> { match (self, from) { (me @ &String(..), from @ String(..)) => *me = from, (me @ &Boolean(..), from @ Boolean(..)) => *me = from, (&List(ref mut old), List(ref mut new)) => { let new = mem::replace(new, Vec::new()); old.extend(new.move_iter()); } (&Table(ref mut old), Table(ref mut new)) => { let new = mem::replace(new, HashMap::new());
|_, old, new| err = old.merge(new), |_, new| new); try!(err); } } (expected, found) => { return Err(internal(format!("expected {}, but found {}", expected.desc(), found.desc()))) } } Ok(()) } pub fn string(&self) -> CargoResult<(&str, &Path)> { match *self { String(ref s, ref p) => Ok((s.as_slice(), p)), _ => Err(internal(format!("expected a string, but found a {}", self.desc()))), } } pub fn table(&self) -> CargoResult<&HashMap<String, ConfigValue>> { match *self { Table(ref table) => Ok(table), _ => Err(internal(format!("expected a table, but found a {}", self.desc()))), } } pub fn list(&self) -> CargoResult<&[(String, Path)]> { match *self { List(ref list) => Ok(list.as_slice()), _ => Err(internal(format!("expected a list, but found a {}", self.desc()))), } } pub fn boolean(&self) -> CargoResult<(bool, &Path)> { match *self { Boolean(b, ref p) => Ok((b, p)), _ => Err(internal(format!("expected a bool, but found a {}", self.desc()))), } } pub fn desc(&self) -> &'static str { match *self { Table(..) => "table", List(..) => "array", String(..) => "string", Boolean(..) => "boolean", } } } pub fn get_config(pwd: Path, key: &str) -> CargoResult<ConfigValue> { find_in_tree(&pwd, |file| extract_config(file, key)).map_err(|_| human(format!("`{}` not found in your configuration", key))) } pub fn all_configs(pwd: Path) -> CargoResult<HashMap<String, ConfigValue>> { let mut cfg = Table(HashMap::new()); try!(walk_tree(&pwd, |mut file| { let path = file.path().clone(); let contents = try!(file.read_to_string()); let table = try!(cargo_toml::parse(contents.as_slice(), &path).chain_error(|| { internal(format!("could not parse Toml manifest; path={}", path.display())) })); let value = try!(ConfigValue::from_toml(&path, toml::Table(table))); try!(cfg.merge(value)); Ok(()) }).map_err(|_| human("Couldn't load Cargo configuration"))); match cfg { Table(map) => Ok(map), _ => unreachable!(), } } fn find_in_tree<T>(pwd: &Path, walk: |io::fs::File| -> CargoResult<T>) -> CargoResult<T> { let mut current = pwd.clone(); loop { let possible = current.join(".cargo").join("config"); if possible.exists() { let file = try!(io::fs::File::open(&possible)); match walk(file) { Ok(res) => return Ok(res), _ => () } } if!current.pop() { break; } } Err(internal("")) } fn walk_tree(pwd: &Path, walk: |io::fs::File| -> CargoResult<()>) -> CargoResult<()> { let mut current = pwd.clone(); let mut err = false; loop { let possible = current.join(".cargo").join("config"); if possible.exists() { let file = try!(io::fs::File::open(&possible)); match walk(file) { Err(_) => err = false, _ => () } } if err { return Err(internal("")); } if!current.pop() { break; } } Ok(()) } fn extract_config(mut file: io::fs::File, key: &str) -> CargoResult<ConfigValue> { let contents = try!(file.read_to_string()); let mut toml = try!(cargo_toml::parse(contents.as_slice(), file.path())); let val = try!(toml.pop(&key.to_string()).require(|| internal(""))); ConfigValue::from_toml(file.path(), val) }
for (key, value) in new.move_iter() { let mut err = Ok(()); old.find_with_or_insert_with(key, value,
random_line_split
config.rs
use std::{io, fmt, os, result, mem}; use std::collections::HashMap; use serialize::{Encodable,Encoder}; use toml; use core::MultiShell; use util::{CargoResult, ChainError, Require, internal, human}; use util::toml as cargo_toml; pub struct
<'a> { home_path: Path, shell: &'a mut MultiShell<'a>, jobs: uint, target: Option<String>, linker: Option<String>, ar: Option<String>, } impl<'a> Config<'a> { pub fn new<'a>(shell: &'a mut MultiShell, jobs: Option<uint>, target: Option<String>) -> CargoResult<Config<'a>> { if jobs == Some(0) { return Err(human("jobs must be at least 1")) } Ok(Config { home_path: try!(os::homedir().require(|| { human("Cargo couldn't find your home directory. \ This probably means that $HOME was not set.") })), shell: shell, jobs: jobs.unwrap_or(os::num_cpus()), target: target, ar: None, linker: None, }) } pub fn home(&self) -> &Path { &self.home_path } pub fn git_db_path(&self) -> Path { self.home_path.join(".cargo").join("git").join("db") } pub fn git_checkout_path(&self) -> Path { self.home_path.join(".cargo").join("git").join("checkouts") } pub fn shell(&mut self) -> &mut MultiShell { &mut *self.shell } pub fn jobs(&self) -> uint { self.jobs } pub fn target(&self) -> Option<&str> { self.target.as_ref().map(|t| t.as_slice()) } pub fn set_ar(&mut self, ar: String) { self.ar = Some(ar); } pub fn set_linker(&mut self, linker: String) { self.linker = Some(linker); } pub fn linker(&self) -> Option<&str> { self.linker.as_ref().map(|t| t.as_slice()) } pub fn ar(&self) -> Option<&str> { self.ar.as_ref().map(|t| t.as_slice()) } } #[deriving(Eq,PartialEq,Clone,Encodable,Decodable)] pub enum Location { Project, Global } #[deriving(Eq,PartialEq,Clone,Decodable)] pub enum ConfigValue { String(String, Path), List(Vec<(String, Path)>), Table(HashMap<String, ConfigValue>), Boolean(bool, Path), } impl fmt::Show for ConfigValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { String(ref string, ref path) => { write!(f, "{} (from {})", string, path.display()) } List(ref list) => { try!(write!(f, "[")); for (i, &(ref s, ref path)) in list.iter().enumerate() { if i > 0 { try!(write!(f, ", ")); } try!(write!(f, "{} (from {})", s, path.display())); } write!(f, "]") } Table(ref table) => write!(f, "{}", table), Boolean(b, ref path) => write!(f, "{} (from {})", b, path.display()), } } } impl<E, S: Encoder<E>> Encodable<S, E> for ConfigValue { fn encode(&self, s: &mut S) -> Result<(), E> { match *self { String(ref string, _) => string.encode(s), List(ref list) => { let list: Vec<&String> = list.iter().map(|s| s.ref0()).collect(); list.encode(s) } Table(ref table) => table.encode(s), Boolean(b, _) => b.encode(s), } } } impl ConfigValue { fn from_toml(path: &Path, toml: toml::Value) -> CargoResult<ConfigValue> { match toml { toml::String(val) => Ok(String(val, path.clone())), toml::Boolean(b) => Ok(Boolean(b, path.clone())), toml::Array(val) => { Ok(List(try!(result::collect(val.move_iter().map(|toml| { match toml { toml::String(val) => Ok((val, path.clone())), _ => Err(internal("")), } }))))) } toml::Table(val) => { Ok(Table(try!(result::collect(val.move_iter().map(|(key, value)| { let value = raw_try!(ConfigValue::from_toml(path, value)); Ok((key, value)) }))))) } _ => return Err(internal("")) } } fn merge(&mut self, from: ConfigValue) -> CargoResult<()> { match (self, from) { (me @ &String(..), from @ String(..)) => *me = from, (me @ &Boolean(..), from @ Boolean(..)) => *me = from, (&List(ref mut old), List(ref mut new)) => { let new = mem::replace(new, Vec::new()); old.extend(new.move_iter()); } (&Table(ref mut old), Table(ref mut new)) => { let new = mem::replace(new, HashMap::new()); for (key, value) in new.move_iter() { let mut err = Ok(()); old.find_with_or_insert_with(key, value, |_, old, new| err = old.merge(new), |_, new| new); try!(err); } } (expected, found) => { return Err(internal(format!("expected {}, but found {}", expected.desc(), found.desc()))) } } Ok(()) } pub fn string(&self) -> CargoResult<(&str, &Path)> { match *self { String(ref s, ref p) => Ok((s.as_slice(), p)), _ => Err(internal(format!("expected a string, but found a {}", self.desc()))), } } pub fn table(&self) -> CargoResult<&HashMap<String, ConfigValue>> { match *self { Table(ref table) => Ok(table), _ => Err(internal(format!("expected a table, but found a {}", self.desc()))), } } pub fn list(&self) -> CargoResult<&[(String, Path)]> { match *self { List(ref list) => Ok(list.as_slice()), _ => Err(internal(format!("expected a list, but found a {}", self.desc()))), } } pub fn boolean(&self) -> CargoResult<(bool, &Path)> { match *self { Boolean(b, ref p) => Ok((b, p)), _ => Err(internal(format!("expected a bool, but found a {}", self.desc()))), } } pub fn desc(&self) -> &'static str { match *self { Table(..) => "table", List(..) => "array", String(..) => "string", Boolean(..) => "boolean", } } } pub fn get_config(pwd: Path, key: &str) -> CargoResult<ConfigValue> { find_in_tree(&pwd, |file| extract_config(file, key)).map_err(|_| human(format!("`{}` not found in your configuration", key))) } pub fn all_configs(pwd: Path) -> CargoResult<HashMap<String, ConfigValue>> { let mut cfg = Table(HashMap::new()); try!(walk_tree(&pwd, |mut file| { let path = file.path().clone(); let contents = try!(file.read_to_string()); let table = try!(cargo_toml::parse(contents.as_slice(), &path).chain_error(|| { internal(format!("could not parse Toml manifest; path={}", path.display())) })); let value = try!(ConfigValue::from_toml(&path, toml::Table(table))); try!(cfg.merge(value)); Ok(()) }).map_err(|_| human("Couldn't load Cargo configuration"))); match cfg { Table(map) => Ok(map), _ => unreachable!(), } } fn find_in_tree<T>(pwd: &Path, walk: |io::fs::File| -> CargoResult<T>) -> CargoResult<T> { let mut current = pwd.clone(); loop { let possible = current.join(".cargo").join("config"); if possible.exists() { let file = try!(io::fs::File::open(&possible)); match walk(file) { Ok(res) => return Ok(res), _ => () } } if!current.pop() { break; } } Err(internal("")) } fn walk_tree(pwd: &Path, walk: |io::fs::File| -> CargoResult<()>) -> CargoResult<()> { let mut current = pwd.clone(); let mut err = false; loop { let possible = current.join(".cargo").join("config"); if possible.exists() { let file = try!(io::fs::File::open(&possible)); match walk(file) { Err(_) => err = false, _ => () } } if err { return Err(internal("")); } if!current.pop() { break; } } Ok(()) } fn extract_config(mut file: io::fs::File, key: &str) -> CargoResult<ConfigValue> { let contents = try!(file.read_to_string()); let mut toml = try!(cargo_toml::parse(contents.as_slice(), file.path())); let val = try!(toml.pop(&key.to_string()).require(|| internal(""))); ConfigValue::from_toml(file.path(), val) }
Config
identifier_name
config.rs
use std::{io, fmt, os, result, mem}; use std::collections::HashMap; use serialize::{Encodable,Encoder}; use toml; use core::MultiShell; use util::{CargoResult, ChainError, Require, internal, human}; use util::toml as cargo_toml; pub struct Config<'a> { home_path: Path, shell: &'a mut MultiShell<'a>, jobs: uint, target: Option<String>, linker: Option<String>, ar: Option<String>, } impl<'a> Config<'a> { pub fn new<'a>(shell: &'a mut MultiShell, jobs: Option<uint>, target: Option<String>) -> CargoResult<Config<'a>> { if jobs == Some(0) { return Err(human("jobs must be at least 1")) } Ok(Config { home_path: try!(os::homedir().require(|| { human("Cargo couldn't find your home directory. \ This probably means that $HOME was not set.") })), shell: shell, jobs: jobs.unwrap_or(os::num_cpus()), target: target, ar: None, linker: None, }) } pub fn home(&self) -> &Path { &self.home_path } pub fn git_db_path(&self) -> Path { self.home_path.join(".cargo").join("git").join("db") } pub fn git_checkout_path(&self) -> Path { self.home_path.join(".cargo").join("git").join("checkouts") } pub fn shell(&mut self) -> &mut MultiShell { &mut *self.shell } pub fn jobs(&self) -> uint { self.jobs } pub fn target(&self) -> Option<&str> { self.target.as_ref().map(|t| t.as_slice()) } pub fn set_ar(&mut self, ar: String) { self.ar = Some(ar); } pub fn set_linker(&mut self, linker: String) { self.linker = Some(linker); } pub fn linker(&self) -> Option<&str> { self.linker.as_ref().map(|t| t.as_slice()) } pub fn ar(&self) -> Option<&str> { self.ar.as_ref().map(|t| t.as_slice()) } } #[deriving(Eq,PartialEq,Clone,Encodable,Decodable)] pub enum Location { Project, Global } #[deriving(Eq,PartialEq,Clone,Decodable)] pub enum ConfigValue { String(String, Path), List(Vec<(String, Path)>), Table(HashMap<String, ConfigValue>), Boolean(bool, Path), } impl fmt::Show for ConfigValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { String(ref string, ref path) => { write!(f, "{} (from {})", string, path.display()) } List(ref list) => { try!(write!(f, "[")); for (i, &(ref s, ref path)) in list.iter().enumerate() { if i > 0 { try!(write!(f, ", ")); } try!(write!(f, "{} (from {})", s, path.display())); } write!(f, "]") } Table(ref table) => write!(f, "{}", table), Boolean(b, ref path) => write!(f, "{} (from {})", b, path.display()), } } } impl<E, S: Encoder<E>> Encodable<S, E> for ConfigValue { fn encode(&self, s: &mut S) -> Result<(), E> { match *self { String(ref string, _) => string.encode(s), List(ref list) => { let list: Vec<&String> = list.iter().map(|s| s.ref0()).collect(); list.encode(s) } Table(ref table) => table.encode(s), Boolean(b, _) => b.encode(s), } } } impl ConfigValue { fn from_toml(path: &Path, toml: toml::Value) -> CargoResult<ConfigValue> { match toml { toml::String(val) => Ok(String(val, path.clone())), toml::Boolean(b) => Ok(Boolean(b, path.clone())), toml::Array(val) => { Ok(List(try!(result::collect(val.move_iter().map(|toml| { match toml { toml::String(val) => Ok((val, path.clone())), _ => Err(internal("")), } }))))) } toml::Table(val) => { Ok(Table(try!(result::collect(val.move_iter().map(|(key, value)| { let value = raw_try!(ConfigValue::from_toml(path, value)); Ok((key, value)) }))))) } _ => return Err(internal("")) } } fn merge(&mut self, from: ConfigValue) -> CargoResult<()> { match (self, from) { (me @ &String(..), from @ String(..)) => *me = from, (me @ &Boolean(..), from @ Boolean(..)) => *me = from, (&List(ref mut old), List(ref mut new)) => { let new = mem::replace(new, Vec::new()); old.extend(new.move_iter()); } (&Table(ref mut old), Table(ref mut new)) => { let new = mem::replace(new, HashMap::new()); for (key, value) in new.move_iter() { let mut err = Ok(()); old.find_with_or_insert_with(key, value, |_, old, new| err = old.merge(new), |_, new| new); try!(err); } } (expected, found) => { return Err(internal(format!("expected {}, but found {}", expected.desc(), found.desc()))) } } Ok(()) } pub fn string(&self) -> CargoResult<(&str, &Path)> { match *self { String(ref s, ref p) => Ok((s.as_slice(), p)), _ => Err(internal(format!("expected a string, but found a {}", self.desc()))), } } pub fn table(&self) -> CargoResult<&HashMap<String, ConfigValue>> { match *self { Table(ref table) => Ok(table), _ => Err(internal(format!("expected a table, but found a {}", self.desc()))), } } pub fn list(&self) -> CargoResult<&[(String, Path)]> { match *self { List(ref list) => Ok(list.as_slice()), _ => Err(internal(format!("expected a list, but found a {}", self.desc()))), } } pub fn boolean(&self) -> CargoResult<(bool, &Path)>
pub fn desc(&self) -> &'static str { match *self { Table(..) => "table", List(..) => "array", String(..) => "string", Boolean(..) => "boolean", } } } pub fn get_config(pwd: Path, key: &str) -> CargoResult<ConfigValue> { find_in_tree(&pwd, |file| extract_config(file, key)).map_err(|_| human(format!("`{}` not found in your configuration", key))) } pub fn all_configs(pwd: Path) -> CargoResult<HashMap<String, ConfigValue>> { let mut cfg = Table(HashMap::new()); try!(walk_tree(&pwd, |mut file| { let path = file.path().clone(); let contents = try!(file.read_to_string()); let table = try!(cargo_toml::parse(contents.as_slice(), &path).chain_error(|| { internal(format!("could not parse Toml manifest; path={}", path.display())) })); let value = try!(ConfigValue::from_toml(&path, toml::Table(table))); try!(cfg.merge(value)); Ok(()) }).map_err(|_| human("Couldn't load Cargo configuration"))); match cfg { Table(map) => Ok(map), _ => unreachable!(), } } fn find_in_tree<T>(pwd: &Path, walk: |io::fs::File| -> CargoResult<T>) -> CargoResult<T> { let mut current = pwd.clone(); loop { let possible = current.join(".cargo").join("config"); if possible.exists() { let file = try!(io::fs::File::open(&possible)); match walk(file) { Ok(res) => return Ok(res), _ => () } } if!current.pop() { break; } } Err(internal("")) } fn walk_tree(pwd: &Path, walk: |io::fs::File| -> CargoResult<()>) -> CargoResult<()> { let mut current = pwd.clone(); let mut err = false; loop { let possible = current.join(".cargo").join("config"); if possible.exists() { let file = try!(io::fs::File::open(&possible)); match walk(file) { Err(_) => err = false, _ => () } } if err { return Err(internal("")); } if!current.pop() { break; } } Ok(()) } fn extract_config(mut file: io::fs::File, key: &str) -> CargoResult<ConfigValue> { let contents = try!(file.read_to_string()); let mut toml = try!(cargo_toml::parse(contents.as_slice(), file.path())); let val = try!(toml.pop(&key.to_string()).require(|| internal(""))); ConfigValue::from_toml(file.path(), val) }
{ match *self { Boolean(b, ref p) => Ok((b, p)), _ => Err(internal(format!("expected a bool, but found a {}", self.desc()))), } }
identifier_body
mtf.rs
/*! MTF (Move To Front) encoder/decoder Produces a rank for each input character based on when it was seen last time. Useful for BWT output encoding, which produces a lot of zeroes and low ranks. # Links http://en.wikipedia.org/wiki/Move-to-front_transform # Example ```rust use std::io::{self, Read, Write}; use compress::bwt::mtf; // Encode a stream of bytes let bytes = b"abracadabra"; let mut e = mtf::Encoder::new(io::BufWriter::new(Vec::new())); e.write_all(bytes).unwrap(); let encoded = e.finish().into_inner().unwrap(); // Decode a stream of ranks let mut d = mtf::Decoder::new(io::BufReader::new(&encoded[..])); let mut decoded = Vec::new(); let result = d.read_to_end(&mut decoded).unwrap(); ``` # Credit */ use std::mem; use std::io::{self, Read, Write}; use super::super::byteorder::{self, WriteBytesExt, ReadBytesExt}; pub type Symbol = u8; pub type Rank = u8; pub const TOTAL_SYMBOLS: usize = 0x100; /// MoveToFront encoder/decoder pub struct MTF { /// rank-ordered list of unique Symbols pub symbols: [Symbol; TOTAL_SYMBOLS], } impl MTF { /// create a new zeroed MTF pub fn new() -> MTF { MTF { symbols: [0; TOTAL_SYMBOLS] } } /// set the order of symbols to be alphabetical pub fn reset_alphabetical(&mut self) { for (i,sym) in self.symbols.iter_mut().enumerate() { *sym = i as Symbol; } } /// encode a symbol into its rank pub fn encode(&mut self, sym: Symbol) -> Rank { let mut next = self.symbols[0]; if next == sym { return 0 } let mut rank: Rank = 1; loop { mem::swap(&mut self.symbols[rank as usize], &mut next); if next == sym { break; } rank += 1; assert!((rank as usize) < self.symbols.len()); } self.symbols[0] = sym; rank } /// decode a rank into its symbol pub fn decode(&mut self, rank: Rank) -> Symbol { let sym = self.symbols[rank as usize]; debug!("\tDecoding rank {} with symbol {}", rank, sym); for i in (0.. rank as usize).rev() { self.symbols[i+1] = self.symbols[i]; } self.symbols[0] = sym; sym } } /// A simple MTF stream encoder pub struct Encoder<W> { w: W, mtf: MTF, } impl<W> Encoder<W> { /// start encoding into the given writer pub fn new(w: W) -> Encoder<W> { let mut mtf = MTF::new(); mtf.reset_alphabetical(); Encoder { w: w, mtf: mtf, } } /// finish encoding and return the wrapped writer pub fn
(self) -> W { self.w } } impl<W: Write> Write for Encoder<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { for sym in buf.iter() { let rank = self.mtf.encode(*sym); try!(self.w.write_u8(rank)); } Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { self.w.flush() } } /// A simple MTF stream decoder pub struct Decoder<R> { r: R, mtf: MTF, } impl<R> Decoder<R> { /// start decoding the given reader pub fn new(r: R) -> Decoder<R> { let mut mtf = MTF::new(); mtf.reset_alphabetical(); Decoder { r: r, mtf: mtf, } } /// finish decoder and return the wrapped reader pub fn finish(self) -> R { self.r } } impl<R: Read> Read for Decoder<R> { fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> { let mut bytes_read = 0; for sym in dst.iter_mut() { let rank = match self.r.read_u8() { Ok(r) => r, Err(byteorder::Error::UnexpectedEOF) => break, Err(byteorder::Error::Io(e)) => return Err(e) }; bytes_read += 1; *sym = self.mtf.decode(rank); } Ok((bytes_read)) } } #[cfg(test)] mod test { use std::io::{self, Read, Write}; #[cfg(feature="unstable")] use test::Bencher; use super::{Encoder, Decoder}; fn roundtrip(bytes: &[u8]) { info!("Roundtrip MTF of size {}", bytes.len()); let buf = Vec::new(); let mut e = Encoder::new(io::BufWriter::new(buf)); e.write_all(bytes).unwrap(); let encoded = e.finish().into_inner().unwrap(); debug!("Roundtrip MTF input: {:?}, ranks: {:?}", bytes, encoded); let mut d = Decoder::new(io::BufReader::new(&encoded[..])); let mut decoded = Vec::new(); d.read_to_end(&mut decoded).unwrap(); assert_eq!(&decoded[..], bytes); } #[test] fn some_roundtrips() { roundtrip(b"teeesst_mtf"); roundtrip(b""); roundtrip(include_bytes!("../data/test.txt")); } #[cfg(feature="unstable")] #[bench] fn encode_speed(bh: &mut Bencher) { let vec = Vec::new(); let input = include_bytes!("../data/test.txt"); let mem = io::BufWriter::with_capacity(input.len(), vec); let mut e = Encoder::new(mem); bh.iter(|| { e.write_all(input).unwrap(); }); bh.bytes = input.len() as u64; } #[cfg(feature="unstable")] #[bench] fn decode_speed(bh: &mut Bencher) { let vec = Vec::new(); let input = include_bytes!("../data/test.txt"); let mut e = Encoder::new(io::BufWriter::new(vec)); e.write_all(input).unwrap(); let encoded = e.finish().into_inner().unwrap(); bh.iter(|| { let mut d = Decoder::new(io::BufReader::new(&encoded[..])); let mut buf = Vec::new(); d.read_to_end(&mut buf).unwrap(); }); bh.bytes = input.len() as u64; } }
finish
identifier_name
mtf.rs
/*! MTF (Move To Front) encoder/decoder Produces a rank for each input character based on when it was seen last time. Useful for BWT output encoding, which produces a lot of zeroes and low ranks. # Links http://en.wikipedia.org/wiki/Move-to-front_transform # Example ```rust use std::io::{self, Read, Write}; use compress::bwt::mtf; // Encode a stream of bytes let bytes = b"abracadabra"; let mut e = mtf::Encoder::new(io::BufWriter::new(Vec::new())); e.write_all(bytes).unwrap(); let encoded = e.finish().into_inner().unwrap(); // Decode a stream of ranks let mut d = mtf::Decoder::new(io::BufReader::new(&encoded[..])); let mut decoded = Vec::new(); let result = d.read_to_end(&mut decoded).unwrap(); ``` # Credit */ use std::mem; use std::io::{self, Read, Write}; use super::super::byteorder::{self, WriteBytesExt, ReadBytesExt}; pub type Symbol = u8; pub type Rank = u8; pub const TOTAL_SYMBOLS: usize = 0x100; /// MoveToFront encoder/decoder pub struct MTF { /// rank-ordered list of unique Symbols pub symbols: [Symbol; TOTAL_SYMBOLS], } impl MTF { /// create a new zeroed MTF pub fn new() -> MTF { MTF { symbols: [0; TOTAL_SYMBOLS] } } /// set the order of symbols to be alphabetical pub fn reset_alphabetical(&mut self) { for (i,sym) in self.symbols.iter_mut().enumerate() { *sym = i as Symbol; } } /// encode a symbol into its rank pub fn encode(&mut self, sym: Symbol) -> Rank { let mut next = self.symbols[0]; if next == sym { return 0 } let mut rank: Rank = 1; loop { mem::swap(&mut self.symbols[rank as usize], &mut next); if next == sym { break; } rank += 1; assert!((rank as usize) < self.symbols.len()); } self.symbols[0] = sym; rank } /// decode a rank into its symbol pub fn decode(&mut self, rank: Rank) -> Symbol { let sym = self.symbols[rank as usize]; debug!("\tDecoding rank {} with symbol {}", rank, sym); for i in (0.. rank as usize).rev() { self.symbols[i+1] = self.symbols[i]; } self.symbols[0] = sym; sym } } /// A simple MTF stream encoder pub struct Encoder<W> { w: W, mtf: MTF, } impl<W> Encoder<W> { /// start encoding into the given writer pub fn new(w: W) -> Encoder<W> { let mut mtf = MTF::new(); mtf.reset_alphabetical(); Encoder { w: w, mtf: mtf, } } /// finish encoding and return the wrapped writer pub fn finish(self) -> W { self.w } } impl<W: Write> Write for Encoder<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { for sym in buf.iter() { let rank = self.mtf.encode(*sym); try!(self.w.write_u8(rank)); } Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { self.w.flush() } } /// A simple MTF stream decoder pub struct Decoder<R> { r: R, mtf: MTF, } impl<R> Decoder<R> { /// start decoding the given reader pub fn new(r: R) -> Decoder<R> { let mut mtf = MTF::new(); mtf.reset_alphabetical(); Decoder { r: r, mtf: mtf, } } /// finish decoder and return the wrapped reader pub fn finish(self) -> R { self.r } } impl<R: Read> Read for Decoder<R> { fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> { let mut bytes_read = 0; for sym in dst.iter_mut() { let rank = match self.r.read_u8() { Ok(r) => r, Err(byteorder::Error::UnexpectedEOF) => break, Err(byteorder::Error::Io(e)) => return Err(e) }; bytes_read += 1; *sym = self.mtf.decode(rank); } Ok((bytes_read)) } } #[cfg(test)] mod test { use std::io::{self, Read, Write}; #[cfg(feature="unstable")] use test::Bencher; use super::{Encoder, Decoder}; fn roundtrip(bytes: &[u8]) { info!("Roundtrip MTF of size {}", bytes.len()); let buf = Vec::new(); let mut e = Encoder::new(io::BufWriter::new(buf)); e.write_all(bytes).unwrap(); let encoded = e.finish().into_inner().unwrap(); debug!("Roundtrip MTF input: {:?}, ranks: {:?}", bytes, encoded); let mut d = Decoder::new(io::BufReader::new(&encoded[..])); let mut decoded = Vec::new(); d.read_to_end(&mut decoded).unwrap(); assert_eq!(&decoded[..], bytes); } #[test] fn some_roundtrips() { roundtrip(b"teeesst_mtf"); roundtrip(b""); roundtrip(include_bytes!("../data/test.txt")); } #[cfg(feature="unstable")] #[bench] fn encode_speed(bh: &mut Bencher) { let vec = Vec::new(); let input = include_bytes!("../data/test.txt"); let mem = io::BufWriter::with_capacity(input.len(), vec); let mut e = Encoder::new(mem); bh.iter(|| { e.write_all(input).unwrap(); }); bh.bytes = input.len() as u64; } #[cfg(feature="unstable")] #[bench] fn decode_speed(bh: &mut Bencher)
}
{ let vec = Vec::new(); let input = include_bytes!("../data/test.txt"); let mut e = Encoder::new(io::BufWriter::new(vec)); e.write_all(input).unwrap(); let encoded = e.finish().into_inner().unwrap(); bh.iter(|| { let mut d = Decoder::new(io::BufReader::new(&encoded[..])); let mut buf = Vec::new(); d.read_to_end(&mut buf).unwrap(); }); bh.bytes = input.len() as u64; }
identifier_body
mtf.rs
/*! MTF (Move To Front) encoder/decoder Produces a rank for each input character based on when it was seen last time. Useful for BWT output encoding, which produces a lot of zeroes and low ranks. # Links http://en.wikipedia.org/wiki/Move-to-front_transform # Example ```rust use std::io::{self, Read, Write}; use compress::bwt::mtf; // Encode a stream of bytes let bytes = b"abracadabra"; let mut e = mtf::Encoder::new(io::BufWriter::new(Vec::new())); e.write_all(bytes).unwrap(); let encoded = e.finish().into_inner().unwrap(); // Decode a stream of ranks let mut d = mtf::Decoder::new(io::BufReader::new(&encoded[..])); let mut decoded = Vec::new(); let result = d.read_to_end(&mut decoded).unwrap(); ``` # Credit */ use std::mem; use std::io::{self, Read, Write}; use super::super::byteorder::{self, WriteBytesExt, ReadBytesExt}; pub type Symbol = u8; pub type Rank = u8; pub const TOTAL_SYMBOLS: usize = 0x100; /// MoveToFront encoder/decoder pub struct MTF { /// rank-ordered list of unique Symbols pub symbols: [Symbol; TOTAL_SYMBOLS], } impl MTF { /// create a new zeroed MTF pub fn new() -> MTF { MTF { symbols: [0; TOTAL_SYMBOLS] } } /// set the order of symbols to be alphabetical pub fn reset_alphabetical(&mut self) { for (i,sym) in self.symbols.iter_mut().enumerate() { *sym = i as Symbol; } } /// encode a symbol into its rank pub fn encode(&mut self, sym: Symbol) -> Rank { let mut next = self.symbols[0]; if next == sym
let mut rank: Rank = 1; loop { mem::swap(&mut self.symbols[rank as usize], &mut next); if next == sym { break; } rank += 1; assert!((rank as usize) < self.symbols.len()); } self.symbols[0] = sym; rank } /// decode a rank into its symbol pub fn decode(&mut self, rank: Rank) -> Symbol { let sym = self.symbols[rank as usize]; debug!("\tDecoding rank {} with symbol {}", rank, sym); for i in (0.. rank as usize).rev() { self.symbols[i+1] = self.symbols[i]; } self.symbols[0] = sym; sym } } /// A simple MTF stream encoder pub struct Encoder<W> { w: W, mtf: MTF, } impl<W> Encoder<W> { /// start encoding into the given writer pub fn new(w: W) -> Encoder<W> { let mut mtf = MTF::new(); mtf.reset_alphabetical(); Encoder { w: w, mtf: mtf, } } /// finish encoding and return the wrapped writer pub fn finish(self) -> W { self.w } } impl<W: Write> Write for Encoder<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { for sym in buf.iter() { let rank = self.mtf.encode(*sym); try!(self.w.write_u8(rank)); } Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { self.w.flush() } } /// A simple MTF stream decoder pub struct Decoder<R> { r: R, mtf: MTF, } impl<R> Decoder<R> { /// start decoding the given reader pub fn new(r: R) -> Decoder<R> { let mut mtf = MTF::new(); mtf.reset_alphabetical(); Decoder { r: r, mtf: mtf, } } /// finish decoder and return the wrapped reader pub fn finish(self) -> R { self.r } } impl<R: Read> Read for Decoder<R> { fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> { let mut bytes_read = 0; for sym in dst.iter_mut() { let rank = match self.r.read_u8() { Ok(r) => r, Err(byteorder::Error::UnexpectedEOF) => break, Err(byteorder::Error::Io(e)) => return Err(e) }; bytes_read += 1; *sym = self.mtf.decode(rank); } Ok((bytes_read)) } } #[cfg(test)] mod test { use std::io::{self, Read, Write}; #[cfg(feature="unstable")] use test::Bencher; use super::{Encoder, Decoder}; fn roundtrip(bytes: &[u8]) { info!("Roundtrip MTF of size {}", bytes.len()); let buf = Vec::new(); let mut e = Encoder::new(io::BufWriter::new(buf)); e.write_all(bytes).unwrap(); let encoded = e.finish().into_inner().unwrap(); debug!("Roundtrip MTF input: {:?}, ranks: {:?}", bytes, encoded); let mut d = Decoder::new(io::BufReader::new(&encoded[..])); let mut decoded = Vec::new(); d.read_to_end(&mut decoded).unwrap(); assert_eq!(&decoded[..], bytes); } #[test] fn some_roundtrips() { roundtrip(b"teeesst_mtf"); roundtrip(b""); roundtrip(include_bytes!("../data/test.txt")); } #[cfg(feature="unstable")] #[bench] fn encode_speed(bh: &mut Bencher) { let vec = Vec::new(); let input = include_bytes!("../data/test.txt"); let mem = io::BufWriter::with_capacity(input.len(), vec); let mut e = Encoder::new(mem); bh.iter(|| { e.write_all(input).unwrap(); }); bh.bytes = input.len() as u64; } #[cfg(feature="unstable")] #[bench] fn decode_speed(bh: &mut Bencher) { let vec = Vec::new(); let input = include_bytes!("../data/test.txt"); let mut e = Encoder::new(io::BufWriter::new(vec)); e.write_all(input).unwrap(); let encoded = e.finish().into_inner().unwrap(); bh.iter(|| { let mut d = Decoder::new(io::BufReader::new(&encoded[..])); let mut buf = Vec::new(); d.read_to_end(&mut buf).unwrap(); }); bh.bytes = input.len() as u64; } }
{ return 0 }
conditional_block
mtf.rs
/*! MTF (Move To Front) encoder/decoder Produces a rank for each input character based on when it was seen last time. Useful for BWT output encoding, which produces a lot of zeroes and low ranks. # Links http://en.wikipedia.org/wiki/Move-to-front_transform # Example ```rust use std::io::{self, Read, Write}; use compress::bwt::mtf; // Encode a stream of bytes let bytes = b"abracadabra"; let mut e = mtf::Encoder::new(io::BufWriter::new(Vec::new())); e.write_all(bytes).unwrap(); let encoded = e.finish().into_inner().unwrap(); // Decode a stream of ranks let mut d = mtf::Decoder::new(io::BufReader::new(&encoded[..])); let mut decoded = Vec::new(); let result = d.read_to_end(&mut decoded).unwrap(); ``` # Credit */ use std::mem; use std::io::{self, Read, Write}; use super::super::byteorder::{self, WriteBytesExt, ReadBytesExt}; pub type Symbol = u8; pub type Rank = u8; pub const TOTAL_SYMBOLS: usize = 0x100; /// MoveToFront encoder/decoder pub struct MTF { /// rank-ordered list of unique Symbols pub symbols: [Symbol; TOTAL_SYMBOLS], } impl MTF { /// create a new zeroed MTF pub fn new() -> MTF { MTF { symbols: [0; TOTAL_SYMBOLS] } } /// set the order of symbols to be alphabetical pub fn reset_alphabetical(&mut self) { for (i,sym) in self.symbols.iter_mut().enumerate() { *sym = i as Symbol; } }
let mut next = self.symbols[0]; if next == sym { return 0 } let mut rank: Rank = 1; loop { mem::swap(&mut self.symbols[rank as usize], &mut next); if next == sym { break; } rank += 1; assert!((rank as usize) < self.symbols.len()); } self.symbols[0] = sym; rank } /// decode a rank into its symbol pub fn decode(&mut self, rank: Rank) -> Symbol { let sym = self.symbols[rank as usize]; debug!("\tDecoding rank {} with symbol {}", rank, sym); for i in (0.. rank as usize).rev() { self.symbols[i+1] = self.symbols[i]; } self.symbols[0] = sym; sym } } /// A simple MTF stream encoder pub struct Encoder<W> { w: W, mtf: MTF, } impl<W> Encoder<W> { /// start encoding into the given writer pub fn new(w: W) -> Encoder<W> { let mut mtf = MTF::new(); mtf.reset_alphabetical(); Encoder { w: w, mtf: mtf, } } /// finish encoding and return the wrapped writer pub fn finish(self) -> W { self.w } } impl<W: Write> Write for Encoder<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { for sym in buf.iter() { let rank = self.mtf.encode(*sym); try!(self.w.write_u8(rank)); } Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { self.w.flush() } } /// A simple MTF stream decoder pub struct Decoder<R> { r: R, mtf: MTF, } impl<R> Decoder<R> { /// start decoding the given reader pub fn new(r: R) -> Decoder<R> { let mut mtf = MTF::new(); mtf.reset_alphabetical(); Decoder { r: r, mtf: mtf, } } /// finish decoder and return the wrapped reader pub fn finish(self) -> R { self.r } } impl<R: Read> Read for Decoder<R> { fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> { let mut bytes_read = 0; for sym in dst.iter_mut() { let rank = match self.r.read_u8() { Ok(r) => r, Err(byteorder::Error::UnexpectedEOF) => break, Err(byteorder::Error::Io(e)) => return Err(e) }; bytes_read += 1; *sym = self.mtf.decode(rank); } Ok((bytes_read)) } } #[cfg(test)] mod test { use std::io::{self, Read, Write}; #[cfg(feature="unstable")] use test::Bencher; use super::{Encoder, Decoder}; fn roundtrip(bytes: &[u8]) { info!("Roundtrip MTF of size {}", bytes.len()); let buf = Vec::new(); let mut e = Encoder::new(io::BufWriter::new(buf)); e.write_all(bytes).unwrap(); let encoded = e.finish().into_inner().unwrap(); debug!("Roundtrip MTF input: {:?}, ranks: {:?}", bytes, encoded); let mut d = Decoder::new(io::BufReader::new(&encoded[..])); let mut decoded = Vec::new(); d.read_to_end(&mut decoded).unwrap(); assert_eq!(&decoded[..], bytes); } #[test] fn some_roundtrips() { roundtrip(b"teeesst_mtf"); roundtrip(b""); roundtrip(include_bytes!("../data/test.txt")); } #[cfg(feature="unstable")] #[bench] fn encode_speed(bh: &mut Bencher) { let vec = Vec::new(); let input = include_bytes!("../data/test.txt"); let mem = io::BufWriter::with_capacity(input.len(), vec); let mut e = Encoder::new(mem); bh.iter(|| { e.write_all(input).unwrap(); }); bh.bytes = input.len() as u64; } #[cfg(feature="unstable")] #[bench] fn decode_speed(bh: &mut Bencher) { let vec = Vec::new(); let input = include_bytes!("../data/test.txt"); let mut e = Encoder::new(io::BufWriter::new(vec)); e.write_all(input).unwrap(); let encoded = e.finish().into_inner().unwrap(); bh.iter(|| { let mut d = Decoder::new(io::BufReader::new(&encoded[..])); let mut buf = Vec::new(); d.read_to_end(&mut buf).unwrap(); }); bh.bytes = input.len() as u64; } }
/// encode a symbol into its rank pub fn encode(&mut self, sym: Symbol) -> Rank {
random_line_split
crateresolve4b-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. // aux-build:crateresolve4a-1.rs // aux-build:crateresolve4a-2.rs #![crate_name="crateresolve4b#0.2"] #![crate_type = "lib"] extern crate "crateresolve4a#0.1" as crateresolve4a; pub fn
() -> int { crateresolve4a::f() }
g
identifier_name
crateresolve4b-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. // aux-build:crateresolve4a-1.rs // aux-build:crateresolve4a-2.rs #![crate_name="crateresolve4b#0.2"] #![crate_type = "lib"] extern crate "crateresolve4a#0.1" as crateresolve4a; pub fn g() -> int
{ crateresolve4a::f() }
identifier_body
crateresolve4b-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. // aux-build:crateresolve4a-1.rs // aux-build:crateresolve4a-2.rs #![crate_name="crateresolve4b#0.2"] #![crate_type = "lib"] extern crate "crateresolve4a#0.1" as crateresolve4a; pub fn g() -> int { crateresolve4a::f() }
random_line_split
activation.rs
// Copyright © 2017 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed
use um::winnt::{HRESULT}; use winrt::inspectable::{IInspectable, IInspectableVtbl}; RIDL!{#[uuid(0x00000035, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46)] interface IActivationFactory(IActivationFactoryVtbl): IInspectable(IInspectableVtbl) { fn ActivateInstance( instance: *mut *mut IInspectable, ) -> HRESULT, }}
// except according to those terms.
random_line_split
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::{Point2D, Rect, Size2D}; use std::borrow::ToOwned; use std::mem; use std::slice; use std::rc::Rc;
use std::cell::RefCell; use util::cache::HashCache; use util::smallvec::{SmallVec, SmallVec8}; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use std::sync::Arc; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use util::geometry::Au; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::{Shaper, TextRun}; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn get_template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn get_metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry,Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32,FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc="Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc="Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc="Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04 } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; match self.shape_cache.find(&lookup_key) { None => {} Some(glyphs) => return glyphs.clone(), } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref mut shaper) => { shaper.set_options(options); return shaper }, None => {} } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase(), font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec8<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: SmallVec8<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts, } } pub fn create_textrun(&self, text: String, options: &ShapingOptions) -> TextRun { assert!(self.fonts.len() > 0); // TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable. TextRun::new(&mut *self.fonts.get(0).borrow_mut(), text.clone(), options) } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
random_line_split
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::{Point2D, Rect, Size2D}; use std::borrow::ToOwned; use std::mem; use std::slice; use std::rc::Rc; use std::cell::RefCell; use util::cache::HashCache; use util::smallvec::{SmallVec, SmallVec8}; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use std::sync::Arc; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use util::geometry::Au; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::{Shaper, TextRun}; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn get_template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn get_metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry,Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32,FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc="Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc="Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc="Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04 } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; match self.shape_cache.find(&lookup_key) { None => {} Some(glyphs) => return glyphs.clone(), } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref mut shaper) => { shaper.set_options(options); return shaper }, None => {} } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase(), font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec8<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: SmallVec8<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts, } } pub fn create_textrun(&self, text: String, options: &ShapingOptions) -> TextRun { assert!(self.fonts.len() > 0); // TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable. TextRun::new(&mut *self.fonts.get(0).borrow_mut(), text.clone(), options) } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn
(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
new
identifier_name
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::{Point2D, Rect, Size2D}; use std::borrow::ToOwned; use std::mem; use std::slice; use std::rc::Rc; use std::cell::RefCell; use util::cache::HashCache; use util::smallvec::{SmallVec, SmallVec8}; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use std::sync::Arc; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use util::geometry::Au; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::{Shaper, TextRun}; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn get_template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn get_metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry,Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32,FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc="Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc="Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc="Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04 } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; match self.shape_cache.find(&lookup_key) { None => {} Some(glyphs) => return glyphs.clone(), } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref mut shaper) => { shaper.set_options(options); return shaper }, None => {} } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some()
else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase(), font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec8<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: SmallVec8<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts, } } pub fn create_textrun(&self, text: String, options: &ShapingOptions) -> TextRun { assert!(self.fonts.len() > 0); // TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable. TextRun::new(&mut *self.fonts.get(0).borrow_mut(), text.clone(), options) } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
{ "Found" }
conditional_block
objc_category.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; #[repr(transparent)] #[derive(Clone)] pub struct Foo(pub id); impl std::ops::Deref for Foo { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref { unsafe fn method(&self) where <Self as std::ops::Deref>::Target: objc::Message + Sized, { msg_send!(*self, method) } } impl Foo_BarCategory for Foo {} pub trait Foo_BarCategory: Sized + std::ops::Deref { unsafe fn categoryMethod(&self) where <Self as std::ops::Deref>::Target: objc::Message + Sized, { msg_send!(*self, categoryMethod)
} }
random_line_split
objc_category.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; #[repr(transparent)] #[derive(Clone)] pub struct
(pub id); impl std::ops::Deref for Foo { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref { unsafe fn method(&self) where <Self as std::ops::Deref>::Target: objc::Message + Sized, { msg_send!(*self, method) } } impl Foo_BarCategory for Foo {} pub trait Foo_BarCategory: Sized + std::ops::Deref { unsafe fn categoryMethod(&self) where <Self as std::ops::Deref>::Target: objc::Message + Sized, { msg_send!(*self, categoryMethod) } }
Foo
identifier_name
objc_category.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; #[repr(transparent)] #[derive(Clone)] pub struct Foo(pub id); impl std::ops::Deref for Foo { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref { unsafe fn method(&self) where <Self as std::ops::Deref>::Target: objc::Message + Sized, { msg_send!(*self, method) } } impl Foo_BarCategory for Foo {} pub trait Foo_BarCategory: Sized + std::ops::Deref { unsafe fn categoryMethod(&self) where <Self as std::ops::Deref>::Target: objc::Message + Sized,
}
{ msg_send!(*self, categoryMethod) }
identifier_body
stdlib_demo.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use diem_framework::{encode_peer_to_peer_with_metadata_script, ScriptCall}; use diem_types::{AccountAddress, Identifier, StructTag, TypeTag}; use serde_bytes::ByteBuf as Bytes; fn main() { let token = TypeTag::Struct(StructTag { address: AccountAddress([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), module: Identifier("XDX".into()), name: Identifier("XDX".into()), type_params: Vec::new(), }); let payee = AccountAddress([ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, ]); let amount = 1234567; let script = encode_peer_to_peer_with_metadata_script( token, payee.clone(), amount, Bytes::from(Vec::new()), Bytes::from(Vec::new()), ); let call = ScriptCall::decode(&script); match call { Some(ScriptCall::PeerToPeerWithMetadata { amount: a, payee: p, .. }) =>
_ => panic!("unexpected type of script"), } let output = bcs::to_bytes(&script).unwrap(); for o in output { print!("{} ", o); } println!(); }
{ assert_eq!(a, amount); assert_eq!(p, payee); }
conditional_block
stdlib_demo.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use diem_framework::{encode_peer_to_peer_with_metadata_script, ScriptCall}; use diem_types::{AccountAddress, Identifier, StructTag, TypeTag}; use serde_bytes::ByteBuf as Bytes; fn main() { let token = TypeTag::Struct(StructTag { address: AccountAddress([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), module: Identifier("XDX".into()), name: Identifier("XDX".into()), type_params: Vec::new(), }); let payee = AccountAddress([ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, ]); let amount = 1234567; let script = encode_peer_to_peer_with_metadata_script( token, payee.clone(), amount, Bytes::from(Vec::new()), Bytes::from(Vec::new()), ); let call = ScriptCall::decode(&script); match call { Some(ScriptCall::PeerToPeerWithMetadata { amount: a, payee: p, .. }) => { assert_eq!(a, amount); assert_eq!(p, payee); } _ => panic!("unexpected type of script"), } let output = bcs::to_bytes(&script).unwrap(); for o in output { print!("{} ", o); } println!();
}
random_line_split
stdlib_demo.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use diem_framework::{encode_peer_to_peer_with_metadata_script, ScriptCall}; use diem_types::{AccountAddress, Identifier, StructTag, TypeTag}; use serde_bytes::ByteBuf as Bytes; fn main()
let call = ScriptCall::decode(&script); match call { Some(ScriptCall::PeerToPeerWithMetadata { amount: a, payee: p, .. }) => { assert_eq!(a, amount); assert_eq!(p, payee); } _ => panic!("unexpected type of script"), } let output = bcs::to_bytes(&script).unwrap(); for o in output { print!("{} ", o); } println!(); }
{ let token = TypeTag::Struct(StructTag { address: AccountAddress([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), module: Identifier("XDX".into()), name: Identifier("XDX".into()), type_params: Vec::new(), }); let payee = AccountAddress([ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, ]); let amount = 1234567; let script = encode_peer_to_peer_with_metadata_script( token, payee.clone(), amount, Bytes::from(Vec::new()), Bytes::from(Vec::new()), );
identifier_body
stdlib_demo.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use diem_framework::{encode_peer_to_peer_with_metadata_script, ScriptCall}; use diem_types::{AccountAddress, Identifier, StructTag, TypeTag}; use serde_bytes::ByteBuf as Bytes; fn
() { let token = TypeTag::Struct(StructTag { address: AccountAddress([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), module: Identifier("XDX".into()), name: Identifier("XDX".into()), type_params: Vec::new(), }); let payee = AccountAddress([ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, ]); let amount = 1234567; let script = encode_peer_to_peer_with_metadata_script( token, payee.clone(), amount, Bytes::from(Vec::new()), Bytes::from(Vec::new()), ); let call = ScriptCall::decode(&script); match call { Some(ScriptCall::PeerToPeerWithMetadata { amount: a, payee: p, .. }) => { assert_eq!(a, amount); assert_eq!(p, payee); } _ => panic!("unexpected type of script"), } let output = bcs::to_bytes(&script).unwrap(); for o in output { print!("{} ", o); } println!(); }
main
identifier_name
associated-types-doubleendediterator-object.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(box_syntax)] fn pairwise_sub(mut t: Box<DoubleEndedIterator<Item=isize>>) -> isize { let mut result = 0; loop { let front = t.next(); let back = t.next_back(); match (front, back) { (Some(f), Some(b)) => { result += b - f; } _ =>
} } } fn main() { let v = vec![1, 2, 3, 4, 5, 6]; let r = pairwise_sub(Box::new(v.into_iter())); assert_eq!(r, 9); }
{ return result; }
conditional_block
associated-types-doubleendediterator-object.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(box_syntax)] fn pairwise_sub(mut t: Box<DoubleEndedIterator<Item=isize>>) -> isize
fn main() { let v = vec![1, 2, 3, 4, 5, 6]; let r = pairwise_sub(Box::new(v.into_iter())); assert_eq!(r, 9); }
{ let mut result = 0; loop { let front = t.next(); let back = t.next_back(); match (front, back) { (Some(f), Some(b)) => { result += b - f; } _ => { return result; } } } }
identifier_body
associated-types-doubleendediterator-object.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(box_syntax)] fn
(mut t: Box<DoubleEndedIterator<Item=isize>>) -> isize { let mut result = 0; loop { let front = t.next(); let back = t.next_back(); match (front, back) { (Some(f), Some(b)) => { result += b - f; } _ => { return result; } } } } fn main() { let v = vec![1, 2, 3, 4, 5, 6]; let r = pairwise_sub(Box::new(v.into_iter())); assert_eq!(r, 9); }
pairwise_sub
identifier_name
associated-types-doubleendediterator-object.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(box_syntax)] fn pairwise_sub(mut t: Box<DoubleEndedIterator<Item=isize>>) -> isize { let mut result = 0; loop { let front = t.next(); let back = t.next_back(); match (front, back) { (Some(f), Some(b)) => { result += b - f; }
fn main() { let v = vec![1, 2, 3, 4, 5, 6]; let r = pairwise_sub(Box::new(v.into_iter())); assert_eq!(r, 9); }
_ => { return result; } } } }
random_line_split
value.rs
use super::MysqlType; use crate::deserialize; use crate::mysql::types::MYSQL_TIME; use std::error::Error; /// Raw mysql value as received from the database #[derive(Copy, Clone, Debug)] pub struct MysqlValue<'a> { raw: &'a [u8], tpe: MysqlType, } impl<'a> MysqlValue<'a> { pub(crate) fn new(raw: &'a [u8], tpe: MysqlType) -> Self { Self { raw, tpe } } /// Get the underlying raw byte representation pub fn as_bytes(&self) -> &[u8] { self.raw } /// Get the mysql type of the current value pub fn value_type(&self) -> MysqlType { self.tpe } /// Checks that the type code is valid, and interprets the data as a /// `MYSQL_TIME` pointer // We use `ptr.read_unaligned()` to read the potential unaligned ptr, // so clippy is clearly wrong here // https://github.com/rust-lang/rust-clippy/issues/2881 #[allow(dead_code, clippy::cast_ptr_alignment)] pub(crate) fn time_value(&self) -> deserialize::Result<MYSQL_TIME> { match self.tpe { MysqlType::Time | MysqlType::Date | MysqlType::DateTime | MysqlType::Timestamp => { let ptr = self.raw.as_ptr() as *const MYSQL_TIME; let result = unsafe { ptr.read_unaligned() }; if result.neg { Err("Negative dates/times are not yet supported".into()) } else { Ok(result) } } _ => Err(self.invalid_type_code("timestamp")), } } /// Returns the numeric representation of this value, based on the type code. /// Returns an error if the type code is not numeric. pub(crate) fn numeric_value(&self) -> deserialize::Result<NumericRepresentation> { use self::NumericRepresentation::*; use std::convert::TryInto; Ok(match self.tpe { MysqlType::UnsignedTiny | MysqlType::Tiny => Tiny(self.raw[0] as i8), MysqlType::UnsignedShort | MysqlType::Short => { Small(i16::from_ne_bytes(self.raw.try_into()?)) } MysqlType::UnsignedLong | MysqlType::Long => { Medium(i32::from_ne_bytes(self.raw.try_into()?)) } MysqlType::UnsignedLongLong | MysqlType::LongLong => { Big(i64::from_ne_bytes(self.raw.try_into()?)) } MysqlType::Float => Float(f32::from_ne_bytes(self.raw.try_into()?)), MysqlType::Double => Double(f64::from_ne_bytes(self.raw.try_into()?)), MysqlType::Numeric => Decimal(self.raw), _ => return Err(self.invalid_type_code("number")), }) } fn invalid_type_code(&self, expected: &str) -> Box<dyn Error + Send + Sync> { format!( "Invalid representation received for {}: {:?}", expected, self.tpe ) .into() } } /// Represents all possible forms MySQL transmits integers #[derive(Debug, Clone, Copy)] #[non_exhaustive] pub enum NumericRepresentation<'a> { /// Correponds to `MYSQL_TYPE_TINY` Tiny(i8), /// Correponds to `MYSQL_TYPE_SHORT` Small(i16), /// Correponds to `MYSQL_TYPE_INT24` and `MYSQL_TYPE_LONG` Medium(i32), /// Correponds to `MYSQL_TYPE_LONGLONG` Big(i64), /// Correponds to `MYSQL_TYPE_FLOAT` Float(f32), /// Correponds to `MYSQL_TYPE_DOUBLE` Double(f64),
Decimal(&'a [u8]), }
/// Correponds to `MYSQL_TYPE_DECIMAL` and `MYSQL_TYPE_NEWDECIMAL`
random_line_split
value.rs
use super::MysqlType; use crate::deserialize; use crate::mysql::types::MYSQL_TIME; use std::error::Error; /// Raw mysql value as received from the database #[derive(Copy, Clone, Debug)] pub struct MysqlValue<'a> { raw: &'a [u8], tpe: MysqlType, } impl<'a> MysqlValue<'a> { pub(crate) fn new(raw: &'a [u8], tpe: MysqlType) -> Self { Self { raw, tpe } } /// Get the underlying raw byte representation pub fn as_bytes(&self) -> &[u8] { self.raw } /// Get the mysql type of the current value pub fn
(&self) -> MysqlType { self.tpe } /// Checks that the type code is valid, and interprets the data as a /// `MYSQL_TIME` pointer // We use `ptr.read_unaligned()` to read the potential unaligned ptr, // so clippy is clearly wrong here // https://github.com/rust-lang/rust-clippy/issues/2881 #[allow(dead_code, clippy::cast_ptr_alignment)] pub(crate) fn time_value(&self) -> deserialize::Result<MYSQL_TIME> { match self.tpe { MysqlType::Time | MysqlType::Date | MysqlType::DateTime | MysqlType::Timestamp => { let ptr = self.raw.as_ptr() as *const MYSQL_TIME; let result = unsafe { ptr.read_unaligned() }; if result.neg { Err("Negative dates/times are not yet supported".into()) } else { Ok(result) } } _ => Err(self.invalid_type_code("timestamp")), } } /// Returns the numeric representation of this value, based on the type code. /// Returns an error if the type code is not numeric. pub(crate) fn numeric_value(&self) -> deserialize::Result<NumericRepresentation> { use self::NumericRepresentation::*; use std::convert::TryInto; Ok(match self.tpe { MysqlType::UnsignedTiny | MysqlType::Tiny => Tiny(self.raw[0] as i8), MysqlType::UnsignedShort | MysqlType::Short => { Small(i16::from_ne_bytes(self.raw.try_into()?)) } MysqlType::UnsignedLong | MysqlType::Long => { Medium(i32::from_ne_bytes(self.raw.try_into()?)) } MysqlType::UnsignedLongLong | MysqlType::LongLong => { Big(i64::from_ne_bytes(self.raw.try_into()?)) } MysqlType::Float => Float(f32::from_ne_bytes(self.raw.try_into()?)), MysqlType::Double => Double(f64::from_ne_bytes(self.raw.try_into()?)), MysqlType::Numeric => Decimal(self.raw), _ => return Err(self.invalid_type_code("number")), }) } fn invalid_type_code(&self, expected: &str) -> Box<dyn Error + Send + Sync> { format!( "Invalid representation received for {}: {:?}", expected, self.tpe ) .into() } } /// Represents all possible forms MySQL transmits integers #[derive(Debug, Clone, Copy)] #[non_exhaustive] pub enum NumericRepresentation<'a> { /// Correponds to `MYSQL_TYPE_TINY` Tiny(i8), /// Correponds to `MYSQL_TYPE_SHORT` Small(i16), /// Correponds to `MYSQL_TYPE_INT24` and `MYSQL_TYPE_LONG` Medium(i32), /// Correponds to `MYSQL_TYPE_LONGLONG` Big(i64), /// Correponds to `MYSQL_TYPE_FLOAT` Float(f32), /// Correponds to `MYSQL_TYPE_DOUBLE` Double(f64), /// Correponds to `MYSQL_TYPE_DECIMAL` and `MYSQL_TYPE_NEWDECIMAL` Decimal(&'a [u8]), }
value_type
identifier_name
logger.rs
use config::Config; use log::{self, Log, LogLevel, LogLevelFilter, LogMetadata, LogRecord, SetLoggerError}; use monitor::{Monitor, MonitorProvider}; pub fn start_logging(config: &Config) -> Result<(), SetLoggerError> { log::set_logger(|max_log_level| { max_log_level.set(LogLevelFilter::Info); if let Some(monitor) = config.monitor.to_owned() { if monitor.enabled == true { match MonitorProvider::find_with_config(&monitor.provider, &monitor) { Some(monitor) => { return Box::new(Logger { monitor: monitor }); } None => { panic!("Monitor {} has not been found.", monitor.provider); } }; } } Box::new(Logger { monitor: MonitorProvider::null_monitor(), }) }) } struct Logger<T: Monitor> { monitor: T, } impl<T: Monitor> Log for Logger<T> { fn enabled(&self, metadata: &LogMetadata) -> bool { metadata.level() <= LogLevel::Info } fn log(&self, record: &LogRecord)
}
{ if self.enabled(record.metadata()) { let error_message = format!("{} - {}", record.level(), record.args()); if record.level() == LogLevel::Error { self.monitor.send(&error_message, record.location()); } println!("{}", error_message); } }
identifier_body
logger.rs
use config::Config; use log::{self, Log, LogLevel, LogLevelFilter, LogMetadata, LogRecord, SetLoggerError}; use monitor::{Monitor, MonitorProvider}; pub fn start_logging(config: &Config) -> Result<(), SetLoggerError> { log::set_logger(|max_log_level| { max_log_level.set(LogLevelFilter::Info); if let Some(monitor) = config.monitor.to_owned() { if monitor.enabled == true { match MonitorProvider::find_with_config(&monitor.provider, &monitor) { Some(monitor) => { return Box::new(Logger { monitor: monitor }); } None => { panic!("Monitor {} has not been found.", monitor.provider); } }; } } Box::new(Logger { monitor: MonitorProvider::null_monitor(), }) }) }
} impl<T: Monitor> Log for Logger<T> { fn enabled(&self, metadata: &LogMetadata) -> bool { metadata.level() <= LogLevel::Info } fn log(&self, record: &LogRecord) { if self.enabled(record.metadata()) { let error_message = format!("{} - {}", record.level(), record.args()); if record.level() == LogLevel::Error { self.monitor.send(&error_message, record.location()); } println!("{}", error_message); } } }
struct Logger<T: Monitor> { monitor: T,
random_line_split
logger.rs
use config::Config; use log::{self, Log, LogLevel, LogLevelFilter, LogMetadata, LogRecord, SetLoggerError}; use monitor::{Monitor, MonitorProvider}; pub fn start_logging(config: &Config) -> Result<(), SetLoggerError> { log::set_logger(|max_log_level| { max_log_level.set(LogLevelFilter::Info); if let Some(monitor) = config.monitor.to_owned() { if monitor.enabled == true { match MonitorProvider::find_with_config(&monitor.provider, &monitor) { Some(monitor) =>
None => { panic!("Monitor {} has not been found.", monitor.provider); } }; } } Box::new(Logger { monitor: MonitorProvider::null_monitor(), }) }) } struct Logger<T: Monitor> { monitor: T, } impl<T: Monitor> Log for Logger<T> { fn enabled(&self, metadata: &LogMetadata) -> bool { metadata.level() <= LogLevel::Info } fn log(&self, record: &LogRecord) { if self.enabled(record.metadata()) { let error_message = format!("{} - {}", record.level(), record.args()); if record.level() == LogLevel::Error { self.monitor.send(&error_message, record.location()); } println!("{}", error_message); } } }
{ return Box::new(Logger { monitor: monitor }); }
conditional_block
logger.rs
use config::Config; use log::{self, Log, LogLevel, LogLevelFilter, LogMetadata, LogRecord, SetLoggerError}; use monitor::{Monitor, MonitorProvider}; pub fn
(config: &Config) -> Result<(), SetLoggerError> { log::set_logger(|max_log_level| { max_log_level.set(LogLevelFilter::Info); if let Some(monitor) = config.monitor.to_owned() { if monitor.enabled == true { match MonitorProvider::find_with_config(&monitor.provider, &monitor) { Some(monitor) => { return Box::new(Logger { monitor: monitor }); } None => { panic!("Monitor {} has not been found.", monitor.provider); } }; } } Box::new(Logger { monitor: MonitorProvider::null_monitor(), }) }) } struct Logger<T: Monitor> { monitor: T, } impl<T: Monitor> Log for Logger<T> { fn enabled(&self, metadata: &LogMetadata) -> bool { metadata.level() <= LogLevel::Info } fn log(&self, record: &LogRecord) { if self.enabled(record.metadata()) { let error_message = format!("{} - {}", record.level(), record.args()); if record.level() == LogLevel::Error { self.monitor.send(&error_message, record.location()); } println!("{}", error_message); } } }
start_logging
identifier_name
utils.rs
extern crate delivery; extern crate log; use delivery::utils; use delivery::utils::path_join_many::PathJoinMany; use std::fs; use std::path::Path; use support::paths::fixture_file; use tempdir::TempDir; macro_rules! setup { () => {}; } test!(copy_recursive { let source_dir = fixture_file("test_repo"); let tmpdir = TempDir::new("utils-copy_recursive").unwrap(); let dest_dir = tmpdir.path().to_path_buf(); panic_on_error!(utils::copy_recursive(&source_dir, &dest_dir)); let expected: &[&[&str]] = &[ &["test_repo", "README.md"], &["test_repo", "cookbooks", "delivery_test", "metadata.rb"], &["test_repo", "cookbooks", "delivery_test", "recipes", "unit.rb"]]; for e in expected { if!file_exists(&dest_dir.join_many(e)) { panic!(format!("copy_recursive failure: NOT FOUND '{:?}'", &dest_dir.join_many(e))); } } }); test!(remove_recursive { let source_dir = fixture_file("test_repo"); let tmpdir = TempDir::new("utils-copy_recursive").unwrap(); let dest_dir = tmpdir.path().to_path_buf(); let cookbooks_dir = dest_dir.join_many(&["test_repo", "cookbooks"]); panic_on_error!(utils::copy_recursive(&source_dir, &dest_dir)); assert!(file_exists(&cookbooks_dir)); panic_on_error!(utils::remove_recursive(&cookbooks_dir)); assert!(!file_exists(&cookbooks_dir)); }); fn
<P:?Sized>(f: &P) -> bool where P: AsRef<Path>, { fs::metadata(f).is_ok() }
file_exists
identifier_name
utils.rs
extern crate delivery; extern crate log; use delivery::utils; use delivery::utils::path_join_many::PathJoinMany; use std::fs; use std::path::Path; use support::paths::fixture_file; use tempdir::TempDir; macro_rules! setup { () => {}; } test!(copy_recursive { let source_dir = fixture_file("test_repo"); let tmpdir = TempDir::new("utils-copy_recursive").unwrap(); let dest_dir = tmpdir.path().to_path_buf(); panic_on_error!(utils::copy_recursive(&source_dir, &dest_dir));
&["test_repo", "README.md"], &["test_repo", "cookbooks", "delivery_test", "metadata.rb"], &["test_repo", "cookbooks", "delivery_test", "recipes", "unit.rb"]]; for e in expected { if!file_exists(&dest_dir.join_many(e)) { panic!(format!("copy_recursive failure: NOT FOUND '{:?}'", &dest_dir.join_many(e))); } } }); test!(remove_recursive { let source_dir = fixture_file("test_repo"); let tmpdir = TempDir::new("utils-copy_recursive").unwrap(); let dest_dir = tmpdir.path().to_path_buf(); let cookbooks_dir = dest_dir.join_many(&["test_repo", "cookbooks"]); panic_on_error!(utils::copy_recursive(&source_dir, &dest_dir)); assert!(file_exists(&cookbooks_dir)); panic_on_error!(utils::remove_recursive(&cookbooks_dir)); assert!(!file_exists(&cookbooks_dir)); }); fn file_exists<P:?Sized>(f: &P) -> bool where P: AsRef<Path>, { fs::metadata(f).is_ok() }
let expected: &[&[&str]] = &[
random_line_split
utils.rs
extern crate delivery; extern crate log; use delivery::utils; use delivery::utils::path_join_many::PathJoinMany; use std::fs; use std::path::Path; use support::paths::fixture_file; use tempdir::TempDir; macro_rules! setup { () => {}; } test!(copy_recursive { let source_dir = fixture_file("test_repo"); let tmpdir = TempDir::new("utils-copy_recursive").unwrap(); let dest_dir = tmpdir.path().to_path_buf(); panic_on_error!(utils::copy_recursive(&source_dir, &dest_dir)); let expected: &[&[&str]] = &[ &["test_repo", "README.md"], &["test_repo", "cookbooks", "delivery_test", "metadata.rb"], &["test_repo", "cookbooks", "delivery_test", "recipes", "unit.rb"]]; for e in expected { if!file_exists(&dest_dir.join_many(e)) { panic!(format!("copy_recursive failure: NOT FOUND '{:?}'", &dest_dir.join_many(e))); } } }); test!(remove_recursive { let source_dir = fixture_file("test_repo"); let tmpdir = TempDir::new("utils-copy_recursive").unwrap(); let dest_dir = tmpdir.path().to_path_buf(); let cookbooks_dir = dest_dir.join_many(&["test_repo", "cookbooks"]); panic_on_error!(utils::copy_recursive(&source_dir, &dest_dir)); assert!(file_exists(&cookbooks_dir)); panic_on_error!(utils::remove_recursive(&cookbooks_dir)); assert!(!file_exists(&cookbooks_dir)); }); fn file_exists<P:?Sized>(f: &P) -> bool where P: AsRef<Path>,
{ fs::metadata(f).is_ok() }
identifier_body
exports.rs
//! Parse the PE export table (if present) to find entries in find exports in //! executable sections. //! //! PEs may export data, which we'll assume isn't in an executable section. use anyhow::Result; use crate::{loader::pe::PE, module::Permissions, VA}; pub fn find_pe_exports(pe: &PE) -> Result<Vec<VA>> { let base_address = match pe.header.optional_header { Some(opt) => opt.windows_fields.image_base, _ => 0x40_0000, }; let exports: Vec<VA> = pe .pe()? .exports .iter() // re-exports are simply strings that point to a `DLL.export_name` ASCII string. // therefore, they're not functions/code. .filter(|&exp| exp.reexport.is_none()) .map(|exp| base_address + exp.rva as u64) .filter(|&va| { // PE may export data, so ensure the exports we track are executable // (functions). pe.module.probe_va(va, Permissions::X) }) .collect(); Ok(exports) } #[cfg(test)] mod tests { use crate::rsrc::*; use anyhow::Result; #[test] fn k32() -> Result<()> { let buf = get_buf(Rsrc::K32); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(1445, fns.len()); Ok(()) } #[test] fn tiny() -> Result<()>
#[test] fn nop() -> Result<()> { let buf = get_buf(Rsrc::NOP); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) } #[test] fn mimi() -> Result<()> { let buf = get_buf(Rsrc::MIMI); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) } }
{ let buf = get_buf(Rsrc::TINY); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) }
identifier_body
exports.rs
//! Parse the PE export table (if present) to find entries in find exports in //! executable sections. //! //! PEs may export data, which we'll assume isn't in an executable section. use anyhow::Result; use crate::{loader::pe::PE, module::Permissions, VA}; pub fn find_pe_exports(pe: &PE) -> Result<Vec<VA>> { let base_address = match pe.header.optional_header { Some(opt) => opt.windows_fields.image_base, _ => 0x40_0000, }; let exports: Vec<VA> = pe .pe()? .exports .iter() // re-exports are simply strings that point to a `DLL.export_name` ASCII string. // therefore, they're not functions/code. .filter(|&exp| exp.reexport.is_none()) .map(|exp| base_address + exp.rva as u64) .filter(|&va| { // PE may export data, so ensure the exports we track are executable // (functions). pe.module.probe_va(va, Permissions::X) }) .collect(); Ok(exports) } #[cfg(test)] mod tests { use crate::rsrc::*; use anyhow::Result;
fn k32() -> Result<()> { let buf = get_buf(Rsrc::K32); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(1445, fns.len()); Ok(()) } #[test] fn tiny() -> Result<()> { let buf = get_buf(Rsrc::TINY); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) } #[test] fn nop() -> Result<()> { let buf = get_buf(Rsrc::NOP); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) } #[test] fn mimi() -> Result<()> { let buf = get_buf(Rsrc::MIMI); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) } }
#[test]
random_line_split
exports.rs
//! Parse the PE export table (if present) to find entries in find exports in //! executable sections. //! //! PEs may export data, which we'll assume isn't in an executable section. use anyhow::Result; use crate::{loader::pe::PE, module::Permissions, VA}; pub fn find_pe_exports(pe: &PE) -> Result<Vec<VA>> { let base_address = match pe.header.optional_header { Some(opt) => opt.windows_fields.image_base, _ => 0x40_0000, }; let exports: Vec<VA> = pe .pe()? .exports .iter() // re-exports are simply strings that point to a `DLL.export_name` ASCII string. // therefore, they're not functions/code. .filter(|&exp| exp.reexport.is_none()) .map(|exp| base_address + exp.rva as u64) .filter(|&va| { // PE may export data, so ensure the exports we track are executable // (functions). pe.module.probe_va(va, Permissions::X) }) .collect(); Ok(exports) } #[cfg(test)] mod tests { use crate::rsrc::*; use anyhow::Result; #[test] fn k32() -> Result<()> { let buf = get_buf(Rsrc::K32); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(1445, fns.len()); Ok(()) } #[test] fn tiny() -> Result<()> { let buf = get_buf(Rsrc::TINY); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) } #[test] fn
() -> Result<()> { let buf = get_buf(Rsrc::NOP); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) } #[test] fn mimi() -> Result<()> { let buf = get_buf(Rsrc::MIMI); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let fns = crate::analysis::pe::exports::find_pe_exports(&pe)?; assert_eq!(0, fns.len()); Ok(()) } }
nop
identifier_name
uct_test.rs
use crate::uct::{UcbType, UctConfig, UctKomiType, UctRoot}; use oppai_field::construct_field::construct_field; use oppai_field::field::NonZeroPos; use oppai_field::player::Player; use oppai_test_images::*; use rand::SeedableRng; use rand_xoshiro::Xoshiro256PlusPlus; use std::sync::atomic::AtomicBool; const UCT_CONFIG: UctConfig = UctConfig { threads_count: 1, radius: 3, ucb_type: UcbType::Ucb1Tuned, draw_weight: 0.4, uctk: 1.0, when_create_children: 2,
depth: 8, komi_type: UctKomiType::Dynamic, red: 0.45, green: 0.5, komi_min_iterations: 3_000, }; macro_rules! uct_test { ($(#[$($attr:meta),+])* $name:ident, $image:ident, $iterations:expr, $seed:expr) => { #[test] $(#[$($attr),+])* fn $name() { env_logger::try_init().ok(); let mut rng = Xoshiro256PlusPlus::seed_from_u64($seed); let field = construct_field(&mut rng, $image.image); let mut uct = UctRoot::new(UCT_CONFIG, field.length()); let should_stop = AtomicBool::new(false); let pos = uct.best_move(&field, Player::Red, &mut rng, &should_stop, $iterations); assert_eq!(pos, NonZeroPos::new(field.to_pos($image.solution.0, $image.solution.1))); } } } uct_test!(uct_1, IMAGE_1, 100_000, 7); uct_test!(uct_2, IMAGE_2, 100_000, 7); uct_test!(uct_3, IMAGE_3, 100_000, 5); uct_test!(uct_4, IMAGE_4, 100_000, 5); uct_test!(uct_5, IMAGE_5, 100_000, 7); uct_test!( #[ignore] uct_6, IMAGE_6, 1_000_000, 7 ); uct_test!( #[ignore] uct_7, IMAGE_7, 1_000_000, 7 ); uct_test!(uct_8, IMAGE_8, 1_00_000, 7); uct_test!(uct_9, IMAGE_9, 100_000, 7); uct_test!( #[ignore] uct_10, IMAGE_10, 1_000_000, 7 ); // uct suggests (7, 6) after 1_000_000_000 iterations // uct_test!(uct_11, IMAGE_11, 1_000_000_000, 7); uct_test!(uct_12, IMAGE_12, 100_000, 7); uct_test!(uct_13, IMAGE_13, 100_000, 7); uct_test!(uct_14, IMAGE_14, 100_000, 39);
random_line_split
main.rs
//! Demonstrates the use of service accounts and the Google Cloud Pubsub API. //! //! Run this binary as.../service_account pub 'your message' in order to publish messages, //! and as.../service_account sub in order to subscribe to those messages. This will look like the //! following: //! //! ``` //! $ target/debug/service_account pub 'Hello oh wonderful world' & //! $ target/debug/service_account sub //! Published message #95491011619126 //! message <95491011619126> 'Hello oh wonderful world' at 2016-09-21T20:04:47.040Z //! Published message #95491011620879 //! message <95491011620879> 'Hello oh wonderful world' at 2016-09-21T20:04:49.086Z //! Published message #95491011622600 //! message <95491011622600> 'Hello oh wonderful world' at 2016-09-21T20:04:51.132Z //! Published message #95491011624393 //! message <95491011624393> 'Hello oh wonderful world' at 2016-09-21T20:04:53.187Z //! Published message #95491011626206 //! message <95491011626206> 'Hello oh wonderful world' at 2016-09-21T20:04:55.233Z //! //! Copyright (c) 2016 Google, Inc. (Lewin Bormann <[email protected]>) //! extern crate base64; extern crate yup_oauth2 as oauth; extern crate google_pubsub1 as pubsub; extern crate hyper; extern crate hyper_rustls; use std::env; use std::time; use std::thread; use hyper::net::HttpsConnector; use pubsub::{Topic, Subscription}; // The prefixes are important! const SUBSCRIPTION_NAME: &'static str = "projects/sanguine-rhythm-105020/subscriptions/rust_authd_sub_1"; const TOPIC_NAME: &'static str = "projects/sanguine-rhythm-105020/topics/topic-01"; type PubsubMethods<'a> = pubsub::ProjectMethods<'a, hyper::Client, oauth::ServiceAccountAccess<hyper::Client>>; // Verifies that the topic TOPIC_NAME exists, or creates it. fn check_or_create_topic(methods: &PubsubMethods) -> Topic { let result = methods.topics_get(TOPIC_NAME).doit(); if result.is_err() { println!("Assuming topic doesn't exist; creating topic"); let topic = pubsub::Topic { name: Some(TOPIC_NAME.to_string()) }; let result = methods.topics_create(topic, TOPIC_NAME).doit().unwrap(); result.1 } else { result.unwrap().1 } } fn check_or_create_subscription(methods: &PubsubMethods) -> Subscription { // check if subscription exists let result = methods.subscriptions_get(SUBSCRIPTION_NAME).doit(); if result.is_err() { println!("Assuming subscription doesn't exist; creating subscription"); let sub = pubsub::Subscription { topic: Some(TOPIC_NAME.to_string()), ack_deadline_seconds: Some(30), push_config: None, name: Some(SUBSCRIPTION_NAME.to_string()), }; let (_resp, sub) = methods.subscriptions_create(sub, SUBSCRIPTION_NAME).doit().unwrap(); sub } else { result.unwrap().1 } } fn ack_message(methods: &PubsubMethods, id: String) { let request = pubsub::AcknowledgeRequest { ack_ids: Some(vec![id]) }; let result = methods.subscriptions_acknowledge(request, SUBSCRIPTION_NAME).doit(); match result { Err(e) =>
Ok(_) => (), } } // Wait for new messages. Print and ack any new messages. fn subscribe_wait(methods: &PubsubMethods) { check_or_create_subscription(&methods); let request = pubsub::PullRequest { return_immediately: Some(false), max_messages: Some(1), }; loop { let result = methods.subscriptions_pull(request.clone(), SUBSCRIPTION_NAME).doit(); match result { Err(e) => { println!("Pull error: {}", e); } Ok((_response, pullresponse)) => { for msg in pullresponse.received_messages.unwrap_or(Vec::new()) { let ack_id = msg.ack_id.unwrap_or(String::new()); let message = msg.message.unwrap_or(Default::default()); println!("message <{}> '{}' at {}", message.message_id.unwrap_or(String::new()), String::from_utf8(base64::decode(&message.data .unwrap_or(String::new())) .unwrap()) .unwrap(), message.publish_time.unwrap_or(String::new())); if ack_id!= "" { ack_message(methods, ack_id); } } } } } } // Publish some message every 2 seconds. fn publish_stuff(methods: &PubsubMethods, message: &str) { check_or_create_topic(&methods); let message = pubsub::PubsubMessage { // Base64 encoded! data: Some(base64::encode(message.as_bytes())), ..Default::default() }; let request = pubsub::PublishRequest { messages: Some(vec![message]) }; loop { let result = methods.topics_publish(request.clone(), TOPIC_NAME).doit(); match result { Err(e) => { println!("Publish error: {}", e); } Ok((_response, pubresponse)) => { for msg in pubresponse.message_ids.unwrap_or(Vec::new()) { println!("Published message #{}", msg); } } } thread::sleep(time::Duration::new(2, 0)); } } // If called as '.../service_account pub', act as publisher; if called as '.../service_account // sub', act as subscriber. fn main() { let client_secret = oauth::service_account_key_from_file(&"pubsub-auth.json".to_string()) .unwrap(); let client = hyper::Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())); let mut access = oauth::ServiceAccountAccess::new(client_secret, client); use oauth::GetToken; println!("{:?}", access.token(&vec!["https://www.googleapis.com/auth/pubsub"]).unwrap()); let client = hyper::Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())); let hub = pubsub::Pubsub::new(client, access); let methods = hub.projects(); let mode = env::args().nth(1).unwrap_or(String::new()); if mode == "pub" { let message = env::args().nth(2).unwrap_or("Hello World!".to_string()); publish_stuff(&methods, &message); } else if mode == "sub" { subscribe_wait(&methods); } else { println!("Please use either of 'pub' or'sub' as first argument to this binary!"); } }
{ println!("Ack error: {:?}", e); }
conditional_block