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
crt-static.rs
// Test proc-macro crate can be built without additional RUSTFLAGS // on musl target
#![crate_type = "proc-macro"] // FIXME: This don't work when crate-type is specified by attribute // `#![crate_type = "proc-macro"]`, not by `--crate-type=proc-macro` // command line flag. This is beacuse the list of `cfg` symbols is generated // before attributes are parsed. See rustc_interface::util::add_configuration #[cfg(target_feature = "crt-static")] compile_error!("crt-static is enabled"); extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(Foo)] pub fn derive_foo(input: TokenStream) -> TokenStream { input }
// override -Ctarget-feature=-crt-static from compiletest // compile-flags: --crate-type proc-macro -Ctarget-feature= // ignore-wasm32 // ignore-sgx no support for proc-macro crate type // build-pass
random_line_split
hashmap.rs
//! This example demonstrates using Raft to implement a replicated hashmap over `n` servers and //! interact with them over `m` clients. //! //! This example uses Serde serialization. //! //! Comments below will aim to be tailored towards Raft and it's usage. If you have any questions, //! Please, just open an issue. //! //! TODO: For the sake of simplicity of this example, we don't implement a `Log` and just use a //! simple testing one. We should improve this in the future. // In order to use Serde we need to enable these nightly features. #![feature(plugin)] #![feature(custom_derive)] #![plugin(serde_macros)] extern crate raft; // <--- Kind of a big deal for this! extern crate env_logger; extern crate docopt; extern crate serde; extern crate serde_json; extern crate rustc_serialize; use std::net::SocketAddr; use std::str::FromStr; use std::collections::HashMap; use serde_json::Value; use docopt::Docopt; // Raft's major components. See comments in code on usage and things. use raft::{ Server, Client, state_machine, persistent_log, ServerId, }; // A payload datatype. We're just using a simple enum. You can use whatever. use Message::*; // Using docopt we define the overall usage of the application. static USAGE: &'static str = " A replicated mutable hashmap. Operations on the register have serializable consistency, but no durability (once all register servers are terminated the map is lost). Each register server holds a replica of the map, and coordinates with its peers to update the maps values according to client commands. The register is available for reading and writing only if a majority of register servers are available. Commands: get Returns the current value of the key. put Sets the current value of the key, and returns the previous value. cas (compare and set) Conditionally sets the value of the key if the current value matches an expected value, returning true if the key was set. server Starts a key server. Servers must be provided a unique ID and address (ip:port) at startup, along with the ID and address of all peer servers.register Usage: hashmap get <key> (<node-address>)... hashmap put <key> <new-value> (<node-address>)... hashmap cas <key> <expected-value> <new-value> (<node-address>)... hashmap server <id> [<node-id> <node-address>]... hashmap (-h | --help) Options: -h --help Show a help message. "; #[derive(Debug, RustcDecodable)] struct Args { cmd_server: bool, cmd_get: bool, cmd_put: bool, cmd_cas: bool, // When creating a server you will necessarily need some sort of unique ID for it as well // as a list of peers. In this example we just accept them straight from args. You might // find it best to use a `toml` or `yaml` or `json` file. arg_id: Option<u64>, arg_node_id: Vec<u64>, arg_node_address: Vec<String>, // In this example keys and values are associated. In your application you can model your data // however you please. arg_key: String, arg_new_value: String, arg_expected_value: String, } /// This is the defined message type for this example. For the sake of simplicity we don't go very /// far with this. In a "real" application you may want to more distinctly distinguish between /// data meant for `.query()` and data meant for `.propose()`. #[derive(Serialize, Deserialize)] pub enum Message { Get(String), Put(String, Value), Cas(String, Value, Value), } /// Just a plain old boring "parse args and dispatch" call. fn main() { let _ = env_logger::init(); let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if args.cmd_server { server(&args); } else if args.cmd_get { get(&args); } else if args.cmd_put { put(&args); } else if args.cmd_cas
} /// A simple convenience method since this is an example and it should exit if given invalid params. fn parse_addr(addr: &str) -> SocketAddr { SocketAddr::from_str(addr) .ok() .expect(&format!("unable to parse socket address: {}", addr)) } /// Creates a Raft server using the specified ID from the list of nodes. fn server(args: &Args) { // Creating a raft server requires several things: // A persistent log implementation, which manages the persistent, replicated log... let persistent_log = persistent_log::MemLog::new(); // A state machine which replicates state. This state should be the same on all nodes. let state_machine = HashmapStateMachine::new(); // As well as a unique server id. let id = ServerId::from(args.arg_id.unwrap()); //... And a list of peers. let mut peers = args.arg_node_id .iter() .zip(args.arg_node_address.iter()) .map(|(&id, addr)| (ServerId::from(id), parse_addr(&addr))) .collect::<HashMap<_,_>>(); // The Raft Server will return an error if it's ID is inside of it's peer set. Don't do that. // Instead, take it out and use it! let addr = peers.remove(&id).unwrap(); // Using all of the above components. // You probably shouldn't `.unwrap()` in production code unless you're totally sure it works // 100% of the time, all the time. Server::run(id, addr, peers, persistent_log, state_machine).unwrap(); } /// Gets a value for a given key from the provided Raft cluster. fn get(args: &Args) { // Clients necessarily need to now the valid set of nodes which they can talk to. // This is both so they can try to talk to all the nodes if some are failing, and so that it // can verify that it's not being lead astray somehow in redirections on leadership changes. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); // Clients and be stored and reused, or used once and discarded. // There is very small overhead in connecting a new client to a cluster as it must discover and // identify itself to the leader. let mut client = Client::new(cluster); // In this example `serde::json` is used to serialize and deserialize messages. // Since Raft accepts `[u8]` the way you structure your data, the serialization method you // choose, and how you interpret that data is entirely up to you. let payload = serde_json::to_string(&Message::Get(args.arg_key.clone())).unwrap(); // A query executes **immutably** on the leader of the cluster and does not pass through the // persistent log. This is intended for querying the current state of the state machine. let response = client.query(payload.as_bytes()).unwrap(); // A response will block until it's query is complete. This is intended and expected behavior // based on the papers specifications. println!("{}", String::from_utf8(response).unwrap()) } /// Sets a value for a given key in the provided Raft cluster. fn put(args: &Args) { // Same as above. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); let mut client = Client::new(cluster); let new_value = serde_json::to_value(&args.arg_new_value); let payload = serde_json::to_string(&Message::Put(args.arg_key.clone(), new_value)).unwrap(); // A propose will go through the persistent log and mutably modify the state machine in some // way. This is **much** slower than `.query()`. let response = client.propose(payload.as_bytes()).unwrap(); // A response will block until it's proposal is complete. This is intended and expected behavior // based on the papers specifications. println!("{}", String::from_utf8(response).unwrap()) } /// Compares and sets a value for a given key in the provided Raft cluster if the value is what is /// expected. fn cas(args: &Args) { // Same as above. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); let mut client = Client::new(cluster); let new_value = serde_json::to_value(&args.arg_new_value); let expected_value = serde_json::to_value(&args.arg_expected_value); let payload = serde_json::to_string(&Message::Cas(args.arg_key.clone(), expected_value, new_value)).unwrap(); let response = client.propose(payload.as_bytes()).unwrap(); println!("{}", String::from_utf8(response).unwrap()) } /// A state machine that holds a hashmap. #[derive(Debug)] pub struct HashmapStateMachine { map: HashMap<String, Value>, } /// Implement anything you want... A `new()` is generally a great idea. impl HashmapStateMachine { pub fn new() -> HashmapStateMachine { HashmapStateMachine { map: HashMap::new(), } } } /// Implementing `state_machine::StateMachine` allows your application specific state machine to be /// used in Raft. Feel encouraged to base yours of one of ours in these examples. impl state_machine::StateMachine for HashmapStateMachine { /// `apply()` is called on when a client's `.propose()` is commited and reaches the state /// machine. At this point it is durable and is going to be applied on at least half the nodes /// within the next couple round trips. fn apply(&mut self, new_value: &[u8]) -> Vec<u8> { // Deserialize let string = String::from_utf8_lossy(new_value); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serde_json::to_string(old_value) }, Put(key, value) => { let old_value = &self.map.insert(key, value); serde_json::to_string(old_value) }, Cas(key, old_check, new) => { if *self.map.get(&key).unwrap() == old_check { let _ = self.map.insert(key, new); serde_json::to_string(&true) } else { serde_json::to_string(&false) } }, }; // Respond. response.unwrap().into_bytes() } /// `query()` is called on when a client's `.query()` is recieved. It does not go through the /// persistent log, it does not mutate the state of the state machine, and it is intended to be /// fast. fn query(&self, query: &[u8]) -> Vec<u8> { // Deserialize let string = String::from_utf8_lossy(query); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serde_json::to_string(old_value) }, _ => panic!("Can't do mutating requests in query"), }; // Respond. response.unwrap().into_bytes() } fn snapshot(&self) -> Vec<u8> { serde_json::to_string(&self.map) .unwrap() .into_bytes() } fn restore_snapshot(&mut self, snapshot_value: Vec<u8>) { self.map = serde_json::from_str(&String::from_utf8_lossy(&snapshot_value)).unwrap(); () } }
{ cas(&args); }
conditional_block
hashmap.rs
//! This example demonstrates using Raft to implement a replicated hashmap over `n` servers and //! interact with them over `m` clients. //! //! This example uses Serde serialization. //! //! Comments below will aim to be tailored towards Raft and it's usage. If you have any questions, //! Please, just open an issue. //! //! TODO: For the sake of simplicity of this example, we don't implement a `Log` and just use a //! simple testing one. We should improve this in the future. // In order to use Serde we need to enable these nightly features. #![feature(plugin)] #![feature(custom_derive)] #![plugin(serde_macros)] extern crate raft; // <--- Kind of a big deal for this! extern crate env_logger; extern crate docopt; extern crate serde; extern crate serde_json; extern crate rustc_serialize; use std::net::SocketAddr; use std::str::FromStr; use std::collections::HashMap; use serde_json::Value; use docopt::Docopt; // Raft's major components. See comments in code on usage and things. use raft::{ Server, Client, state_machine, persistent_log, ServerId, }; // A payload datatype. We're just using a simple enum. You can use whatever. use Message::*; // Using docopt we define the overall usage of the application. static USAGE: &'static str = " A replicated mutable hashmap. Operations on the register have serializable consistency, but no durability (once all register servers are terminated the map is lost). Each register server holds a replica of the map, and coordinates with its peers to update the maps values according to client commands. The register is available for reading and writing only if a majority of register servers are available. Commands: get Returns the current value of the key. put Sets the current value of the key, and returns the previous value. cas (compare and set) Conditionally sets the value of the key if the current value matches an expected value, returning true if the key was set. server Starts a key server. Servers must be provided a unique ID and address (ip:port) at startup, along with the ID and address of all peer servers.register Usage: hashmap get <key> (<node-address>)... hashmap put <key> <new-value> (<node-address>)... hashmap cas <key> <expected-value> <new-value> (<node-address>)... hashmap server <id> [<node-id> <node-address>]... hashmap (-h | --help) Options: -h --help Show a help message. "; #[derive(Debug, RustcDecodable)] struct Args { cmd_server: bool, cmd_get: bool, cmd_put: bool, cmd_cas: bool, // When creating a server you will necessarily need some sort of unique ID for it as well // as a list of peers. In this example we just accept them straight from args. You might // find it best to use a `toml` or `yaml` or `json` file. arg_id: Option<u64>, arg_node_id: Vec<u64>, arg_node_address: Vec<String>, // In this example keys and values are associated. In your application you can model your data // however you please. arg_key: String, arg_new_value: String, arg_expected_value: String, } /// This is the defined message type for this example. For the sake of simplicity we don't go very /// far with this. In a "real" application you may want to more distinctly distinguish between /// data meant for `.query()` and data meant for `.propose()`. #[derive(Serialize, Deserialize)] pub enum Message { Get(String), Put(String, Value), Cas(String, Value, Value), } /// Just a plain old boring "parse args and dispatch" call. fn main() { let _ = env_logger::init(); let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if args.cmd_server { server(&args); } else if args.cmd_get { get(&args); } else if args.cmd_put { put(&args); } else if args.cmd_cas { cas(&args); } } /// A simple convenience method since this is an example and it should exit if given invalid params. fn parse_addr(addr: &str) -> SocketAddr { SocketAddr::from_str(addr) .ok() .expect(&format!("unable to parse socket address: {}", addr)) } /// Creates a Raft server using the specified ID from the list of nodes. fn server(args: &Args) { // Creating a raft server requires several things: // A persistent log implementation, which manages the persistent, replicated log... let persistent_log = persistent_log::MemLog::new(); // A state machine which replicates state. This state should be the same on all nodes. let state_machine = HashmapStateMachine::new(); // As well as a unique server id. let id = ServerId::from(args.arg_id.unwrap()); //... And a list of peers. let mut peers = args.arg_node_id .iter() .zip(args.arg_node_address.iter()) .map(|(&id, addr)| (ServerId::from(id), parse_addr(&addr))) .collect::<HashMap<_,_>>(); // The Raft Server will return an error if it's ID is inside of it's peer set. Don't do that. // Instead, take it out and use it! let addr = peers.remove(&id).unwrap(); // Using all of the above components. // You probably shouldn't `.unwrap()` in production code unless you're totally sure it works // 100% of the time, all the time. Server::run(id, addr, peers, persistent_log, state_machine).unwrap(); } /// Gets a value for a given key from the provided Raft cluster. fn get(args: &Args) { // Clients necessarily need to now the valid set of nodes which they can talk to. // This is both so they can try to talk to all the nodes if some are failing, and so that it // can verify that it's not being lead astray somehow in redirections on leadership changes. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); // Clients and be stored and reused, or used once and discarded. // There is very small overhead in connecting a new client to a cluster as it must discover and // identify itself to the leader. let mut client = Client::new(cluster); // In this example `serde::json` is used to serialize and deserialize messages. // Since Raft accepts `[u8]` the way you structure your data, the serialization method you // choose, and how you interpret that data is entirely up to you. let payload = serde_json::to_string(&Message::Get(args.arg_key.clone())).unwrap(); // A query executes **immutably** on the leader of the cluster and does not pass through the // persistent log. This is intended for querying the current state of the state machine. let response = client.query(payload.as_bytes()).unwrap(); // A response will block until it's query is complete. This is intended and expected behavior // based on the papers specifications. println!("{}", String::from_utf8(response).unwrap()) } /// Sets a value for a given key in the provided Raft cluster. fn put(args: &Args) { // Same as above. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); let mut client = Client::new(cluster); let new_value = serde_json::to_value(&args.arg_new_value); let payload = serde_json::to_string(&Message::Put(args.arg_key.clone(), new_value)).unwrap(); // A propose will go through the persistent log and mutably modify the state machine in some // way. This is **much** slower than `.query()`. let response = client.propose(payload.as_bytes()).unwrap(); // A response will block until it's proposal is complete. This is intended and expected behavior // based on the papers specifications. println!("{}", String::from_utf8(response).unwrap()) } /// Compares and sets a value for a given key in the provided Raft cluster if the value is what is /// expected. fn cas(args: &Args) { // Same as above. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); let mut client = Client::new(cluster); let new_value = serde_json::to_value(&args.arg_new_value); let expected_value = serde_json::to_value(&args.arg_expected_value); let payload = serde_json::to_string(&Message::Cas(args.arg_key.clone(), expected_value, new_value)).unwrap(); let response = client.propose(payload.as_bytes()).unwrap(); println!("{}", String::from_utf8(response).unwrap()) } /// A state machine that holds a hashmap. #[derive(Debug)] pub struct HashmapStateMachine { map: HashMap<String, Value>, } /// Implement anything you want... A `new()` is generally a great idea. impl HashmapStateMachine { pub fn new() -> HashmapStateMachine { HashmapStateMachine { map: HashMap::new(), } } } /// Implementing `state_machine::StateMachine` allows your application specific state machine to be /// used in Raft. Feel encouraged to base yours of one of ours in these examples. impl state_machine::StateMachine for HashmapStateMachine { /// `apply()` is called on when a client's `.propose()` is commited and reaches the state /// machine. At this point it is durable and is going to be applied on at least half the nodes /// within the next couple round trips. fn
(&mut self, new_value: &[u8]) -> Vec<u8> { // Deserialize let string = String::from_utf8_lossy(new_value); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serde_json::to_string(old_value) }, Put(key, value) => { let old_value = &self.map.insert(key, value); serde_json::to_string(old_value) }, Cas(key, old_check, new) => { if *self.map.get(&key).unwrap() == old_check { let _ = self.map.insert(key, new); serde_json::to_string(&true) } else { serde_json::to_string(&false) } }, }; // Respond. response.unwrap().into_bytes() } /// `query()` is called on when a client's `.query()` is recieved. It does not go through the /// persistent log, it does not mutate the state of the state machine, and it is intended to be /// fast. fn query(&self, query: &[u8]) -> Vec<u8> { // Deserialize let string = String::from_utf8_lossy(query); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serde_json::to_string(old_value) }, _ => panic!("Can't do mutating requests in query"), }; // Respond. response.unwrap().into_bytes() } fn snapshot(&self) -> Vec<u8> { serde_json::to_string(&self.map) .unwrap() .into_bytes() } fn restore_snapshot(&mut self, snapshot_value: Vec<u8>) { self.map = serde_json::from_str(&String::from_utf8_lossy(&snapshot_value)).unwrap(); () } }
apply
identifier_name
hashmap.rs
//! This example demonstrates using Raft to implement a replicated hashmap over `n` servers and //! interact with them over `m` clients. //! //! This example uses Serde serialization. //! //! Comments below will aim to be tailored towards Raft and it's usage. If you have any questions, //! Please, just open an issue. //! //! TODO: For the sake of simplicity of this example, we don't implement a `Log` and just use a //! simple testing one. We should improve this in the future. // In order to use Serde we need to enable these nightly features. #![feature(plugin)] #![feature(custom_derive)] #![plugin(serde_macros)] extern crate raft; // <--- Kind of a big deal for this! extern crate env_logger; extern crate docopt; extern crate serde; extern crate serde_json; extern crate rustc_serialize; use std::net::SocketAddr; use std::str::FromStr; use std::collections::HashMap; use serde_json::Value; use docopt::Docopt; // Raft's major components. See comments in code on usage and things. use raft::{ Server, Client, state_machine, persistent_log, ServerId, }; // A payload datatype. We're just using a simple enum. You can use whatever. use Message::*; // Using docopt we define the overall usage of the application. static USAGE: &'static str = " A replicated mutable hashmap. Operations on the register have serializable consistency, but no durability (once all register servers are terminated the map is lost). Each register server holds a replica of the map, and coordinates with its peers to update the maps values according to client commands. The register is available for reading and writing only if a majority of register servers are available. Commands: get Returns the current value of the key. put Sets the current value of the key, and returns the previous value. cas (compare and set) Conditionally sets the value of the key if the current value matches an expected value, returning true if the key was set. server Starts a key server. Servers must be provided a unique ID and address (ip:port) at startup, along with the ID and address of all peer servers.register Usage: hashmap get <key> (<node-address>)... hashmap put <key> <new-value> (<node-address>)... hashmap cas <key> <expected-value> <new-value> (<node-address>)... hashmap server <id> [<node-id> <node-address>]... hashmap (-h | --help) Options: -h --help Show a help message. "; #[derive(Debug, RustcDecodable)] struct Args { cmd_server: bool, cmd_get: bool, cmd_put: bool, cmd_cas: bool, // When creating a server you will necessarily need some sort of unique ID for it as well // as a list of peers. In this example we just accept them straight from args. You might // find it best to use a `toml` or `yaml` or `json` file. arg_id: Option<u64>, arg_node_id: Vec<u64>, arg_node_address: Vec<String>, // In this example keys and values are associated. In your application you can model your data // however you please. arg_key: String, arg_new_value: String, arg_expected_value: String, } /// This is the defined message type for this example. For the sake of simplicity we don't go very /// far with this. In a "real" application you may want to more distinctly distinguish between /// data meant for `.query()` and data meant for `.propose()`. #[derive(Serialize, Deserialize)] pub enum Message { Get(String), Put(String, Value), Cas(String, Value, Value), } /// Just a plain old boring "parse args and dispatch" call. fn main() { let _ = env_logger::init(); let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if args.cmd_server { server(&args); } else if args.cmd_get { get(&args); } else if args.cmd_put { put(&args); } else if args.cmd_cas { cas(&args); } } /// A simple convenience method since this is an example and it should exit if given invalid params. fn parse_addr(addr: &str) -> SocketAddr { SocketAddr::from_str(addr) .ok() .expect(&format!("unable to parse socket address: {}", addr)) } /// Creates a Raft server using the specified ID from the list of nodes. fn server(args: &Args) { // Creating a raft server requires several things: // A persistent log implementation, which manages the persistent, replicated log... let persistent_log = persistent_log::MemLog::new(); // A state machine which replicates state. This state should be the same on all nodes. let state_machine = HashmapStateMachine::new(); // As well as a unique server id. let id = ServerId::from(args.arg_id.unwrap()); //... And a list of peers. let mut peers = args.arg_node_id .iter() .zip(args.arg_node_address.iter()) .map(|(&id, addr)| (ServerId::from(id), parse_addr(&addr))) .collect::<HashMap<_,_>>(); // The Raft Server will return an error if it's ID is inside of it's peer set. Don't do that. // Instead, take it out and use it! let addr = peers.remove(&id).unwrap(); // Using all of the above components. // You probably shouldn't `.unwrap()` in production code unless you're totally sure it works // 100% of the time, all the time. Server::run(id, addr, peers, persistent_log, state_machine).unwrap(); } /// Gets a value for a given key from the provided Raft cluster. fn get(args: &Args) { // Clients necessarily need to now the valid set of nodes which they can talk to. // This is both so they can try to talk to all the nodes if some are failing, and so that it // can verify that it's not being lead astray somehow in redirections on leadership changes. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); // Clients and be stored and reused, or used once and discarded. // There is very small overhead in connecting a new client to a cluster as it must discover and // identify itself to the leader. let mut client = Client::new(cluster); // In this example `serde::json` is used to serialize and deserialize messages. // Since Raft accepts `[u8]` the way you structure your data, the serialization method you // choose, and how you interpret that data is entirely up to you. let payload = serde_json::to_string(&Message::Get(args.arg_key.clone())).unwrap(); // A query executes **immutably** on the leader of the cluster and does not pass through the // persistent log. This is intended for querying the current state of the state machine. let response = client.query(payload.as_bytes()).unwrap(); // A response will block until it's query is complete. This is intended and expected behavior // based on the papers specifications. println!("{}", String::from_utf8(response).unwrap()) } /// Sets a value for a given key in the provided Raft cluster. fn put(args: &Args) { // Same as above. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); let mut client = Client::new(cluster); let new_value = serde_json::to_value(&args.arg_new_value); let payload = serde_json::to_string(&Message::Put(args.arg_key.clone(), new_value)).unwrap(); // A propose will go through the persistent log and mutably modify the state machine in some // way. This is **much** slower than `.query()`. let response = client.propose(payload.as_bytes()).unwrap(); // A response will block until it's proposal is complete. This is intended and expected behavior // based on the papers specifications. println!("{}", String::from_utf8(response).unwrap()) } /// Compares and sets a value for a given key in the provided Raft cluster if the value is what is /// expected. fn cas(args: &Args) { // Same as above. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); let mut client = Client::new(cluster); let new_value = serde_json::to_value(&args.arg_new_value); let expected_value = serde_json::to_value(&args.arg_expected_value); let payload = serde_json::to_string(&Message::Cas(args.arg_key.clone(), expected_value, new_value)).unwrap(); let response = client.propose(payload.as_bytes()).unwrap(); println!("{}", String::from_utf8(response).unwrap()) } /// A state machine that holds a hashmap. #[derive(Debug)] pub struct HashmapStateMachine { map: HashMap<String, Value>, } /// Implement anything you want... A `new()` is generally a great idea. impl HashmapStateMachine { pub fn new() -> HashmapStateMachine { HashmapStateMachine { map: HashMap::new(), } } } /// Implementing `state_machine::StateMachine` allows your application specific state machine to be /// used in Raft. Feel encouraged to base yours of one of ours in these examples. impl state_machine::StateMachine for HashmapStateMachine { /// `apply()` is called on when a client's `.propose()` is commited and reaches the state /// machine. At this point it is durable and is going to be applied on at least half the nodes /// within the next couple round trips. fn apply(&mut self, new_value: &[u8]) -> Vec<u8>
serde_json::to_string(&false) } }, }; // Respond. response.unwrap().into_bytes() } /// `query()` is called on when a client's `.query()` is recieved. It does not go through the /// persistent log, it does not mutate the state of the state machine, and it is intended to be /// fast. fn query(&self, query: &[u8]) -> Vec<u8> { // Deserialize let string = String::from_utf8_lossy(query); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serde_json::to_string(old_value) }, _ => panic!("Can't do mutating requests in query"), }; // Respond. response.unwrap().into_bytes() } fn snapshot(&self) -> Vec<u8> { serde_json::to_string(&self.map) .unwrap() .into_bytes() } fn restore_snapshot(&mut self, snapshot_value: Vec<u8>) { self.map = serde_json::from_str(&String::from_utf8_lossy(&snapshot_value)).unwrap(); () } }
{ // Deserialize let string = String::from_utf8_lossy(new_value); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serde_json::to_string(old_value) }, Put(key, value) => { let old_value = &self.map.insert(key, value); serde_json::to_string(old_value) }, Cas(key, old_check, new) => { if *self.map.get(&key).unwrap() == old_check { let _ = self.map.insert(key, new); serde_json::to_string(&true) } else {
identifier_body
hashmap.rs
//! This example demonstrates using Raft to implement a replicated hashmap over `n` servers and //! interact with them over `m` clients. //! //! This example uses Serde serialization. //! //! Comments below will aim to be tailored towards Raft and it's usage. If you have any questions, //! Please, just open an issue. //! //! TODO: For the sake of simplicity of this example, we don't implement a `Log` and just use a //! simple testing one. We should improve this in the future. // In order to use Serde we need to enable these nightly features. #![feature(plugin)] #![feature(custom_derive)] #![plugin(serde_macros)] extern crate raft; // <--- Kind of a big deal for this! extern crate env_logger; extern crate docopt; extern crate serde; extern crate serde_json; extern crate rustc_serialize; use std::net::SocketAddr; use std::str::FromStr; use std::collections::HashMap; use serde_json::Value; use docopt::Docopt; // Raft's major components. See comments in code on usage and things. use raft::{ Server, Client, state_machine, persistent_log, ServerId, }; // A payload datatype. We're just using a simple enum. You can use whatever. use Message::*; // Using docopt we define the overall usage of the application. static USAGE: &'static str = " A replicated mutable hashmap. Operations on the register have serializable consistency, but no durability (once all register servers are terminated the map is lost). Each register server holds a replica of the map, and coordinates with its peers to update the maps values according to client commands. The register is available for reading and writing only if a majority of register servers are available. Commands: get Returns the current value of the key. put Sets the current value of the key, and returns the previous value. cas (compare and set) Conditionally sets the value of the key if the current value matches an expected value, returning true if the key was set. server Starts a key server. Servers must be provided a unique ID and address (ip:port) at startup, along with the ID and address of all peer servers.register Usage: hashmap get <key> (<node-address>)... hashmap put <key> <new-value> (<node-address>)... hashmap cas <key> <expected-value> <new-value> (<node-address>)... hashmap server <id> [<node-id> <node-address>]... hashmap (-h | --help) Options: -h --help Show a help message. "; #[derive(Debug, RustcDecodable)] struct Args { cmd_server: bool, cmd_get: bool, cmd_put: bool, cmd_cas: bool, // When creating a server you will necessarily need some sort of unique ID for it as well // as a list of peers. In this example we just accept them straight from args. You might // find it best to use a `toml` or `yaml` or `json` file. arg_id: Option<u64>, arg_node_id: Vec<u64>, arg_node_address: Vec<String>, // In this example keys and values are associated. In your application you can model your data // however you please. arg_key: String, arg_new_value: String, arg_expected_value: String, } /// This is the defined message type for this example. For the sake of simplicity we don't go very /// far with this. In a "real" application you may want to more distinctly distinguish between /// data meant for `.query()` and data meant for `.propose()`. #[derive(Serialize, Deserialize)] pub enum Message { Get(String), Put(String, Value), Cas(String, Value, Value), } /// Just a plain old boring "parse args and dispatch" call. fn main() { let _ = env_logger::init(); let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if args.cmd_server { server(&args); } else if args.cmd_get { get(&args); } else if args.cmd_put { put(&args); } else if args.cmd_cas { cas(&args); } } /// A simple convenience method since this is an example and it should exit if given invalid params. fn parse_addr(addr: &str) -> SocketAddr { SocketAddr::from_str(addr) .ok() .expect(&format!("unable to parse socket address: {}", addr)) } /// Creates a Raft server using the specified ID from the list of nodes. fn server(args: &Args) { // Creating a raft server requires several things: // A persistent log implementation, which manages the persistent, replicated log... let persistent_log = persistent_log::MemLog::new(); // A state machine which replicates state. This state should be the same on all nodes. let state_machine = HashmapStateMachine::new(); // As well as a unique server id. let id = ServerId::from(args.arg_id.unwrap()); //... And a list of peers. let mut peers = args.arg_node_id .iter() .zip(args.arg_node_address.iter()) .map(|(&id, addr)| (ServerId::from(id), parse_addr(&addr))) .collect::<HashMap<_,_>>(); // The Raft Server will return an error if it's ID is inside of it's peer set. Don't do that. // Instead, take it out and use it! let addr = peers.remove(&id).unwrap(); // Using all of the above components. // You probably shouldn't `.unwrap()` in production code unless you're totally sure it works // 100% of the time, all the time. Server::run(id, addr, peers, persistent_log, state_machine).unwrap(); } /// Gets a value for a given key from the provided Raft cluster. fn get(args: &Args) { // Clients necessarily need to now the valid set of nodes which they can talk to. // This is both so they can try to talk to all the nodes if some are failing, and so that it // can verify that it's not being lead astray somehow in redirections on leadership changes. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect();
let mut client = Client::new(cluster); // In this example `serde::json` is used to serialize and deserialize messages. // Since Raft accepts `[u8]` the way you structure your data, the serialization method you // choose, and how you interpret that data is entirely up to you. let payload = serde_json::to_string(&Message::Get(args.arg_key.clone())).unwrap(); // A query executes **immutably** on the leader of the cluster and does not pass through the // persistent log. This is intended for querying the current state of the state machine. let response = client.query(payload.as_bytes()).unwrap(); // A response will block until it's query is complete. This is intended and expected behavior // based on the papers specifications. println!("{}", String::from_utf8(response).unwrap()) } /// Sets a value for a given key in the provided Raft cluster. fn put(args: &Args) { // Same as above. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); let mut client = Client::new(cluster); let new_value = serde_json::to_value(&args.arg_new_value); let payload = serde_json::to_string(&Message::Put(args.arg_key.clone(), new_value)).unwrap(); // A propose will go through the persistent log and mutably modify the state machine in some // way. This is **much** slower than `.query()`. let response = client.propose(payload.as_bytes()).unwrap(); // A response will block until it's proposal is complete. This is intended and expected behavior // based on the papers specifications. println!("{}", String::from_utf8(response).unwrap()) } /// Compares and sets a value for a given key in the provided Raft cluster if the value is what is /// expected. fn cas(args: &Args) { // Same as above. let cluster = args.arg_node_address.iter() .map(|v| parse_addr(&v)) .collect(); let mut client = Client::new(cluster); let new_value = serde_json::to_value(&args.arg_new_value); let expected_value = serde_json::to_value(&args.arg_expected_value); let payload = serde_json::to_string(&Message::Cas(args.arg_key.clone(), expected_value, new_value)).unwrap(); let response = client.propose(payload.as_bytes()).unwrap(); println!("{}", String::from_utf8(response).unwrap()) } /// A state machine that holds a hashmap. #[derive(Debug)] pub struct HashmapStateMachine { map: HashMap<String, Value>, } /// Implement anything you want... A `new()` is generally a great idea. impl HashmapStateMachine { pub fn new() -> HashmapStateMachine { HashmapStateMachine { map: HashMap::new(), } } } /// Implementing `state_machine::StateMachine` allows your application specific state machine to be /// used in Raft. Feel encouraged to base yours of one of ours in these examples. impl state_machine::StateMachine for HashmapStateMachine { /// `apply()` is called on when a client's `.propose()` is commited and reaches the state /// machine. At this point it is durable and is going to be applied on at least half the nodes /// within the next couple round trips. fn apply(&mut self, new_value: &[u8]) -> Vec<u8> { // Deserialize let string = String::from_utf8_lossy(new_value); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serde_json::to_string(old_value) }, Put(key, value) => { let old_value = &self.map.insert(key, value); serde_json::to_string(old_value) }, Cas(key, old_check, new) => { if *self.map.get(&key).unwrap() == old_check { let _ = self.map.insert(key, new); serde_json::to_string(&true) } else { serde_json::to_string(&false) } }, }; // Respond. response.unwrap().into_bytes() } /// `query()` is called on when a client's `.query()` is recieved. It does not go through the /// persistent log, it does not mutate the state of the state machine, and it is intended to be /// fast. fn query(&self, query: &[u8]) -> Vec<u8> { // Deserialize let string = String::from_utf8_lossy(query); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serde_json::to_string(old_value) }, _ => panic!("Can't do mutating requests in query"), }; // Respond. response.unwrap().into_bytes() } fn snapshot(&self) -> Vec<u8> { serde_json::to_string(&self.map) .unwrap() .into_bytes() } fn restore_snapshot(&mut self, snapshot_value: Vec<u8>) { self.map = serde_json::from_str(&String::from_utf8_lossy(&snapshot_value)).unwrap(); () } }
// Clients and be stored and reused, or used once and discarded. // There is very small overhead in connecting a new client to a cluster as it must discover and // identify itself to the leader.
random_line_split
macro_rules.rs
<'a> { parser: RefCell<Parser<'a>>, } impl<'a> ParserAnyMacro<'a> { /// Make sure we don't have any tokens left to parse, so we don't /// silently drop anything. `allow_semi` is so that "optional" /// semicolons at the end of normal expressions aren't complained /// about e.g. the semicolon in `macro_rules! kapow { () => { /// panic!(); } }` doesn't get picked up by.parse_expr(), but it's /// allowed to be there. fn ensure_complete_parse(&self, allow_semi: bool) { let mut parser = self.parser.borrow_mut(); if allow_semi && parser.token == token::Semi { parser.bump() } if parser.token!= token::Eof { let token_str = parser.this_token_to_string(); let msg = format!("macro expansion ignores token `{}` and any \ following", token_str); let span = parser.span; parser.span_err(span, &msg[]); } } } impl<'a> MacResult for ParserAnyMacro<'a> { fn make_expr(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Expr>> { let ret = self.parser.borrow_mut().parse_expr(); self.ensure_complete_parse(true); Some(ret) } fn make_pat(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Pat>> { let ret = self.parser.borrow_mut().parse_pat(); self.ensure_complete_parse(false); Some(ret) } fn make_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); // so... do outer attributes attached to the macro invocation // just disappear? This question applies to make_methods, as // well. match parser.parse_item_with_outer_attributes() { Some(item) => ret.push(item), None => break } } self.ensure_complete_parse(false); Some(ret) } fn make_methods(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Method>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => { let attrs = parser.parse_outer_attributes(); ret.push(parser.parse_method(attrs, ast::Inherited)) } } } self.ensure_complete_parse(false); Some(ret) } fn make_stmt(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Stmt>> { let attrs = self.parser.borrow_mut().parse_outer_attributes(); let ret = self.parser.borrow_mut().parse_stmt(attrs); self.ensure_complete_parse(true); Some(ret) } } struct MacroRulesMacroExpander { name: ast::Ident, imported_from: Option<ast::Ident>, lhses: Vec<Rc<NamedMatch>>, rhses: Vec<Rc<NamedMatch>>, } impl TTMacroExpander for MacroRulesMacroExpander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: Span, arg: &[ast::TokenTree]) -> Box<MacResult+'cx> { generic_extension(cx, sp, self.name, self.imported_from, arg, &self.lhses[], &self.rhses[]) } } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>(cx: &'cx ExtCtxt, sp: Span, name: ast::Ident, imported_from: Option<ast::Ident>, arg: &[ast::TokenTree], lhses: &[Rc<NamedMatch>], rhses: &[Rc<NamedMatch>]) -> Box<MacResult+'cx> { if cx.trace_macros() { println!("{}! {{ {} }}", token::get_ident(name), print::pprust::tts_to_string(arg)); } // Which arm's failure should we report? (the one furthest along) let mut best_fail_spot = DUMMY_SP; let mut best_fail_msg = "internal error: ran no matchers".to_string(); for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { TtDelimited(_, ref delim) => &delim.tts[], _ => cx.span_fatal(sp, "malformed macro lhs") }; // `None` is because we're not interpolating let arg_rdr = new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic, None, None, arg.iter() .map(|x| (*x).clone()) .collect(), true); match parse(cx.parse_sess(), cx.cfg(), arg_rdr, lhs_tt) { Success(named_matches) => { let rhs = match *rhses[i] { // okay, what's your transcriber? MatchedNonterminal(NtTT(ref tt)) => { match **tt { // ignore delimiters TtDelimited(_, ref delimed) => delimed.tts.clone(), _ => cx.span_fatal(sp, "macro rhs must be delimited"), } }, _ => cx.span_bug(sp, "bad thing in rhs") }; // rhs has holes ( `$id` and `$(...)` that need filled) let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic, Some(named_matches), imported_from, rhs); let mut p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr); p.check_unknown_macro_variable(); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return box ParserAnyMacro { parser: RefCell::new(p), } as Box<MacResult+'cx> } Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo { best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, Error(sp, ref msg) => cx.span_fatal(sp, &msg[]) } } _ => cx.bug("non-matcher found in parsed lhses") } } cx.span_fatal(best_fail_spot, &best_fail_msg[]); } // Note that macro-by-example's input is also matched against a token tree: // $( $lhs:tt => $rhs:tt );+ // // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. pub fn compile<'cx>(cx: &'cx mut ExtCtxt, def: &ast::MacroDef) -> SyntaxExtension { let lhs_nm = gensym_ident("lhs"); let rhs_nm = gensym_ident("rhs"); // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ //...quasiquoting this would be nice. // These spans won't matter, anyways let match_lhs_tok = MatchNt(lhs_nm, special_idents::tt, token::Plain, token::Plain); let match_rhs_tok = MatchNt(rhs_nm, special_idents::tt, token::Plain, token::Plain); let argument_gram = vec!( TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![ TtToken(DUMMY_SP, match_lhs_tok), TtToken(DUMMY_SP, token::FatArrow), TtToken(DUMMY_SP, match_rhs_tok)], separator: Some(token::Semi), op: ast::OneOrMore, num_captures: 2 })), //to phase into semicolon-termination instead of //semicolon-separation TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![TtToken(DUMMY_SP, token::Semi)], separator: None, op: ast::ZeroOrMore, num_captures: 0 }))); // Parse the macro_rules! invocation (`none` is for no interpolations): let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic, None, None, def.body.clone()); let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(), arg_reader, argument_gram); // Extract the arguments: let lhses = match *argument_map[lhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; for lhs in lhses.iter() { check_lhs_nt_follows(cx, &**lhs, def.span); } let rhses = match *argument_map[rhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") }; let exp = box MacroRulesMacroExpander { name: def.ident, imported_from: def.imported_from, lhses: lhses, rhses: rhses, }; NormalTT(exp, Some(def.span)) } fn check_lhs_nt_follows(cx: &mut ExtCtxt, lhs: &NamedMatch, sp: Span) { // lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where // the entire lhs is those tts. // if ever we get box/deref patterns, this could turn into an `if let // &MatchedNonterminal(NtTT(box TtDelimited(...))) = lhs` let matcher = match lhs { &MatchedNonterminal(NtTT(ref inner)) => match &**inner { &TtDelimited(_, ref tts) => tts.tts.as_slice(), _ => cx.span_bug(sp, "wrong-structured lhs for follow check") }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check") }; check_matcher(cx, matcher.iter(), &Eof); // we don't abort on errors on rejection, the driver will do that for us // after parsing/expansion. we can report every error in every macro this way. } // returns the last token that was checked, for TtSequence. this gets used later on. fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) -> Option<(Span, Token)> where I: Iterator<Item=&'a TokenTree> { use print::pprust::token_to_string; let mut last = None; // 2. For each token T in M: let mut tokens = matcher.peekable(); while let Some(token) = tokens.next() { last = match *token { TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { // ii. If T is a simple NT, look ahead to the next token T' in // M. let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { cx.span_err(sp, format!("`${0}:{1}` is followed by a \ sequence repetition, which is not \ allowed for `{1}` fragments", name.as_str(), frag_spec.as_str()) .as_slice()); Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match &next_token { &Eof => return Some((sp, tok.clone())), _ if is_in_follow(cx, &next_token, frag_spec.as_str()) => continue, next => { cx.span_err(sp, format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next)).as_slice()); continue }, } }, TtSequence(sp, ref seq) => { // iii. Else, T is a complex NT. match seq.separator { // If T has the form $(...)U+ or $(...)U* for some token U, // run the algorithm on the contents with F set to U. If it // accepts, continue, else, reject. Some(ref u) => { let last = check_matcher(cx, seq.tts.iter(), u); match last { // Since the delimiter isn't required after the last // repetition, make sure that the *next* token is // sane. This doesn't actually compute the FIRST of // the rest of the matcher yet, it only considers // single tokens and simple NTs. This is imprecise, // but conservatively correct. Some((span, tok)) => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => { cx.span_err(sp, "sequence repetition followed by \ another sequence repetition, which is not allowed"); Eof }, None => Eof }; check_matcher(cx, Some(&TtToken(span, tok.clone())).into_iter(), &fol) }, None => last, } }, // If T has the form $(...)+ or $(...)*, run the algorithm // on the contents with F set to the token following the // sequence. If it accepts, continue, else, reject.
ParserAnyMacro
identifier_name
macro_rules.rs
.parser.borrow_mut(); if allow_semi && parser.token == token::Semi { parser.bump() } if parser.token!= token::Eof { let token_str = parser.this_token_to_string(); let msg = format!("macro expansion ignores token `{}` and any \ following", token_str); let span = parser.span; parser.span_err(span, &msg[]); } } } impl<'a> MacResult for ParserAnyMacro<'a> { fn make_expr(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Expr>> { let ret = self.parser.borrow_mut().parse_expr(); self.ensure_complete_parse(true); Some(ret) } fn make_pat(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Pat>> { let ret = self.parser.borrow_mut().parse_pat(); self.ensure_complete_parse(false); Some(ret) } fn make_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); // so... do outer attributes attached to the macro invocation // just disappear? This question applies to make_methods, as // well. match parser.parse_item_with_outer_attributes() { Some(item) => ret.push(item), None => break } } self.ensure_complete_parse(false); Some(ret) } fn make_methods(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Method>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => { let attrs = parser.parse_outer_attributes(); ret.push(parser.parse_method(attrs, ast::Inherited)) } } } self.ensure_complete_parse(false); Some(ret) } fn make_stmt(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Stmt>> { let attrs = self.parser.borrow_mut().parse_outer_attributes(); let ret = self.parser.borrow_mut().parse_stmt(attrs); self.ensure_complete_parse(true); Some(ret) } } struct MacroRulesMacroExpander { name: ast::Ident, imported_from: Option<ast::Ident>, lhses: Vec<Rc<NamedMatch>>, rhses: Vec<Rc<NamedMatch>>, } impl TTMacroExpander for MacroRulesMacroExpander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: Span, arg: &[ast::TokenTree]) -> Box<MacResult+'cx> { generic_extension(cx, sp, self.name, self.imported_from, arg, &self.lhses[], &self.rhses[]) } } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>(cx: &'cx ExtCtxt, sp: Span, name: ast::Ident, imported_from: Option<ast::Ident>, arg: &[ast::TokenTree], lhses: &[Rc<NamedMatch>], rhses: &[Rc<NamedMatch>]) -> Box<MacResult+'cx> { if cx.trace_macros() { println!("{}! {{ {} }}", token::get_ident(name), print::pprust::tts_to_string(arg)); } // Which arm's failure should we report? (the one furthest along) let mut best_fail_spot = DUMMY_SP; let mut best_fail_msg = "internal error: ran no matchers".to_string(); for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { TtDelimited(_, ref delim) => &delim.tts[], _ => cx.span_fatal(sp, "malformed macro lhs") }; // `None` is because we're not interpolating let arg_rdr = new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic, None, None, arg.iter() .map(|x| (*x).clone()) .collect(), true); match parse(cx.parse_sess(), cx.cfg(), arg_rdr, lhs_tt) { Success(named_matches) => { let rhs = match *rhses[i] { // okay, what's your transcriber? MatchedNonterminal(NtTT(ref tt)) => { match **tt { // ignore delimiters TtDelimited(_, ref delimed) => delimed.tts.clone(), _ => cx.span_fatal(sp, "macro rhs must be delimited"), } }, _ => cx.span_bug(sp, "bad thing in rhs") }; // rhs has holes ( `$id` and `$(...)` that need filled) let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic, Some(named_matches), imported_from, rhs); let mut p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr); p.check_unknown_macro_variable(); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return box ParserAnyMacro { parser: RefCell::new(p), } as Box<MacResult+'cx> } Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo { best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, Error(sp, ref msg) => cx.span_fatal(sp, &msg[]) } } _ => cx.bug("non-matcher found in parsed lhses") } } cx.span_fatal(best_fail_spot, &best_fail_msg[]); } // Note that macro-by-example's input is also matched against a token tree: // $( $lhs:tt => $rhs:tt );+ // // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. pub fn compile<'cx>(cx: &'cx mut ExtCtxt, def: &ast::MacroDef) -> SyntaxExtension { let lhs_nm = gensym_ident("lhs"); let rhs_nm = gensym_ident("rhs"); // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ //...quasiquoting this would be nice. // These spans won't matter, anyways let match_lhs_tok = MatchNt(lhs_nm, special_idents::tt, token::Plain, token::Plain); let match_rhs_tok = MatchNt(rhs_nm, special_idents::tt, token::Plain, token::Plain); let argument_gram = vec!( TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![ TtToken(DUMMY_SP, match_lhs_tok), TtToken(DUMMY_SP, token::FatArrow), TtToken(DUMMY_SP, match_rhs_tok)], separator: Some(token::Semi), op: ast::OneOrMore, num_captures: 2 })), //to phase into semicolon-termination instead of //semicolon-separation TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![TtToken(DUMMY_SP, token::Semi)], separator: None, op: ast::ZeroOrMore, num_captures: 0 }))); // Parse the macro_rules! invocation (`none` is for no interpolations): let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic, None, None,
arg_reader, argument_gram); // Extract the arguments: let lhses = match *argument_map[lhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; for lhs in lhses.iter() { check_lhs_nt_follows(cx, &**lhs, def.span); } let rhses = match *argument_map[rhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") }; let exp = box MacroRulesMacroExpander { name: def.ident, imported_from: def.imported_from, lhses: lhses, rhses: rhses, }; NormalTT(exp, Some(def.span)) } fn check_lhs_nt_follows(cx: &mut ExtCtxt, lhs: &NamedMatch, sp: Span) { // lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where // the entire lhs is those tts. // if ever we get box/deref patterns, this could turn into an `if let // &MatchedNonterminal(NtTT(box TtDelimited(...))) = lhs` let matcher = match lhs { &MatchedNonterminal(NtTT(ref inner)) => match &**inner { &TtDelimited(_, ref tts) => tts.tts.as_slice(), _ => cx.span_bug(sp, "wrong-structured lhs for follow check") }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check") }; check_matcher(cx, matcher.iter(), &Eof); // we don't abort on errors on rejection, the driver will do that for us // after parsing/expansion. we can report every error in every macro this way. } // returns the last token that was checked, for TtSequence. this gets used later on. fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) -> Option<(Span, Token)> where I: Iterator<Item=&'a TokenTree> { use print::pprust::token_to_string; let mut last = None; // 2. For each token T in M: let mut tokens = matcher.peekable(); while let Some(token) = tokens.next() { last = match *token { TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { // ii. If T is a simple NT, look ahead to the next token T' in // M. let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { cx.span_err(sp, format!("`${0}:{1}` is followed by a \ sequence repetition, which is not \ allowed for `{1}` fragments", name.as_str(), frag_spec.as_str()) .as_slice()); Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match &next_token { &Eof => return Some((sp, tok.clone())), _ if is_in_follow(cx, &next_token, frag_spec.as_str()) => continue, next => { cx.span_err(sp, format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next)).as_slice()); continue }, } }, TtSequence(sp, ref seq) => { // iii. Else, T is a complex NT. match seq.separator { // If T has the form $(...)U+ or $(...)U* for some token U, // run the algorithm on the contents with F set to U. If it // accepts, continue, else, reject. Some(ref u) => { let last = check_matcher(cx, seq.tts.iter(), u); match last { // Since the delimiter isn't required after the last // repetition, make sure that the *next* token is // sane. This doesn't actually compute the FIRST of // the rest of the matcher yet, it only considers // single tokens and simple NTs. This is imprecise, // but conservatively correct. Some((span, tok)) => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => { cx.span_err(sp, "sequence repetition followed by \ another sequence repetition, which is not allowed"); Eof }, None => Eof }; check_matcher(cx, Some(&TtToken(span, tok.clone())).into_iter(), &fol) }, None => last, } }, // If T has the form $(...)+ or $(...)*, run the algorithm // on the contents with F set to the token following the // sequence. If it accepts, continue, else, reject. None => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => {
def.body.clone()); let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(),
random_line_split
macro_rules.rs
parser.borrow_mut(); if allow_semi && parser.token == token::Semi { parser.bump() } if parser.token!= token::Eof { let token_str = parser.this_token_to_string(); let msg = format!("macro expansion ignores token `{}` and any \ following", token_str); let span = parser.span; parser.span_err(span, &msg[]); } } } impl<'a> MacResult for ParserAnyMacro<'a> { fn make_expr(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Expr>> { let ret = self.parser.borrow_mut().parse_expr(); self.ensure_complete_parse(true); Some(ret) } fn make_pat(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Pat>> { let ret = self.parser.borrow_mut().parse_pat(); self.ensure_complete_parse(false); Some(ret) } fn make_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); // so... do outer attributes attached to the macro invocation // just disappear? This question applies to make_methods, as // well. match parser.parse_item_with_outer_attributes() { Some(item) => ret.push(item), None => break } } self.ensure_complete_parse(false); Some(ret) } fn make_methods(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Method>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => { let attrs = parser.parse_outer_attributes(); ret.push(parser.parse_method(attrs, ast::Inherited)) } } } self.ensure_complete_parse(false); Some(ret) } fn make_stmt(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Stmt>> { let attrs = self.parser.borrow_mut().parse_outer_attributes(); let ret = self.parser.borrow_mut().parse_stmt(attrs); self.ensure_complete_parse(true); Some(ret) } } struct MacroRulesMacroExpander { name: ast::Ident, imported_from: Option<ast::Ident>, lhses: Vec<Rc<NamedMatch>>, rhses: Vec<Rc<NamedMatch>>, } impl TTMacroExpander for MacroRulesMacroExpander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: Span, arg: &[ast::TokenTree]) -> Box<MacResult+'cx> { generic_extension(cx, sp, self.name, self.imported_from, arg, &self.lhses[], &self.rhses[]) } } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>(cx: &'cx ExtCtxt, sp: Span, name: ast::Ident, imported_from: Option<ast::Ident>, arg: &[ast::TokenTree], lhses: &[Rc<NamedMatch>], rhses: &[Rc<NamedMatch>]) -> Box<MacResult+'cx> { if cx.trace_macros() { println!("{}! {{ {} }}", token::get_ident(name), print::pprust::tts_to_string(arg)); } // Which arm's failure should we report? (the one furthest along) let mut best_fail_spot = DUMMY_SP; let mut best_fail_msg = "internal error: ran no matchers".to_string(); for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { TtDelimited(_, ref delim) => &delim.tts[], _ => cx.span_fatal(sp, "malformed macro lhs") }; // `None` is because we're not interpolating let arg_rdr = new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic, None, None, arg.iter() .map(|x| (*x).clone()) .collect(), true); match parse(cx.parse_sess(), cx.cfg(), arg_rdr, lhs_tt) { Success(named_matches) => { let rhs = match *rhses[i] { // okay, what's your transcriber? MatchedNonterminal(NtTT(ref tt)) => { match **tt { // ignore delimiters TtDelimited(_, ref delimed) => delimed.tts.clone(), _ => cx.span_fatal(sp, "macro rhs must be delimited"), } }, _ => cx.span_bug(sp, "bad thing in rhs") }; // rhs has holes ( `$id` and `$(...)` that need filled) let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic, Some(named_matches), imported_from, rhs); let mut p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr); p.check_unknown_macro_variable(); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return box ParserAnyMacro { parser: RefCell::new(p), } as Box<MacResult+'cx> } Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo { best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, Error(sp, ref msg) => cx.span_fatal(sp, &msg[]) } } _ => cx.bug("non-matcher found in parsed lhses") } } cx.span_fatal(best_fail_spot, &best_fail_msg[]); } // Note that macro-by-example's input is also matched against a token tree: // $( $lhs:tt => $rhs:tt );+ // // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. pub fn compile<'cx>(cx: &'cx mut ExtCtxt, def: &ast::MacroDef) -> SyntaxExtension
op: ast::OneOrMore, num_captures: 2 })), //to phase into semicolon-termination instead of //semicolon-separation TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![TtToken(DUMMY_SP, token::Semi)], separator: None, op: ast::ZeroOrMore, num_captures: 0 }))); // Parse the macro_rules! invocation (`none` is for no interpolations): let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic, None, None, def.body.clone()); let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(), arg_reader, argument_gram); // Extract the arguments: let lhses = match *argument_map[lhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; for lhs in lhses.iter() { check_lhs_nt_follows(cx, &**lhs, def.span); } let rhses = match *argument_map[rhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") }; let exp = box MacroRulesMacroExpander { name: def.ident, imported_from: def.imported_from, lhses: lhses, rhses: rhses, }; NormalTT(exp, Some(def.span)) } fn check_lhs_nt_follows(cx: &mut ExtCtxt, lhs: &NamedMatch, sp: Span) { // lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where // the entire lhs is those tts. // if ever we get box/deref patterns, this could turn into an `if let // &MatchedNonterminal(NtTT(box TtDelimited(...))) = lhs` let matcher = match lhs { &MatchedNonterminal(NtTT(ref inner)) => match &**inner { &TtDelimited(_, ref tts) => tts.tts.as_slice(), _ => cx.span_bug(sp, "wrong-structured lhs for follow check") }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check") }; check_matcher(cx, matcher.iter(), &Eof); // we don't abort on errors on rejection, the driver will do that for us // after parsing/expansion. we can report every error in every macro this way. } // returns the last token that was checked, for TtSequence. this gets used later on. fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) -> Option<(Span, Token)> where I: Iterator<Item=&'a TokenTree> { use print::pprust::token_to_string; let mut last = None; // 2. For each token T in M: let mut tokens = matcher.peekable(); while let Some(token) = tokens.next() { last = match *token { TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { // ii. If T is a simple NT, look ahead to the next token T' in // M. let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { cx.span_err(sp, format!("`${0}:{1}` is followed by a \ sequence repetition, which is not \ allowed for `{1}` fragments", name.as_str(), frag_spec.as_str()) .as_slice()); Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match &next_token { &Eof => return Some((sp, tok.clone())), _ if is_in_follow(cx, &next_token, frag_spec.as_str()) => continue, next => { cx.span_err(sp, format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next)).as_slice()); continue }, } }, TtSequence(sp, ref seq) => { // iii. Else, T is a complex NT. match seq.separator { // If T has the form $(...)U+ or $(...)U* for some token U, // run the algorithm on the contents with F set to U. If it // accepts, continue, else, reject. Some(ref u) => { let last = check_matcher(cx, seq.tts.iter(), u); match last { // Since the delimiter isn't required after the last // repetition, make sure that the *next* token is // sane. This doesn't actually compute the FIRST of // the rest of the matcher yet, it only considers // single tokens and simple NTs. This is imprecise, // but conservatively correct. Some((span, tok)) => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => { cx.span_err(sp, "sequence repetition followed by \ another sequence repetition, which is not allowed"); Eof }, None => Eof }; check_matcher(cx, Some(&TtToken(span, tok.clone())).into_iter(), &fol) }, None => last, } }, // If T has the form $(...)+ or $(...)*, run the algorithm // on the contents with F set to the token following the // sequence. If it accepts, continue, else, reject. None => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => {
{ let lhs_nm = gensym_ident("lhs"); let rhs_nm = gensym_ident("rhs"); // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ // ...quasiquoting this would be nice. // These spans won't matter, anyways let match_lhs_tok = MatchNt(lhs_nm, special_idents::tt, token::Plain, token::Plain); let match_rhs_tok = MatchNt(rhs_nm, special_idents::tt, token::Plain, token::Plain); let argument_gram = vec!( TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![ TtToken(DUMMY_SP, match_lhs_tok), TtToken(DUMMY_SP, token::FatArrow), TtToken(DUMMY_SP, match_rhs_tok)], separator: Some(token::Semi),
identifier_body
grpc_status.rs
// copied from https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/status.h /// gRPC status constants. #[allow(dead_code)] #[derive(Copy, Clone, Debug)] pub enum GrpcStatus { /* Not an error; returned on success */ Ok = 0, /* The operation was cancelled (typically by the caller). */ Cancelled = 1, /* Unknown error. An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error. */ Unknown = 2, /* Client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name). */ Argument = 3, /* Deadline expired before operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire. */ DeadlineExceeded = 4, /* Some requested entity (e.g., file or directory) was not found. */ NotFound = 5, /* Some entity that we attempted to create (e.g., file or directory) already exists. */ AlreadyExists = 6, /* The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). */ PermissionDenied = 7, /* The request does not have valid authentication credentials for the operation. */ Unauthenticated = 16, /* Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. */ ResourceExhausted = 8, /* Operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to a non-directory, etc. A litmus test that may help a service implementor in deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher-level (e.g., restarting a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless they have first fixed up the directory by deleting files from it. (d) Use FAILED_PRECONDITION if the client performs conditional REST Get/Update/Delete on a resource and the resource on the server does not match the condition. E.g., conflicting read-modify-write on the same resource. */ FailedPrecondition = 9, /* The operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc. See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE. */ Aborted = 10, /* Operation was attempted past the valid range. E.g., seeking or reading past end of file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done. */ OutOfRange = 11, /* Operation is not implemented or not supported/enabled in this service. */ Unimplemented = 12, /* Internal errors. Means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken. */ Internal = 13, /* The service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff. See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE. */ Unavailable = 14, /* Unrecoverable data loss or corruption. */ DataLoss = 15, } const ALL_STATUSES: &[GrpcStatus] = &[ GrpcStatus::Ok, GrpcStatus::Cancelled, GrpcStatus::Unknown, GrpcStatus::Argument, GrpcStatus::DeadlineExceeded, GrpcStatus::NotFound, GrpcStatus::AlreadyExists, GrpcStatus::PermissionDenied, GrpcStatus::Unauthenticated, GrpcStatus::ResourceExhausted, GrpcStatus::FailedPrecondition, GrpcStatus::Aborted, GrpcStatus::OutOfRange, GrpcStatus::Unimplemented, GrpcStatus::Internal, GrpcStatus::Unavailable, GrpcStatus::DataLoss, ]; impl GrpcStatus { /// GrpcStatus as protocol numeric code pub fn code(&self) -> u32 { *self as u32 } /// Find GrpcStatus enum variant by code pub fn
(code: u32) -> Option<GrpcStatus> { ALL_STATUSES.into_iter().cloned().find(|s| s.code() == code) } /// Find GrpcStatus enum variant by code or return default value pub fn from_code_or_unknown(code: u32) -> GrpcStatus { GrpcStatus::from_code(code).unwrap_or(GrpcStatus::Unknown) } }
from_code
identifier_name
grpc_status.rs
// copied from https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/status.h /// gRPC status constants. #[allow(dead_code)] #[derive(Copy, Clone, Debug)] pub enum GrpcStatus { /* Not an error; returned on success */ Ok = 0, /* The operation was cancelled (typically by the caller). */ Cancelled = 1, /* Unknown error. An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error. */ Unknown = 2, /* Client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name). */ Argument = 3, /* Deadline expired before operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire. */ DeadlineExceeded = 4, /* Some requested entity (e.g., file or directory) was not found. */ NotFound = 5, /* Some entity that we attempted to create (e.g., file or directory) already exists. */ AlreadyExists = 6, /* The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). */ PermissionDenied = 7, /* The request does not have valid authentication credentials for the operation. */ Unauthenticated = 16, /* Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. */ ResourceExhausted = 8, /* Operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to a non-directory, etc. A litmus test that may help a service implementor in deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher-level (e.g., restarting a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless they have first fixed up the directory by deleting files from it. (d) Use FAILED_PRECONDITION if the client performs conditional REST Get/Update/Delete on a resource and the resource on the server does not match the condition. E.g., conflicting read-modify-write on the same resource. */ FailedPrecondition = 9, /* The operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc. See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE. */ Aborted = 10, /* Operation was attempted past the valid range. E.g., seeking or reading past end of file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done. */ OutOfRange = 11, /* Operation is not implemented or not supported/enabled in this service. */ Unimplemented = 12, /* Internal errors. Means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken. */ Internal = 13, /* The service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff. See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE. */ Unavailable = 14, /* Unrecoverable data loss or corruption. */ DataLoss = 15, } const ALL_STATUSES: &[GrpcStatus] = &[ GrpcStatus::Ok, GrpcStatus::Cancelled, GrpcStatus::Unknown, GrpcStatus::Argument, GrpcStatus::DeadlineExceeded, GrpcStatus::NotFound, GrpcStatus::AlreadyExists, GrpcStatus::PermissionDenied, GrpcStatus::Unauthenticated, GrpcStatus::ResourceExhausted, GrpcStatus::FailedPrecondition, GrpcStatus::Aborted, GrpcStatus::OutOfRange, GrpcStatus::Unimplemented, GrpcStatus::Internal, GrpcStatus::Unavailable, GrpcStatus::DataLoss, ]; impl GrpcStatus { /// GrpcStatus as protocol numeric code pub fn code(&self) -> u32 { *self as u32 } /// Find GrpcStatus enum variant by code pub fn from_code(code: u32) -> Option<GrpcStatus> { ALL_STATUSES.into_iter().cloned().find(|s| s.code() == code) } /// Find GrpcStatus enum variant by code or return default value pub fn from_code_or_unknown(code: u32) -> GrpcStatus
}
{ GrpcStatus::from_code(code).unwrap_or(GrpcStatus::Unknown) }
identifier_body
grpc_status.rs
// copied from https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/status.h /// gRPC status constants. #[allow(dead_code)] #[derive(Copy, Clone, Debug)] pub enum GrpcStatus { /* Not an error; returned on success */ Ok = 0, /* The operation was cancelled (typically by the caller). */ Cancelled = 1, /* Unknown error. An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error. */ Unknown = 2, /* Client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name). */ Argument = 3, /* Deadline expired before operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire. */ DeadlineExceeded = 4, /* Some requested entity (e.g., file or directory) was not found. */ NotFound = 5, /* Some entity that we attempted to create (e.g., file or directory) already exists. */ AlreadyExists = 6, /* The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). */ PermissionDenied = 7, /* The request does not have valid authentication credentials for the operation. */ Unauthenticated = 16, /* Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. */ ResourceExhausted = 8, /* Operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to a non-directory, etc. A litmus test that may help a service implementor in deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher-level (e.g., restarting a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless they have first fixed up the directory by deleting files from it. (d) Use FAILED_PRECONDITION if the client performs conditional REST Get/Update/Delete on a resource and the resource on the server does not match the condition. E.g., conflicting read-modify-write on the same resource. */ FailedPrecondition = 9, /* The operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc. See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE. */ Aborted = 10,
/* Operation was attempted past the valid range. E.g., seeking or reading past end of file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done. */ OutOfRange = 11, /* Operation is not implemented or not supported/enabled in this service. */ Unimplemented = 12, /* Internal errors. Means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken. */ Internal = 13, /* The service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff. See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE. */ Unavailable = 14, /* Unrecoverable data loss or corruption. */ DataLoss = 15, } const ALL_STATUSES: &[GrpcStatus] = &[ GrpcStatus::Ok, GrpcStatus::Cancelled, GrpcStatus::Unknown, GrpcStatus::Argument, GrpcStatus::DeadlineExceeded, GrpcStatus::NotFound, GrpcStatus::AlreadyExists, GrpcStatus::PermissionDenied, GrpcStatus::Unauthenticated, GrpcStatus::ResourceExhausted, GrpcStatus::FailedPrecondition, GrpcStatus::Aborted, GrpcStatus::OutOfRange, GrpcStatus::Unimplemented, GrpcStatus::Internal, GrpcStatus::Unavailable, GrpcStatus::DataLoss, ]; impl GrpcStatus { /// GrpcStatus as protocol numeric code pub fn code(&self) -> u32 { *self as u32 } /// Find GrpcStatus enum variant by code pub fn from_code(code: u32) -> Option<GrpcStatus> { ALL_STATUSES.into_iter().cloned().find(|s| s.code() == code) } /// Find GrpcStatus enum variant by code or return default value pub fn from_code_or_unknown(code: u32) -> GrpcStatus { GrpcStatus::from_code(code).unwrap_or(GrpcStatus::Unknown) } }
random_line_split
util.rs
use std::fs::File; use std::io::BufReader; use std::io::Error; use std::io::prelude::*; use std::path::Path; pub fn get_mnist_vector(fname: &str) -> Result<Vec<Vec<f32>>, Error> { let path = Path::new(fname); match File::open(&path) { Ok(file) => { let mut new_vec: Vec<Vec<f32>> = Vec::new(); let reader = BufReader::new(file); for line in reader.lines() { match line { Ok(s) => { new_vec.push(mnist_test_to_vector(&s)); } Err(reason) => { return Err(reason); } }; } Ok(new_vec) } Err(reason) => Err(reason), } } pub fn mnist_test_to_vector(line: &str) -> Vec<f32> { line.trim().split(' ').map(|instr| instr.parse().unwrap()).collect() } pub mod xvecs { extern crate byteorder; use std::fs::File; use std::path::Path; use std::io::{BufReader, Result}; use self::byteorder::{ReadBytesExt, LittleEndian}; pub fn read_fvecs_file(fname: &str) -> Result<Vec<Vec<f32>>> { let path = Path::new(fname); let f = try!(File::open(path)); let mut br = BufReader::new(f); let mut output_vec = Vec::new(); while let Ok(i) = br.read_u32::<LittleEndian>() { let ind = i as usize; let mut line_vec = vec![0.0 as f32; ind]; for j in 0..ind { line_vec[j] = try!(br.read_f32::<LittleEndian>()); } output_vec.push(line_vec); } Ok(output_vec) } pub fn read_ivecs_file(fname: &str) -> Result<Vec<Vec<i32>>> { let path = Path::new(fname); let f = try!(File::open(path)); let mut br = BufReader::new(f); let mut output_vec = Vec::new(); while let Ok(i) = br.read_u32::<LittleEndian>() { let ind = i as usize; let mut line_vec = vec![0 as i32; ind]; for j in 0..ind { line_vec[j] = try!(br.read_i32::<LittleEndian>()); } output_vec.push(line_vec); } Ok(output_vec) } } #[cfg(test)] mod tests { use super::*; use super::xvecs::*; #[test] fn test_read_mnist_file() { let fname: &str = "./mnist1k.dts"; match get_mnist_vector(fname) { Ok(v) => println!("{:?}", v), Err(reason) => panic!("couldn't open because {}", reason), } } #[test] fn test_mnist_line_to_vector() { let my_vec = vec![0.0000, 1.0000, 0.00000, 0.20000]; let my_string = "0.0000 1.0000 0.00000 0.20000"; assert!(my_vec == mnist_test_to_vector(&my_string)); } #[test] fn test_read_fvecs_file()
}
{ let y = read_fvecs_file("./sift_query.fvecs").unwrap(); println!("{} vectors, length of first is {}", y.len(), y[0].len()); }
identifier_body
util.rs
use std::fs::File; use std::io::BufReader; use std::io::Error; use std::io::prelude::*; use std::path::Path; pub fn get_mnist_vector(fname: &str) -> Result<Vec<Vec<f32>>, Error> { let path = Path::new(fname); match File::open(&path) { Ok(file) => { let mut new_vec: Vec<Vec<f32>> = Vec::new(); let reader = BufReader::new(file); for line in reader.lines() { match line { Ok(s) => { new_vec.push(mnist_test_to_vector(&s)); } Err(reason) => { return Err(reason); } }; } Ok(new_vec) } Err(reason) => Err(reason), } } pub fn mnist_test_to_vector(line: &str) -> Vec<f32> { line.trim().split(' ').map(|instr| instr.parse().unwrap()).collect() } pub mod xvecs { extern crate byteorder; use std::fs::File; use std::path::Path; use std::io::{BufReader, Result}; use self::byteorder::{ReadBytesExt, LittleEndian}; pub fn
(fname: &str) -> Result<Vec<Vec<f32>>> { let path = Path::new(fname); let f = try!(File::open(path)); let mut br = BufReader::new(f); let mut output_vec = Vec::new(); while let Ok(i) = br.read_u32::<LittleEndian>() { let ind = i as usize; let mut line_vec = vec![0.0 as f32; ind]; for j in 0..ind { line_vec[j] = try!(br.read_f32::<LittleEndian>()); } output_vec.push(line_vec); } Ok(output_vec) } pub fn read_ivecs_file(fname: &str) -> Result<Vec<Vec<i32>>> { let path = Path::new(fname); let f = try!(File::open(path)); let mut br = BufReader::new(f); let mut output_vec = Vec::new(); while let Ok(i) = br.read_u32::<LittleEndian>() { let ind = i as usize; let mut line_vec = vec![0 as i32; ind]; for j in 0..ind { line_vec[j] = try!(br.read_i32::<LittleEndian>()); } output_vec.push(line_vec); } Ok(output_vec) } } #[cfg(test)] mod tests { use super::*; use super::xvecs::*; #[test] fn test_read_mnist_file() { let fname: &str = "./mnist1k.dts"; match get_mnist_vector(fname) { Ok(v) => println!("{:?}", v), Err(reason) => panic!("couldn't open because {}", reason), } } #[test] fn test_mnist_line_to_vector() { let my_vec = vec![0.0000, 1.0000, 0.00000, 0.20000]; let my_string = "0.0000 1.0000 0.00000 0.20000"; assert!(my_vec == mnist_test_to_vector(&my_string)); } #[test] fn test_read_fvecs_file() { let y = read_fvecs_file("./sift_query.fvecs").unwrap(); println!("{} vectors, length of first is {}", y.len(), y[0].len()); } }
read_fvecs_file
identifier_name
util.rs
use std::fs::File; use std::io::BufReader; use std::io::Error; use std::io::prelude::*; use std::path::Path; pub fn get_mnist_vector(fname: &str) -> Result<Vec<Vec<f32>>, Error> { let path = Path::new(fname); match File::open(&path) { Ok(file) => { let mut new_vec: Vec<Vec<f32>> = Vec::new(); let reader = BufReader::new(file); for line in reader.lines() { match line { Ok(s) => { new_vec.push(mnist_test_to_vector(&s)); } Err(reason) => { return Err(reason); } }; } Ok(new_vec) } Err(reason) => Err(reason), } } pub fn mnist_test_to_vector(line: &str) -> Vec<f32> { line.trim().split(' ').map(|instr| instr.parse().unwrap()).collect() } pub mod xvecs { extern crate byteorder; use std::fs::File; use std::path::Path; use std::io::{BufReader, Result}; use self::byteorder::{ReadBytesExt, LittleEndian}; pub fn read_fvecs_file(fname: &str) -> Result<Vec<Vec<f32>>> { let path = Path::new(fname); let f = try!(File::open(path)); let mut br = BufReader::new(f); let mut output_vec = Vec::new(); while let Ok(i) = br.read_u32::<LittleEndian>() { let ind = i as usize; let mut line_vec = vec![0.0 as f32; ind]; for j in 0..ind { line_vec[j] = try!(br.read_f32::<LittleEndian>()); } output_vec.push(line_vec); } Ok(output_vec) } pub fn read_ivecs_file(fname: &str) -> Result<Vec<Vec<i32>>> { let path = Path::new(fname); let f = try!(File::open(path)); let mut br = BufReader::new(f); let mut output_vec = Vec::new(); while let Ok(i) = br.read_u32::<LittleEndian>() { let ind = i as usize; let mut line_vec = vec![0 as i32; ind]; for j in 0..ind { line_vec[j] = try!(br.read_i32::<LittleEndian>()); } output_vec.push(line_vec); } Ok(output_vec) } } #[cfg(test)] mod tests { use super::*; use super::xvecs::*; #[test] fn test_read_mnist_file() { let fname: &str = "./mnist1k.dts"; match get_mnist_vector(fname) { Ok(v) => println!("{:?}", v), Err(reason) => panic!("couldn't open because {}", reason), } } #[test] fn test_mnist_line_to_vector() { let my_vec = vec![0.0000, 1.0000, 0.00000, 0.20000]; let my_string = "0.0000 1.0000 0.00000 0.20000"; assert!(my_vec == mnist_test_to_vector(&my_string)); } #[test]
}
fn test_read_fvecs_file() { let y = read_fvecs_file("./sift_query.fvecs").unwrap(); println!("{} vectors, length of first is {}", y.len(), y[0].len()); }
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! An actor-based remote devtools server implementation. Only tested with //! nightly Firefox versions at time of writing. Largely based on //! reverse-engineering of Firefox chrome devtool logs and reading of //! [code](http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/). #![crate_name = "devtools"] #![crate_type = "rlib"] #![feature(int_uint, box_syntax, io, old_io, core, rustc_private)] #![feature(collections, std_misc)] #![allow(non_snake_case)] #[macro_use] extern crate log; extern crate collections; extern crate core; extern crate devtools_traits; extern crate "rustc-serialize" as rustc_serialize; extern crate msg; extern crate time; extern crate util; use actor::{Actor, ActorRegistry}; use actors::console::ConsoleActor; use actors::inspector::InspectorActor; use actors::root::RootActor; use actors::tab::TabActor; use protocol::JsonPacketStream; use devtools_traits::{ConsoleMessage, DevtoolsControlMsg}; use devtools_traits::{DevtoolsPageInfo, DevtoolScriptControlMsg}; use msg::constellation_msg::PipelineId; use util::task::spawn_named; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::mpsc::TryRecvError::{Disconnected, Empty}; use std::old_io::{TcpListener, TcpStream}; use std::old_io::{Acceptor, Listener, TimedOut}; use std::sync::{Arc, Mutex}; use time::precise_time_ns; mod actor; /// Corresponds to http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/ mod actors { pub mod console; pub mod inspector; pub mod root; pub mod tab; } mod protocol; #[derive(RustcEncodable)] struct ConsoleAPICall { from: String, __type__: String, message: ConsoleMsg, } #[derive(RustcEncodable)] struct ConsoleMsg { level: String, timeStamp: u64, arguments: Vec<String>, filename: String, lineNumber: u32, columnNumber: u32, } /// Spin up a devtools server that listens for connections on the specified port. pub fn start_server(port: u16) -> Sender<DevtoolsControlMsg> { let (sender, receiver) = channel(); spawn_named("Devtools".to_owned(), move || { run_server(receiver, port) }); sender } static POLL_TIMEOUT: u64 = 300; fn run_server(receiver: Receiver<DevtoolsControlMsg>, port: u16) { let listener = TcpListener::bind(&*format!("{}:{}", "127.0.0.1", port)); // bind the listener to the specified address let mut acceptor = listener.listen().unwrap(); acceptor.set_timeout(Some(POLL_TIMEOUT)); let mut registry = ActorRegistry::new(); let root = box RootActor { tabs: vec!(), }; registry.register(root); registry.find::<RootActor>("root"); let actors = Arc::new(Mutex::new(registry)); let mut accepted_connections: Vec<TcpStream> = Vec::new(); let mut actor_pipelines: HashMap<PipelineId, String> = HashMap::new(); /// Process the input from a single devtools client until EOF. fn handle_client(actors: Arc<Mutex<ActorRegistry>>, mut stream: TcpStream) { println!("connection established to {}", stream.peer_name().unwrap()); { let actors = actors.lock().unwrap(); let msg = actors.find::<RootActor>("root").encodable(); stream.write_json_packet(&msg); } 'outer: loop { match stream.read_json_packet() { Ok(json_packet) => { let mut actors = actors.lock().unwrap(); match actors.handle_message(json_packet.as_object().unwrap(), &mut stream) { Ok(()) => {}, Err(()) => { println!("error: devtools actor stopped responding"); let _ = stream.close_read(); let _ = stream.close_write(); break 'outer } } } Err(e) => { println!("error: {}", e.desc); break 'outer } } } } // We need separate actor representations for each script global that exists; // clients can theoretically connect to multiple globals simultaneously. // TODO: move this into the root or tab modules? fn handle_new_global(actors: Arc<Mutex<ActorRegistry>>, pipeline: PipelineId, sender: Sender<DevtoolScriptControlMsg>, actor_pipelines: &mut HashMap<PipelineId, String>, page_info: DevtoolsPageInfo) { let mut actors = actors.lock().unwrap(); //TODO: move all this actor creation into a constructor method on TabActor let (tab, console, inspector) = { let console = ConsoleActor { name: actors.new_name("console"), script_chan: sender.clone(), pipeline: pipeline, streams: RefCell::new(Vec::new()), }; let inspector = InspectorActor { name: actors.new_name("inspector"), walker: RefCell::new(None), pageStyle: RefCell::new(None), highlighter: RefCell::new(None), script_chan: sender, pipeline: pipeline, }; let DevtoolsPageInfo { title, url } = page_info; let tab = TabActor { name: actors.new_name("tab"), title: title, url: url.serialize(), console: console.name(), inspector: inspector.name(), }; let root = actors.find_mut::<RootActor>("root"); root.tabs.push(tab.name.clone()); (tab, console, inspector) }; actor_pipelines.insert(pipeline, tab.name.clone()); actors.register(box tab); actors.register(box console); actors.register(box inspector); } fn handle_console_message(actors: Arc<Mutex<ActorRegistry>>, id: PipelineId, console_message: ConsoleMessage, actor_pipelines: &HashMap<PipelineId, String>) { let console_actor_name = find_console_actor(actors.clone(), id, actor_pipelines); let actors = actors.lock().unwrap(); let console_actor = actors.find::<ConsoleActor>(&console_actor_name); match console_message { ConsoleMessage::LogMessage(message, filename, lineNumber, columnNumber) => { let msg = ConsoleAPICall { from: console_actor.name.clone(), __type__: "consoleAPICall".to_string(), message: ConsoleMsg { level: "log".to_string(), timeStamp: precise_time_ns(), arguments: vec!(message), filename: filename, lineNumber: lineNumber, columnNumber: columnNumber, }, }; for stream in console_actor.streams.borrow_mut().iter_mut() { stream.write_json_packet(&msg); } } } } fn find_console_actor(actors: Arc<Mutex<ActorRegistry>>, id: PipelineId, actor_pipelines: &HashMap<PipelineId, String>) -> String { let actors = actors.lock().unwrap(); let ref tab_actor_name = (*actor_pipelines)[id]; let tab_actor = actors.find::<TabActor>(tab_actor_name); let console_actor_name = tab_actor.console.clone(); return console_actor_name; } //TODO: figure out some system that allows us to watch for new connections, // shut down existing ones at arbitrary times, and also watch for messages // from multiple script tasks simultaneously. Polling for new connections // for 300ms and then checking the receiver is not a good compromise // (and makes Servo hang on exit if there's an open connection, no less). // accept connections and process them, spawning a new tasks for each one loop { match acceptor.accept() { Err(ref e) if e.kind == TimedOut => { match receiver.try_recv() { Ok(DevtoolsControlMsg::ServerExitMsg) | Err(Disconnected) => break, Ok(DevtoolsControlMsg::NewGlobal(id, sender, pageinfo)) => handle_new_global(actors.clone(), id,sender, &mut actor_pipelines,
&actor_pipelines), Err(Empty) => acceptor.set_timeout(Some(POLL_TIMEOUT)), } } Err(_e) => { /* connection failed */ } Ok(stream) => { let actors = actors.clone(); accepted_connections.push(stream.clone()); spawn_named("DevtoolsClientHandler".to_owned(), move || { // connection succeeded handle_client(actors, stream.clone()) }) } } } for connection in accepted_connections.iter_mut() { let _read = connection.close_read(); let _write = connection.close_write(); } }
pageinfo), Ok(DevtoolsControlMsg::SendConsoleMessage(id, console_message)) => handle_console_message(actors.clone(), id, console_message,
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! An actor-based remote devtools server implementation. Only tested with //! nightly Firefox versions at time of writing. Largely based on //! reverse-engineering of Firefox chrome devtool logs and reading of //! [code](http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/). #![crate_name = "devtools"] #![crate_type = "rlib"] #![feature(int_uint, box_syntax, io, old_io, core, rustc_private)] #![feature(collections, std_misc)] #![allow(non_snake_case)] #[macro_use] extern crate log; extern crate collections; extern crate core; extern crate devtools_traits; extern crate "rustc-serialize" as rustc_serialize; extern crate msg; extern crate time; extern crate util; use actor::{Actor, ActorRegistry}; use actors::console::ConsoleActor; use actors::inspector::InspectorActor; use actors::root::RootActor; use actors::tab::TabActor; use protocol::JsonPacketStream; use devtools_traits::{ConsoleMessage, DevtoolsControlMsg}; use devtools_traits::{DevtoolsPageInfo, DevtoolScriptControlMsg}; use msg::constellation_msg::PipelineId; use util::task::spawn_named; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::mpsc::TryRecvError::{Disconnected, Empty}; use std::old_io::{TcpListener, TcpStream}; use std::old_io::{Acceptor, Listener, TimedOut}; use std::sync::{Arc, Mutex}; use time::precise_time_ns; mod actor; /// Corresponds to http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/ mod actors { pub mod console; pub mod inspector; pub mod root; pub mod tab; } mod protocol; #[derive(RustcEncodable)] struct ConsoleAPICall { from: String, __type__: String, message: ConsoleMsg, } #[derive(RustcEncodable)] struct
{ level: String, timeStamp: u64, arguments: Vec<String>, filename: String, lineNumber: u32, columnNumber: u32, } /// Spin up a devtools server that listens for connections on the specified port. pub fn start_server(port: u16) -> Sender<DevtoolsControlMsg> { let (sender, receiver) = channel(); spawn_named("Devtools".to_owned(), move || { run_server(receiver, port) }); sender } static POLL_TIMEOUT: u64 = 300; fn run_server(receiver: Receiver<DevtoolsControlMsg>, port: u16) { let listener = TcpListener::bind(&*format!("{}:{}", "127.0.0.1", port)); // bind the listener to the specified address let mut acceptor = listener.listen().unwrap(); acceptor.set_timeout(Some(POLL_TIMEOUT)); let mut registry = ActorRegistry::new(); let root = box RootActor { tabs: vec!(), }; registry.register(root); registry.find::<RootActor>("root"); let actors = Arc::new(Mutex::new(registry)); let mut accepted_connections: Vec<TcpStream> = Vec::new(); let mut actor_pipelines: HashMap<PipelineId, String> = HashMap::new(); /// Process the input from a single devtools client until EOF. fn handle_client(actors: Arc<Mutex<ActorRegistry>>, mut stream: TcpStream) { println!("connection established to {}", stream.peer_name().unwrap()); { let actors = actors.lock().unwrap(); let msg = actors.find::<RootActor>("root").encodable(); stream.write_json_packet(&msg); } 'outer: loop { match stream.read_json_packet() { Ok(json_packet) => { let mut actors = actors.lock().unwrap(); match actors.handle_message(json_packet.as_object().unwrap(), &mut stream) { Ok(()) => {}, Err(()) => { println!("error: devtools actor stopped responding"); let _ = stream.close_read(); let _ = stream.close_write(); break 'outer } } } Err(e) => { println!("error: {}", e.desc); break 'outer } } } } // We need separate actor representations for each script global that exists; // clients can theoretically connect to multiple globals simultaneously. // TODO: move this into the root or tab modules? fn handle_new_global(actors: Arc<Mutex<ActorRegistry>>, pipeline: PipelineId, sender: Sender<DevtoolScriptControlMsg>, actor_pipelines: &mut HashMap<PipelineId, String>, page_info: DevtoolsPageInfo) { let mut actors = actors.lock().unwrap(); //TODO: move all this actor creation into a constructor method on TabActor let (tab, console, inspector) = { let console = ConsoleActor { name: actors.new_name("console"), script_chan: sender.clone(), pipeline: pipeline, streams: RefCell::new(Vec::new()), }; let inspector = InspectorActor { name: actors.new_name("inspector"), walker: RefCell::new(None), pageStyle: RefCell::new(None), highlighter: RefCell::new(None), script_chan: sender, pipeline: pipeline, }; let DevtoolsPageInfo { title, url } = page_info; let tab = TabActor { name: actors.new_name("tab"), title: title, url: url.serialize(), console: console.name(), inspector: inspector.name(), }; let root = actors.find_mut::<RootActor>("root"); root.tabs.push(tab.name.clone()); (tab, console, inspector) }; actor_pipelines.insert(pipeline, tab.name.clone()); actors.register(box tab); actors.register(box console); actors.register(box inspector); } fn handle_console_message(actors: Arc<Mutex<ActorRegistry>>, id: PipelineId, console_message: ConsoleMessage, actor_pipelines: &HashMap<PipelineId, String>) { let console_actor_name = find_console_actor(actors.clone(), id, actor_pipelines); let actors = actors.lock().unwrap(); let console_actor = actors.find::<ConsoleActor>(&console_actor_name); match console_message { ConsoleMessage::LogMessage(message, filename, lineNumber, columnNumber) => { let msg = ConsoleAPICall { from: console_actor.name.clone(), __type__: "consoleAPICall".to_string(), message: ConsoleMsg { level: "log".to_string(), timeStamp: precise_time_ns(), arguments: vec!(message), filename: filename, lineNumber: lineNumber, columnNumber: columnNumber, }, }; for stream in console_actor.streams.borrow_mut().iter_mut() { stream.write_json_packet(&msg); } } } } fn find_console_actor(actors: Arc<Mutex<ActorRegistry>>, id: PipelineId, actor_pipelines: &HashMap<PipelineId, String>) -> String { let actors = actors.lock().unwrap(); let ref tab_actor_name = (*actor_pipelines)[id]; let tab_actor = actors.find::<TabActor>(tab_actor_name); let console_actor_name = tab_actor.console.clone(); return console_actor_name; } //TODO: figure out some system that allows us to watch for new connections, // shut down existing ones at arbitrary times, and also watch for messages // from multiple script tasks simultaneously. Polling for new connections // for 300ms and then checking the receiver is not a good compromise // (and makes Servo hang on exit if there's an open connection, no less). // accept connections and process them, spawning a new tasks for each one loop { match acceptor.accept() { Err(ref e) if e.kind == TimedOut => { match receiver.try_recv() { Ok(DevtoolsControlMsg::ServerExitMsg) | Err(Disconnected) => break, Ok(DevtoolsControlMsg::NewGlobal(id, sender, pageinfo)) => handle_new_global(actors.clone(), id,sender, &mut actor_pipelines, pageinfo), Ok(DevtoolsControlMsg::SendConsoleMessage(id, console_message)) => handle_console_message(actors.clone(), id, console_message, &actor_pipelines), Err(Empty) => acceptor.set_timeout(Some(POLL_TIMEOUT)), } } Err(_e) => { /* connection failed */ } Ok(stream) => { let actors = actors.clone(); accepted_connections.push(stream.clone()); spawn_named("DevtoolsClientHandler".to_owned(), move || { // connection succeeded handle_client(actors, stream.clone()) }) } } } for connection in accepted_connections.iter_mut() { let _read = connection.close_read(); let _write = connection.close_write(); } }
ConsoleMsg
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! An actor-based remote devtools server implementation. Only tested with //! nightly Firefox versions at time of writing. Largely based on //! reverse-engineering of Firefox chrome devtool logs and reading of //! [code](http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/). #![crate_name = "devtools"] #![crate_type = "rlib"] #![feature(int_uint, box_syntax, io, old_io, core, rustc_private)] #![feature(collections, std_misc)] #![allow(non_snake_case)] #[macro_use] extern crate log; extern crate collections; extern crate core; extern crate devtools_traits; extern crate "rustc-serialize" as rustc_serialize; extern crate msg; extern crate time; extern crate util; use actor::{Actor, ActorRegistry}; use actors::console::ConsoleActor; use actors::inspector::InspectorActor; use actors::root::RootActor; use actors::tab::TabActor; use protocol::JsonPacketStream; use devtools_traits::{ConsoleMessage, DevtoolsControlMsg}; use devtools_traits::{DevtoolsPageInfo, DevtoolScriptControlMsg}; use msg::constellation_msg::PipelineId; use util::task::spawn_named; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::mpsc::TryRecvError::{Disconnected, Empty}; use std::old_io::{TcpListener, TcpStream}; use std::old_io::{Acceptor, Listener, TimedOut}; use std::sync::{Arc, Mutex}; use time::precise_time_ns; mod actor; /// Corresponds to http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/ mod actors { pub mod console; pub mod inspector; pub mod root; pub mod tab; } mod protocol; #[derive(RustcEncodable)] struct ConsoleAPICall { from: String, __type__: String, message: ConsoleMsg, } #[derive(RustcEncodable)] struct ConsoleMsg { level: String, timeStamp: u64, arguments: Vec<String>, filename: String, lineNumber: u32, columnNumber: u32, } /// Spin up a devtools server that listens for connections on the specified port. pub fn start_server(port: u16) -> Sender<DevtoolsControlMsg> { let (sender, receiver) = channel(); spawn_named("Devtools".to_owned(), move || { run_server(receiver, port) }); sender } static POLL_TIMEOUT: u64 = 300; fn run_server(receiver: Receiver<DevtoolsControlMsg>, port: u16) { let listener = TcpListener::bind(&*format!("{}:{}", "127.0.0.1", port)); // bind the listener to the specified address let mut acceptor = listener.listen().unwrap(); acceptor.set_timeout(Some(POLL_TIMEOUT)); let mut registry = ActorRegistry::new(); let root = box RootActor { tabs: vec!(), }; registry.register(root); registry.find::<RootActor>("root"); let actors = Arc::new(Mutex::new(registry)); let mut accepted_connections: Vec<TcpStream> = Vec::new(); let mut actor_pipelines: HashMap<PipelineId, String> = HashMap::new(); /// Process the input from a single devtools client until EOF. fn handle_client(actors: Arc<Mutex<ActorRegistry>>, mut stream: TcpStream)
} } } Err(e) => { println!("error: {}", e.desc); break 'outer } } } } // We need separate actor representations for each script global that exists; // clients can theoretically connect to multiple globals simultaneously. // TODO: move this into the root or tab modules? fn handle_new_global(actors: Arc<Mutex<ActorRegistry>>, pipeline: PipelineId, sender: Sender<DevtoolScriptControlMsg>, actor_pipelines: &mut HashMap<PipelineId, String>, page_info: DevtoolsPageInfo) { let mut actors = actors.lock().unwrap(); //TODO: move all this actor creation into a constructor method on TabActor let (tab, console, inspector) = { let console = ConsoleActor { name: actors.new_name("console"), script_chan: sender.clone(), pipeline: pipeline, streams: RefCell::new(Vec::new()), }; let inspector = InspectorActor { name: actors.new_name("inspector"), walker: RefCell::new(None), pageStyle: RefCell::new(None), highlighter: RefCell::new(None), script_chan: sender, pipeline: pipeline, }; let DevtoolsPageInfo { title, url } = page_info; let tab = TabActor { name: actors.new_name("tab"), title: title, url: url.serialize(), console: console.name(), inspector: inspector.name(), }; let root = actors.find_mut::<RootActor>("root"); root.tabs.push(tab.name.clone()); (tab, console, inspector) }; actor_pipelines.insert(pipeline, tab.name.clone()); actors.register(box tab); actors.register(box console); actors.register(box inspector); } fn handle_console_message(actors: Arc<Mutex<ActorRegistry>>, id: PipelineId, console_message: ConsoleMessage, actor_pipelines: &HashMap<PipelineId, String>) { let console_actor_name = find_console_actor(actors.clone(), id, actor_pipelines); let actors = actors.lock().unwrap(); let console_actor = actors.find::<ConsoleActor>(&console_actor_name); match console_message { ConsoleMessage::LogMessage(message, filename, lineNumber, columnNumber) => { let msg = ConsoleAPICall { from: console_actor.name.clone(), __type__: "consoleAPICall".to_string(), message: ConsoleMsg { level: "log".to_string(), timeStamp: precise_time_ns(), arguments: vec!(message), filename: filename, lineNumber: lineNumber, columnNumber: columnNumber, }, }; for stream in console_actor.streams.borrow_mut().iter_mut() { stream.write_json_packet(&msg); } } } } fn find_console_actor(actors: Arc<Mutex<ActorRegistry>>, id: PipelineId, actor_pipelines: &HashMap<PipelineId, String>) -> String { let actors = actors.lock().unwrap(); let ref tab_actor_name = (*actor_pipelines)[id]; let tab_actor = actors.find::<TabActor>(tab_actor_name); let console_actor_name = tab_actor.console.clone(); return console_actor_name; } //TODO: figure out some system that allows us to watch for new connections, // shut down existing ones at arbitrary times, and also watch for messages // from multiple script tasks simultaneously. Polling for new connections // for 300ms and then checking the receiver is not a good compromise // (and makes Servo hang on exit if there's an open connection, no less). // accept connections and process them, spawning a new tasks for each one loop { match acceptor.accept() { Err(ref e) if e.kind == TimedOut => { match receiver.try_recv() { Ok(DevtoolsControlMsg::ServerExitMsg) | Err(Disconnected) => break, Ok(DevtoolsControlMsg::NewGlobal(id, sender, pageinfo)) => handle_new_global(actors.clone(), id,sender, &mut actor_pipelines, pageinfo), Ok(DevtoolsControlMsg::SendConsoleMessage(id, console_message)) => handle_console_message(actors.clone(), id, console_message, &actor_pipelines), Err(Empty) => acceptor.set_timeout(Some(POLL_TIMEOUT)), } } Err(_e) => { /* connection failed */ } Ok(stream) => { let actors = actors.clone(); accepted_connections.push(stream.clone()); spawn_named("DevtoolsClientHandler".to_owned(), move || { // connection succeeded handle_client(actors, stream.clone()) }) } } } for connection in accepted_connections.iter_mut() { let _read = connection.close_read(); let _write = connection.close_write(); } }
{ println!("connection established to {}", stream.peer_name().unwrap()); { let actors = actors.lock().unwrap(); let msg = actors.find::<RootActor>("root").encodable(); stream.write_json_packet(&msg); } 'outer: loop { match stream.read_json_packet() { Ok(json_packet) => { let mut actors = actors.lock().unwrap(); match actors.handle_message(json_packet.as_object().unwrap(), &mut stream) { Ok(()) => {}, Err(()) => { println!("error: devtools actor stopped responding"); let _ = stream.close_read(); let _ = stream.close_write(); break 'outer
identifier_body
builder.rs
extern crate libc; use std::ops::Drop; use std::collections::HashMap; use std::ffi::CString; use basic_block::BasicBlock; use value::Value; use context::Context; use switch::Switch; use function::Function; use function_call::FunctionCall; use bindings::*; #[derive(PartialEq,Eq)] pub struct IRBuilder(pub(super) LLVMBuilderRef); impl IRBuilder { pub fn new() -> IRBuilder { IRBuilder(unsafe { LLVMCreateBuilder() }) } pub fn new_in_context(cont: &Context) -> IRBuilder { IRBuilder(unsafe { LLVMCreateBuilderInContext(cont.0) }) } pub fn position_at_end(&self, bb: BasicBlock) { unsafe { LLVMPositionBuilderAtEnd(self.0, bb.0); } } pub fn insertion_block(&self) -> Option<BasicBlock> { let r = unsafe { LLVMGetInsertBlock(self.0) }; if r.is_null()
else { Some(BasicBlock(r)) } } pub fn ret_void(&self) -> Value { Value(unsafe { LLVMBuildRetVoid(self.0) }) } pub fn ret(&self, val: Value) -> Value { Value(unsafe { LLVMBuildRet(self.0, val.0) }) } pub fn br(&self, br: BasicBlock) -> Value { Value(unsafe { LLVMBuildBr(self.0, br.0) }) } pub fn cond_br(&self, cond: Value, then: &BasicBlock, els: &BasicBlock) -> Value { Value(unsafe { LLVMBuildCondBr(self.0, cond.0, then.0, els.0) }) } pub fn switch(&self, val: Value, default: BasicBlock, cases: HashMap<Value, BasicBlock>) -> Switch { let switch = unsafe { LLVMBuildSwitch(self.0, val.0, default.0, cases.len() as u32) }; for (on_val, dest) in cases { unsafe { LLVMAddCase(switch, on_val.0, dest.0); } } Switch(switch) } pub fn call(&self, f: Function, args: &[Value]) -> FunctionCall { unsafe { FunctionCall(LLVMBuildCall(self.0, f.0, args.iter().map(|x| x.0).collect::<Vec<_>>().as_mut_ptr(), args.len() as u32, CString::new("").unwrap().as_ptr() ) ) } } } impl Drop for IRBuilder { fn drop(&mut self) { unsafe { LLVMDisposeBuilder(self.0); } } } #[cfg(test)] mod tests { use super::IRBuilder; use module::Module; use types::{Type,FunctionType}; use value::Value; #[test] fn test_insertion_block_and_position_at_end() { let modl = Module::new("test"); let f = modl.add_function("testf", FunctionType::new(Type::int32(), &vec![], false)); let entry_b = f.append_bb("entry"); let builder = IRBuilder::new(); builder.position_at_end(f.entry_bb().unwrap()); assert_eq!(builder.insertion_block().unwrap(), entry_b); } #[test] fn test_function_calling() { let modl = Module::new("test"); let f = modl.add_function("testf", FunctionType::new(Type::int32(), &vec![], false)); let f2 = modl.add_function("testf2", FunctionType::new(Type::int32(), &vec![], false)); let _ = f.append_bb("entry"); let _ = f2.append_bb("entry"); let builder = IRBuilder::new(); builder.position_at_end(f.entry_bb().unwrap()); let call = builder.call(f2, &vec![Value::const_int(Type::int32(), 10)]); assert_eq!(call.called_value(), f2); } }
{ None }
conditional_block
builder.rs
extern crate libc; use std::ops::Drop; use std::collections::HashMap; use std::ffi::CString; use basic_block::BasicBlock; use value::Value; use context::Context; use switch::Switch; use function::Function; use function_call::FunctionCall; use bindings::*; #[derive(PartialEq,Eq)] pub struct IRBuilder(pub(super) LLVMBuilderRef); impl IRBuilder { pub fn new() -> IRBuilder { IRBuilder(unsafe { LLVMCreateBuilder() }) } pub fn new_in_context(cont: &Context) -> IRBuilder
pub fn position_at_end(&self, bb: BasicBlock) { unsafe { LLVMPositionBuilderAtEnd(self.0, bb.0); } } pub fn insertion_block(&self) -> Option<BasicBlock> { let r = unsafe { LLVMGetInsertBlock(self.0) }; if r.is_null() { None } else { Some(BasicBlock(r)) } } pub fn ret_void(&self) -> Value { Value(unsafe { LLVMBuildRetVoid(self.0) }) } pub fn ret(&self, val: Value) -> Value { Value(unsafe { LLVMBuildRet(self.0, val.0) }) } pub fn br(&self, br: BasicBlock) -> Value { Value(unsafe { LLVMBuildBr(self.0, br.0) }) } pub fn cond_br(&self, cond: Value, then: &BasicBlock, els: &BasicBlock) -> Value { Value(unsafe { LLVMBuildCondBr(self.0, cond.0, then.0, els.0) }) } pub fn switch(&self, val: Value, default: BasicBlock, cases: HashMap<Value, BasicBlock>) -> Switch { let switch = unsafe { LLVMBuildSwitch(self.0, val.0, default.0, cases.len() as u32) }; for (on_val, dest) in cases { unsafe { LLVMAddCase(switch, on_val.0, dest.0); } } Switch(switch) } pub fn call(&self, f: Function, args: &[Value]) -> FunctionCall { unsafe { FunctionCall(LLVMBuildCall(self.0, f.0, args.iter().map(|x| x.0).collect::<Vec<_>>().as_mut_ptr(), args.len() as u32, CString::new("").unwrap().as_ptr() ) ) } } } impl Drop for IRBuilder { fn drop(&mut self) { unsafe { LLVMDisposeBuilder(self.0); } } } #[cfg(test)] mod tests { use super::IRBuilder; use module::Module; use types::{Type,FunctionType}; use value::Value; #[test] fn test_insertion_block_and_position_at_end() { let modl = Module::new("test"); let f = modl.add_function("testf", FunctionType::new(Type::int32(), &vec![], false)); let entry_b = f.append_bb("entry"); let builder = IRBuilder::new(); builder.position_at_end(f.entry_bb().unwrap()); assert_eq!(builder.insertion_block().unwrap(), entry_b); } #[test] fn test_function_calling() { let modl = Module::new("test"); let f = modl.add_function("testf", FunctionType::new(Type::int32(), &vec![], false)); let f2 = modl.add_function("testf2", FunctionType::new(Type::int32(), &vec![], false)); let _ = f.append_bb("entry"); let _ = f2.append_bb("entry"); let builder = IRBuilder::new(); builder.position_at_end(f.entry_bb().unwrap()); let call = builder.call(f2, &vec![Value::const_int(Type::int32(), 10)]); assert_eq!(call.called_value(), f2); } }
{ IRBuilder(unsafe { LLVMCreateBuilderInContext(cont.0) }) }
identifier_body
builder.rs
extern crate libc; use std::ops::Drop; use std::collections::HashMap; use std::ffi::CString; use basic_block::BasicBlock; use value::Value; use context::Context; use switch::Switch; use function::Function; use function_call::FunctionCall; use bindings::*; #[derive(PartialEq,Eq)] pub struct IRBuilder(pub(super) LLVMBuilderRef); impl IRBuilder { pub fn new() -> IRBuilder {
IRBuilder(unsafe { LLVMCreateBuilderInContext(cont.0) }) } pub fn position_at_end(&self, bb: BasicBlock) { unsafe { LLVMPositionBuilderAtEnd(self.0, bb.0); } } pub fn insertion_block(&self) -> Option<BasicBlock> { let r = unsafe { LLVMGetInsertBlock(self.0) }; if r.is_null() { None } else { Some(BasicBlock(r)) } } pub fn ret_void(&self) -> Value { Value(unsafe { LLVMBuildRetVoid(self.0) }) } pub fn ret(&self, val: Value) -> Value { Value(unsafe { LLVMBuildRet(self.0, val.0) }) } pub fn br(&self, br: BasicBlock) -> Value { Value(unsafe { LLVMBuildBr(self.0, br.0) }) } pub fn cond_br(&self, cond: Value, then: &BasicBlock, els: &BasicBlock) -> Value { Value(unsafe { LLVMBuildCondBr(self.0, cond.0, then.0, els.0) }) } pub fn switch(&self, val: Value, default: BasicBlock, cases: HashMap<Value, BasicBlock>) -> Switch { let switch = unsafe { LLVMBuildSwitch(self.0, val.0, default.0, cases.len() as u32) }; for (on_val, dest) in cases { unsafe { LLVMAddCase(switch, on_val.0, dest.0); } } Switch(switch) } pub fn call(&self, f: Function, args: &[Value]) -> FunctionCall { unsafe { FunctionCall(LLVMBuildCall(self.0, f.0, args.iter().map(|x| x.0).collect::<Vec<_>>().as_mut_ptr(), args.len() as u32, CString::new("").unwrap().as_ptr() ) ) } } } impl Drop for IRBuilder { fn drop(&mut self) { unsafe { LLVMDisposeBuilder(self.0); } } } #[cfg(test)] mod tests { use super::IRBuilder; use module::Module; use types::{Type,FunctionType}; use value::Value; #[test] fn test_insertion_block_and_position_at_end() { let modl = Module::new("test"); let f = modl.add_function("testf", FunctionType::new(Type::int32(), &vec![], false)); let entry_b = f.append_bb("entry"); let builder = IRBuilder::new(); builder.position_at_end(f.entry_bb().unwrap()); assert_eq!(builder.insertion_block().unwrap(), entry_b); } #[test] fn test_function_calling() { let modl = Module::new("test"); let f = modl.add_function("testf", FunctionType::new(Type::int32(), &vec![], false)); let f2 = modl.add_function("testf2", FunctionType::new(Type::int32(), &vec![], false)); let _ = f.append_bb("entry"); let _ = f2.append_bb("entry"); let builder = IRBuilder::new(); builder.position_at_end(f.entry_bb().unwrap()); let call = builder.call(f2, &vec![Value::const_int(Type::int32(), 10)]); assert_eq!(call.called_value(), f2); } }
IRBuilder(unsafe { LLVMCreateBuilder() }) } pub fn new_in_context(cont: &Context) -> IRBuilder {
random_line_split
builder.rs
extern crate libc; use std::ops::Drop; use std::collections::HashMap; use std::ffi::CString; use basic_block::BasicBlock; use value::Value; use context::Context; use switch::Switch; use function::Function; use function_call::FunctionCall; use bindings::*; #[derive(PartialEq,Eq)] pub struct
(pub(super) LLVMBuilderRef); impl IRBuilder { pub fn new() -> IRBuilder { IRBuilder(unsafe { LLVMCreateBuilder() }) } pub fn new_in_context(cont: &Context) -> IRBuilder { IRBuilder(unsafe { LLVMCreateBuilderInContext(cont.0) }) } pub fn position_at_end(&self, bb: BasicBlock) { unsafe { LLVMPositionBuilderAtEnd(self.0, bb.0); } } pub fn insertion_block(&self) -> Option<BasicBlock> { let r = unsafe { LLVMGetInsertBlock(self.0) }; if r.is_null() { None } else { Some(BasicBlock(r)) } } pub fn ret_void(&self) -> Value { Value(unsafe { LLVMBuildRetVoid(self.0) }) } pub fn ret(&self, val: Value) -> Value { Value(unsafe { LLVMBuildRet(self.0, val.0) }) } pub fn br(&self, br: BasicBlock) -> Value { Value(unsafe { LLVMBuildBr(self.0, br.0) }) } pub fn cond_br(&self, cond: Value, then: &BasicBlock, els: &BasicBlock) -> Value { Value(unsafe { LLVMBuildCondBr(self.0, cond.0, then.0, els.0) }) } pub fn switch(&self, val: Value, default: BasicBlock, cases: HashMap<Value, BasicBlock>) -> Switch { let switch = unsafe { LLVMBuildSwitch(self.0, val.0, default.0, cases.len() as u32) }; for (on_val, dest) in cases { unsafe { LLVMAddCase(switch, on_val.0, dest.0); } } Switch(switch) } pub fn call(&self, f: Function, args: &[Value]) -> FunctionCall { unsafe { FunctionCall(LLVMBuildCall(self.0, f.0, args.iter().map(|x| x.0).collect::<Vec<_>>().as_mut_ptr(), args.len() as u32, CString::new("").unwrap().as_ptr() ) ) } } } impl Drop for IRBuilder { fn drop(&mut self) { unsafe { LLVMDisposeBuilder(self.0); } } } #[cfg(test)] mod tests { use super::IRBuilder; use module::Module; use types::{Type,FunctionType}; use value::Value; #[test] fn test_insertion_block_and_position_at_end() { let modl = Module::new("test"); let f = modl.add_function("testf", FunctionType::new(Type::int32(), &vec![], false)); let entry_b = f.append_bb("entry"); let builder = IRBuilder::new(); builder.position_at_end(f.entry_bb().unwrap()); assert_eq!(builder.insertion_block().unwrap(), entry_b); } #[test] fn test_function_calling() { let modl = Module::new("test"); let f = modl.add_function("testf", FunctionType::new(Type::int32(), &vec![], false)); let f2 = modl.add_function("testf2", FunctionType::new(Type::int32(), &vec![], false)); let _ = f.append_bb("entry"); let _ = f2.append_bb("entry"); let builder = IRBuilder::new(); builder.position_at_end(f.entry_bb().unwrap()); let call = builder.call(f2, &vec![Value::const_int(Type::int32(), 10)]); assert_eq!(call.called_value(), f2); } }
IRBuilder
identifier_name
input.rs
use sdl2::rect::{Rect, Point}; use sdl2::event::Event as Sdl2Event; use sdl2::keyboard::Keycode; use sdl2::EventPump; use crate::core::*; use crate::ui::{ClickArea, ClickAreas, ScreenPos, UI}; pub fn poll(sdl_events: &mut EventPump, click_areas: &ClickAreas, ui: &UI) -> Option<UserInput> { for event in sdl_events.poll_iter() { match event { Sdl2Event::Quit {.. } | Sdl2Event::KeyDown { keycode: Some(Keycode::Escape), .. } => return Some(UserInput::Exit()), Sdl2Event::MouseMotion { xrel, yrel,.. } => { let is_scrolling = ui.scrolling.as_ref().map(|s| s.is_scrolling).unwrap_or(false); if is_scrolling { return Some(UserInput::ScrollTo( ui.pixel_ratio as i32 * xrel, ui.pixel_ratio as i32 * yrel, )); } } Sdl2Event::MouseButtonUp { x, y,.. } => { let has_scrolled = ui.scrolling.as_ref().map(|s| s.has_scrolled).unwrap_or(false); if has_scrolled { return Some(UserInput::EndScrolling()); } else { let p = ScreenPos(ui.pixel_ratio as i32 * x, ui.pixel_ratio as i32 * y); for ClickArea {clipping_area, action} in click_areas.iter() { if contains_point(*clipping_area, p) { return Some(action(p)); } } } } Sdl2Event::MouseButtonDown {.. } => { return Some(UserInput::StartScrolling()); } _ => {} } } None } fn contains_point((x, y, w, h): (i32, i32, u32, u32), p: ScreenPos) -> bool
{ Rect::new(x, y, w, h).contains_point(Point::new(p.0, p.1)) }
identifier_body
input.rs
use sdl2::rect::{Rect, Point}; use sdl2::event::Event as Sdl2Event; use sdl2::keyboard::Keycode; use sdl2::EventPump; use crate::core::*; use crate::ui::{ClickArea, ClickAreas, ScreenPos, UI}; pub fn
(sdl_events: &mut EventPump, click_areas: &ClickAreas, ui: &UI) -> Option<UserInput> { for event in sdl_events.poll_iter() { match event { Sdl2Event::Quit {.. } | Sdl2Event::KeyDown { keycode: Some(Keycode::Escape), .. } => return Some(UserInput::Exit()), Sdl2Event::MouseMotion { xrel, yrel,.. } => { let is_scrolling = ui.scrolling.as_ref().map(|s| s.is_scrolling).unwrap_or(false); if is_scrolling { return Some(UserInput::ScrollTo( ui.pixel_ratio as i32 * xrel, ui.pixel_ratio as i32 * yrel, )); } } Sdl2Event::MouseButtonUp { x, y,.. } => { let has_scrolled = ui.scrolling.as_ref().map(|s| s.has_scrolled).unwrap_or(false); if has_scrolled { return Some(UserInput::EndScrolling()); } else { let p = ScreenPos(ui.pixel_ratio as i32 * x, ui.pixel_ratio as i32 * y); for ClickArea {clipping_area, action} in click_areas.iter() { if contains_point(*clipping_area, p) { return Some(action(p)); } } } } Sdl2Event::MouseButtonDown {.. } => { return Some(UserInput::StartScrolling()); } _ => {} } } None } fn contains_point((x, y, w, h): (i32, i32, u32, u32), p: ScreenPos) -> bool { Rect::new(x, y, w, h).contains_point(Point::new(p.0, p.1)) }
poll
identifier_name
input.rs
use sdl2::rect::{Rect, Point}; use sdl2::event::Event as Sdl2Event; use sdl2::keyboard::Keycode; use sdl2::EventPump; use crate::core::*; use crate::ui::{ClickArea, ClickAreas, ScreenPos, UI}; pub fn poll(sdl_events: &mut EventPump, click_areas: &ClickAreas, ui: &UI) -> Option<UserInput> { for event in sdl_events.poll_iter() { match event { Sdl2Event::Quit {.. } | Sdl2Event::KeyDown { keycode: Some(Keycode::Escape), .. } => return Some(UserInput::Exit()), Sdl2Event::MouseMotion { xrel, yrel,.. } => { let is_scrolling = ui.scrolling.as_ref().map(|s| s.is_scrolling).unwrap_or(false); if is_scrolling { return Some(UserInput::ScrollTo( ui.pixel_ratio as i32 * xrel, ui.pixel_ratio as i32 * yrel, )); } } Sdl2Event::MouseButtonUp { x, y,.. } => { let has_scrolled = ui.scrolling.as_ref().map(|s| s.has_scrolled).unwrap_or(false); if has_scrolled { return Some(UserInput::EndScrolling()); } else { let p = ScreenPos(ui.pixel_ratio as i32 * x, ui.pixel_ratio as i32 * y); for ClickArea {clipping_area, action} in click_areas.iter() { if contains_point(*clipping_area, p) { return Some(action(p)); } } } } Sdl2Event::MouseButtonDown {.. } =>
_ => {} } } None } fn contains_point((x, y, w, h): (i32, i32, u32, u32), p: ScreenPos) -> bool { Rect::new(x, y, w, h).contains_point(Point::new(p.0, p.1)) }
{ return Some(UserInput::StartScrolling()); }
conditional_block
input.rs
use sdl2::rect::{Rect, Point}; use sdl2::event::Event as Sdl2Event; use sdl2::keyboard::Keycode; use sdl2::EventPump;
use crate::ui::{ClickArea, ClickAreas, ScreenPos, UI}; pub fn poll(sdl_events: &mut EventPump, click_areas: &ClickAreas, ui: &UI) -> Option<UserInput> { for event in sdl_events.poll_iter() { match event { Sdl2Event::Quit {.. } | Sdl2Event::KeyDown { keycode: Some(Keycode::Escape), .. } => return Some(UserInput::Exit()), Sdl2Event::MouseMotion { xrel, yrel,.. } => { let is_scrolling = ui.scrolling.as_ref().map(|s| s.is_scrolling).unwrap_or(false); if is_scrolling { return Some(UserInput::ScrollTo( ui.pixel_ratio as i32 * xrel, ui.pixel_ratio as i32 * yrel, )); } } Sdl2Event::MouseButtonUp { x, y,.. } => { let has_scrolled = ui.scrolling.as_ref().map(|s| s.has_scrolled).unwrap_or(false); if has_scrolled { return Some(UserInput::EndScrolling()); } else { let p = ScreenPos(ui.pixel_ratio as i32 * x, ui.pixel_ratio as i32 * y); for ClickArea {clipping_area, action} in click_areas.iter() { if contains_point(*clipping_area, p) { return Some(action(p)); } } } } Sdl2Event::MouseButtonDown {.. } => { return Some(UserInput::StartScrolling()); } _ => {} } } None } fn contains_point((x, y, w, h): (i32, i32, u32, u32), p: ScreenPos) -> bool { Rect::new(x, y, w, h).contains_point(Point::new(p.0, p.1)) }
use crate::core::*;
random_line_split
join_halves.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::JoinHalves; use malachite_base_test_util::bench::bucketers::pair_max_bit_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_pair_gen_var_27; use malachite_base_test_util::runner::Runner; pub(crate) fn register(runner: &mut Runner)
fn demo_join_halves<T: JoinHalves + PrimitiveUnsigned>(gm: GenMode, config: GenConfig, limit: usize) where T::Half: PrimitiveUnsigned, { for (x, y) in unsigned_pair_gen_var_27::<T::Half>() .get(gm, &config) .take(limit) { println!( "{}::join_halves({}, {}) = {}", T::NAME, x, y, T::join_halves(x, y) ); } } fn benchmark_join_halves<T: JoinHalves + PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) where T::Half: PrimitiveUnsigned, { run_benchmark( &format!( "{}::join_halves({}, {})", T::NAME, T::Half::NAME, T::Half::NAME ), BenchmarkType::Single, unsigned_pair_gen_var_27::<T::Half>().get(gm, &config), gm.name(), limit, file_name, &pair_max_bit_bucketer("x", "y"), &mut [("Malachite", &mut |(x, y)| no_out!(T::join_halves(x, y)))], ); }
{ register_generic_demos!(runner, demo_join_halves, u16, u32, u64, u128); register_generic_benches!(runner, benchmark_join_halves, u16, u32, u64, u128); }
identifier_body
join_halves.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::JoinHalves; use malachite_base_test_util::bench::bucketers::pair_max_bit_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_pair_gen_var_27; use malachite_base_test_util::runner::Runner; pub(crate) fn register(runner: &mut Runner) { register_generic_demos!(runner, demo_join_halves, u16, u32, u64, u128); register_generic_benches!(runner, benchmark_join_halves, u16, u32, u64, u128); } fn demo_join_halves<T: JoinHalves + PrimitiveUnsigned>(gm: GenMode, config: GenConfig, limit: usize) where T::Half: PrimitiveUnsigned, { for (x, y) in unsigned_pair_gen_var_27::<T::Half>() .get(gm, &config) .take(limit) { println!( "{}::join_halves({}, {}) = {}", T::NAME, x, y, T::join_halves(x, y) ); } } fn
<T: JoinHalves + PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) where T::Half: PrimitiveUnsigned, { run_benchmark( &format!( "{}::join_halves({}, {})", T::NAME, T::Half::NAME, T::Half::NAME ), BenchmarkType::Single, unsigned_pair_gen_var_27::<T::Half>().get(gm, &config), gm.name(), limit, file_name, &pair_max_bit_bucketer("x", "y"), &mut [("Malachite", &mut |(x, y)| no_out!(T::join_halves(x, y)))], ); }
benchmark_join_halves
identifier_name
join_halves.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::JoinHalves; use malachite_base_test_util::bench::bucketers::pair_max_bit_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_pair_gen_var_27; use malachite_base_test_util::runner::Runner; pub(crate) fn register(runner: &mut Runner) { register_generic_demos!(runner, demo_join_halves, u16, u32, u64, u128); register_generic_benches!(runner, benchmark_join_halves, u16, u32, u64, u128); } fn demo_join_halves<T: JoinHalves + PrimitiveUnsigned>(gm: GenMode, config: GenConfig, limit: usize) where T::Half: PrimitiveUnsigned, { for (x, y) in unsigned_pair_gen_var_27::<T::Half>() .get(gm, &config) .take(limit) { println!( "{}::join_halves({}, {}) = {}", T::NAME, x,
fn benchmark_join_halves<T: JoinHalves + PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) where T::Half: PrimitiveUnsigned, { run_benchmark( &format!( "{}::join_halves({}, {})", T::NAME, T::Half::NAME, T::Half::NAME ), BenchmarkType::Single, unsigned_pair_gen_var_27::<T::Half>().get(gm, &config), gm.name(), limit, file_name, &pair_max_bit_bucketer("x", "y"), &mut [("Malachite", &mut |(x, y)| no_out!(T::join_halves(x, y)))], ); }
y, T::join_halves(x, y) ); } }
random_line_split
cursor.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/. */ //! A list of common mouse cursors per CSS3-UI § 8.1.1. use super::ToCss; macro_rules! define_cursor { ( common properties = [ $( $c_css: expr => $c_variant: ident = $c_value: expr, )+ ] gecko properties = [ $( $g_css: expr => $g_variant: ident = $g_value: expr, )+ ] ) => { /// https://drafts.csswg.org/css-ui/#cursor #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize, HeapSizeOf))] #[repr(u8)] #[allow(missing_docs)] pub enum Cursor { $( $c_variant = $c_value, )+ $( #[cfg(feature = "gecko")] $g_variant = $g_value, )+ } impl Cursor { /// Given a CSS keyword, get the corresponding cursor enum. pub fn from_css_keyword(keyword: &str) -> Result<Cursor, ()> { match_ignore_ascii_case! { &keyword, $( $c_css => Ok(Cursor::$c_variant), )+ $( #[cfg(feature = "gecko")] $g_css => Ok(Cursor::$g_variant), )+ _ => Err(()) } } } impl ToCss for Cursor {
} } } } } define_cursor! { common properties = [ "none" => None = 0, "default" => Default = 1, "pointer" => Pointer = 2, "context-menu" => ContextMenu = 3, "help" => Help = 4, "progress" => Progress = 5, "wait" => Wait = 6, "cell" => Cell = 7, "crosshair" => Crosshair = 8, "text" => Text = 9, "vertical-text" => VerticalText = 10, "alias" => Alias = 11, "copy" => Copy = 12, "move" => Move = 13, "no-drop" => NoDrop = 14, "not-allowed" => NotAllowed = 15, "grab" => Grab = 16, "grabbing" => Grabbing = 17, "e-resize" => EResize = 18, "n-resize" => NResize = 19, "ne-resize" => NeResize = 20, "nw-resize" => NwResize = 21, "s-resize" => SResize = 22, "se-resize" => SeResize = 23, "sw-resize" => SwResize = 24, "w-resize" => WResize = 25, "ew-resize" => EwResize = 26, "ns-resize" => NsResize = 27, "nesw-resize" => NeswResize = 28, "nwse-resize" => NwseResize = 29, "col-resize" => ColResize = 30, "row-resize" => RowResize = 31, "all-scroll" => AllScroll = 32, "zoom-in" => ZoomIn = 33, "zoom-out" => ZoomOut = 34, ] // gecko only properties gecko properties = [ "-moz-grab" => MozGrab = 35, "-moz-grabbing" => MozGrabbing = 36, "-moz-zoom-in" => MozZoomIn = 37, "-moz-zoom-out" => MozZoomOut = 38, ] }
fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result where W: ::std::fmt::Write { match *self { $( Cursor::$c_variant => dest.write_str($c_css), )+ $( #[cfg(feature = "gecko")] Cursor::$g_variant => dest.write_str($g_css), )+
random_line_split
lib.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2014,2015,2016 Kai Michaelis * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //! Panopticon is a libre disassembler and binary analysis tool. It started as //! platform for experiments in static program analysis and grew into a complete //! library (libpanopticon) and a Qt 5 based UI. The library is written in Rust, the //! UI is a mix of Rust and QML. Both are licensed as GPLv3. //! //! Library Overview //! ---------------- //! //! The libpanopticon implements structures to model the in-memory representation of a //! program including is control flow, call graph and memory maps. //! The most important types and their interaction are as follows: //! //!.. graphviz:: //! //! digraph G { //! rankdir=LR //! graph [bgcolor="transparent"] //! node [shape=rect] //! Project -> Program [label="contains"] //! Program -> Function [label="contains"] //! Function -> BasicBlock [label="contains"] //! BasicBlock -> Mnemonic [label="contains"] //! Mnemonic -> Statement [label="contains"] //! Project -> Region [label="contains"] //! Region -> Layer [label="contains"] //! } //! //! The `Program`, `Function`, `BasicBlock` and `Statement` types model the behaviour of code. //! The `Region` and `Layer` types represent how the program is laid out in memory. //! //! Code //! ~~~~ //! //! Panopticon models code as a collection of programs contained in a file. Each
//! has a sequence of RREIL instructions (`Statement` type) implementing it. //! //! Panopticon allows multiple programs per project. An example for that would be a //! C# application that calls functions of a DLL written in C. Such an application //! would have two program instances. One for the CIL code of the C# program and one //! for the AMD64 of Intel 32 object code of the DLL. //! //! One of the key features of Panopticon is the ability to "understand" the binary. //! The disassembler not only knowns about the shape of mnemonics (its syntax) but //! also what is does (the semantics). Each mnemonic includes a short program in RREIL //! the implements the mnemonic. This allows sophisticated analysis like symbolic //! execution, automatic crafting of input to reach certain basic blocks, //! decompilation and computing bounds on register values without executing the code. //! //! Instances of the `Program`, `Function`, `BasicBlock` and `Statement` types are created by //! the disassembler subsystem (`Disassembler` and `CodeGen` types). A //! `Disassembler` is given a range of data and an instruction set architecture and //! creates a model of the code found in the data. //! //! Sources //! ~~~~~~~ //! //! The in-memory layout of an executable is modeled using the `Region`, `Layer` and //! `Cell` types. All data is organized into `Region`s. Each `Region` is an array of //! `Cell`s numbered from 0 to n. Each `Cell` is an is either //! undefined or has a value between 0 and 255 (both including). `Region`s are read //! only. Changing their contents is done by applying `Layer` instance to them. A `Layer` //! reads part of a `Region` or another `Layer` and returns a new `Cell` array. `Layer`s //! can for example decrypt parts of a `Region` or replace individual `Cell`s with new //! ones. //! //! In normal operation there is one `Region` for each memory address space, one on //! Von-Neumann machines two on Harvard architectures. Other uses for `Region`s are //! applying functions to `Cell` array where the result is not equal in size to the //! input (for example uncompressing parts of the executable image). //! //! Graphical UI //! ------------ //! //! The qtpanopticon application uses the functionality implemented in the //! libpanopticon to allow browsing the disassembled code. //! //! The UI widgets are mostly implemented in QML ("qml/"), with glue functions written //! in Rust to connect the QML code to libpanopticon. The UI includes a implementation //! of DOT for layouting control flow graphs. //! //! Moving data to QML is done by JSON RPC. //! This makes memory management easier and save us from implementing dozens of //! QObject subclasses. #![recursion_limit="100"] #[macro_use] extern crate log; extern crate num; extern crate rustc_serialize; extern crate flate2; extern crate graph_algos; extern crate tempdir; extern crate uuid; extern crate rmp_serialize; #[macro_use] extern crate lazy_static; extern crate byteorder; // core pub mod disassembler; pub use disassembler::{ State, Architecture, Disassembler, }; pub mod il; pub use il::{ Rvalue, Lvalue, Guard, Statement, Operation, execute, lift, }; pub mod codegen; pub use codegen::CodeGen; pub mod mnemonic; pub use mnemonic::{ Mnemonic, MnemonicFormatToken, Bound, }; pub mod basic_block; pub use basic_block::{ BasicBlock, }; pub mod function; pub use function::{ Function, ControlFlowTarget, ControlFlowRef, ControlFlowEdge, ControlFlowGraph, }; pub mod program; pub use program::{ Program, CallTarget, CallGraph, CallGraphRef, DisassembleEvent, }; pub mod project; pub use project::Project; pub mod region; pub use region::{ Region, Regions, }; pub mod layer; pub use layer::{ Layer, OpaqueLayer, LayerIter, }; pub mod result; pub use result::{ Result, Error, }; pub mod dataflow; pub use dataflow::*; pub mod abstractinterp; pub use abstractinterp::{ Kset, approximate, }; // disassembler pub mod avr; pub mod amd64; pub mod mos; // file formats pub mod pe; pub mod elf;
//! program consists of functions. A function is a control flow //! graph, e.g. a graph with nodes representing a sequence of instructions and //! directed edges for (un)conditional jumps. These instruction sequences are basic //! blocks and contain a list of mnemonics. Panopticon models the semantic of each //! mnemonic using the RREIL language. Each mnemonic instance
random_line_split
node_table.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::mem; use std::slice::from_raw_parts; use std::net::{SocketAddr, ToSocketAddrs, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr}; use std::hash::{Hash, Hasher}; use std::str::{FromStr}; use std::collections::{HashMap, HashSet}; use std::fmt::{Display, Formatter}; use std::path::{PathBuf}; use std::fmt; use std::fs; use std::io::{Read, Write}; use util::hash::*; use util::UtilError; use rlp::*; use time::Tm; use error::NetworkError; use AllowIP; use discovery::{TableUpdates, NodeEntry}; use ip_utils::*; pub use rustc_serialize::json::Json; /// Node public key pub type NodeId = H512; #[derive(Debug, Clone)] /// Node address info pub struct NodeEndpoint { /// IP(V4 or V6) address pub address: SocketAddr, /// Conneciton port. pub udp_port: u16 } impl NodeEndpoint { pub fn udp_address(&self) -> SocketAddr { match self.address { SocketAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a.ip().clone(), self.udp_port)), SocketAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a.ip().clone(), self.udp_port, a.flowinfo(), a.scope_id())), } } pub fn is_allowed(&self, filter: AllowIP) -> bool { match filter { AllowIP::All => true, AllowIP::Private =>!self.address.ip().is_global_s(), AllowIP::Public => self.address.ip().is_global_s(), } } pub fn from_rlp(rlp: &UntrustedRlp) -> Result<Self, DecoderError> { let tcp_port = try!(rlp.val_at::<u16>(2)); let udp_port = try!(rlp.val_at::<u16>(1)); let addr_bytes = try!(try!(rlp.at(0)).data()); let address = try!(match addr_bytes.len() { 4 => Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(addr_bytes[0], addr_bytes[1], addr_bytes[2], addr_bytes[3]), tcp_port))), 16 => unsafe { let o: *const u16 = mem::transmute(addr_bytes.as_ptr()); let o = from_raw_parts(o, 8); Ok(SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7]), tcp_port, 0, 0))) }, _ => Err(DecoderError::RlpInconsistentLengthAndData) }); Ok(NodeEndpoint { address: address, udp_port: udp_port }) } pub fn to_rlp(&self, rlp: &mut RlpStream) { match self.address { SocketAddr::V4(a) => { rlp.append(&(&a.ip().octets()[..])); } SocketAddr::V6(a) => unsafe { let o: *const u8 = mem::transmute(a.ip().segments().as_ptr()); rlp.append(&from_raw_parts(o, 16)); } }; rlp.append(&self.udp_port); rlp.append(&self.address.port()); } pub fn to_rlp_list(&self, rlp: &mut RlpStream) { rlp.begin_list(3); self.to_rlp(rlp); } pub fn is_valid(&self) -> bool { self.udp_port!= 0 && self.address.port()!= 0 && match self.address { SocketAddr::V4(a) =>!a.ip().is_unspecified_s(), SocketAddr::V6(a) =>!a.ip().is_unspecified_s() } } } impl FromStr for NodeEndpoint { type Err = NetworkError; /// Create endpoint from string. Performs name resolution if given a host name. fn from_str(s: &str) -> Result<NodeEndpoint, NetworkError> { let address = s.to_socket_addrs().map(|mut i| i.next()); match address { Ok(Some(a)) => Ok(NodeEndpoint { address: a, udp_port: a.port() }), Ok(_) => Err(NetworkError::AddressResolve(None)), Err(e) => Err(NetworkError::AddressResolve(Some(e))) } } } #[derive(PartialEq, Eq, Copy, Clone)] pub enum PeerType { _Required, Optional } pub struct Node { pub id: NodeId, pub endpoint: NodeEndpoint, pub peer_type: PeerType, pub failures: u32, pub last_attempted: Option<Tm>, } impl Node { pub fn new(id: NodeId, endpoint: NodeEndpoint) -> Node { Node { id: id, endpoint: endpoint, peer_type: PeerType::Optional, failures: 0, last_attempted: None, } } } impl Display for Node { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.endpoint.udp_port!= self.endpoint.address.port() { try!(write!(f, "enode://{}@{}+{}", self.id.hex(), self.endpoint.address, self.endpoint.udp_port)); } else { try!(write!(f, "enode://{}@{}", self.id.hex(), self.endpoint.address)); } Ok(()) } } impl FromStr for Node { type Err = NetworkError; fn from_str(s: &str) -> Result<Self, Self::Err> { let (id, endpoint) = if s.len() > 136 && &s[0..8] == "enode://" && &s[136..137] == "@" { (try!(s[8..136].parse().map_err(UtilError::from)), try!(NodeEndpoint::from_str(&s[137..]))) } else { (NodeId::new(), try!(NodeEndpoint::from_str(s))) }; Ok(Node { id: id, endpoint: endpoint, peer_type: PeerType::Optional, last_attempted: None, failures: 0, }) } } impl PartialEq for Node { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for Node {} impl Hash for Node { fn hash<H>(&self, state: &mut H) where H: Hasher { self.id.hash(state) } } /// Node table backed by disk file. pub struct NodeTable { nodes: HashMap<NodeId, Node>, useless_nodes: HashSet<NodeId>, path: Option<String>, } impl NodeTable { pub fn new(path: Option<String>) -> NodeTable { NodeTable { path: path.clone(), nodes: NodeTable::load(path), useless_nodes: HashSet::new(), } } /// Add a node to table pub fn add_node(&mut self, mut node: Node) { // preserve failure counter let failures = self.nodes.get(&node.id).map_or(0, |n| n.failures); node.failures = failures; self.nodes.insert(node.id.clone(), node); } /// Returns node ids sorted by number of failures pub fn nodes(&self, filter: AllowIP) -> Vec<NodeId> { let mut refs: Vec<&Node> = self.nodes.values().filter(|n|!self.useless_nodes.contains(&n.id) && n.endpoint.is_allowed(filter)).collect(); refs.sort_by(|a, b| a.failures.cmp(&b.failures)); refs.iter().map(|n| n.id.clone()).collect() } /// Unordered list of all entries pub fn unordered_entries(&self) -> Vec<NodeEntry> { // preserve failure counter self.nodes.values().map(|n| NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() }).collect() } /// Get particular node pub fn get_mut(&mut self, id: &NodeId) -> Option<&mut Node> { self.nodes.get_mut(id) } /// Apply table changes coming from discovery pub fn update(&mut self, mut update: TableUpdates, reserved: &HashSet<NodeId>) { for (_, node) in update.added.drain() { let mut entry = self.nodes.entry(node.id.clone()).or_insert_with(|| Node::new(node.id.clone(), node.endpoint.clone())); entry.endpoint = node.endpoint; } for r in update.removed { if!reserved.contains(&r) { self.nodes.remove(&r); } } } /// Increase failure counte for a node pub fn note_failure(&mut self, id: &NodeId) { if let Some(node) = self.nodes.get_mut(id) { node.failures += 1; } } /// Mark as useless, no furter attempts to connect until next call to `clear_useless`. pub fn mark_as_useless(&mut self, id: &NodeId) { self.useless_nodes.insert(id.clone()); } /// Atempt to connect to useless nodes again. pub fn clear_useless(&mut self) { self.useless_nodes.clear(); } /// Save the nodes.json file. pub fn save(&self) { if let Some(ref path) = self.path { let mut path_buf = PathBuf::from(path); if let Err(e) = fs::create_dir_all(path_buf.as_path()) { warn!("Error creating node table directory: {:?}", e); return; }; path_buf.push("nodes.json"); let mut json = String::new(); json.push_str("{\n"); json.push_str("\"nodes\": [\n"); let node_ids = self.nodes(AllowIP::All); for i in 0.. node_ids.len() { let node = self.nodes.get(&node_ids[i]).expect("self.nodes() only returns node IDs from self.nodes"); json.push_str(&format!("\t{{ \"url\": \"{}\", \"failures\": {} }}{}\n", node, node.failures, if i == node_ids.len() - 1 {""} else {","})) } json.push_str("]\n"); json.push_str("}"); let mut file = match fs::File::create(path_buf.as_path()) { Ok(file) => file, Err(e) => { warn!("Error creating node table file: {:?}", e); return; } }; if let Err(e) = file.write(&json.into_bytes()) { warn!("Error writing node table file: {:?}", e); } } } fn
(path: Option<String>) -> HashMap<NodeId, Node> { let mut nodes: HashMap<NodeId, Node> = HashMap::new(); if let Some(path) = path { let mut path_buf = PathBuf::from(path); path_buf.push("nodes.json"); let mut file = match fs::File::open(path_buf.as_path()) { Ok(file) => file, Err(e) => { debug!("Error opening node table file: {:?}", e); return nodes; } }; let mut buf = String::new(); match file.read_to_string(&mut buf) { Ok(_) => {}, Err(e) => { warn!("Error reading node table file: {:?}", e); return nodes; } } let json = match Json::from_str(&buf) { Ok(json) => json, Err(e) => { warn!("Error parsing node table file: {:?}", e); return nodes; } }; if let Some(list) = json.as_object().and_then(|o| o.get("nodes")).and_then(|n| n.as_array()) { for n in list.iter().filter_map(|n| n.as_object()) { if let Some(url) = n.get("url").and_then(|u| u.as_string()) { if let Ok(mut node) = Node::from_str(url) { if let Some(failures) = n.get("failures").and_then(|f| f.as_u64()) { node.failures = failures as u32; } nodes.insert(node.id.clone(), node); } } } } } nodes } } impl Drop for NodeTable { fn drop(&mut self) { self.save(); } } /// Check if node url is valid pub fn is_valid_node_url(url: &str) -> bool { use std::str::FromStr; Node::from_str(url).is_ok() } #[cfg(test)] mod tests { use super::*; use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr}; use util::H512; use std::str::FromStr; use devtools::*; use AllowIP; #[test] fn endpoint_parse() { let endpoint = NodeEndpoint::from_str("123.99.55.44:7770"); assert!(endpoint.is_ok()); let v4 = match endpoint.unwrap().address { SocketAddr::V4(v4address) => v4address, _ => panic!("should ve v4 address") }; assert_eq!(SocketAddrV4::new(Ipv4Addr::new(123, 99, 55, 44), 7770), v4); } #[test] fn node_parse() { assert!(is_valid_node_url("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770")); let node = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770"); assert!(node.is_ok()); let node = node.unwrap(); let v4 = match node.endpoint.address { SocketAddr::V4(v4address) => v4address, _ => panic!("should ve v4 address") }; assert_eq!(SocketAddrV4::new(Ipv4Addr::new(22, 99, 55, 44), 7770), v4); assert_eq!( H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(), node.id); } #[test] fn table_failure_order() { let node1 = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node2 = Node::from_str("enode://b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node3 = Node::from_str("enode://c979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let id1 = H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id2 = H512::from_str("b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id3 = H512::from_str("c979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let mut table = NodeTable::new(None); table.add_node(node3); table.add_node(node1); table.add_node(node2); table.note_failure(&id1); table.note_failure(&id1); table.note_failure(&id2); let r = table.nodes(AllowIP::All); assert_eq!(r[0][..], id3[..]); assert_eq!(r[1][..], id2[..]); assert_eq!(r[2][..], id1[..]); } #[test] fn table_save_load() { let temp_path = RandomTempPath::create_dir(); let node1 = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node2 = Node::from_str("enode://b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let id1 = H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id2 = H512::from_str("b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); { let mut table = NodeTable::new(Some(temp_path.as_path().to_str().unwrap().to_owned())); table.add_node(node1); table.add_node(node2); table.note_failure(&id2); } { let table = NodeTable::new(Some(temp_path.as_path().to_str().unwrap().to_owned())); let r = table.nodes(AllowIP::All); assert_eq!(r[0][..], id1[..]); assert_eq!(r[1][..], id2[..]); } } }
load
identifier_name
node_table.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::mem; use std::slice::from_raw_parts; use std::net::{SocketAddr, ToSocketAddrs, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr}; use std::hash::{Hash, Hasher}; use std::str::{FromStr}; use std::collections::{HashMap, HashSet}; use std::fmt::{Display, Formatter}; use std::path::{PathBuf}; use std::fmt; use std::fs; use std::io::{Read, Write}; use util::hash::*; use util::UtilError; use rlp::*; use time::Tm; use error::NetworkError; use AllowIP; use discovery::{TableUpdates, NodeEntry}; use ip_utils::*; pub use rustc_serialize::json::Json; /// Node public key pub type NodeId = H512; #[derive(Debug, Clone)] /// Node address info pub struct NodeEndpoint { /// IP(V4 or V6) address pub address: SocketAddr, /// Conneciton port. pub udp_port: u16 } impl NodeEndpoint { pub fn udp_address(&self) -> SocketAddr { match self.address { SocketAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a.ip().clone(), self.udp_port)), SocketAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a.ip().clone(), self.udp_port, a.flowinfo(), a.scope_id())), } } pub fn is_allowed(&self, filter: AllowIP) -> bool { match filter { AllowIP::All => true, AllowIP::Private =>!self.address.ip().is_global_s(), AllowIP::Public => self.address.ip().is_global_s(), } } pub fn from_rlp(rlp: &UntrustedRlp) -> Result<Self, DecoderError> { let tcp_port = try!(rlp.val_at::<u16>(2)); let udp_port = try!(rlp.val_at::<u16>(1)); let addr_bytes = try!(try!(rlp.at(0)).data()); let address = try!(match addr_bytes.len() { 4 => Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(addr_bytes[0], addr_bytes[1], addr_bytes[2], addr_bytes[3]), tcp_port))), 16 => unsafe { let o: *const u16 = mem::transmute(addr_bytes.as_ptr()); let o = from_raw_parts(o, 8); Ok(SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7]), tcp_port, 0, 0)))
pub fn to_rlp(&self, rlp: &mut RlpStream) { match self.address { SocketAddr::V4(a) => { rlp.append(&(&a.ip().octets()[..])); } SocketAddr::V6(a) => unsafe { let o: *const u8 = mem::transmute(a.ip().segments().as_ptr()); rlp.append(&from_raw_parts(o, 16)); } }; rlp.append(&self.udp_port); rlp.append(&self.address.port()); } pub fn to_rlp_list(&self, rlp: &mut RlpStream) { rlp.begin_list(3); self.to_rlp(rlp); } pub fn is_valid(&self) -> bool { self.udp_port!= 0 && self.address.port()!= 0 && match self.address { SocketAddr::V4(a) =>!a.ip().is_unspecified_s(), SocketAddr::V6(a) =>!a.ip().is_unspecified_s() } } } impl FromStr for NodeEndpoint { type Err = NetworkError; /// Create endpoint from string. Performs name resolution if given a host name. fn from_str(s: &str) -> Result<NodeEndpoint, NetworkError> { let address = s.to_socket_addrs().map(|mut i| i.next()); match address { Ok(Some(a)) => Ok(NodeEndpoint { address: a, udp_port: a.port() }), Ok(_) => Err(NetworkError::AddressResolve(None)), Err(e) => Err(NetworkError::AddressResolve(Some(e))) } } } #[derive(PartialEq, Eq, Copy, Clone)] pub enum PeerType { _Required, Optional } pub struct Node { pub id: NodeId, pub endpoint: NodeEndpoint, pub peer_type: PeerType, pub failures: u32, pub last_attempted: Option<Tm>, } impl Node { pub fn new(id: NodeId, endpoint: NodeEndpoint) -> Node { Node { id: id, endpoint: endpoint, peer_type: PeerType::Optional, failures: 0, last_attempted: None, } } } impl Display for Node { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.endpoint.udp_port!= self.endpoint.address.port() { try!(write!(f, "enode://{}@{}+{}", self.id.hex(), self.endpoint.address, self.endpoint.udp_port)); } else { try!(write!(f, "enode://{}@{}", self.id.hex(), self.endpoint.address)); } Ok(()) } } impl FromStr for Node { type Err = NetworkError; fn from_str(s: &str) -> Result<Self, Self::Err> { let (id, endpoint) = if s.len() > 136 && &s[0..8] == "enode://" && &s[136..137] == "@" { (try!(s[8..136].parse().map_err(UtilError::from)), try!(NodeEndpoint::from_str(&s[137..]))) } else { (NodeId::new(), try!(NodeEndpoint::from_str(s))) }; Ok(Node { id: id, endpoint: endpoint, peer_type: PeerType::Optional, last_attempted: None, failures: 0, }) } } impl PartialEq for Node { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for Node {} impl Hash for Node { fn hash<H>(&self, state: &mut H) where H: Hasher { self.id.hash(state) } } /// Node table backed by disk file. pub struct NodeTable { nodes: HashMap<NodeId, Node>, useless_nodes: HashSet<NodeId>, path: Option<String>, } impl NodeTable { pub fn new(path: Option<String>) -> NodeTable { NodeTable { path: path.clone(), nodes: NodeTable::load(path), useless_nodes: HashSet::new(), } } /// Add a node to table pub fn add_node(&mut self, mut node: Node) { // preserve failure counter let failures = self.nodes.get(&node.id).map_or(0, |n| n.failures); node.failures = failures; self.nodes.insert(node.id.clone(), node); } /// Returns node ids sorted by number of failures pub fn nodes(&self, filter: AllowIP) -> Vec<NodeId> { let mut refs: Vec<&Node> = self.nodes.values().filter(|n|!self.useless_nodes.contains(&n.id) && n.endpoint.is_allowed(filter)).collect(); refs.sort_by(|a, b| a.failures.cmp(&b.failures)); refs.iter().map(|n| n.id.clone()).collect() } /// Unordered list of all entries pub fn unordered_entries(&self) -> Vec<NodeEntry> { // preserve failure counter self.nodes.values().map(|n| NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() }).collect() } /// Get particular node pub fn get_mut(&mut self, id: &NodeId) -> Option<&mut Node> { self.nodes.get_mut(id) } /// Apply table changes coming from discovery pub fn update(&mut self, mut update: TableUpdates, reserved: &HashSet<NodeId>) { for (_, node) in update.added.drain() { let mut entry = self.nodes.entry(node.id.clone()).or_insert_with(|| Node::new(node.id.clone(), node.endpoint.clone())); entry.endpoint = node.endpoint; } for r in update.removed { if!reserved.contains(&r) { self.nodes.remove(&r); } } } /// Increase failure counte for a node pub fn note_failure(&mut self, id: &NodeId) { if let Some(node) = self.nodes.get_mut(id) { node.failures += 1; } } /// Mark as useless, no furter attempts to connect until next call to `clear_useless`. pub fn mark_as_useless(&mut self, id: &NodeId) { self.useless_nodes.insert(id.clone()); } /// Atempt to connect to useless nodes again. pub fn clear_useless(&mut self) { self.useless_nodes.clear(); } /// Save the nodes.json file. pub fn save(&self) { if let Some(ref path) = self.path { let mut path_buf = PathBuf::from(path); if let Err(e) = fs::create_dir_all(path_buf.as_path()) { warn!("Error creating node table directory: {:?}", e); return; }; path_buf.push("nodes.json"); let mut json = String::new(); json.push_str("{\n"); json.push_str("\"nodes\": [\n"); let node_ids = self.nodes(AllowIP::All); for i in 0.. node_ids.len() { let node = self.nodes.get(&node_ids[i]).expect("self.nodes() only returns node IDs from self.nodes"); json.push_str(&format!("\t{{ \"url\": \"{}\", \"failures\": {} }}{}\n", node, node.failures, if i == node_ids.len() - 1 {""} else {","})) } json.push_str("]\n"); json.push_str("}"); let mut file = match fs::File::create(path_buf.as_path()) { Ok(file) => file, Err(e) => { warn!("Error creating node table file: {:?}", e); return; } }; if let Err(e) = file.write(&json.into_bytes()) { warn!("Error writing node table file: {:?}", e); } } } fn load(path: Option<String>) -> HashMap<NodeId, Node> { let mut nodes: HashMap<NodeId, Node> = HashMap::new(); if let Some(path) = path { let mut path_buf = PathBuf::from(path); path_buf.push("nodes.json"); let mut file = match fs::File::open(path_buf.as_path()) { Ok(file) => file, Err(e) => { debug!("Error opening node table file: {:?}", e); return nodes; } }; let mut buf = String::new(); match file.read_to_string(&mut buf) { Ok(_) => {}, Err(e) => { warn!("Error reading node table file: {:?}", e); return nodes; } } let json = match Json::from_str(&buf) { Ok(json) => json, Err(e) => { warn!("Error parsing node table file: {:?}", e); return nodes; } }; if let Some(list) = json.as_object().and_then(|o| o.get("nodes")).and_then(|n| n.as_array()) { for n in list.iter().filter_map(|n| n.as_object()) { if let Some(url) = n.get("url").and_then(|u| u.as_string()) { if let Ok(mut node) = Node::from_str(url) { if let Some(failures) = n.get("failures").and_then(|f| f.as_u64()) { node.failures = failures as u32; } nodes.insert(node.id.clone(), node); } } } } } nodes } } impl Drop for NodeTable { fn drop(&mut self) { self.save(); } } /// Check if node url is valid pub fn is_valid_node_url(url: &str) -> bool { use std::str::FromStr; Node::from_str(url).is_ok() } #[cfg(test)] mod tests { use super::*; use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr}; use util::H512; use std::str::FromStr; use devtools::*; use AllowIP; #[test] fn endpoint_parse() { let endpoint = NodeEndpoint::from_str("123.99.55.44:7770"); assert!(endpoint.is_ok()); let v4 = match endpoint.unwrap().address { SocketAddr::V4(v4address) => v4address, _ => panic!("should ve v4 address") }; assert_eq!(SocketAddrV4::new(Ipv4Addr::new(123, 99, 55, 44), 7770), v4); } #[test] fn node_parse() { assert!(is_valid_node_url("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770")); let node = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770"); assert!(node.is_ok()); let node = node.unwrap(); let v4 = match node.endpoint.address { SocketAddr::V4(v4address) => v4address, _ => panic!("should ve v4 address") }; assert_eq!(SocketAddrV4::new(Ipv4Addr::new(22, 99, 55, 44), 7770), v4); assert_eq!( H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(), node.id); } #[test] fn table_failure_order() { let node1 = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node2 = Node::from_str("enode://b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node3 = Node::from_str("enode://c979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let id1 = H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id2 = H512::from_str("b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id3 = H512::from_str("c979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let mut table = NodeTable::new(None); table.add_node(node3); table.add_node(node1); table.add_node(node2); table.note_failure(&id1); table.note_failure(&id1); table.note_failure(&id2); let r = table.nodes(AllowIP::All); assert_eq!(r[0][..], id3[..]); assert_eq!(r[1][..], id2[..]); assert_eq!(r[2][..], id1[..]); } #[test] fn table_save_load() { let temp_path = RandomTempPath::create_dir(); let node1 = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node2 = Node::from_str("enode://b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let id1 = H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id2 = H512::from_str("b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); { let mut table = NodeTable::new(Some(temp_path.as_path().to_str().unwrap().to_owned())); table.add_node(node1); table.add_node(node2); table.note_failure(&id2); } { let table = NodeTable::new(Some(temp_path.as_path().to_str().unwrap().to_owned())); let r = table.nodes(AllowIP::All); assert_eq!(r[0][..], id1[..]); assert_eq!(r[1][..], id2[..]); } } }
}, _ => Err(DecoderError::RlpInconsistentLengthAndData) }); Ok(NodeEndpoint { address: address, udp_port: udp_port }) }
random_line_split
node_table.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::mem; use std::slice::from_raw_parts; use std::net::{SocketAddr, ToSocketAddrs, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr}; use std::hash::{Hash, Hasher}; use std::str::{FromStr}; use std::collections::{HashMap, HashSet}; use std::fmt::{Display, Formatter}; use std::path::{PathBuf}; use std::fmt; use std::fs; use std::io::{Read, Write}; use util::hash::*; use util::UtilError; use rlp::*; use time::Tm; use error::NetworkError; use AllowIP; use discovery::{TableUpdates, NodeEntry}; use ip_utils::*; pub use rustc_serialize::json::Json; /// Node public key pub type NodeId = H512; #[derive(Debug, Clone)] /// Node address info pub struct NodeEndpoint { /// IP(V4 or V6) address pub address: SocketAddr, /// Conneciton port. pub udp_port: u16 } impl NodeEndpoint { pub fn udp_address(&self) -> SocketAddr { match self.address { SocketAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a.ip().clone(), self.udp_port)), SocketAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a.ip().clone(), self.udp_port, a.flowinfo(), a.scope_id())), } } pub fn is_allowed(&self, filter: AllowIP) -> bool { match filter { AllowIP::All => true, AllowIP::Private =>!self.address.ip().is_global_s(), AllowIP::Public => self.address.ip().is_global_s(), } } pub fn from_rlp(rlp: &UntrustedRlp) -> Result<Self, DecoderError> { let tcp_port = try!(rlp.val_at::<u16>(2)); let udp_port = try!(rlp.val_at::<u16>(1)); let addr_bytes = try!(try!(rlp.at(0)).data()); let address = try!(match addr_bytes.len() { 4 => Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(addr_bytes[0], addr_bytes[1], addr_bytes[2], addr_bytes[3]), tcp_port))), 16 => unsafe { let o: *const u16 = mem::transmute(addr_bytes.as_ptr()); let o = from_raw_parts(o, 8); Ok(SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7]), tcp_port, 0, 0))) }, _ => Err(DecoderError::RlpInconsistentLengthAndData) }); Ok(NodeEndpoint { address: address, udp_port: udp_port }) } pub fn to_rlp(&self, rlp: &mut RlpStream) { match self.address { SocketAddr::V4(a) => { rlp.append(&(&a.ip().octets()[..])); } SocketAddr::V6(a) => unsafe { let o: *const u8 = mem::transmute(a.ip().segments().as_ptr()); rlp.append(&from_raw_parts(o, 16)); } }; rlp.append(&self.udp_port); rlp.append(&self.address.port()); } pub fn to_rlp_list(&self, rlp: &mut RlpStream) { rlp.begin_list(3); self.to_rlp(rlp); } pub fn is_valid(&self) -> bool { self.udp_port!= 0 && self.address.port()!= 0 && match self.address { SocketAddr::V4(a) =>!a.ip().is_unspecified_s(), SocketAddr::V6(a) =>!a.ip().is_unspecified_s() } } } impl FromStr for NodeEndpoint { type Err = NetworkError; /// Create endpoint from string. Performs name resolution if given a host name. fn from_str(s: &str) -> Result<NodeEndpoint, NetworkError> { let address = s.to_socket_addrs().map(|mut i| i.next()); match address { Ok(Some(a)) => Ok(NodeEndpoint { address: a, udp_port: a.port() }), Ok(_) => Err(NetworkError::AddressResolve(None)), Err(e) => Err(NetworkError::AddressResolve(Some(e))) } } } #[derive(PartialEq, Eq, Copy, Clone)] pub enum PeerType { _Required, Optional } pub struct Node { pub id: NodeId, pub endpoint: NodeEndpoint, pub peer_type: PeerType, pub failures: u32, pub last_attempted: Option<Tm>, } impl Node { pub fn new(id: NodeId, endpoint: NodeEndpoint) -> Node
} impl Display for Node { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.endpoint.udp_port!= self.endpoint.address.port() { try!(write!(f, "enode://{}@{}+{}", self.id.hex(), self.endpoint.address, self.endpoint.udp_port)); } else { try!(write!(f, "enode://{}@{}", self.id.hex(), self.endpoint.address)); } Ok(()) } } impl FromStr for Node { type Err = NetworkError; fn from_str(s: &str) -> Result<Self, Self::Err> { let (id, endpoint) = if s.len() > 136 && &s[0..8] == "enode://" && &s[136..137] == "@" { (try!(s[8..136].parse().map_err(UtilError::from)), try!(NodeEndpoint::from_str(&s[137..]))) } else { (NodeId::new(), try!(NodeEndpoint::from_str(s))) }; Ok(Node { id: id, endpoint: endpoint, peer_type: PeerType::Optional, last_attempted: None, failures: 0, }) } } impl PartialEq for Node { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for Node {} impl Hash for Node { fn hash<H>(&self, state: &mut H) where H: Hasher { self.id.hash(state) } } /// Node table backed by disk file. pub struct NodeTable { nodes: HashMap<NodeId, Node>, useless_nodes: HashSet<NodeId>, path: Option<String>, } impl NodeTable { pub fn new(path: Option<String>) -> NodeTable { NodeTable { path: path.clone(), nodes: NodeTable::load(path), useless_nodes: HashSet::new(), } } /// Add a node to table pub fn add_node(&mut self, mut node: Node) { // preserve failure counter let failures = self.nodes.get(&node.id).map_or(0, |n| n.failures); node.failures = failures; self.nodes.insert(node.id.clone(), node); } /// Returns node ids sorted by number of failures pub fn nodes(&self, filter: AllowIP) -> Vec<NodeId> { let mut refs: Vec<&Node> = self.nodes.values().filter(|n|!self.useless_nodes.contains(&n.id) && n.endpoint.is_allowed(filter)).collect(); refs.sort_by(|a, b| a.failures.cmp(&b.failures)); refs.iter().map(|n| n.id.clone()).collect() } /// Unordered list of all entries pub fn unordered_entries(&self) -> Vec<NodeEntry> { // preserve failure counter self.nodes.values().map(|n| NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() }).collect() } /// Get particular node pub fn get_mut(&mut self, id: &NodeId) -> Option<&mut Node> { self.nodes.get_mut(id) } /// Apply table changes coming from discovery pub fn update(&mut self, mut update: TableUpdates, reserved: &HashSet<NodeId>) { for (_, node) in update.added.drain() { let mut entry = self.nodes.entry(node.id.clone()).or_insert_with(|| Node::new(node.id.clone(), node.endpoint.clone())); entry.endpoint = node.endpoint; } for r in update.removed { if!reserved.contains(&r) { self.nodes.remove(&r); } } } /// Increase failure counte for a node pub fn note_failure(&mut self, id: &NodeId) { if let Some(node) = self.nodes.get_mut(id) { node.failures += 1; } } /// Mark as useless, no furter attempts to connect until next call to `clear_useless`. pub fn mark_as_useless(&mut self, id: &NodeId) { self.useless_nodes.insert(id.clone()); } /// Atempt to connect to useless nodes again. pub fn clear_useless(&mut self) { self.useless_nodes.clear(); } /// Save the nodes.json file. pub fn save(&self) { if let Some(ref path) = self.path { let mut path_buf = PathBuf::from(path); if let Err(e) = fs::create_dir_all(path_buf.as_path()) { warn!("Error creating node table directory: {:?}", e); return; }; path_buf.push("nodes.json"); let mut json = String::new(); json.push_str("{\n"); json.push_str("\"nodes\": [\n"); let node_ids = self.nodes(AllowIP::All); for i in 0.. node_ids.len() { let node = self.nodes.get(&node_ids[i]).expect("self.nodes() only returns node IDs from self.nodes"); json.push_str(&format!("\t{{ \"url\": \"{}\", \"failures\": {} }}{}\n", node, node.failures, if i == node_ids.len() - 1 {""} else {","})) } json.push_str("]\n"); json.push_str("}"); let mut file = match fs::File::create(path_buf.as_path()) { Ok(file) => file, Err(e) => { warn!("Error creating node table file: {:?}", e); return; } }; if let Err(e) = file.write(&json.into_bytes()) { warn!("Error writing node table file: {:?}", e); } } } fn load(path: Option<String>) -> HashMap<NodeId, Node> { let mut nodes: HashMap<NodeId, Node> = HashMap::new(); if let Some(path) = path { let mut path_buf = PathBuf::from(path); path_buf.push("nodes.json"); let mut file = match fs::File::open(path_buf.as_path()) { Ok(file) => file, Err(e) => { debug!("Error opening node table file: {:?}", e); return nodes; } }; let mut buf = String::new(); match file.read_to_string(&mut buf) { Ok(_) => {}, Err(e) => { warn!("Error reading node table file: {:?}", e); return nodes; } } let json = match Json::from_str(&buf) { Ok(json) => json, Err(e) => { warn!("Error parsing node table file: {:?}", e); return nodes; } }; if let Some(list) = json.as_object().and_then(|o| o.get("nodes")).and_then(|n| n.as_array()) { for n in list.iter().filter_map(|n| n.as_object()) { if let Some(url) = n.get("url").and_then(|u| u.as_string()) { if let Ok(mut node) = Node::from_str(url) { if let Some(failures) = n.get("failures").and_then(|f| f.as_u64()) { node.failures = failures as u32; } nodes.insert(node.id.clone(), node); } } } } } nodes } } impl Drop for NodeTable { fn drop(&mut self) { self.save(); } } /// Check if node url is valid pub fn is_valid_node_url(url: &str) -> bool { use std::str::FromStr; Node::from_str(url).is_ok() } #[cfg(test)] mod tests { use super::*; use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr}; use util::H512; use std::str::FromStr; use devtools::*; use AllowIP; #[test] fn endpoint_parse() { let endpoint = NodeEndpoint::from_str("123.99.55.44:7770"); assert!(endpoint.is_ok()); let v4 = match endpoint.unwrap().address { SocketAddr::V4(v4address) => v4address, _ => panic!("should ve v4 address") }; assert_eq!(SocketAddrV4::new(Ipv4Addr::new(123, 99, 55, 44), 7770), v4); } #[test] fn node_parse() { assert!(is_valid_node_url("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770")); let node = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770"); assert!(node.is_ok()); let node = node.unwrap(); let v4 = match node.endpoint.address { SocketAddr::V4(v4address) => v4address, _ => panic!("should ve v4 address") }; assert_eq!(SocketAddrV4::new(Ipv4Addr::new(22, 99, 55, 44), 7770), v4); assert_eq!( H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(), node.id); } #[test] fn table_failure_order() { let node1 = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node2 = Node::from_str("enode://b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node3 = Node::from_str("enode://c979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let id1 = H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id2 = H512::from_str("b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id3 = H512::from_str("c979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let mut table = NodeTable::new(None); table.add_node(node3); table.add_node(node1); table.add_node(node2); table.note_failure(&id1); table.note_failure(&id1); table.note_failure(&id2); let r = table.nodes(AllowIP::All); assert_eq!(r[0][..], id3[..]); assert_eq!(r[1][..], id2[..]); assert_eq!(r[2][..], id1[..]); } #[test] fn table_save_load() { let temp_path = RandomTempPath::create_dir(); let node1 = Node::from_str("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let node2 = Node::from_str("enode://b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@22.99.55.44:7770").unwrap(); let id1 = H512::from_str("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); let id2 = H512::from_str("b979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c").unwrap(); { let mut table = NodeTable::new(Some(temp_path.as_path().to_str().unwrap().to_owned())); table.add_node(node1); table.add_node(node2); table.note_failure(&id2); } { let table = NodeTable::new(Some(temp_path.as_path().to_str().unwrap().to_owned())); let r = table.nodes(AllowIP::All); assert_eq!(r[0][..], id1[..]); assert_eq!(r[1][..], id2[..]); } } }
{ Node { id: id, endpoint: endpoint, peer_type: PeerType::Optional, failures: 0, last_attempted: None, } }
identifier_body
stdio.rs
use crate::platform::vga::{Color, COLS, ROWS}; use crate::platform::vga; pub struct StdioWriter { pub xpos: u32, pub ypos: u32, pub fg: Color, pub bg: Color } impl Copy for StdioWriter {} impl Clone for StdioWriter { fn clone(&self) -> Self { *self } } impl StdioWriter { pub fn new() -> StdioWriter { StdioWriter { xpos: 0, ypos: 0, fg: Color::White, bg: Color::Black } } pub fn clear_screen(&mut self) { for y in 0u32.. ROWS { for x in 0u32.. COLS { vga::putc(x, y, 0); vga::setfg(x, y, self.fg); vga::setbg(x, y, self.bg); } } self.go_to(0, 0); } pub fn go_to(&mut self, x: u32, y: u32) { self.move_coords(x, y); self.set_cursor(); } pub fn backspace(&mut self) { self.go_left(); self.raw_print_char(''as u8); self.set_cursor(); } pub fn tab(&mut self) { let x = self.xpos; for _ in 0.. 4 - (x % 4) { self.raw_print_char(''as u8); self.go_right(); } self.set_cursor(); } pub fn crlf(&mut self) { self.xpos = 0; self.ypos = if self.ypos == ROWS - 1 { 0 } else { self.ypos + 1 }; self.set_cursor(); } fn go_right(&mut self) { if self.xpos == COLS - 1 { self.xpos = 0; self.ypos = (self.ypos + ROWS + 1) % ROWS; } else { self.xpos += 1; } } fn go_left(&mut self) { if self.xpos == 0 { self.xpos = COLS - 1; self.ypos = (self.ypos + ROWS - 1) % ROWS; } else { self.xpos -= 1; } } fn move_coords(&mut self, x: u32, y: u32) { let mut newx = x; let mut newy = y; if newx >= COLS { newx = 0; newy += 1; } if newy >= ROWS { newy = 0; } self.xpos = newx; self.ypos = newy; } fn set_cursor(&self) { vga::move_cursor(self.xpos, self.ypos); } pub fn
(&mut self, v: u32) { if v == 0 { self.print_char('0'); return; } let mut fac = 1; let mut nv = v; while fac <= v { fac *= 10; } fac /= 10; while fac > 0 { let n = nv / fac; let c = n as u8 + '0' as u8; self.raw_print_char(c); self.go_right(); nv -= n * fac; fac /= 10; } self.set_cursor(); } pub fn print_bin(&mut self, v: u32, sz: u32) { self.print_screen("0b"); let mut i = (sz - 1) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0x1 { 0 => '0', _ => '1', } as u8; self.raw_print_char(c); self.go_right(); i -= 1; } self.set_cursor(); } pub fn print_hex(&mut self, v: u32, sz: u32) { self.print_screen("0x"); let mut i = (sz - 4) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0xF { c if c <= 9 => c + '0' as u32, c => c - 10 + 'A' as u32, } as u8; self.raw_print_char(c); self.go_right(); i -= 4; } self.set_cursor(); } pub fn print_char(&mut self, value: char) { self.raw_print_char(value as u8); self.go_right(); self.set_cursor(); } fn raw_print_char(&self, value: u8) { vga::putc(self.xpos, self.ypos, value); vga::setfg(self.xpos, self.ypos, self.fg); vga::setbg(self.xpos, self.ypos, self.bg); } pub fn print_screen(&mut self, value: &str) { for c in value.bytes() { self.raw_print_char(c); self.go_right(); } self.set_cursor(); } } impl ::core::fmt::Write for StdioWriter { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for b in s.bytes() { self.raw_print_char(b); self.go_right(); } self.set_cursor(); Ok(()) } }
print_dec
identifier_name
stdio.rs
use crate::platform::vga::{Color, COLS, ROWS}; use crate::platform::vga; pub struct StdioWriter { pub xpos: u32, pub ypos: u32, pub fg: Color, pub bg: Color } impl Copy for StdioWriter {} impl Clone for StdioWriter { fn clone(&self) -> Self { *self } } impl StdioWriter { pub fn new() -> StdioWriter { StdioWriter { xpos: 0, ypos: 0, fg: Color::White, bg: Color::Black } } pub fn clear_screen(&mut self) { for y in 0u32.. ROWS { for x in 0u32.. COLS { vga::putc(x, y, 0); vga::setfg(x, y, self.fg); vga::setbg(x, y, self.bg); } } self.go_to(0, 0); } pub fn go_to(&mut self, x: u32, y: u32) { self.move_coords(x, y); self.set_cursor(); } pub fn backspace(&mut self) { self.go_left(); self.raw_print_char(''as u8); self.set_cursor(); } pub fn tab(&mut self) { let x = self.xpos; for _ in 0.. 4 - (x % 4) { self.raw_print_char(''as u8); self.go_right(); } self.set_cursor(); } pub fn crlf(&mut self) { self.xpos = 0; self.ypos = if self.ypos == ROWS - 1 { 0 } else { self.ypos + 1 }; self.set_cursor(); } fn go_right(&mut self) { if self.xpos == COLS - 1 { self.xpos = 0; self.ypos = (self.ypos + ROWS + 1) % ROWS; } else { self.xpos += 1; } } fn go_left(&mut self) { if self.xpos == 0 { self.xpos = COLS - 1; self.ypos = (self.ypos + ROWS - 1) % ROWS; } else { self.xpos -= 1; } } fn move_coords(&mut self, x: u32, y: u32) { let mut newx = x; let mut newy = y; if newx >= COLS { newx = 0; newy += 1; } if newy >= ROWS { newy = 0; } self.xpos = newx; self.ypos = newy; } fn set_cursor(&self) { vga::move_cursor(self.xpos, self.ypos); } pub fn print_dec(&mut self, v: u32) { if v == 0 { self.print_char('0'); return; } let mut fac = 1; let mut nv = v; while fac <= v { fac *= 10; } fac /= 10; while fac > 0 { let n = nv / fac; let c = n as u8 + '0' as u8; self.raw_print_char(c); self.go_right(); nv -= n * fac; fac /= 10; } self.set_cursor(); } pub fn print_bin(&mut self, v: u32, sz: u32) { self.print_screen("0b"); let mut i = (sz - 1) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0x1 { 0 => '0', _ => '1', } as u8; self.raw_print_char(c); self.go_right(); i -= 1; } self.set_cursor(); } pub fn print_hex(&mut self, v: u32, sz: u32) { self.print_screen("0x"); let mut i = (sz - 4) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0xF { c if c <= 9 => c + '0' as u32, c => c - 10 + 'A' as u32, } as u8; self.raw_print_char(c); self.go_right(); i -= 4; } self.set_cursor(); } pub fn print_char(&mut self, value: char) { self.raw_print_char(value as u8); self.go_right(); self.set_cursor(); } fn raw_print_char(&self, value: u8) { vga::putc(self.xpos, self.ypos, value); vga::setfg(self.xpos, self.ypos, self.fg); vga::setbg(self.xpos, self.ypos, self.bg); } pub fn print_screen(&mut self, value: &str) { for c in value.bytes() { self.raw_print_char(c); self.go_right(); } self.set_cursor(); } } impl ::core::fmt::Write for StdioWriter { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for b in s.bytes()
self.set_cursor(); Ok(()) } }
{ self.raw_print_char(b); self.go_right(); }
random_line_split
stdio.rs
use crate::platform::vga::{Color, COLS, ROWS}; use crate::platform::vga; pub struct StdioWriter { pub xpos: u32, pub ypos: u32, pub fg: Color, pub bg: Color } impl Copy for StdioWriter {} impl Clone for StdioWriter { fn clone(&self) -> Self { *self } } impl StdioWriter { pub fn new() -> StdioWriter { StdioWriter { xpos: 0, ypos: 0, fg: Color::White, bg: Color::Black } } pub fn clear_screen(&mut self) { for y in 0u32.. ROWS { for x in 0u32.. COLS { vga::putc(x, y, 0); vga::setfg(x, y, self.fg); vga::setbg(x, y, self.bg); } } self.go_to(0, 0); } pub fn go_to(&mut self, x: u32, y: u32) { self.move_coords(x, y); self.set_cursor(); } pub fn backspace(&mut self) { self.go_left(); self.raw_print_char(''as u8); self.set_cursor(); } pub fn tab(&mut self) { let x = self.xpos; for _ in 0.. 4 - (x % 4) { self.raw_print_char(''as u8); self.go_right(); } self.set_cursor(); } pub fn crlf(&mut self) { self.xpos = 0; self.ypos = if self.ypos == ROWS - 1 { 0 } else { self.ypos + 1 }; self.set_cursor(); } fn go_right(&mut self) { if self.xpos == COLS - 1 { self.xpos = 0; self.ypos = (self.ypos + ROWS + 1) % ROWS; } else { self.xpos += 1; } } fn go_left(&mut self) { if self.xpos == 0 { self.xpos = COLS - 1; self.ypos = (self.ypos + ROWS - 1) % ROWS; } else { self.xpos -= 1; } } fn move_coords(&mut self, x: u32, y: u32) { let mut newx = x; let mut newy = y; if newx >= COLS { newx = 0; newy += 1; } if newy >= ROWS
self.xpos = newx; self.ypos = newy; } fn set_cursor(&self) { vga::move_cursor(self.xpos, self.ypos); } pub fn print_dec(&mut self, v: u32) { if v == 0 { self.print_char('0'); return; } let mut fac = 1; let mut nv = v; while fac <= v { fac *= 10; } fac /= 10; while fac > 0 { let n = nv / fac; let c = n as u8 + '0' as u8; self.raw_print_char(c); self.go_right(); nv -= n * fac; fac /= 10; } self.set_cursor(); } pub fn print_bin(&mut self, v: u32, sz: u32) { self.print_screen("0b"); let mut i = (sz - 1) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0x1 { 0 => '0', _ => '1', } as u8; self.raw_print_char(c); self.go_right(); i -= 1; } self.set_cursor(); } pub fn print_hex(&mut self, v: u32, sz: u32) { self.print_screen("0x"); let mut i = (sz - 4) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0xF { c if c <= 9 => c + '0' as u32, c => c - 10 + 'A' as u32, } as u8; self.raw_print_char(c); self.go_right(); i -= 4; } self.set_cursor(); } pub fn print_char(&mut self, value: char) { self.raw_print_char(value as u8); self.go_right(); self.set_cursor(); } fn raw_print_char(&self, value: u8) { vga::putc(self.xpos, self.ypos, value); vga::setfg(self.xpos, self.ypos, self.fg); vga::setbg(self.xpos, self.ypos, self.bg); } pub fn print_screen(&mut self, value: &str) { for c in value.bytes() { self.raw_print_char(c); self.go_right(); } self.set_cursor(); } } impl ::core::fmt::Write for StdioWriter { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for b in s.bytes() { self.raw_print_char(b); self.go_right(); } self.set_cursor(); Ok(()) } }
{ newy = 0; }
conditional_block
stdio.rs
use crate::platform::vga::{Color, COLS, ROWS}; use crate::platform::vga; pub struct StdioWriter { pub xpos: u32, pub ypos: u32, pub fg: Color, pub bg: Color } impl Copy for StdioWriter {} impl Clone for StdioWriter { fn clone(&self) -> Self { *self } } impl StdioWriter { pub fn new() -> StdioWriter { StdioWriter { xpos: 0, ypos: 0, fg: Color::White, bg: Color::Black } } pub fn clear_screen(&mut self) { for y in 0u32.. ROWS { for x in 0u32.. COLS { vga::putc(x, y, 0); vga::setfg(x, y, self.fg); vga::setbg(x, y, self.bg); } } self.go_to(0, 0); } pub fn go_to(&mut self, x: u32, y: u32) { self.move_coords(x, y); self.set_cursor(); } pub fn backspace(&mut self) { self.go_left(); self.raw_print_char(''as u8); self.set_cursor(); } pub fn tab(&mut self) { let x = self.xpos; for _ in 0.. 4 - (x % 4) { self.raw_print_char(''as u8); self.go_right(); } self.set_cursor(); } pub fn crlf(&mut self) { self.xpos = 0; self.ypos = if self.ypos == ROWS - 1 { 0 } else { self.ypos + 1 }; self.set_cursor(); } fn go_right(&mut self) { if self.xpos == COLS - 1 { self.xpos = 0; self.ypos = (self.ypos + ROWS + 1) % ROWS; } else { self.xpos += 1; } } fn go_left(&mut self) { if self.xpos == 0 { self.xpos = COLS - 1; self.ypos = (self.ypos + ROWS - 1) % ROWS; } else { self.xpos -= 1; } } fn move_coords(&mut self, x: u32, y: u32) { let mut newx = x; let mut newy = y; if newx >= COLS { newx = 0; newy += 1; } if newy >= ROWS { newy = 0; } self.xpos = newx; self.ypos = newy; } fn set_cursor(&self) { vga::move_cursor(self.xpos, self.ypos); } pub fn print_dec(&mut self, v: u32) { if v == 0 { self.print_char('0'); return; } let mut fac = 1; let mut nv = v; while fac <= v { fac *= 10; } fac /= 10; while fac > 0 { let n = nv / fac; let c = n as u8 + '0' as u8; self.raw_print_char(c); self.go_right(); nv -= n * fac; fac /= 10; } self.set_cursor(); } pub fn print_bin(&mut self, v: u32, sz: u32) { self.print_screen("0b"); let mut i = (sz - 1) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0x1 { 0 => '0', _ => '1', } as u8; self.raw_print_char(c); self.go_right(); i -= 1; } self.set_cursor(); } pub fn print_hex(&mut self, v: u32, sz: u32)
pub fn print_char(&mut self, value: char) { self.raw_print_char(value as u8); self.go_right(); self.set_cursor(); } fn raw_print_char(&self, value: u8) { vga::putc(self.xpos, self.ypos, value); vga::setfg(self.xpos, self.ypos, self.fg); vga::setbg(self.xpos, self.ypos, self.bg); } pub fn print_screen(&mut self, value: &str) { for c in value.bytes() { self.raw_print_char(c); self.go_right(); } self.set_cursor(); } } impl ::core::fmt::Write for StdioWriter { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for b in s.bytes() { self.raw_print_char(b); self.go_right(); } self.set_cursor(); Ok(()) } }
{ self.print_screen("0x"); let mut i = (sz - 4) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0xF { c if c <= 9 => c + '0' as u32, c => c - 10 + 'A' as u32, } as u8; self.raw_print_char(c); self.go_right(); i -= 4; } self.set_cursor(); }
identifier_body
next.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; use core::iter::Rev; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } // fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator { // Rev{iter: self} // } } } } impl DoubleEndedIterator for A<T> { fn next_back(&mut self) -> Option<Self::Item> { if self.begin < self.end { self.end = self.end.wrapping_sub(1); Some::<Self::Item>(self.end) } else { None::<Self::Item> } } } type T = i32; Iterator_impl!(T); // impl<I> Iterator for Rev<I> where I: DoubleEndedIterator { // type Item = <I as Iterator>::Item; // // #[inline] // fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() } // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } // } #[test] fn next_test1() { let a: A<T> = A { begin: 1, end: 6 }; let mut rev: Rev<A<T>> = a.rev(); for x in 1..6 { let y: Option<T> = rev.next(); match y { Some(v) =>
None => { assert!(false); } } } assert_eq!(rev.next(), None::<T>); } }
{ assert_eq!(v, 6 - x); }
conditional_block
next.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; use core::iter::Rev; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } // fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator { // Rev{iter: self} // } } } } impl DoubleEndedIterator for A<T> { fn next_back(&mut self) -> Option<Self::Item> { if self.begin < self.end { self.end = self.end.wrapping_sub(1); Some::<Self::Item>(self.end) } else { None::<Self::Item> } } } type T = i32; Iterator_impl!(T); // impl<I> Iterator for Rev<I> where I: DoubleEndedIterator { // type Item = <I as Iterator>::Item; // // #[inline] // fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() } // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } // } #[test] fn
() { let a: A<T> = A { begin: 1, end: 6 }; let mut rev: Rev<A<T>> = a.rev(); for x in 1..6 { let y: Option<T> = rev.next(); match y { Some(v) => { assert_eq!(v, 6 - x); } None => { assert!(false); } } } assert_eq!(rev.next(), None::<T>); } }
next_test1
identifier_name
next.rs
#[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; use core::iter::Rev; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } // fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator { // Rev{iter: self} // } } } } impl DoubleEndedIterator for A<T> { fn next_back(&mut self) -> Option<Self::Item> { if self.begin < self.end { self.end = self.end.wrapping_sub(1); Some::<Self::Item>(self.end) } else { None::<Self::Item> } } } type T = i32; Iterator_impl!(T); // impl<I> Iterator for Rev<I> where I: DoubleEndedIterator { // type Item = <I as Iterator>::Item; // // #[inline] // fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() } // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } // } #[test] fn next_test1() { let a: A<T> = A { begin: 1, end: 6 }; let mut rev: Rev<A<T>> = a.rev(); for x in 1..6 { let y: Option<T> = rev.next(); match y { Some(v) => { assert_eq!(v, 6 - x); } None => { assert!(false); } } } assert_eq!(rev.next(), None::<T>); } }
#![feature(core)] extern crate core;
random_line_split
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use bytes::{Buf, Bytes}; use diem_infallible::Mutex; use futures::{ channel::mpsc::{self, UnboundedReceiver, UnboundedSender}, io::{AsyncRead, AsyncWrite, Error, ErrorKind, Result}, ready, stream::{FusedStream, Stream}, task::{Context, Poll}, }; use once_cell::sync::Lazy; use std::{collections::HashMap, num::NonZeroU16, pin::Pin}; static SWITCHBOARD: Lazy<Mutex<SwitchBoard>> = Lazy::new(|| Mutex::new(SwitchBoard(HashMap::default(), 1))); struct SwitchBoard(HashMap<NonZeroU16, UnboundedSender<MemorySocket>>, u16); /// An in-memory socket server, listening for connections. /// /// After creating a `MemoryListener` by [`bind`]ing it to a socket address, it listens /// for incoming connections. These can be accepted by awaiting elements from the /// async stream of incoming connections, [`incoming`][`MemoryListener::incoming`]. /// /// The socket will be closed when the value is dropped. /// /// [`bind`]: #method.bind /// [`MemoryListener::incoming`]: #method.incoming /// /// # Examples /// /// ```rust,no_run /// use std::io::Result; /// /// use memsocket::{MemoryListener, MemorySocket}; /// use futures::prelude::*; /// /// async fn write_stormlight(mut stream: MemorySocket) -> Result<()> { /// let msg = b"The most important step a person can take is always the next one."; /// stream.write_all(msg).await?; /// stream.flush().await /// } /// /// async fn listen() -> Result<()> { /// let mut listener = MemoryListener::bind(16)?; /// let mut incoming = listener.incoming(); /// /// // accept connections and process them serially /// while let Some(stream) = incoming.next().await { /// write_stormlight(stream?).await?; /// } /// Ok(()) /// } /// ``` #[derive(Debug)] pub struct MemoryListener { incoming: UnboundedReceiver<MemorySocket>, port: NonZeroU16, } impl Drop for MemoryListener { fn drop(&mut self) { let mut switchboard = (&*SWITCHBOARD).lock(); // Remove the Sending side of the channel in the switchboard when // MemoryListener is dropped switchboard.0.remove(&self.port); } } impl MemoryListener { /// Creates a new `MemoryListener` which will be bound to the specified /// port. /// /// The returned listener is ready for accepting connections. /// /// Binding with a port number of 0 will request that a port be assigned /// to this listener. The port allocated can be queried via the /// [`local_addr`] method. /// /// # Examples /// Create a MemoryListener bound to port 16: /// /// ```rust,no_run /// use memsocket::MemoryListener; /// /// # fn main () -> ::std::io::Result<()> { /// let listener = MemoryListener::bind(16)?; /// # Ok(())} /// ``` /// /// [`local_addr`]: #method.local_addr pub fn bind(port: u16) -> Result<Self> { let mut switchboard = (&*SWITCHBOARD).lock(); // Get the port we should bind to. If 0 was given, use a random port let port = if let Some(port) = NonZeroU16::new(port) { if switchboard.0.contains_key(&port) { return Err(ErrorKind::AddrInUse.into()); } port } else { loop { let port = NonZeroU16::new(switchboard.1).unwrap_or_else(|| unreachable!()); // The switchboard is full and all ports are in use if Some(switchboard.0.len()) == std::u16::MAX.checked_sub(1).map(usize::from) { return Err(ErrorKind::AddrInUse.into()); } // Instead of overflowing to 0, resume searching at port 1 since port 0 isn't a // valid port to bind to. switchboard.1 = switchboard.1.checked_add(1).unwrap_or(1); if!switchboard.0.contains_key(&port) { break port; } } }; let (sender, receiver) = mpsc::unbounded(); switchboard.0.insert(port, sender); Ok(Self { incoming: receiver, port, }) } /// Returns the local address that this listener is bound to. /// /// This can be useful, for example, when binding to port 0 to figure out /// which port was actually bound. /// /// # Examples /// /// ```rust /// use memsocket::MemoryListener; /// /// # fn main () -> ::std::io::Result<()> { /// let listener = MemoryListener::bind(16)?; /// /// assert_eq!(listener.local_addr(), 16); /// # Ok(())} /// ``` pub fn local_addr(&self) -> u16 { self.port.get() } /// Consumes this listener, returning a stream of the sockets this listener /// accepts. /// /// This method returns an implementation of the `Stream` trait which /// resolves to the sockets the are accepted on this listener. /// /// # Examples /// /// ```rust,no_run /// use futures::prelude::*; /// use memsocket::MemoryListener; /// /// # async fn work () -> ::std::io::Result<()> { /// let mut listener = MemoryListener::bind(16)?; /// let mut incoming = listener.incoming(); /// /// // accept connections and process them serially /// while let Some(stream) = incoming.next().await { /// match stream { /// Ok(stream) => { /// println!("new connection!"); /// }, /// Err(e) => { /* connection failed */ } /// } /// } /// # Ok(())} /// ``` pub fn incoming(&mut self) -> Incoming<'_> { Incoming { inner: self } } fn poll_accept(&mut self, context: &mut Context) -> Poll<Result<MemorySocket>>
} /// Stream returned by the `MemoryListener::incoming` function representing the /// stream of sockets received from a listener. #[must_use = "streams do nothing unless polled"] #[derive(Debug)] pub struct Incoming<'a> { inner: &'a mut MemoryListener, } impl<'a> Stream for Incoming<'a> { type Item = Result<MemorySocket>; fn poll_next(mut self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Self::Item>> { let socket = ready!(self.inner.poll_accept(context)?); Poll::Ready(Some(Ok(socket))) } } /// An in-memory stream between two local sockets. /// /// A `MemorySocket` can either be created by connecting to an endpoint, via the /// [`connect`] method, or by [accepting] a connection from a [listener]. /// It can be read or written to using the `AsyncRead`, `AsyncWrite`, and related /// extension traits in `futures::io`. /// /// # Examples /// /// ```rust, no_run /// use futures::prelude::*; /// use memsocket::MemorySocket; /// /// # async fn run() -> ::std::io::Result<()> { /// let (mut socket_a, mut socket_b) = MemorySocket::new_pair(); /// /// socket_a.write_all(b"stormlight").await?; /// socket_a.flush().await?; /// /// let mut buf = [0; 10]; /// socket_b.read_exact(&mut buf).await?; /// assert_eq!(&buf, b"stormlight"); /// /// # Ok(())} /// ``` /// /// [`connect`]: struct.MemorySocket.html#method.connect /// [accepting]: struct.MemoryListener.html#method.accept /// [listener]: struct.MemoryListener.html #[derive(Debug)] pub struct MemorySocket { incoming: UnboundedReceiver<Bytes>, outgoing: UnboundedSender<Bytes>, current_buffer: Option<Bytes>, seen_eof: bool, } impl MemorySocket { /// Construct both sides of an in-memory socket. /// /// # Examples /// /// ```rust /// use memsocket::MemorySocket; /// /// let (socket_a, socket_b) = MemorySocket::new_pair(); /// ``` pub fn new_pair() -> (Self, Self) { let (a_tx, a_rx) = mpsc::unbounded(); let (b_tx, b_rx) = mpsc::unbounded(); let a = Self { incoming: a_rx, outgoing: b_tx, current_buffer: None, seen_eof: false, }; let b = Self { incoming: b_rx, outgoing: a_tx, current_buffer: None, seen_eof: false, }; (a, b) } /// Create a new in-memory Socket connected to the specified port. /// /// This function will create a new MemorySocket socket and attempt to connect it to /// the `port` provided. /// /// # Examples /// /// ```rust,no_run /// use memsocket::MemorySocket; /// /// # fn main () -> ::std::io::Result<()> { /// let socket = MemorySocket::connect(16)?; /// # Ok(())} /// ``` pub fn connect(port: u16) -> Result<MemorySocket> { let mut switchboard = (&*SWITCHBOARD).lock(); // Find port to connect to let port = NonZeroU16::new(port).ok_or(ErrorKind::AddrNotAvailable)?; let sender = switchboard .0 .get_mut(&port) .ok_or(ErrorKind::AddrNotAvailable)?; let (socket_a, socket_b) = Self::new_pair(); // Send the socket to the listener if let Err(e) = sender.unbounded_send(socket_a) { if e.is_disconnected() { return Err(ErrorKind::AddrNotAvailable.into()); } unreachable!(); } Ok(socket_b) } } impl AsyncRead for MemorySocket { /// Attempt to read from the `AsyncRead` into `buf`. fn poll_read( mut self: Pin<&mut Self>, mut context: &mut Context, buf: &mut [u8], ) -> Poll<Result<usize>> { if self.incoming.is_terminated() { if self.seen_eof { return Poll::Ready(Err(ErrorKind::UnexpectedEof.into())); } else { self.seen_eof = true; return Poll::Ready(Ok(0)); } } let mut bytes_read = 0; loop { // If we're already filled up the buffer then we can return if bytes_read == buf.len() { return Poll::Ready(Ok(bytes_read)); } match self.current_buffer { // We have data to copy to buf Some(ref mut current_buffer) if current_buffer.has_remaining() => { let bytes_to_read = ::std::cmp::min(buf.len() - bytes_read, current_buffer.remaining()); debug_assert!(bytes_to_read > 0); current_buffer .take(bytes_to_read) .copy_to_slice(&mut buf[bytes_read..(bytes_read + bytes_to_read)]); bytes_read += bytes_to_read; } // Either we've exhausted our current buffer or don't have one _ => { self.current_buffer = { match Pin::new(&mut self.incoming).poll_next(&mut context) { Poll::Pending => { // If we've read anything up to this point return the bytes read if bytes_read > 0 { return Poll::Ready(Ok(bytes_read)); } else { return Poll::Pending; } } Poll::Ready(Some(buf)) => Some(buf), Poll::Ready(None) => return Poll::Ready(Ok(bytes_read)), } }; } } } } } impl AsyncWrite for MemorySocket { /// Attempt to write bytes from `buf` into the outgoing channel. fn poll_write( mut self: Pin<&mut Self>, context: &mut Context, buf: &[u8], ) -> Poll<Result<usize>> { let len = buf.len(); match self.outgoing.poll_ready(context) { Poll::Ready(Ok(())) => { if let Err(e) = self.outgoing.start_send(Bytes::copy_from_slice(buf)) { if e.is_disconnected() { return Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, e))); } // Unbounded channels should only ever have "Disconnected" errors unreachable!(); } } Poll::Ready(Err(e)) => { if e.is_disconnected() { return Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, e))); } // Unbounded channels should only ever have "Disconnected" errors unreachable!(); } Poll::Pending => return Poll::Pending, } Poll::Ready(Ok(len)) } /// Attempt to flush the channel. Cannot Fail. fn poll_flush(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { Poll::Ready(Ok(())) } /// Attempt to close the channel. Cannot Fail. fn poll_close(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { self.outgoing.close_channel(); Poll::Ready(Ok(())) } }
{ match Pin::new(&mut self.incoming).poll_next(context) { Poll::Ready(Some(socket)) => Poll::Ready(Ok(socket)), Poll::Ready(None) => { let err = Error::new(ErrorKind::Other, "MemoryListener unknown error"); Poll::Ready(Err(err)) } Poll::Pending => Poll::Pending, } }
identifier_body
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use bytes::{Buf, Bytes}; use diem_infallible::Mutex; use futures::{ channel::mpsc::{self, UnboundedReceiver, UnboundedSender}, io::{AsyncRead, AsyncWrite, Error, ErrorKind, Result}, ready, stream::{FusedStream, Stream}, task::{Context, Poll}, }; use once_cell::sync::Lazy; use std::{collections::HashMap, num::NonZeroU16, pin::Pin}; static SWITCHBOARD: Lazy<Mutex<SwitchBoard>> = Lazy::new(|| Mutex::new(SwitchBoard(HashMap::default(), 1))); struct SwitchBoard(HashMap<NonZeroU16, UnboundedSender<MemorySocket>>, u16); /// An in-memory socket server, listening for connections. /// /// After creating a `MemoryListener` by [`bind`]ing it to a socket address, it listens /// for incoming connections. These can be accepted by awaiting elements from the /// async stream of incoming connections, [`incoming`][`MemoryListener::incoming`]. /// /// The socket will be closed when the value is dropped. /// /// [`bind`]: #method.bind /// [`MemoryListener::incoming`]: #method.incoming /// /// # Examples /// /// ```rust,no_run /// use std::io::Result; /// /// use memsocket::{MemoryListener, MemorySocket}; /// use futures::prelude::*; /// /// async fn write_stormlight(mut stream: MemorySocket) -> Result<()> { /// let msg = b"The most important step a person can take is always the next one."; /// stream.write_all(msg).await?; /// stream.flush().await /// } /// /// async fn listen() -> Result<()> { /// let mut listener = MemoryListener::bind(16)?; /// let mut incoming = listener.incoming(); /// /// // accept connections and process them serially /// while let Some(stream) = incoming.next().await { /// write_stormlight(stream?).await?; /// } /// Ok(()) /// } /// ``` #[derive(Debug)] pub struct MemoryListener { incoming: UnboundedReceiver<MemorySocket>, port: NonZeroU16, } impl Drop for MemoryListener { fn drop(&mut self) { let mut switchboard = (&*SWITCHBOARD).lock(); // Remove the Sending side of the channel in the switchboard when // MemoryListener is dropped switchboard.0.remove(&self.port); } } impl MemoryListener { /// Creates a new `MemoryListener` which will be bound to the specified /// port. /// /// The returned listener is ready for accepting connections. /// /// Binding with a port number of 0 will request that a port be assigned /// to this listener. The port allocated can be queried via the /// [`local_addr`] method. /// /// # Examples /// Create a MemoryListener bound to port 16: /// /// ```rust,no_run /// use memsocket::MemoryListener; /// /// # fn main () -> ::std::io::Result<()> { /// let listener = MemoryListener::bind(16)?; /// # Ok(())} /// ``` /// /// [`local_addr`]: #method.local_addr pub fn bind(port: u16) -> Result<Self> { let mut switchboard = (&*SWITCHBOARD).lock(); // Get the port we should bind to. If 0 was given, use a random port let port = if let Some(port) = NonZeroU16::new(port) { if switchboard.0.contains_key(&port)
port } else { loop { let port = NonZeroU16::new(switchboard.1).unwrap_or_else(|| unreachable!()); // The switchboard is full and all ports are in use if Some(switchboard.0.len()) == std::u16::MAX.checked_sub(1).map(usize::from) { return Err(ErrorKind::AddrInUse.into()); } // Instead of overflowing to 0, resume searching at port 1 since port 0 isn't a // valid port to bind to. switchboard.1 = switchboard.1.checked_add(1).unwrap_or(1); if!switchboard.0.contains_key(&port) { break port; } } }; let (sender, receiver) = mpsc::unbounded(); switchboard.0.insert(port, sender); Ok(Self { incoming: receiver, port, }) } /// Returns the local address that this listener is bound to. /// /// This can be useful, for example, when binding to port 0 to figure out /// which port was actually bound. /// /// # Examples /// /// ```rust /// use memsocket::MemoryListener; /// /// # fn main () -> ::std::io::Result<()> { /// let listener = MemoryListener::bind(16)?; /// /// assert_eq!(listener.local_addr(), 16); /// # Ok(())} /// ``` pub fn local_addr(&self) -> u16 { self.port.get() } /// Consumes this listener, returning a stream of the sockets this listener /// accepts. /// /// This method returns an implementation of the `Stream` trait which /// resolves to the sockets the are accepted on this listener. /// /// # Examples /// /// ```rust,no_run /// use futures::prelude::*; /// use memsocket::MemoryListener; /// /// # async fn work () -> ::std::io::Result<()> { /// let mut listener = MemoryListener::bind(16)?; /// let mut incoming = listener.incoming(); /// /// // accept connections and process them serially /// while let Some(stream) = incoming.next().await { /// match stream { /// Ok(stream) => { /// println!("new connection!"); /// }, /// Err(e) => { /* connection failed */ } /// } /// } /// # Ok(())} /// ``` pub fn incoming(&mut self) -> Incoming<'_> { Incoming { inner: self } } fn poll_accept(&mut self, context: &mut Context) -> Poll<Result<MemorySocket>> { match Pin::new(&mut self.incoming).poll_next(context) { Poll::Ready(Some(socket)) => Poll::Ready(Ok(socket)), Poll::Ready(None) => { let err = Error::new(ErrorKind::Other, "MemoryListener unknown error"); Poll::Ready(Err(err)) } Poll::Pending => Poll::Pending, } } } /// Stream returned by the `MemoryListener::incoming` function representing the /// stream of sockets received from a listener. #[must_use = "streams do nothing unless polled"] #[derive(Debug)] pub struct Incoming<'a> { inner: &'a mut MemoryListener, } impl<'a> Stream for Incoming<'a> { type Item = Result<MemorySocket>; fn poll_next(mut self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Self::Item>> { let socket = ready!(self.inner.poll_accept(context)?); Poll::Ready(Some(Ok(socket))) } } /// An in-memory stream between two local sockets. /// /// A `MemorySocket` can either be created by connecting to an endpoint, via the /// [`connect`] method, or by [accepting] a connection from a [listener]. /// It can be read or written to using the `AsyncRead`, `AsyncWrite`, and related /// extension traits in `futures::io`. /// /// # Examples /// /// ```rust, no_run /// use futures::prelude::*; /// use memsocket::MemorySocket; /// /// # async fn run() -> ::std::io::Result<()> { /// let (mut socket_a, mut socket_b) = MemorySocket::new_pair(); /// /// socket_a.write_all(b"stormlight").await?; /// socket_a.flush().await?; /// /// let mut buf = [0; 10]; /// socket_b.read_exact(&mut buf).await?; /// assert_eq!(&buf, b"stormlight"); /// /// # Ok(())} /// ``` /// /// [`connect`]: struct.MemorySocket.html#method.connect /// [accepting]: struct.MemoryListener.html#method.accept /// [listener]: struct.MemoryListener.html #[derive(Debug)] pub struct MemorySocket { incoming: UnboundedReceiver<Bytes>, outgoing: UnboundedSender<Bytes>, current_buffer: Option<Bytes>, seen_eof: bool, } impl MemorySocket { /// Construct both sides of an in-memory socket. /// /// # Examples /// /// ```rust /// use memsocket::MemorySocket; /// /// let (socket_a, socket_b) = MemorySocket::new_pair(); /// ``` pub fn new_pair() -> (Self, Self) { let (a_tx, a_rx) = mpsc::unbounded(); let (b_tx, b_rx) = mpsc::unbounded(); let a = Self { incoming: a_rx, outgoing: b_tx, current_buffer: None, seen_eof: false, }; let b = Self { incoming: b_rx, outgoing: a_tx, current_buffer: None, seen_eof: false, }; (a, b) } /// Create a new in-memory Socket connected to the specified port. /// /// This function will create a new MemorySocket socket and attempt to connect it to /// the `port` provided. /// /// # Examples /// /// ```rust,no_run /// use memsocket::MemorySocket; /// /// # fn main () -> ::std::io::Result<()> { /// let socket = MemorySocket::connect(16)?; /// # Ok(())} /// ``` pub fn connect(port: u16) -> Result<MemorySocket> { let mut switchboard = (&*SWITCHBOARD).lock(); // Find port to connect to let port = NonZeroU16::new(port).ok_or(ErrorKind::AddrNotAvailable)?; let sender = switchboard .0 .get_mut(&port) .ok_or(ErrorKind::AddrNotAvailable)?; let (socket_a, socket_b) = Self::new_pair(); // Send the socket to the listener if let Err(e) = sender.unbounded_send(socket_a) { if e.is_disconnected() { return Err(ErrorKind::AddrNotAvailable.into()); } unreachable!(); } Ok(socket_b) } } impl AsyncRead for MemorySocket { /// Attempt to read from the `AsyncRead` into `buf`. fn poll_read( mut self: Pin<&mut Self>, mut context: &mut Context, buf: &mut [u8], ) -> Poll<Result<usize>> { if self.incoming.is_terminated() { if self.seen_eof { return Poll::Ready(Err(ErrorKind::UnexpectedEof.into())); } else { self.seen_eof = true; return Poll::Ready(Ok(0)); } } let mut bytes_read = 0; loop { // If we're already filled up the buffer then we can return if bytes_read == buf.len() { return Poll::Ready(Ok(bytes_read)); } match self.current_buffer { // We have data to copy to buf Some(ref mut current_buffer) if current_buffer.has_remaining() => { let bytes_to_read = ::std::cmp::min(buf.len() - bytes_read, current_buffer.remaining()); debug_assert!(bytes_to_read > 0); current_buffer .take(bytes_to_read) .copy_to_slice(&mut buf[bytes_read..(bytes_read + bytes_to_read)]); bytes_read += bytes_to_read; } // Either we've exhausted our current buffer or don't have one _ => { self.current_buffer = { match Pin::new(&mut self.incoming).poll_next(&mut context) { Poll::Pending => { // If we've read anything up to this point return the bytes read if bytes_read > 0 { return Poll::Ready(Ok(bytes_read)); } else { return Poll::Pending; } } Poll::Ready(Some(buf)) => Some(buf), Poll::Ready(None) => return Poll::Ready(Ok(bytes_read)), } }; } } } } } impl AsyncWrite for MemorySocket { /// Attempt to write bytes from `buf` into the outgoing channel. fn poll_write( mut self: Pin<&mut Self>, context: &mut Context, buf: &[u8], ) -> Poll<Result<usize>> { let len = buf.len(); match self.outgoing.poll_ready(context) { Poll::Ready(Ok(())) => { if let Err(e) = self.outgoing.start_send(Bytes::copy_from_slice(buf)) { if e.is_disconnected() { return Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, e))); } // Unbounded channels should only ever have "Disconnected" errors unreachable!(); } } Poll::Ready(Err(e)) => { if e.is_disconnected() { return Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, e))); } // Unbounded channels should only ever have "Disconnected" errors unreachable!(); } Poll::Pending => return Poll::Pending, } Poll::Ready(Ok(len)) } /// Attempt to flush the channel. Cannot Fail. fn poll_flush(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { Poll::Ready(Ok(())) } /// Attempt to close the channel. Cannot Fail. fn poll_close(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { self.outgoing.close_channel(); Poll::Ready(Ok(())) } }
{ return Err(ErrorKind::AddrInUse.into()); }
conditional_block
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use bytes::{Buf, Bytes}; use diem_infallible::Mutex; use futures::{ channel::mpsc::{self, UnboundedReceiver, UnboundedSender}, io::{AsyncRead, AsyncWrite, Error, ErrorKind, Result}, ready, stream::{FusedStream, Stream}, task::{Context, Poll}, }; use once_cell::sync::Lazy; use std::{collections::HashMap, num::NonZeroU16, pin::Pin}; static SWITCHBOARD: Lazy<Mutex<SwitchBoard>> = Lazy::new(|| Mutex::new(SwitchBoard(HashMap::default(), 1))); struct SwitchBoard(HashMap<NonZeroU16, UnboundedSender<MemorySocket>>, u16); /// An in-memory socket server, listening for connections. /// /// After creating a `MemoryListener` by [`bind`]ing it to a socket address, it listens /// for incoming connections. These can be accepted by awaiting elements from the /// async stream of incoming connections, [`incoming`][`MemoryListener::incoming`]. /// /// The socket will be closed when the value is dropped. /// /// [`bind`]: #method.bind /// [`MemoryListener::incoming`]: #method.incoming /// /// # Examples /// /// ```rust,no_run /// use std::io::Result; /// /// use memsocket::{MemoryListener, MemorySocket}; /// use futures::prelude::*; /// /// async fn write_stormlight(mut stream: MemorySocket) -> Result<()> { /// let msg = b"The most important step a person can take is always the next one."; /// stream.write_all(msg).await?; /// stream.flush().await /// } /// /// async fn listen() -> Result<()> { /// let mut listener = MemoryListener::bind(16)?; /// let mut incoming = listener.incoming(); /// /// // accept connections and process them serially /// while let Some(stream) = incoming.next().await { /// write_stormlight(stream?).await?; /// } /// Ok(()) /// } /// ``` #[derive(Debug)] pub struct MemoryListener { incoming: UnboundedReceiver<MemorySocket>, port: NonZeroU16, } impl Drop for MemoryListener { fn drop(&mut self) { let mut switchboard = (&*SWITCHBOARD).lock(); // Remove the Sending side of the channel in the switchboard when // MemoryListener is dropped switchboard.0.remove(&self.port); } } impl MemoryListener { /// Creates a new `MemoryListener` which will be bound to the specified /// port. /// /// The returned listener is ready for accepting connections. /// /// Binding with a port number of 0 will request that a port be assigned /// to this listener. The port allocated can be queried via the /// [`local_addr`] method. /// /// # Examples /// Create a MemoryListener bound to port 16: /// /// ```rust,no_run /// use memsocket::MemoryListener; /// /// # fn main () -> ::std::io::Result<()> { /// let listener = MemoryListener::bind(16)?; /// # Ok(())} /// ``` /// /// [`local_addr`]: #method.local_addr pub fn bind(port: u16) -> Result<Self> { let mut switchboard = (&*SWITCHBOARD).lock(); // Get the port we should bind to. If 0 was given, use a random port let port = if let Some(port) = NonZeroU16::new(port) { if switchboard.0.contains_key(&port) { return Err(ErrorKind::AddrInUse.into());
loop { let port = NonZeroU16::new(switchboard.1).unwrap_or_else(|| unreachable!()); // The switchboard is full and all ports are in use if Some(switchboard.0.len()) == std::u16::MAX.checked_sub(1).map(usize::from) { return Err(ErrorKind::AddrInUse.into()); } // Instead of overflowing to 0, resume searching at port 1 since port 0 isn't a // valid port to bind to. switchboard.1 = switchboard.1.checked_add(1).unwrap_or(1); if!switchboard.0.contains_key(&port) { break port; } } }; let (sender, receiver) = mpsc::unbounded(); switchboard.0.insert(port, sender); Ok(Self { incoming: receiver, port, }) } /// Returns the local address that this listener is bound to. /// /// This can be useful, for example, when binding to port 0 to figure out /// which port was actually bound. /// /// # Examples /// /// ```rust /// use memsocket::MemoryListener; /// /// # fn main () -> ::std::io::Result<()> { /// let listener = MemoryListener::bind(16)?; /// /// assert_eq!(listener.local_addr(), 16); /// # Ok(())} /// ``` pub fn local_addr(&self) -> u16 { self.port.get() } /// Consumes this listener, returning a stream of the sockets this listener /// accepts. /// /// This method returns an implementation of the `Stream` trait which /// resolves to the sockets the are accepted on this listener. /// /// # Examples /// /// ```rust,no_run /// use futures::prelude::*; /// use memsocket::MemoryListener; /// /// # async fn work () -> ::std::io::Result<()> { /// let mut listener = MemoryListener::bind(16)?; /// let mut incoming = listener.incoming(); /// /// // accept connections and process them serially /// while let Some(stream) = incoming.next().await { /// match stream { /// Ok(stream) => { /// println!("new connection!"); /// }, /// Err(e) => { /* connection failed */ } /// } /// } /// # Ok(())} /// ``` pub fn incoming(&mut self) -> Incoming<'_> { Incoming { inner: self } } fn poll_accept(&mut self, context: &mut Context) -> Poll<Result<MemorySocket>> { match Pin::new(&mut self.incoming).poll_next(context) { Poll::Ready(Some(socket)) => Poll::Ready(Ok(socket)), Poll::Ready(None) => { let err = Error::new(ErrorKind::Other, "MemoryListener unknown error"); Poll::Ready(Err(err)) } Poll::Pending => Poll::Pending, } } } /// Stream returned by the `MemoryListener::incoming` function representing the /// stream of sockets received from a listener. #[must_use = "streams do nothing unless polled"] #[derive(Debug)] pub struct Incoming<'a> { inner: &'a mut MemoryListener, } impl<'a> Stream for Incoming<'a> { type Item = Result<MemorySocket>; fn poll_next(mut self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Self::Item>> { let socket = ready!(self.inner.poll_accept(context)?); Poll::Ready(Some(Ok(socket))) } } /// An in-memory stream between two local sockets. /// /// A `MemorySocket` can either be created by connecting to an endpoint, via the /// [`connect`] method, or by [accepting] a connection from a [listener]. /// It can be read or written to using the `AsyncRead`, `AsyncWrite`, and related /// extension traits in `futures::io`. /// /// # Examples /// /// ```rust, no_run /// use futures::prelude::*; /// use memsocket::MemorySocket; /// /// # async fn run() -> ::std::io::Result<()> { /// let (mut socket_a, mut socket_b) = MemorySocket::new_pair(); /// /// socket_a.write_all(b"stormlight").await?; /// socket_a.flush().await?; /// /// let mut buf = [0; 10]; /// socket_b.read_exact(&mut buf).await?; /// assert_eq!(&buf, b"stormlight"); /// /// # Ok(())} /// ``` /// /// [`connect`]: struct.MemorySocket.html#method.connect /// [accepting]: struct.MemoryListener.html#method.accept /// [listener]: struct.MemoryListener.html #[derive(Debug)] pub struct MemorySocket { incoming: UnboundedReceiver<Bytes>, outgoing: UnboundedSender<Bytes>, current_buffer: Option<Bytes>, seen_eof: bool, } impl MemorySocket { /// Construct both sides of an in-memory socket. /// /// # Examples /// /// ```rust /// use memsocket::MemorySocket; /// /// let (socket_a, socket_b) = MemorySocket::new_pair(); /// ``` pub fn new_pair() -> (Self, Self) { let (a_tx, a_rx) = mpsc::unbounded(); let (b_tx, b_rx) = mpsc::unbounded(); let a = Self { incoming: a_rx, outgoing: b_tx, current_buffer: None, seen_eof: false, }; let b = Self { incoming: b_rx, outgoing: a_tx, current_buffer: None, seen_eof: false, }; (a, b) } /// Create a new in-memory Socket connected to the specified port. /// /// This function will create a new MemorySocket socket and attempt to connect it to /// the `port` provided. /// /// # Examples /// /// ```rust,no_run /// use memsocket::MemorySocket; /// /// # fn main () -> ::std::io::Result<()> { /// let socket = MemorySocket::connect(16)?; /// # Ok(())} /// ``` pub fn connect(port: u16) -> Result<MemorySocket> { let mut switchboard = (&*SWITCHBOARD).lock(); // Find port to connect to let port = NonZeroU16::new(port).ok_or(ErrorKind::AddrNotAvailable)?; let sender = switchboard .0 .get_mut(&port) .ok_or(ErrorKind::AddrNotAvailable)?; let (socket_a, socket_b) = Self::new_pair(); // Send the socket to the listener if let Err(e) = sender.unbounded_send(socket_a) { if e.is_disconnected() { return Err(ErrorKind::AddrNotAvailable.into()); } unreachable!(); } Ok(socket_b) } } impl AsyncRead for MemorySocket { /// Attempt to read from the `AsyncRead` into `buf`. fn poll_read( mut self: Pin<&mut Self>, mut context: &mut Context, buf: &mut [u8], ) -> Poll<Result<usize>> { if self.incoming.is_terminated() { if self.seen_eof { return Poll::Ready(Err(ErrorKind::UnexpectedEof.into())); } else { self.seen_eof = true; return Poll::Ready(Ok(0)); } } let mut bytes_read = 0; loop { // If we're already filled up the buffer then we can return if bytes_read == buf.len() { return Poll::Ready(Ok(bytes_read)); } match self.current_buffer { // We have data to copy to buf Some(ref mut current_buffer) if current_buffer.has_remaining() => { let bytes_to_read = ::std::cmp::min(buf.len() - bytes_read, current_buffer.remaining()); debug_assert!(bytes_to_read > 0); current_buffer .take(bytes_to_read) .copy_to_slice(&mut buf[bytes_read..(bytes_read + bytes_to_read)]); bytes_read += bytes_to_read; } // Either we've exhausted our current buffer or don't have one _ => { self.current_buffer = { match Pin::new(&mut self.incoming).poll_next(&mut context) { Poll::Pending => { // If we've read anything up to this point return the bytes read if bytes_read > 0 { return Poll::Ready(Ok(bytes_read)); } else { return Poll::Pending; } } Poll::Ready(Some(buf)) => Some(buf), Poll::Ready(None) => return Poll::Ready(Ok(bytes_read)), } }; } } } } } impl AsyncWrite for MemorySocket { /// Attempt to write bytes from `buf` into the outgoing channel. fn poll_write( mut self: Pin<&mut Self>, context: &mut Context, buf: &[u8], ) -> Poll<Result<usize>> { let len = buf.len(); match self.outgoing.poll_ready(context) { Poll::Ready(Ok(())) => { if let Err(e) = self.outgoing.start_send(Bytes::copy_from_slice(buf)) { if e.is_disconnected() { return Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, e))); } // Unbounded channels should only ever have "Disconnected" errors unreachable!(); } } Poll::Ready(Err(e)) => { if e.is_disconnected() { return Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, e))); } // Unbounded channels should only ever have "Disconnected" errors unreachable!(); } Poll::Pending => return Poll::Pending, } Poll::Ready(Ok(len)) } /// Attempt to flush the channel. Cannot Fail. fn poll_flush(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { Poll::Ready(Ok(())) } /// Attempt to close the channel. Cannot Fail. fn poll_close(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { self.outgoing.close_channel(); Poll::Ready(Ok(())) } }
} port } else {
random_line_split
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use bytes::{Buf, Bytes}; use diem_infallible::Mutex; use futures::{ channel::mpsc::{self, UnboundedReceiver, UnboundedSender}, io::{AsyncRead, AsyncWrite, Error, ErrorKind, Result}, ready, stream::{FusedStream, Stream}, task::{Context, Poll}, }; use once_cell::sync::Lazy; use std::{collections::HashMap, num::NonZeroU16, pin::Pin}; static SWITCHBOARD: Lazy<Mutex<SwitchBoard>> = Lazy::new(|| Mutex::new(SwitchBoard(HashMap::default(), 1))); struct SwitchBoard(HashMap<NonZeroU16, UnboundedSender<MemorySocket>>, u16); /// An in-memory socket server, listening for connections. /// /// After creating a `MemoryListener` by [`bind`]ing it to a socket address, it listens /// for incoming connections. These can be accepted by awaiting elements from the /// async stream of incoming connections, [`incoming`][`MemoryListener::incoming`]. /// /// The socket will be closed when the value is dropped. /// /// [`bind`]: #method.bind /// [`MemoryListener::incoming`]: #method.incoming /// /// # Examples /// /// ```rust,no_run /// use std::io::Result; /// /// use memsocket::{MemoryListener, MemorySocket}; /// use futures::prelude::*; /// /// async fn write_stormlight(mut stream: MemorySocket) -> Result<()> { /// let msg = b"The most important step a person can take is always the next one."; /// stream.write_all(msg).await?; /// stream.flush().await /// } /// /// async fn listen() -> Result<()> { /// let mut listener = MemoryListener::bind(16)?; /// let mut incoming = listener.incoming(); /// /// // accept connections and process them serially /// while let Some(stream) = incoming.next().await { /// write_stormlight(stream?).await?; /// } /// Ok(()) /// } /// ``` #[derive(Debug)] pub struct MemoryListener { incoming: UnboundedReceiver<MemorySocket>, port: NonZeroU16, } impl Drop for MemoryListener { fn drop(&mut self) { let mut switchboard = (&*SWITCHBOARD).lock(); // Remove the Sending side of the channel in the switchboard when // MemoryListener is dropped switchboard.0.remove(&self.port); } } impl MemoryListener { /// Creates a new `MemoryListener` which will be bound to the specified /// port. /// /// The returned listener is ready for accepting connections. /// /// Binding with a port number of 0 will request that a port be assigned /// to this listener. The port allocated can be queried via the /// [`local_addr`] method. /// /// # Examples /// Create a MemoryListener bound to port 16: /// /// ```rust,no_run /// use memsocket::MemoryListener; /// /// # fn main () -> ::std::io::Result<()> { /// let listener = MemoryListener::bind(16)?; /// # Ok(())} /// ``` /// /// [`local_addr`]: #method.local_addr pub fn bind(port: u16) -> Result<Self> { let mut switchboard = (&*SWITCHBOARD).lock(); // Get the port we should bind to. If 0 was given, use a random port let port = if let Some(port) = NonZeroU16::new(port) { if switchboard.0.contains_key(&port) { return Err(ErrorKind::AddrInUse.into()); } port } else { loop { let port = NonZeroU16::new(switchboard.1).unwrap_or_else(|| unreachable!()); // The switchboard is full and all ports are in use if Some(switchboard.0.len()) == std::u16::MAX.checked_sub(1).map(usize::from) { return Err(ErrorKind::AddrInUse.into()); } // Instead of overflowing to 0, resume searching at port 1 since port 0 isn't a // valid port to bind to. switchboard.1 = switchboard.1.checked_add(1).unwrap_or(1); if!switchboard.0.contains_key(&port) { break port; } } }; let (sender, receiver) = mpsc::unbounded(); switchboard.0.insert(port, sender); Ok(Self { incoming: receiver, port, }) } /// Returns the local address that this listener is bound to. /// /// This can be useful, for example, when binding to port 0 to figure out /// which port was actually bound. /// /// # Examples /// /// ```rust /// use memsocket::MemoryListener; /// /// # fn main () -> ::std::io::Result<()> { /// let listener = MemoryListener::bind(16)?; /// /// assert_eq!(listener.local_addr(), 16); /// # Ok(())} /// ``` pub fn local_addr(&self) -> u16 { self.port.get() } /// Consumes this listener, returning a stream of the sockets this listener /// accepts. /// /// This method returns an implementation of the `Stream` trait which /// resolves to the sockets the are accepted on this listener. /// /// # Examples /// /// ```rust,no_run /// use futures::prelude::*; /// use memsocket::MemoryListener; /// /// # async fn work () -> ::std::io::Result<()> { /// let mut listener = MemoryListener::bind(16)?; /// let mut incoming = listener.incoming(); /// /// // accept connections and process them serially /// while let Some(stream) = incoming.next().await { /// match stream { /// Ok(stream) => { /// println!("new connection!"); /// }, /// Err(e) => { /* connection failed */ } /// } /// } /// # Ok(())} /// ``` pub fn incoming(&mut self) -> Incoming<'_> { Incoming { inner: self } } fn poll_accept(&mut self, context: &mut Context) -> Poll<Result<MemorySocket>> { match Pin::new(&mut self.incoming).poll_next(context) { Poll::Ready(Some(socket)) => Poll::Ready(Ok(socket)), Poll::Ready(None) => { let err = Error::new(ErrorKind::Other, "MemoryListener unknown error"); Poll::Ready(Err(err)) } Poll::Pending => Poll::Pending, } } } /// Stream returned by the `MemoryListener::incoming` function representing the /// stream of sockets received from a listener. #[must_use = "streams do nothing unless polled"] #[derive(Debug)] pub struct Incoming<'a> { inner: &'a mut MemoryListener, } impl<'a> Stream for Incoming<'a> { type Item = Result<MemorySocket>; fn poll_next(mut self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Self::Item>> { let socket = ready!(self.inner.poll_accept(context)?); Poll::Ready(Some(Ok(socket))) } } /// An in-memory stream between two local sockets. /// /// A `MemorySocket` can either be created by connecting to an endpoint, via the /// [`connect`] method, or by [accepting] a connection from a [listener]. /// It can be read or written to using the `AsyncRead`, `AsyncWrite`, and related /// extension traits in `futures::io`. /// /// # Examples /// /// ```rust, no_run /// use futures::prelude::*; /// use memsocket::MemorySocket; /// /// # async fn run() -> ::std::io::Result<()> { /// let (mut socket_a, mut socket_b) = MemorySocket::new_pair(); /// /// socket_a.write_all(b"stormlight").await?; /// socket_a.flush().await?; /// /// let mut buf = [0; 10]; /// socket_b.read_exact(&mut buf).await?; /// assert_eq!(&buf, b"stormlight"); /// /// # Ok(())} /// ``` /// /// [`connect`]: struct.MemorySocket.html#method.connect /// [accepting]: struct.MemoryListener.html#method.accept /// [listener]: struct.MemoryListener.html #[derive(Debug)] pub struct MemorySocket { incoming: UnboundedReceiver<Bytes>, outgoing: UnboundedSender<Bytes>, current_buffer: Option<Bytes>, seen_eof: bool, } impl MemorySocket { /// Construct both sides of an in-memory socket. /// /// # Examples /// /// ```rust /// use memsocket::MemorySocket; /// /// let (socket_a, socket_b) = MemorySocket::new_pair(); /// ``` pub fn new_pair() -> (Self, Self) { let (a_tx, a_rx) = mpsc::unbounded(); let (b_tx, b_rx) = mpsc::unbounded(); let a = Self { incoming: a_rx, outgoing: b_tx, current_buffer: None, seen_eof: false, }; let b = Self { incoming: b_rx, outgoing: a_tx, current_buffer: None, seen_eof: false, }; (a, b) } /// Create a new in-memory Socket connected to the specified port. /// /// This function will create a new MemorySocket socket and attempt to connect it to /// the `port` provided. /// /// # Examples /// /// ```rust,no_run /// use memsocket::MemorySocket; /// /// # fn main () -> ::std::io::Result<()> { /// let socket = MemorySocket::connect(16)?; /// # Ok(())} /// ``` pub fn connect(port: u16) -> Result<MemorySocket> { let mut switchboard = (&*SWITCHBOARD).lock(); // Find port to connect to let port = NonZeroU16::new(port).ok_or(ErrorKind::AddrNotAvailable)?; let sender = switchboard .0 .get_mut(&port) .ok_or(ErrorKind::AddrNotAvailable)?; let (socket_a, socket_b) = Self::new_pair(); // Send the socket to the listener if let Err(e) = sender.unbounded_send(socket_a) { if e.is_disconnected() { return Err(ErrorKind::AddrNotAvailable.into()); } unreachable!(); } Ok(socket_b) } } impl AsyncRead for MemorySocket { /// Attempt to read from the `AsyncRead` into `buf`. fn poll_read( mut self: Pin<&mut Self>, mut context: &mut Context, buf: &mut [u8], ) -> Poll<Result<usize>> { if self.incoming.is_terminated() { if self.seen_eof { return Poll::Ready(Err(ErrorKind::UnexpectedEof.into())); } else { self.seen_eof = true; return Poll::Ready(Ok(0)); } } let mut bytes_read = 0; loop { // If we're already filled up the buffer then we can return if bytes_read == buf.len() { return Poll::Ready(Ok(bytes_read)); } match self.current_buffer { // We have data to copy to buf Some(ref mut current_buffer) if current_buffer.has_remaining() => { let bytes_to_read = ::std::cmp::min(buf.len() - bytes_read, current_buffer.remaining()); debug_assert!(bytes_to_read > 0); current_buffer .take(bytes_to_read) .copy_to_slice(&mut buf[bytes_read..(bytes_read + bytes_to_read)]); bytes_read += bytes_to_read; } // Either we've exhausted our current buffer or don't have one _ => { self.current_buffer = { match Pin::new(&mut self.incoming).poll_next(&mut context) { Poll::Pending => { // If we've read anything up to this point return the bytes read if bytes_read > 0 { return Poll::Ready(Ok(bytes_read)); } else { return Poll::Pending; } } Poll::Ready(Some(buf)) => Some(buf), Poll::Ready(None) => return Poll::Ready(Ok(bytes_read)), } }; } } } } } impl AsyncWrite for MemorySocket { /// Attempt to write bytes from `buf` into the outgoing channel. fn poll_write( mut self: Pin<&mut Self>, context: &mut Context, buf: &[u8], ) -> Poll<Result<usize>> { let len = buf.len(); match self.outgoing.poll_ready(context) { Poll::Ready(Ok(())) => { if let Err(e) = self.outgoing.start_send(Bytes::copy_from_slice(buf)) { if e.is_disconnected() { return Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, e))); } // Unbounded channels should only ever have "Disconnected" errors unreachable!(); } } Poll::Ready(Err(e)) => { if e.is_disconnected() { return Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, e))); } // Unbounded channels should only ever have "Disconnected" errors unreachable!(); } Poll::Pending => return Poll::Pending, } Poll::Ready(Ok(len)) } /// Attempt to flush the channel. Cannot Fail. fn poll_flush(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { Poll::Ready(Ok(())) } /// Attempt to close the channel. Cannot Fail. fn
(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { self.outgoing.close_channel(); Poll::Ready(Ok(())) } }
poll_close
identifier_name
reflect.rs
use std::collections::HashMap; #[derive(RustcDecodable)] pub struct Demo { pub name: String, pub generate: bool, pub control: Control, pub debug: Debug, pub palette: Palette, } #[derive(RustcDecodable)] pub struct Control { pub move_speed: f32, pub rotate_speed: f32, }
pub struct Debug { pub offset: (i32, i32), pub line_jump: i32, pub color: (f32, f32, f32, f32), pub time_factor: u64, } #[derive(RustcDecodable)] pub struct Palette { pub scene: String, pub size: f32, pub model: Model, pub tiles: HashMap<String, String>, pub water_plants: Vec<String>, pub plants: Vec<String>, pub tents: Vec<String>, pub camp_fires: Vec<String>, } #[derive(RustcDecodable)] pub struct Model { pub grid_size: (i32, i32), pub water_plant_chance: f32, pub plant_chance: f32, pub max_grass_plants: u8, pub max_river_plants: u8, pub tent_chance: f32, pub water_height: f32, pub ground_height: f32, }
#[derive(RustcDecodable)]
random_line_split
reflect.rs
use std::collections::HashMap; #[derive(RustcDecodable)] pub struct Demo { pub name: String, pub generate: bool, pub control: Control, pub debug: Debug, pub palette: Palette, } #[derive(RustcDecodable)] pub struct Control { pub move_speed: f32, pub rotate_speed: f32, } #[derive(RustcDecodable)] pub struct
{ pub offset: (i32, i32), pub line_jump: i32, pub color: (f32, f32, f32, f32), pub time_factor: u64, } #[derive(RustcDecodable)] pub struct Palette { pub scene: String, pub size: f32, pub model: Model, pub tiles: HashMap<String, String>, pub water_plants: Vec<String>, pub plants: Vec<String>, pub tents: Vec<String>, pub camp_fires: Vec<String>, } #[derive(RustcDecodable)] pub struct Model { pub grid_size: (i32, i32), pub water_plant_chance: f32, pub plant_chance: f32, pub max_grass_plants: u8, pub max_river_plants: u8, pub tent_chance: f32, pub water_height: f32, pub ground_height: f32, }
Debug
identifier_name
poll.rs
#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::time::TimeSpec; #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::signal::SigSet; use std::os::unix::io::RawFd; use libc; use {Errno, Result}; /// This is a wrapper around `libc::pollfd`. /// /// It's meant to be used as an argument to the [`poll`](fn.poll.html) and /// [`ppoll`](fn.ppoll.html) functions to specify the events of interest /// for a specific file descriptor. /// /// After a call to `poll` or `ppoll`, the events that occured can be /// retrieved by calling [`revents()`](#method.revents) on the `PollFd`. #[repr(C)] #[derive(Clone, Copy)] pub struct PollFd { pollfd: libc::pollfd, } impl PollFd { /// Creates a new `PollFd` specifying the events of interest /// for a given file descriptor. pub fn new(fd: RawFd, events: EventFlags) -> PollFd { PollFd { pollfd: libc::pollfd { fd: fd, events: events.bits(), revents: EventFlags::empty().bits(), }, } } /// Returns the events that occured in the last call to `poll` or `ppoll`. pub fn
(&self) -> Option<EventFlags> { EventFlags::from_bits(self.pollfd.revents) } } libc_bitflags! { /// These flags define the different events that can be monitored by `poll` and `ppoll` pub struct EventFlags: libc::c_short { /// There is data to read. POLLIN; /// There is some exceptional condition on the file descriptor. /// /// Possibilities include: /// /// * There is out-of-band data on a TCP socket (see /// [tcp(7)](http://man7.org/linux/man-pages/man7/tcp.7.html)). /// * A pseudoterminal master in packet mode has seen a state /// change on the slave (see /// [ioctl_tty(2)](http://man7.org/linux/man-pages/man2/ioctl_tty.2.html)). /// * A cgroup.events file has been modified (see /// [cgroups(7)](http://man7.org/linux/man-pages/man7/cgroups.7.html)). POLLPRI; /// Writing is now possible, though a write larger that the /// available space in a socket or pipe will still block (unless /// `O_NONBLOCK` is set). POLLOUT; /// Equivalent to [`POLLIN`](constant.POLLIN.html) POLLRDNORM; /// Equivalent to [`POLLOUT`](constant.POLLOUT.html) POLLWRNORM; /// Priority band data can be read (generally unused on Linux). POLLRDBAND; /// Priority data may be written. POLLWRBAND; /// Error condition (only returned in /// [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). /// This bit is also set for a file descriptor referring to the /// write end of a pipe when the read end has been closed. POLLERR; /// Hang up (only returned in [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). /// Note that when reading from a channel such as a pipe or a stream /// socket, this event merely indicates that the peer closed its /// end of the channel. Subsequent reads from the channel will /// return 0 (end of file) only after all outstanding data in the /// channel has been consumed. POLLHUP; /// Invalid request: `fd` not open (only returned in /// [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). POLLNVAL; } } /// `poll` waits for one of a set of file descriptors to become ready to perform I/O. /// ([`poll(2)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/poll.html)) /// /// `fds` contains all [`PollFd`](struct.PollFd.html) to poll. /// The function will return as soon as any event occur for any of these `PollFd`s. /// /// The `timeout` argument specifies the number of milliseconds that `poll()` /// should block waiting for a file descriptor to become ready. The call /// will block until either: /// /// * a file descriptor becomes ready; /// * the call is interrupted by a signal handler; or /// * the timeout expires. /// /// Note that the timeout interval will be rounded up to the system clock /// granularity, and kernel scheduling delays mean that the blocking /// interval may overrun by a small amount. Specifying a negative value /// in timeout means an infinite timeout. Specifying a timeout of zero /// causes `poll()` to return immediately, even if no file descriptors are /// ready. pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result<libc::c_int> { let res = unsafe { libc::poll(fds.as_mut_ptr() as *mut libc::pollfd, fds.len() as libc::nfds_t, timeout) }; Errno::result(res) } /// `ppoll()` allows an application to safely wait until either a file /// descriptor becomes ready or until a signal is caught. /// ([`poll(2)`](http://man7.org/linux/man-pages/man2/poll.2.html)) /// /// `ppoll` behaves like `poll`, but let you specify what signals may interrupt it /// with the `sigmask` argument. /// #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] pub fn ppoll(fds: &mut [PollFd], timeout: TimeSpec, sigmask: SigSet) -> Result<libc::c_int> { let res = unsafe { libc::ppoll(fds.as_mut_ptr() as *mut libc::pollfd, fds.len() as libc::nfds_t, timeout.as_ref(), sigmask.as_ref()) }; Errno::result(res) }
revents
identifier_name
poll.rs
#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::time::TimeSpec; #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::signal::SigSet; use std::os::unix::io::RawFd; use libc; use {Errno, Result}; /// This is a wrapper around `libc::pollfd`. /// /// It's meant to be used as an argument to the [`poll`](fn.poll.html) and /// [`ppoll`](fn.ppoll.html) functions to specify the events of interest /// for a specific file descriptor. /// /// After a call to `poll` or `ppoll`, the events that occured can be /// retrieved by calling [`revents()`](#method.revents) on the `PollFd`. #[repr(C)] #[derive(Clone, Copy)] pub struct PollFd { pollfd: libc::pollfd, } impl PollFd { /// Creates a new `PollFd` specifying the events of interest /// for a given file descriptor. pub fn new(fd: RawFd, events: EventFlags) -> PollFd { PollFd { pollfd: libc::pollfd { fd: fd, events: events.bits(), revents: EventFlags::empty().bits(), }, } } /// Returns the events that occured in the last call to `poll` or `ppoll`. pub fn revents(&self) -> Option<EventFlags> { EventFlags::from_bits(self.pollfd.revents) } } libc_bitflags! { /// These flags define the different events that can be monitored by `poll` and `ppoll` pub struct EventFlags: libc::c_short { /// There is data to read. POLLIN; /// There is some exceptional condition on the file descriptor. /// /// Possibilities include: /// /// * There is out-of-band data on a TCP socket (see /// [tcp(7)](http://man7.org/linux/man-pages/man7/tcp.7.html)). /// * A pseudoterminal master in packet mode has seen a state /// change on the slave (see /// [ioctl_tty(2)](http://man7.org/linux/man-pages/man2/ioctl_tty.2.html)). /// * A cgroup.events file has been modified (see /// [cgroups(7)](http://man7.org/linux/man-pages/man7/cgroups.7.html)). POLLPRI; /// Writing is now possible, though a write larger that the /// available space in a socket or pipe will still block (unless /// `O_NONBLOCK` is set). POLLOUT; /// Equivalent to [`POLLIN`](constant.POLLIN.html) POLLRDNORM; /// Equivalent to [`POLLOUT`](constant.POLLOUT.html) POLLWRNORM; /// Priority band data can be read (generally unused on Linux). POLLRDBAND;
POLLWRBAND; /// Error condition (only returned in /// [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). /// This bit is also set for a file descriptor referring to the /// write end of a pipe when the read end has been closed. POLLERR; /// Hang up (only returned in [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). /// Note that when reading from a channel such as a pipe or a stream /// socket, this event merely indicates that the peer closed its /// end of the channel. Subsequent reads from the channel will /// return 0 (end of file) only after all outstanding data in the /// channel has been consumed. POLLHUP; /// Invalid request: `fd` not open (only returned in /// [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). POLLNVAL; } } /// `poll` waits for one of a set of file descriptors to become ready to perform I/O. /// ([`poll(2)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/poll.html)) /// /// `fds` contains all [`PollFd`](struct.PollFd.html) to poll. /// The function will return as soon as any event occur for any of these `PollFd`s. /// /// The `timeout` argument specifies the number of milliseconds that `poll()` /// should block waiting for a file descriptor to become ready. The call /// will block until either: /// /// * a file descriptor becomes ready; /// * the call is interrupted by a signal handler; or /// * the timeout expires. /// /// Note that the timeout interval will be rounded up to the system clock /// granularity, and kernel scheduling delays mean that the blocking /// interval may overrun by a small amount. Specifying a negative value /// in timeout means an infinite timeout. Specifying a timeout of zero /// causes `poll()` to return immediately, even if no file descriptors are /// ready. pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result<libc::c_int> { let res = unsafe { libc::poll(fds.as_mut_ptr() as *mut libc::pollfd, fds.len() as libc::nfds_t, timeout) }; Errno::result(res) } /// `ppoll()` allows an application to safely wait until either a file /// descriptor becomes ready or until a signal is caught. /// ([`poll(2)`](http://man7.org/linux/man-pages/man2/poll.2.html)) /// /// `ppoll` behaves like `poll`, but let you specify what signals may interrupt it /// with the `sigmask` argument. /// #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] pub fn ppoll(fds: &mut [PollFd], timeout: TimeSpec, sigmask: SigSet) -> Result<libc::c_int> { let res = unsafe { libc::ppoll(fds.as_mut_ptr() as *mut libc::pollfd, fds.len() as libc::nfds_t, timeout.as_ref(), sigmask.as_ref()) }; Errno::result(res) }
/// Priority data may be written.
random_line_split
poll.rs
#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::time::TimeSpec; #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::signal::SigSet; use std::os::unix::io::RawFd; use libc; use {Errno, Result}; /// This is a wrapper around `libc::pollfd`. /// /// It's meant to be used as an argument to the [`poll`](fn.poll.html) and /// [`ppoll`](fn.ppoll.html) functions to specify the events of interest /// for a specific file descriptor. /// /// After a call to `poll` or `ppoll`, the events that occured can be /// retrieved by calling [`revents()`](#method.revents) on the `PollFd`. #[repr(C)] #[derive(Clone, Copy)] pub struct PollFd { pollfd: libc::pollfd, } impl PollFd { /// Creates a new `PollFd` specifying the events of interest /// for a given file descriptor. pub fn new(fd: RawFd, events: EventFlags) -> PollFd { PollFd { pollfd: libc::pollfd { fd: fd, events: events.bits(), revents: EventFlags::empty().bits(), }, } } /// Returns the events that occured in the last call to `poll` or `ppoll`. pub fn revents(&self) -> Option<EventFlags>
} libc_bitflags! { /// These flags define the different events that can be monitored by `poll` and `ppoll` pub struct EventFlags: libc::c_short { /// There is data to read. POLLIN; /// There is some exceptional condition on the file descriptor. /// /// Possibilities include: /// /// * There is out-of-band data on a TCP socket (see /// [tcp(7)](http://man7.org/linux/man-pages/man7/tcp.7.html)). /// * A pseudoterminal master in packet mode has seen a state /// change on the slave (see /// [ioctl_tty(2)](http://man7.org/linux/man-pages/man2/ioctl_tty.2.html)). /// * A cgroup.events file has been modified (see /// [cgroups(7)](http://man7.org/linux/man-pages/man7/cgroups.7.html)). POLLPRI; /// Writing is now possible, though a write larger that the /// available space in a socket or pipe will still block (unless /// `O_NONBLOCK` is set). POLLOUT; /// Equivalent to [`POLLIN`](constant.POLLIN.html) POLLRDNORM; /// Equivalent to [`POLLOUT`](constant.POLLOUT.html) POLLWRNORM; /// Priority band data can be read (generally unused on Linux). POLLRDBAND; /// Priority data may be written. POLLWRBAND; /// Error condition (only returned in /// [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). /// This bit is also set for a file descriptor referring to the /// write end of a pipe when the read end has been closed. POLLERR; /// Hang up (only returned in [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). /// Note that when reading from a channel such as a pipe or a stream /// socket, this event merely indicates that the peer closed its /// end of the channel. Subsequent reads from the channel will /// return 0 (end of file) only after all outstanding data in the /// channel has been consumed. POLLHUP; /// Invalid request: `fd` not open (only returned in /// [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). POLLNVAL; } } /// `poll` waits for one of a set of file descriptors to become ready to perform I/O. /// ([`poll(2)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/poll.html)) /// /// `fds` contains all [`PollFd`](struct.PollFd.html) to poll. /// The function will return as soon as any event occur for any of these `PollFd`s. /// /// The `timeout` argument specifies the number of milliseconds that `poll()` /// should block waiting for a file descriptor to become ready. The call /// will block until either: /// /// * a file descriptor becomes ready; /// * the call is interrupted by a signal handler; or /// * the timeout expires. /// /// Note that the timeout interval will be rounded up to the system clock /// granularity, and kernel scheduling delays mean that the blocking /// interval may overrun by a small amount. Specifying a negative value /// in timeout means an infinite timeout. Specifying a timeout of zero /// causes `poll()` to return immediately, even if no file descriptors are /// ready. pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result<libc::c_int> { let res = unsafe { libc::poll(fds.as_mut_ptr() as *mut libc::pollfd, fds.len() as libc::nfds_t, timeout) }; Errno::result(res) } /// `ppoll()` allows an application to safely wait until either a file /// descriptor becomes ready or until a signal is caught. /// ([`poll(2)`](http://man7.org/linux/man-pages/man2/poll.2.html)) /// /// `ppoll` behaves like `poll`, but let you specify what signals may interrupt it /// with the `sigmask` argument. /// #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] pub fn ppoll(fds: &mut [PollFd], timeout: TimeSpec, sigmask: SigSet) -> Result<libc::c_int> { let res = unsafe { libc::ppoll(fds.as_mut_ptr() as *mut libc::pollfd, fds.len() as libc::nfds_t, timeout.as_ref(), sigmask.as_ref()) }; Errno::result(res) }
{ EventFlags::from_bits(self.pollfd.revents) }
identifier_body
build.rs
extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{Write, BufWriter}; use std::path::Path; use std::convert::AsRef; // From http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html static SQLSTATES: &'static [(&'static str, &'static str)] = &[ // Class 00 — Successful Completion ("00000", "SuccessfulCompletion"), // Class 01 — Warning ("01000", "Warning"), ("0100C", "DynamicResultSetsReturned"), ("01008", "ImplicitZeroBitPadding"), ("01003", "NullValueEliminatedInSetFunction"), ("01007", "PrivilegeNotGranted"), ("01006", "PrivilegeNotRevoked"), ("01004", "StringDataRightTruncationWarning"), ("01P01", "DeprecatedFeature"), // Class 02 — No Data ("02000", "NoData"), ("02001", "NoAdditionalDynamicResultSetsReturned"), // Class 03 — SQL Statement Not Yet Complete ("03000", "SqlStatementNotYetComplete"), // Class 08 — Connection Exception ("08000", "ConnectionException"), ("08003", "ConnectionDoesNotExist"), ("08006", "ConnectionFailure"), ("08001", "SqlclientUnableToEstablishSqlconnection"), ("08004", "SqlserverRejectedEstablishmentOfSqlconnection"), ("08007", "TransactionResolutionUnknown"), ("08P01", "ProtocolViolation"), // Class 09 — Triggered Action Exception ("09000", "TriggeredActionException"), // Class 0A — Feature Not Supported ("0A000", "FeatureNotSupported"), // Class 0B — Invalid Transaction Initiation ("0B000", "InvalidTransactionInitiation"), // Class 0F — Locator Exception ("0F000", "LocatorException"), ("0F001", "InvalidLocatorException"), // Class 0L — Invalid Grantor ("0L000", "InvalidGrantor"), ("0LP01", "InvalidGrantOperation"), // Class 0P — Invalid Role Specification ("0P000", "InvalidRoleSpecification"), // Class 0Z — Diagnostics Exception ("0Z000", "DiagnosticsException"), ("0Z002", "StackedDiagnosticsAccessedWithoutActiveHandler"), // Class 20 — Case Not Found ("20000", "CaseNotFound"), // Class 21 — Cardinality Violation ("21000", "CardinalityViolation"), // Class 22 — Data Exception ("22000", "DataException"), ("2202E", "ArraySubscriptError"), ("22021", "CharacterNotInRepertoire"), ("22008", "DatetimeFieldOverflow"), ("22012", "DivisionByZero"), ("22005", "ErrorInAssignment"), ("2200B", "EscapeCharacterConflict"), ("22022", "IndicatorOverflow"), ("22015", "IntervalFieldOverflow"), ("2201E", "InvalidArgumentForLogarithm"), ("22014", "InvalidArgumentForNtileFunction"), ("22016", "InvalidArgumentForNthValueFunction"), ("2201F", "InvalidArgumentForPowerFunction"), ("2201G", "InvalidArgumentForWidthBucketFunction"), ("22018", "InvalidCharacterValueForCast"), ("22007", "InvalidDatetimeFormat"), ("22019", "InvalidEscapeCharacter"), ("2200D", "InvalidEscapeOctet"), ("22025", "InvalidEscapeSequence"), ("22P06", "NonstandardUseOfEscapeCharacter"), ("22010", "InvalidIndicatorParameterValue"), ("22023", "InvalidParameterValue"), ("2201B", "InvalidRegularExpression"), ("2201W", "InvalidRowCountInLimitClause"), ("2201X", "InvalidRowCountInResultOffsetClause"), ("22009", "InvalidTimeZoneDisplacementValue"), ("2200C", "InvalidUseOfEscapeCharacter"), ("2200G", "MostSpecificTypeMismatch"), ("22004", "NullValueNotAllowedData"), ("22002", "NullValueNoIndicatorParameter"), ("22003", "NumericValueOutOfRange"), ("22026", "StringDataLengthMismatch"), ("22001", "StringDataRightTruncationException"), ("22011", "SubstringError"), ("22027", "TrimError"), ("22024", "UnterminatedCString"), ("2200F", "ZeroLengthCharacterString"), ("22P01", "FloatingPointException"), ("22P02", "InvalidTextRepresentation"), ("22P03", "InvalidBinaryRepresentation"), ("22P04", "BadCopyFileFormat"), ("22P05", "UntranslatableCharacter"), ("2200L", "NotAnXmlDocument"), ("2200M", "InvalidXmlDocument"), ("2200N", "InvalidXmlContent"), ("2200S", "InvalidXmlComment"), ("2200T", "InvalidXmlProcessingInstruction"), // Class 23 — Integrity Constraint Violation ("23000", "IntegrityConstraintViolation"), ("23001", "RestrictViolation"), ("23502", "NotNullViolation"), ("23503", "ForeignKeyViolation"), ("23505", "UniqueViolation"), ("23514", "CheckViolation"), ("32P01", "ExclusionViolation"), // Class 24 — Invalid Cursor State ("24000", "InvalidCursorState"), // Class 25 — Invalid Transaction State ("25000", "InvalidTransactionState"), ("25001", "ActiveSqlTransaction"), ("25002", "BranchTransactionAlreadyActive"), ("25008", "HeldCursorRequiresSameIsolationLevel"), ("25003", "InappropriateAccessModeForBranchTransaction"), ("25004", "InappropriateIsolationLevelForBranchTransaction"), ("25005", "NoActiveSqlTransactionForBranchTransaction"), ("25006", "ReadOnlySqlTransaction"), ("25007", "SchemaAndDataStatementMixingNotSupported"), ("25P01", "NoActiveSqlTransaction"), ("25P02", "InFailedSqlTransaction"), // Class 26 — Invalid SQL Statement Name ("26000", "InvalidSqlStatementName"), // Class 27 — Triggered Data Change Violation ("27000", "TriggeredDataChangeViolation"), // Class 28 — Invalid Authorization Specification ("28000", "InvalidAuthorizationSpecification"), ("28P01", "InvalidPassword"), // Class 2B — Dependent Privilege Descriptors Still Exist ("2B000", "DependentPrivilegeDescriptorsStillExist"), ("2BP01", "DependentObjectsStillExist"), // Class 2D — Invalid Transaction Termination ("2D000", "InvalidTransactionTermination"), // Class 2F — SQL Routine Exception ("2F000", "SqlRoutineException"), ("2F005", "FunctionExecutedNoReturnStatement"), ("2F002", "ModifyingSqlDataNotPermittedSqlRoutine"), ("2F003", "ProhibitedSqlStatementAttemptedSqlRoutine"), ("2F004", "ReadingSqlDataNotPermittedSqlRoutine"), // Class 34 — Invalid Cursor Name ("34000", "InvalidCursorName"), // Class 38 — External Routine Exception ("38000", "ExternalRoutineException"), ("38001", "ContainingSqlNotPermitted"), ("38002", "ModifyingSqlDataNotPermittedExternalRoutine"), ("38003", "ProhibitedSqlStatementAttemptedExternalRoutine"), ("38004", "ReadingSqlDataNotPermittedExternalRoutine"), // Class 39 — External Routine Invocation Exception ("39000", "ExternalRoutineInvocationException"), ("39001", "InvalidSqlstateReturned"), ("39004", "NullValueNotAllowedExternalRoutine"), ("39P01", "TriggerProtocolViolated"), ("39P02", "SrfProtocolViolated"), // Class 3B — Savepoint Exception ("3B000", "SavepointException"), ("3B001", "InvalidSavepointException"), // Class 3D — Invalid Catalog Name ("3D000", "InvalidCatalogName"), // Class 3F — Invalid Schema Name ("3F000", "InvalidSchemaName"), // Class 40 — Transaction Rollback ("40000", "TransactionRollback"), ("40002", "TransactionIntegrityConstraintViolation"), ("40001", "SerializationFailure"), ("40003", "StatementCompletionUnknown"), ("40P01", "DeadlockDetected"), // Class 42 — Syntax Error or Access Rule Violation ("42000", "SyntaxErrorOrAccessRuleViolation"), ("42601", "SyntaxError"), ("42501", "InsufficientPrivilege"), ("42846", "CannotCoerce"), ("42803", "GroupingError"), ("42P20", "WindowingError"), ("42P19", "InvalidRecursion"), ("42830", "InvalidForeignKey"), ("42602", "InvalidName"), ("42622", "NameTooLong"), ("42939", "ReservedName"), ("42804", "DatatypeMismatch"), ("42P18", "IndeterminateDatatype"), ("42P21", "CollationMismatch"), ("42P22", "IndeterminateCollation"), ("42809", "WrongObjectType"), ("42703", "UndefinedColumn"), ("42883", "UndefinedFunction"), ("42P01", "UndefinedTable"), ("42P02", "UndefinedParameter"), ("42704", "UndefinedObject"), ("42701", "DuplicateColumn"), ("42P03", "DuplicateCursor"), ("42P04", "DuplicateDatabase"), ("42723", "DuplicateFunction"), ("42P05", "DuplicatePreparedStatement"), ("42P06", "DuplicateSchema"), ("42P07", "DuplicateTable"), ("42712", "DuplicateAliaas"), ("42710", "DuplicateObject"), ("42702", "AmbiguousColumn"), ("42725", "AmbiguousFunction"), ("42P08", "AmbiguousParameter"), ("42P09", "AmbiguousAlias"), ("42P10", "InvalidColumnReference"), ("42611", "InvalidColumnDefinition"), ("42P11", "InvalidCursorDefinition"), ("42P12", "InvalidDatabaseDefinition"), ("42P13", "InvalidFunctionDefinition"), ("42P14", "InvalidPreparedStatementDefinition"), ("42P15", "InvalidSchemaDefinition"), ("42P16", "InvalidTableDefinition"), ("42P17", "InvalidObjectDefinition"), // Class 44 — WITH CHECK OPTION Violation ("44000", "WithCheckOptionViolation"), // Class 53 — Insufficient Resources ("53000", "InsufficientResources"), ("53100", "DiskFull"), ("53200", "OutOfMemory"), ("53300", "TooManyConnections"), ("53400", "ConfigurationLimitExceeded"), // Class 54 — Program Limit Exceeded ("54000", "ProgramLimitExceeded"), ("54001", "StatementTooComplex"), ("54011", "TooManyColumns"), ("54023", "TooManyArguments"), // Class 55 — Object Not In Prerequisite State ("55000", "ObjectNotInPrerequisiteState"), ("55006", "ObjectInUse"), ("55P02", "CantChangeRuntimeParam"), ("55P03", "LockNotAvailable"), // Class 57 — Operator Intervention ("57000", "OperatorIntervention"), ("57014", "QueryCanceled"), ("57P01", "AdminShutdown"), ("57P02", "CrashShutdown"), ("57P03", "CannotConnectNow"), ("57P04", "DatabaseDropped"), // Class 58 — System Error ("58000", "SystemError"), ("58030", "IoError"), ("58P01", "UndefinedFile"), ("58P02", "DuplicateFile"), // Class F0 — Configuration File Error ("F0000", "ConfigFileError"), ("F0001", "LockFileExists"), // Class HV — Foreign Data Wrapper Error (SQL/MED) ("HV000", "FdwError"), ("HV005", "FdwColumnNameNotFound"), ("HV002", "FdwDynamicParameterValueNeeded"), ("HV010", "FdwFunctionSequenceError"), ("HV021", "FdwInconsistentDescriptorInformation"), ("HV024", "FdwInvalidAttributeValue"), ("HV007", "FdwInvalidColumnName"), ("HV008", "FdwInvalidColumnNumber"), ("HV004", "FdwInvalidDataType"), ("HV006", "FdwInvalidDataTypeDescriptors"), ("HV091", "FdwInvalidDescriptorFieldIdentifier"), ("HV00B", "FdwInvalidHandle"), ("HV00C", "FdwInvalidOptionIndex"), ("HV00D", "FdwInvalidOptionName"), ("HV090", "FdwInvalidStringLengthOrBufferLength"), ("HV00A", "FdwInvalidStringFormat"), ("HV009", "FdwInvalidUseOfNullPointer"), ("HV014", "FdwTooManyHandles"), ("HV001", "FdwOutOfMemory"), ("HV00P", "FdwNoSchemas"), ("HV00J", "FdwOptionNameNotFound"), ("HV00K", "FdwReplyHandle"), ("HV00Q", "FdwSchemaNotFound"), ("HV00R", "FdwTableNotFound"), ("HV00L", "FdwUnableToCreateExcecution"), ("HV00M", "FdwUnableToCreateReply"), ("HV00N", "FdwUnableToEstablishConnection"), // Class P0 — PL/pgSQL Error ("P0000", "PlpgsqlError"), ("P0001", "RaiseException"), ("P0002", "NoDataFound"), ("P0003", "TooManyRows"), // Class XX — Internal Error ("XX000", "InternalError"), ("XX001", "DataCorrupted"), ("XX002", "IndexCorrupted"), ]; fn main() { let path = env::var_os("OUT_DIR").unwrap(); let path: &Path = path.as_ref(); let path = path.join("sqlstate.rs"); let mut file = BufWriter::new(File::create(&path).unwrap()); make_enum(&mut file); make_map(&mut file); make_impl(&mut file); make_debug(&mut file); } fn make_enum(file: &mut BufWriter<File>) { write!(file, r#"/// SQLSTATE error codes #[derive(PartialEq, Eq, Clone)] pub enum SqlState {{ "# ).unwrap(); for &(code, variant) in SQLSTATES { write!(file, " /// `{}` {},\n", code, variant).unwrap(); } write!(file, " /// An unknown code Unknown(String) }} " ).unwrap(); } fn make_map(file: &mut BufWriter<File>) { write!(file, "static SQLSTATE_MAP: phf::M
tic str, SqlState> = ").unwrap(); let mut builder = phf_codegen::Map::new(); for &(code, variant) in SQLSTATES { builder.entry(code, &format!("SqlState::{}", variant)); } builder.build(file).unwrap(); write!(file, ";\n").unwrap(); } fn make_impl(file: &mut BufWriter<File>) { write!(file, r#" impl SqlState {{ /// Creates a `SqlState` from its error code. pub fn from_code(s: String) -> SqlState {{ match SQLSTATE_MAP.get(&*s) {{ Some(state) => state.clone(), None => SqlState::Unknown(s) }} }} /// Returns the error code corresponding to the `SqlState`. pub fn code(&self) -> &str {{ match *self {{"# ).unwrap(); for &(code, variant) in SQLSTATES { write!(file, r#" SqlState::{} => "{}","#, variant, code).unwrap(); } write!(file, r#" SqlState::Unknown(ref s) => &**s, }} }} }} "# ).unwrap(); } fn make_debug(file: &mut BufWriter<File>) { write!(file, r#" impl fmt::Debug for SqlState {{ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {{ let s = match *self {{"# ).unwrap(); for &(_, variant) in SQLSTATES { write!(file, r#" SqlState::{0} => "{0}","#, variant).unwrap(); } write!(file, r#" SqlState::Unknown(ref s) => return write!(fmt, "Unknown({{:?}})", s), }}; fmt.write_str(s) }} }} "# ).unwrap(); }
ap<&'sta
identifier_name
build.rs
extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{Write, BufWriter}; use std::path::Path; use std::convert::AsRef; // From http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html static SQLSTATES: &'static [(&'static str, &'static str)] = &[ // Class 00 — Successful Completion ("00000", "SuccessfulCompletion"), // Class 01 — Warning ("01000", "Warning"), ("0100C", "DynamicResultSetsReturned"), ("01008", "ImplicitZeroBitPadding"), ("01003", "NullValueEliminatedInSetFunction"), ("01007", "PrivilegeNotGranted"), ("01006", "PrivilegeNotRevoked"), ("01004", "StringDataRightTruncationWarning"), ("01P01", "DeprecatedFeature"), // Class 02 — No Data ("02000", "NoData"), ("02001", "NoAdditionalDynamicResultSetsReturned"), // Class 03 — SQL Statement Not Yet Complete ("03000", "SqlStatementNotYetComplete"), // Class 08 — Connection Exception ("08000", "ConnectionException"), ("08003", "ConnectionDoesNotExist"), ("08006", "ConnectionFailure"), ("08001", "SqlclientUnableToEstablishSqlconnection"), ("08004", "SqlserverRejectedEstablishmentOfSqlconnection"), ("08007", "TransactionResolutionUnknown"), ("08P01", "ProtocolViolation"), // Class 09 — Triggered Action Exception ("09000", "TriggeredActionException"), // Class 0A — Feature Not Supported ("0A000", "FeatureNotSupported"), // Class 0B — Invalid Transaction Initiation ("0B000", "InvalidTransactionInitiation"), // Class 0F — Locator Exception ("0F000", "LocatorException"), ("0F001", "InvalidLocatorException"), // Class 0L — Invalid Grantor ("0L000", "InvalidGrantor"), ("0LP01", "InvalidGrantOperation"), // Class 0P — Invalid Role Specification ("0P000", "InvalidRoleSpecification"), // Class 0Z — Diagnostics Exception ("0Z000", "DiagnosticsException"), ("0Z002", "StackedDiagnosticsAccessedWithoutActiveHandler"), // Class 20 — Case Not Found ("20000", "CaseNotFound"), // Class 21 — Cardinality Violation ("21000", "CardinalityViolation"), // Class 22 — Data Exception ("22000", "DataException"), ("2202E", "ArraySubscriptError"), ("22021", "CharacterNotInRepertoire"), ("22008", "DatetimeFieldOverflow"), ("22012", "DivisionByZero"), ("22005", "ErrorInAssignment"), ("2200B", "EscapeCharacterConflict"), ("22022", "IndicatorOverflow"), ("22015", "IntervalFieldOverflow"), ("2201E", "InvalidArgumentForLogarithm"), ("22014", "InvalidArgumentForNtileFunction"), ("22016", "InvalidArgumentForNthValueFunction"), ("2201F", "InvalidArgumentForPowerFunction"), ("2201G", "InvalidArgumentForWidthBucketFunction"), ("22018", "InvalidCharacterValueForCast"), ("22007", "InvalidDatetimeFormat"), ("22019", "InvalidEscapeCharacter"), ("2200D", "InvalidEscapeOctet"), ("22025", "InvalidEscapeSequence"), ("22P06", "NonstandardUseOfEscapeCharacter"), ("22010", "InvalidIndicatorParameterValue"), ("22023", "InvalidParameterValue"), ("2201B", "InvalidRegularExpression"), ("2201W", "InvalidRowCountInLimitClause"), ("2201X", "InvalidRowCountInResultOffsetClause"), ("22009", "InvalidTimeZoneDisplacementValue"), ("2200C", "InvalidUseOfEscapeCharacter"), ("2200G", "MostSpecificTypeMismatch"), ("22004", "NullValueNotAllowedData"), ("22002", "NullValueNoIndicatorParameter"), ("22003", "NumericValueOutOfRange"), ("22026", "StringDataLengthMismatch"), ("22001", "StringDataRightTruncationException"), ("22011", "SubstringError"), ("22027", "TrimError"), ("22024", "UnterminatedCString"), ("2200F", "ZeroLengthCharacterString"), ("22P01", "FloatingPointException"), ("22P02", "InvalidTextRepresentation"), ("22P03", "InvalidBinaryRepresentation"), ("22P04", "BadCopyFileFormat"), ("22P05", "UntranslatableCharacter"), ("2200L", "NotAnXmlDocument"), ("2200M", "InvalidXmlDocument"), ("2200N", "InvalidXmlContent"), ("2200S", "InvalidXmlComment"), ("2200T", "InvalidXmlProcessingInstruction"), // Class 23 — Integrity Constraint Violation ("23000", "IntegrityConstraintViolation"), ("23001", "RestrictViolation"), ("23502", "NotNullViolation"), ("23503", "ForeignKeyViolation"), ("23505", "UniqueViolation"), ("23514", "CheckViolation"), ("32P01", "ExclusionViolation"), // Class 24 — Invalid Cursor State ("24000", "InvalidCursorState"), // Class 25 — Invalid Transaction State ("25000", "InvalidTransactionState"), ("25001", "ActiveSqlTransaction"), ("25002", "BranchTransactionAlreadyActive"), ("25008", "HeldCursorRequiresSameIsolationLevel"), ("25003", "InappropriateAccessModeForBranchTransaction"), ("25004", "InappropriateIsolationLevelForBranchTransaction"), ("25005", "NoActiveSqlTransactionForBranchTransaction"), ("25006", "ReadOnlySqlTransaction"), ("25007", "SchemaAndDataStatementMixingNotSupported"), ("25P01", "NoActiveSqlTransaction"), ("25P02", "InFailedSqlTransaction"), // Class 26 — Invalid SQL Statement Name ("26000", "InvalidSqlStatementName"), // Class 27 — Triggered Data Change Violation ("27000", "TriggeredDataChangeViolation"), // Class 28 — Invalid Authorization Specification ("28000", "InvalidAuthorizationSpecification"), ("28P01", "InvalidPassword"), // Class 2B — Dependent Privilege Descriptors Still Exist ("2B000", "DependentPrivilegeDescriptorsStillExist"), ("2BP01", "DependentObjectsStillExist"), // Class 2D — Invalid Transaction Termination ("2D000", "InvalidTransactionTermination"), // Class 2F — SQL Routine Exception ("2F000", "SqlRoutineException"), ("2F005", "FunctionExecutedNoReturnStatement"), ("2F002", "ModifyingSqlDataNotPermittedSqlRoutine"), ("2F003", "ProhibitedSqlStatementAttemptedSqlRoutine"), ("2F004", "ReadingSqlDataNotPermittedSqlRoutine"), // Class 34 — Invalid Cursor Name ("34000", "InvalidCursorName"), // Class 38 — External Routine Exception ("38000", "ExternalRoutineException"), ("38001", "ContainingSqlNotPermitted"), ("38002", "ModifyingSqlDataNotPermittedExternalRoutine"), ("38003", "ProhibitedSqlStatementAttemptedExternalRoutine"), ("38004", "ReadingSqlDataNotPermittedExternalRoutine"), // Class 39 — External Routine Invocation Exception ("39000", "ExternalRoutineInvocationException"), ("39001", "InvalidSqlstateReturned"), ("39004", "NullValueNotAllowedExternalRoutine"), ("39P01", "TriggerProtocolViolated"), ("39P02", "SrfProtocolViolated"), // Class 3B — Savepoint Exception ("3B000", "SavepointException"), ("3B001", "InvalidSavepointException"), // Class 3D — Invalid Catalog Name ("3D000", "InvalidCatalogName"), // Class 3F — Invalid Schema Name ("3F000", "InvalidSchemaName"), // Class 40 — Transaction Rollback ("40000", "TransactionRollback"), ("40002", "TransactionIntegrityConstraintViolation"), ("40001", "SerializationFailure"), ("40003", "StatementCompletionUnknown"), ("40P01", "DeadlockDetected"), // Class 42 — Syntax Error or Access Rule Violation ("42000", "SyntaxErrorOrAccessRuleViolation"), ("42601", "SyntaxError"), ("42501", "InsufficientPrivilege"), ("42846", "CannotCoerce"), ("42803", "GroupingError"), ("42P20", "WindowingError"), ("42P19", "InvalidRecursion"), ("42830", "InvalidForeignKey"), ("42602", "InvalidName"), ("42622", "NameTooLong"), ("42939", "ReservedName"), ("42804", "DatatypeMismatch"), ("42P18", "IndeterminateDatatype"), ("42P21", "CollationMismatch"), ("42P22", "IndeterminateCollation"), ("42809", "WrongObjectType"), ("42703", "UndefinedColumn"), ("42883", "UndefinedFunction"), ("42P01", "UndefinedTable"), ("42P02", "UndefinedParameter"), ("42704", "UndefinedObject"), ("42701", "DuplicateColumn"), ("42P03", "DuplicateCursor"), ("42P04", "DuplicateDatabase"), ("42723", "DuplicateFunction"), ("42P05", "DuplicatePreparedStatement"), ("42P06", "DuplicateSchema"), ("42P07", "DuplicateTable"), ("42712", "DuplicateAliaas"), ("42710", "DuplicateObject"), ("42702", "AmbiguousColumn"), ("42725", "AmbiguousFunction"), ("42P08", "AmbiguousParameter"), ("42P09", "AmbiguousAlias"), ("42P10", "InvalidColumnReference"), ("42611", "InvalidColumnDefinition"), ("42P11", "InvalidCursorDefinition"), ("42P12", "InvalidDatabaseDefinition"), ("42P13", "InvalidFunctionDefinition"), ("42P14", "InvalidPreparedStatementDefinition"), ("42P15", "InvalidSchemaDefinition"), ("42P16", "InvalidTableDefinition"), ("42P17", "InvalidObjectDefinition"), // Class 44 — WITH CHECK OPTION Violation ("44000", "WithCheckOptionViolation"), // Class 53 — Insufficient Resources ("53000", "InsufficientResources"), ("53100", "DiskFull"), ("53200", "OutOfMemory"), ("53300", "TooManyConnections"), ("53400", "ConfigurationLimitExceeded"), // Class 54 — Program Limit Exceeded ("54000", "ProgramLimitExceeded"), ("54001", "StatementTooComplex"), ("54011", "TooManyColumns"), ("54023", "TooManyArguments"), // Class 55 — Object Not In Prerequisite State ("55000", "ObjectNotInPrerequisiteState"), ("55006", "ObjectInUse"), ("55P02", "CantChangeRuntimeParam"), ("55P03", "LockNotAvailable"), // Class 57 — Operator Intervention ("57000", "OperatorIntervention"), ("57014", "QueryCanceled"), ("57P01", "AdminShutdown"), ("57P02", "CrashShutdown"), ("57P03", "CannotConnectNow"), ("57P04", "DatabaseDropped"), // Class 58 — System Error ("58000", "SystemError"), ("58030", "IoError"), ("58P01", "UndefinedFile"), ("58P02", "DuplicateFile"), // Class F0 — Configuration File Error ("F0000", "ConfigFileError"), ("F0001", "LockFileExists"), // Class HV — Foreign Data Wrapper Error (SQL/MED) ("HV000", "FdwError"), ("HV005", "FdwColumnNameNotFound"), ("HV002", "FdwDynamicParameterValueNeeded"), ("HV010", "FdwFunctionSequenceError"), ("HV021", "FdwInconsistentDescriptorInformation"), ("HV024", "FdwInvalidAttributeValue"), ("HV007", "FdwInvalidColumnName"), ("HV008", "FdwInvalidColumnNumber"), ("HV004", "FdwInvalidDataType"), ("HV006", "FdwInvalidDataTypeDescriptors"), ("HV091", "FdwInvalidDescriptorFieldIdentifier"), ("HV00B", "FdwInvalidHandle"), ("HV00C", "FdwInvalidOptionIndex"), ("HV00D", "FdwInvalidOptionName"), ("HV090", "FdwInvalidStringLengthOrBufferLength"), ("HV00A", "FdwInvalidStringFormat"), ("HV009", "FdwInvalidUseOfNullPointer"), ("HV014", "FdwTooManyHandles"), ("HV001", "FdwOutOfMemory"), ("HV00P", "FdwNoSchemas"), ("HV00J", "FdwOptionNameNotFound"), ("HV00K", "FdwReplyHandle"), ("HV00Q", "FdwSchemaNotFound"), ("HV00R", "FdwTableNotFound"), ("HV00L", "FdwUnableToCreateExcecution"), ("HV00M", "FdwUnableToCreateReply"), ("HV00N", "FdwUnableToEstablishConnection"), // Class P0 — PL/pgSQL Error ("P0000", "PlpgsqlError"), ("P0001", "RaiseException"), ("P0002", "NoDataFound"), ("P0003", "TooManyRows"), // Class XX — Internal Error ("XX000", "InternalError"), ("XX001", "DataCorrupted"), ("XX002", "IndexCorrupted"), ]; fn main() { let path = env::var_os("OUT_DIR").unwrap(); let path: &Path = path.as_ref(
codes #[derive(PartialEq, Eq, Clone)] pub enum SqlState {{ "# ).unwrap(); for &(code, variant) in SQLSTATES { write!(file, " /// `{}` {},\n", code, variant).unwrap(); } write!(file, " /// An unknown code Unknown(String) }} " ).unwrap(); } fn make_map(file: &mut BufWriter<File>) { write!(file, "static SQLSTATE_MAP: phf::Map<&'static str, SqlState> = ").unwrap(); let mut builder = phf_codegen::Map::new(); for &(code, variant) in SQLSTATES { builder.entry(code, &format!("SqlState::{}", variant)); } builder.build(file).unwrap(); write!(file, ";\n").unwrap(); } fn make_impl(file: &mut BufWriter<File>) { write!(file, r#" impl SqlState {{ /// Creates a `SqlState` from its error code. pub fn from_code(s: String) -> SqlState {{ match SQLSTATE_MAP.get(&*s) {{ Some(state) => state.clone(), None => SqlState::Unknown(s) }} }} /// Returns the error code corresponding to the `SqlState`. pub fn code(&self) -> &str {{ match *self {{"# ).unwrap(); for &(code, variant) in SQLSTATES { write!(file, r#" SqlState::{} => "{}","#, variant, code).unwrap(); } write!(file, r#" SqlState::Unknown(ref s) => &**s, }} }} }} "# ).unwrap(); } fn make_debug(file: &mut BufWriter<File>) { write!(file, r#" impl fmt::Debug for SqlState {{ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {{ let s = match *self {{"# ).unwrap(); for &(_, variant) in SQLSTATES { write!(file, r#" SqlState::{0} => "{0}","#, variant).unwrap(); } write!(file, r#" SqlState::Unknown(ref s) => return write!(fmt, "Unknown({{:?}})", s), }}; fmt.write_str(s) }} }} "# ).unwrap(); }
); let path = path.join("sqlstate.rs"); let mut file = BufWriter::new(File::create(&path).unwrap()); make_enum(&mut file); make_map(&mut file); make_impl(&mut file); make_debug(&mut file); } fn make_enum(file: &mut BufWriter<File>) { write!(file, r#"/// SQLSTATE error
identifier_body
build.rs
extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{Write, BufWriter}; use std::path::Path; use std::convert::AsRef; // From http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html static SQLSTATES: &'static [(&'static str, &'static str)] = &[ // Class 00 — Successful Completion ("00000", "SuccessfulCompletion"), // Class 01 — Warning ("01000", "Warning"), ("0100C", "DynamicResultSetsReturned"), ("01008", "ImplicitZeroBitPadding"), ("01003", "NullValueEliminatedInSetFunction"), ("01007", "PrivilegeNotGranted"), ("01006", "PrivilegeNotRevoked"), ("01004", "StringDataRightTruncationWarning"), ("01P01", "DeprecatedFeature"), // Class 02 — No Data ("02000", "NoData"), ("02001", "NoAdditionalDynamicResultSetsReturned"), // Class 03 — SQL Statement Not Yet Complete ("03000", "SqlStatementNotYetComplete"), // Class 08 — Connection Exception ("08000", "ConnectionException"), ("08003", "ConnectionDoesNotExist"), ("08006", "ConnectionFailure"), ("08001", "SqlclientUnableToEstablishSqlconnection"), ("08004", "SqlserverRejectedEstablishmentOfSqlconnection"), ("08007", "TransactionResolutionUnknown"), ("08P01", "ProtocolViolation"), // Class 09 — Triggered Action Exception ("09000", "TriggeredActionException"), // Class 0A — Feature Not Supported ("0A000", "FeatureNotSupported"), // Class 0B — Invalid Transaction Initiation ("0B000", "InvalidTransactionInitiation"), // Class 0F — Locator Exception ("0F000", "LocatorException"), ("0F001", "InvalidLocatorException"), // Class 0L — Invalid Grantor ("0L000", "InvalidGrantor"), ("0LP01", "InvalidGrantOperation"), // Class 0P — Invalid Role Specification ("0P000", "InvalidRoleSpecification"), // Class 0Z — Diagnostics Exception ("0Z000", "DiagnosticsException"), ("0Z002", "StackedDiagnosticsAccessedWithoutActiveHandler"), // Class 20 — Case Not Found ("20000", "CaseNotFound"), // Class 21 — Cardinality Violation ("21000", "CardinalityViolation"), // Class 22 — Data Exception ("22000", "DataException"), ("2202E", "ArraySubscriptError"), ("22021", "CharacterNotInRepertoire"), ("22008", "DatetimeFieldOverflow"), ("22012", "DivisionByZero"), ("22005", "ErrorInAssignment"), ("2200B", "EscapeCharacterConflict"), ("22022", "IndicatorOverflow"), ("22015", "IntervalFieldOverflow"), ("2201E", "InvalidArgumentForLogarithm"), ("22014", "InvalidArgumentForNtileFunction"), ("22016", "InvalidArgumentForNthValueFunction"), ("2201F", "InvalidArgumentForPowerFunction"), ("2201G", "InvalidArgumentForWidthBucketFunction"), ("22018", "InvalidCharacterValueForCast"), ("22007", "InvalidDatetimeFormat"), ("22019", "InvalidEscapeCharacter"), ("2200D", "InvalidEscapeOctet"), ("22025", "InvalidEscapeSequence"), ("22P06", "NonstandardUseOfEscapeCharacter"), ("22010", "InvalidIndicatorParameterValue"), ("22023", "InvalidParameterValue"), ("2201B", "InvalidRegularExpression"), ("2201W", "InvalidRowCountInLimitClause"), ("2201X", "InvalidRowCountInResultOffsetClause"), ("22009", "InvalidTimeZoneDisplacementValue"), ("2200C", "InvalidUseOfEscapeCharacter"), ("2200G", "MostSpecificTypeMismatch"), ("22004", "NullValueNotAllowedData"), ("22002", "NullValueNoIndicatorParameter"), ("22003", "NumericValueOutOfRange"), ("22026", "StringDataLengthMismatch"), ("22001", "StringDataRightTruncationException"), ("22011", "SubstringError"), ("22027", "TrimError"), ("22024", "UnterminatedCString"), ("2200F", "ZeroLengthCharacterString"), ("22P01", "FloatingPointException"), ("22P02", "InvalidTextRepresentation"), ("22P03", "InvalidBinaryRepresentation"), ("22P04", "BadCopyFileFormat"), ("22P05", "UntranslatableCharacter"), ("2200L", "NotAnXmlDocument"), ("2200M", "InvalidXmlDocument"), ("2200N", "InvalidXmlContent"), ("2200S", "InvalidXmlComment"), ("2200T", "InvalidXmlProcessingInstruction"), // Class 23 — Integrity Constraint Violation ("23000", "IntegrityConstraintViolation"), ("23001", "RestrictViolation"), ("23502", "NotNullViolation"), ("23503", "ForeignKeyViolation"), ("23505", "UniqueViolation"), ("23514", "CheckViolation"), ("32P01", "ExclusionViolation"), // Class 24 — Invalid Cursor State ("24000", "InvalidCursorState"), // Class 25 — Invalid Transaction State ("25000", "InvalidTransactionState"), ("25001", "ActiveSqlTransaction"), ("25002", "BranchTransactionAlreadyActive"), ("25008", "HeldCursorRequiresSameIsolationLevel"), ("25003", "InappropriateAccessModeForBranchTransaction"), ("25004", "InappropriateIsolationLevelForBranchTransaction"), ("25005", "NoActiveSqlTransactionForBranchTransaction"), ("25006", "ReadOnlySqlTransaction"), ("25007", "SchemaAndDataStatementMixingNotSupported"), ("25P01", "NoActiveSqlTransaction"), ("25P02", "InFailedSqlTransaction"), // Class 26 — Invalid SQL Statement Name ("26000", "InvalidSqlStatementName"),
// Class 27 — Triggered Data Change Violation ("27000", "TriggeredDataChangeViolation"), // Class 28 — Invalid Authorization Specification ("28000", "InvalidAuthorizationSpecification"), ("28P01", "InvalidPassword"), // Class 2B — Dependent Privilege Descriptors Still Exist ("2B000", "DependentPrivilegeDescriptorsStillExist"), ("2BP01", "DependentObjectsStillExist"), // Class 2D — Invalid Transaction Termination ("2D000", "InvalidTransactionTermination"), // Class 2F — SQL Routine Exception ("2F000", "SqlRoutineException"), ("2F005", "FunctionExecutedNoReturnStatement"), ("2F002", "ModifyingSqlDataNotPermittedSqlRoutine"), ("2F003", "ProhibitedSqlStatementAttemptedSqlRoutine"), ("2F004", "ReadingSqlDataNotPermittedSqlRoutine"), // Class 34 — Invalid Cursor Name ("34000", "InvalidCursorName"), // Class 38 — External Routine Exception ("38000", "ExternalRoutineException"), ("38001", "ContainingSqlNotPermitted"), ("38002", "ModifyingSqlDataNotPermittedExternalRoutine"), ("38003", "ProhibitedSqlStatementAttemptedExternalRoutine"), ("38004", "ReadingSqlDataNotPermittedExternalRoutine"), // Class 39 — External Routine Invocation Exception ("39000", "ExternalRoutineInvocationException"), ("39001", "InvalidSqlstateReturned"), ("39004", "NullValueNotAllowedExternalRoutine"), ("39P01", "TriggerProtocolViolated"), ("39P02", "SrfProtocolViolated"), // Class 3B — Savepoint Exception ("3B000", "SavepointException"), ("3B001", "InvalidSavepointException"), // Class 3D — Invalid Catalog Name ("3D000", "InvalidCatalogName"), // Class 3F — Invalid Schema Name ("3F000", "InvalidSchemaName"), // Class 40 — Transaction Rollback ("40000", "TransactionRollback"), ("40002", "TransactionIntegrityConstraintViolation"), ("40001", "SerializationFailure"), ("40003", "StatementCompletionUnknown"), ("40P01", "DeadlockDetected"), // Class 42 — Syntax Error or Access Rule Violation ("42000", "SyntaxErrorOrAccessRuleViolation"), ("42601", "SyntaxError"), ("42501", "InsufficientPrivilege"), ("42846", "CannotCoerce"), ("42803", "GroupingError"), ("42P20", "WindowingError"), ("42P19", "InvalidRecursion"), ("42830", "InvalidForeignKey"), ("42602", "InvalidName"), ("42622", "NameTooLong"), ("42939", "ReservedName"), ("42804", "DatatypeMismatch"), ("42P18", "IndeterminateDatatype"), ("42P21", "CollationMismatch"), ("42P22", "IndeterminateCollation"), ("42809", "WrongObjectType"), ("42703", "UndefinedColumn"), ("42883", "UndefinedFunction"), ("42P01", "UndefinedTable"), ("42P02", "UndefinedParameter"), ("42704", "UndefinedObject"), ("42701", "DuplicateColumn"), ("42P03", "DuplicateCursor"), ("42P04", "DuplicateDatabase"), ("42723", "DuplicateFunction"), ("42P05", "DuplicatePreparedStatement"), ("42P06", "DuplicateSchema"), ("42P07", "DuplicateTable"), ("42712", "DuplicateAliaas"), ("42710", "DuplicateObject"), ("42702", "AmbiguousColumn"), ("42725", "AmbiguousFunction"), ("42P08", "AmbiguousParameter"), ("42P09", "AmbiguousAlias"), ("42P10", "InvalidColumnReference"), ("42611", "InvalidColumnDefinition"), ("42P11", "InvalidCursorDefinition"), ("42P12", "InvalidDatabaseDefinition"), ("42P13", "InvalidFunctionDefinition"), ("42P14", "InvalidPreparedStatementDefinition"), ("42P15", "InvalidSchemaDefinition"), ("42P16", "InvalidTableDefinition"), ("42P17", "InvalidObjectDefinition"), // Class 44 — WITH CHECK OPTION Violation ("44000", "WithCheckOptionViolation"), // Class 53 — Insufficient Resources ("53000", "InsufficientResources"), ("53100", "DiskFull"), ("53200", "OutOfMemory"), ("53300", "TooManyConnections"), ("53400", "ConfigurationLimitExceeded"), // Class 54 — Program Limit Exceeded ("54000", "ProgramLimitExceeded"), ("54001", "StatementTooComplex"), ("54011", "TooManyColumns"), ("54023", "TooManyArguments"), // Class 55 — Object Not In Prerequisite State ("55000", "ObjectNotInPrerequisiteState"), ("55006", "ObjectInUse"), ("55P02", "CantChangeRuntimeParam"), ("55P03", "LockNotAvailable"), // Class 57 — Operator Intervention ("57000", "OperatorIntervention"), ("57014", "QueryCanceled"), ("57P01", "AdminShutdown"), ("57P02", "CrashShutdown"), ("57P03", "CannotConnectNow"), ("57P04", "DatabaseDropped"), // Class 58 — System Error ("58000", "SystemError"), ("58030", "IoError"), ("58P01", "UndefinedFile"), ("58P02", "DuplicateFile"), // Class F0 — Configuration File Error ("F0000", "ConfigFileError"), ("F0001", "LockFileExists"), // Class HV — Foreign Data Wrapper Error (SQL/MED) ("HV000", "FdwError"), ("HV005", "FdwColumnNameNotFound"), ("HV002", "FdwDynamicParameterValueNeeded"), ("HV010", "FdwFunctionSequenceError"), ("HV021", "FdwInconsistentDescriptorInformation"), ("HV024", "FdwInvalidAttributeValue"), ("HV007", "FdwInvalidColumnName"), ("HV008", "FdwInvalidColumnNumber"), ("HV004", "FdwInvalidDataType"), ("HV006", "FdwInvalidDataTypeDescriptors"), ("HV091", "FdwInvalidDescriptorFieldIdentifier"), ("HV00B", "FdwInvalidHandle"), ("HV00C", "FdwInvalidOptionIndex"), ("HV00D", "FdwInvalidOptionName"), ("HV090", "FdwInvalidStringLengthOrBufferLength"), ("HV00A", "FdwInvalidStringFormat"), ("HV009", "FdwInvalidUseOfNullPointer"), ("HV014", "FdwTooManyHandles"), ("HV001", "FdwOutOfMemory"), ("HV00P", "FdwNoSchemas"), ("HV00J", "FdwOptionNameNotFound"), ("HV00K", "FdwReplyHandle"), ("HV00Q", "FdwSchemaNotFound"), ("HV00R", "FdwTableNotFound"), ("HV00L", "FdwUnableToCreateExcecution"), ("HV00M", "FdwUnableToCreateReply"), ("HV00N", "FdwUnableToEstablishConnection"), // Class P0 — PL/pgSQL Error ("P0000", "PlpgsqlError"), ("P0001", "RaiseException"), ("P0002", "NoDataFound"), ("P0003", "TooManyRows"), // Class XX — Internal Error ("XX000", "InternalError"), ("XX001", "DataCorrupted"), ("XX002", "IndexCorrupted"), ]; fn main() { let path = env::var_os("OUT_DIR").unwrap(); let path: &Path = path.as_ref(); let path = path.join("sqlstate.rs"); let mut file = BufWriter::new(File::create(&path).unwrap()); make_enum(&mut file); make_map(&mut file); make_impl(&mut file); make_debug(&mut file); } fn make_enum(file: &mut BufWriter<File>) { write!(file, r#"/// SQLSTATE error codes #[derive(PartialEq, Eq, Clone)] pub enum SqlState {{ "# ).unwrap(); for &(code, variant) in SQLSTATES { write!(file, " /// `{}` {},\n", code, variant).unwrap(); } write!(file, " /// An unknown code Unknown(String) }} " ).unwrap(); } fn make_map(file: &mut BufWriter<File>) { write!(file, "static SQLSTATE_MAP: phf::Map<&'static str, SqlState> = ").unwrap(); let mut builder = phf_codegen::Map::new(); for &(code, variant) in SQLSTATES { builder.entry(code, &format!("SqlState::{}", variant)); } builder.build(file).unwrap(); write!(file, ";\n").unwrap(); } fn make_impl(file: &mut BufWriter<File>) { write!(file, r#" impl SqlState {{ /// Creates a `SqlState` from its error code. pub fn from_code(s: String) -> SqlState {{ match SQLSTATE_MAP.get(&*s) {{ Some(state) => state.clone(), None => SqlState::Unknown(s) }} }} /// Returns the error code corresponding to the `SqlState`. pub fn code(&self) -> &str {{ match *self {{"# ).unwrap(); for &(code, variant) in SQLSTATES { write!(file, r#" SqlState::{} => "{}","#, variant, code).unwrap(); } write!(file, r#" SqlState::Unknown(ref s) => &**s, }} }} }} "# ).unwrap(); } fn make_debug(file: &mut BufWriter<File>) { write!(file, r#" impl fmt::Debug for SqlState {{ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {{ let s = match *self {{"# ).unwrap(); for &(_, variant) in SQLSTATES { write!(file, r#" SqlState::{0} => "{0}","#, variant).unwrap(); } write!(file, r#" SqlState::Unknown(ref s) => return write!(fmt, "Unknown({{:?}})", s), }}; fmt.write_str(s) }} }} "# ).unwrap(); }
random_line_split
coverage.rs
use truetype::{GlyphID, Result, Tape, Value}; /// A coverage table. #[derive(Clone, Debug)] pub enum Coverage { /// Format 1. Format1(Coverage1), /// Format 2. Format2(Coverage2), } table! { #[doc = "A coverage table in format 1."] pub Coverage1 { // CoverageFormat1 format (u16), // CoverageFormat count (u16), // GlyphCount glyph_ids (Vec<GlyphID>) |this, tape| { // GlyphArray tape.take_given(this.count as usize) }, } } table! { #[doc = "A coverage table in format 2."] pub Coverage2 { // CoverageFormat2 format (u16), // CoverageFormat count (u16), // RangeCount ranges (Vec<CoverageRange>) |this, tape| { // RangeRecord tape.take_given(this.count as usize) }, } } table! { #[doc = "A coverage range."] #[derive(Copy)] pub CoverageRange { // RangeRecord start (GlyphID), // Start end (GlyphID), // End index (u16 ), // StartCoverageIndex } } impl Default for Coverage { #[inline] fn default() -> Self { Coverage::Format1(Coverage1::default()) } } impl Value for Coverage { fn read<T: Tape>(tape: &mut T) -> Result<Self> { Ok(match tape.peek::<u16>()? { 1 => Coverage::Format1(tape.take()?),
} }
2 => Coverage::Format2(tape.take()?), _ => raise!("found an unknown format of the coverage table"), })
random_line_split
coverage.rs
use truetype::{GlyphID, Result, Tape, Value}; /// A coverage table. #[derive(Clone, Debug)] pub enum Coverage { /// Format 1. Format1(Coverage1), /// Format 2. Format2(Coverage2), } table! { #[doc = "A coverage table in format 1."] pub Coverage1 { // CoverageFormat1 format (u16), // CoverageFormat count (u16), // GlyphCount glyph_ids (Vec<GlyphID>) |this, tape| { // GlyphArray tape.take_given(this.count as usize) }, } } table! { #[doc = "A coverage table in format 2."] pub Coverage2 { // CoverageFormat2 format (u16), // CoverageFormat count (u16), // RangeCount ranges (Vec<CoverageRange>) |this, tape| { // RangeRecord tape.take_given(this.count as usize) }, } } table! { #[doc = "A coverage range."] #[derive(Copy)] pub CoverageRange { // RangeRecord start (GlyphID), // Start end (GlyphID), // End index (u16 ), // StartCoverageIndex } } impl Default for Coverage { #[inline] fn default() -> Self
} impl Value for Coverage { fn read<T: Tape>(tape: &mut T) -> Result<Self> { Ok(match tape.peek::<u16>()? { 1 => Coverage::Format1(tape.take()?), 2 => Coverage::Format2(tape.take()?), _ => raise!("found an unknown format of the coverage table"), }) } }
{ Coverage::Format1(Coverage1::default()) }
identifier_body
coverage.rs
use truetype::{GlyphID, Result, Tape, Value}; /// A coverage table. #[derive(Clone, Debug)] pub enum Coverage { /// Format 1. Format1(Coverage1), /// Format 2. Format2(Coverage2), } table! { #[doc = "A coverage table in format 1."] pub Coverage1 { // CoverageFormat1 format (u16), // CoverageFormat count (u16), // GlyphCount glyph_ids (Vec<GlyphID>) |this, tape| { // GlyphArray tape.take_given(this.count as usize) }, } } table! { #[doc = "A coverage table in format 2."] pub Coverage2 { // CoverageFormat2 format (u16), // CoverageFormat count (u16), // RangeCount ranges (Vec<CoverageRange>) |this, tape| { // RangeRecord tape.take_given(this.count as usize) }, } } table! { #[doc = "A coverage range."] #[derive(Copy)] pub CoverageRange { // RangeRecord start (GlyphID), // Start end (GlyphID), // End index (u16 ), // StartCoverageIndex } } impl Default for Coverage { #[inline] fn
() -> Self { Coverage::Format1(Coverage1::default()) } } impl Value for Coverage { fn read<T: Tape>(tape: &mut T) -> Result<Self> { Ok(match tape.peek::<u16>()? { 1 => Coverage::Format1(tape.take()?), 2 => Coverage::Format2(tape.take()?), _ => raise!("found an unknown format of the coverage table"), }) } }
default
identifier_name
lib.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![cfg_attr(not(feature = "std"), no_std)]
extern crate core; pub mod macros; pub mod reader; pub mod values; pub mod writer; pub use self::reader::read; pub use self::values::{KeyType, SimpleValue, Value}; pub use self::writer::write;
extern crate alloc; #[cfg(feature = "std")]
random_line_split
image_action.rs
use super::action::Action; use super::image::Image; use crate::method::{Create, Get, List}; use crate::request::{ImageActionRequest, ImageRequest}; use crate::STATIC_URL_ERROR; use serde::Serialize; use std::fmt::Display; const IMAGE_ACTIONS_SEGMENT: &str = "actions"; impl ImageRequest<Get, Image> { /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#list-all-actions-for-an-image) pub fn actions(mut self) -> ImageActionRequest<List, Vec<Action>> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.transmute() } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#transfer-an-image) pub fn transfer<S>(mut self, region: S) -> ImageActionRequest<Create, Action> where S: AsRef<str> + Display + Serialize,
/// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#convert-an-image-to-a-snapshot) pub fn convert(mut self) -> ImageActionRequest<Create, Action> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.set_body(json!({ "type": "convert", })); self.transmute() } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#retrieve-an-existing-image-action) pub fn action(mut self, id: usize) -> ImageActionRequest<Get, Action> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT) .push(&id.to_string()); self.transmute() } }
{ self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.set_body(json!({ "type": "transfer", "region": region, })); self.transmute() }
identifier_body
image_action.rs
use super::action::Action; use super::image::Image; use crate::method::{Create, Get, List}; use crate::request::{ImageActionRequest, ImageRequest}; use crate::STATIC_URL_ERROR; use serde::Serialize; use std::fmt::Display; const IMAGE_ACTIONS_SEGMENT: &str = "actions"; impl ImageRequest<Get, Image> { /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#list-all-actions-for-an-image) pub fn actions(mut self) -> ImageActionRequest<List, Vec<Action>> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.transmute() } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#transfer-an-image) pub fn transfer<S>(mut self, region: S) -> ImageActionRequest<Create, Action> where S: AsRef<str> + Display + Serialize, { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.set_body(json!({ "type": "transfer", "region": region, })); self.transmute() } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#convert-an-image-to-a-snapshot) pub fn convert(mut self) -> ImageActionRequest<Create, Action> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.set_body(json!({ "type": "convert", })); self.transmute() } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#retrieve-an-existing-image-action)
.path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT) .push(&id.to_string()); self.transmute() } }
pub fn action(mut self, id: usize) -> ImageActionRequest<Get, Action> { self.url_mut()
random_line_split
image_action.rs
use super::action::Action; use super::image::Image; use crate::method::{Create, Get, List}; use crate::request::{ImageActionRequest, ImageRequest}; use crate::STATIC_URL_ERROR; use serde::Serialize; use std::fmt::Display; const IMAGE_ACTIONS_SEGMENT: &str = "actions"; impl ImageRequest<Get, Image> { /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#list-all-actions-for-an-image) pub fn actions(mut self) -> ImageActionRequest<List, Vec<Action>> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.transmute() } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#transfer-an-image) pub fn transfer<S>(mut self, region: S) -> ImageActionRequest<Create, Action> where S: AsRef<str> + Display + Serialize, { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.set_body(json!({ "type": "transfer", "region": region, })); self.transmute() } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#convert-an-image-to-a-snapshot) pub fn convert(mut self) -> ImageActionRequest<Create, Action> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.set_body(json!({ "type": "convert", })); self.transmute() } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#retrieve-an-existing-image-action) pub fn
(mut self, id: usize) -> ImageActionRequest<Get, Action> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT) .push(&id.to_string()); self.transmute() } }
action
identifier_name
tty.rs
use std::process::{Command, Stdio, ChildStderr, Child}; use std::ptr; use std::io::{Read, Error}; use std::fs::File; #[cfg(target_os = "linux")] pub fn get_tty(mut command: Command) -> Handle { use libc::{self, winsize, c_int, TIOCGWINSZ}; use std::os::unix::io::FromRawFd; use std::fs::File; let mut master: c_int = 0; let mut slave: c_int = 0; let mut win = winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0, }; let res = unsafe { libc::ioctl(0, TIOCGWINSZ, &mut win); libc::openpty(&mut master, &mut slave, ptr::null_mut(), ptr::null(), &win) }; if res < 0 { panic!("Failed to open pty: {}", res); } let child = command.stderr(unsafe { Stdio::from_raw_fd(slave) } ) .spawn() .unwrap(); unsafe { Handle::Pty {child: child, fd: master as usize, file: File::from_raw_fd(master) } } } pub enum
{ Pty {child: Child, fd: usize, file: File }, Stderr(ChildStderr) } impl Read for Handle { fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> { match *self { Handle::Pty{ref mut file,..} => file.read(buf), Handle::Stderr(ref mut stderr) => stderr.read(buf) } } } pub fn handle_err(handle: &mut Handle, err: &Error) -> bool { if let Handle::Pty {ref mut child,..} = *handle { if child.try_wait().unwrap().is_some() { return true; } } panic!("Error: {:?}", err) } #[cfg(target_os = "linux")] pub fn get_handle(command: Command, tty: bool) -> Handle { if tty { return get_tty(command) } get_handle_base(command) } #[cfg(not(target_os = "linux"))] pub fn get_handle(mut command: Command, tty: bool) -> Handle { get_handle_base(command) } fn get_handle_base(mut command: Command) -> Handle { let child = command.stderr(Stdio::piped()) .spawn() .unwrap(); Handle::Stderr(child.stderr.unwrap()) }
Handle
identifier_name
tty.rs
use std::process::{Command, Stdio, ChildStderr, Child}; use std::ptr; use std::io::{Read, Error}; use std::fs::File; #[cfg(target_os = "linux")] pub fn get_tty(mut command: Command) -> Handle { use libc::{self, winsize, c_int, TIOCGWINSZ}; use std::os::unix::io::FromRawFd; use std::fs::File; let mut master: c_int = 0; let mut slave: c_int = 0; let mut win = winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0, }; let res = unsafe { libc::ioctl(0, TIOCGWINSZ, &mut win); libc::openpty(&mut master, &mut slave, ptr::null_mut(), ptr::null(), &win) }; if res < 0 { panic!("Failed to open pty: {}", res); } let child = command.stderr(unsafe { Stdio::from_raw_fd(slave) } ) .spawn() .unwrap(); unsafe { Handle::Pty {child: child, fd: master as usize, file: File::from_raw_fd(master) } } } pub enum Handle { Pty {child: Child, fd: usize, file: File }, Stderr(ChildStderr) } impl Read for Handle { fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> { match *self { Handle::Pty{ref mut file,..} => file.read(buf), Handle::Stderr(ref mut stderr) => stderr.read(buf) } } } pub fn handle_err(handle: &mut Handle, err: &Error) -> bool { if let Handle::Pty {ref mut child,..} = *handle { if child.try_wait().unwrap().is_some()
} panic!("Error: {:?}", err) } #[cfg(target_os = "linux")] pub fn get_handle(command: Command, tty: bool) -> Handle { if tty { return get_tty(command) } get_handle_base(command) } #[cfg(not(target_os = "linux"))] pub fn get_handle(mut command: Command, tty: bool) -> Handle { get_handle_base(command) } fn get_handle_base(mut command: Command) -> Handle { let child = command.stderr(Stdio::piped()) .spawn() .unwrap(); Handle::Stderr(child.stderr.unwrap()) }
{ return true; }
conditional_block
tty.rs
use std::process::{Command, Stdio, ChildStderr, Child}; use std::ptr; use std::io::{Read, Error}; use std::fs::File; #[cfg(target_os = "linux")] pub fn get_tty(mut command: Command) -> Handle { use libc::{self, winsize, c_int, TIOCGWINSZ}; use std::os::unix::io::FromRawFd; use std::fs::File; let mut master: c_int = 0; let mut slave: c_int = 0; let mut win = winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0, }; let res = unsafe { libc::ioctl(0, TIOCGWINSZ, &mut win); libc::openpty(&mut master, &mut slave, ptr::null_mut(), ptr::null(), &win) }; if res < 0 { panic!("Failed to open pty: {}", res); } let child = command.stderr(unsafe { Stdio::from_raw_fd(slave) } ) .spawn() .unwrap(); unsafe { Handle::Pty {child: child, fd: master as usize, file: File::from_raw_fd(master) } } } pub enum Handle { Pty {child: Child, fd: usize, file: File }, Stderr(ChildStderr) } impl Read for Handle { fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>
} pub fn handle_err(handle: &mut Handle, err: &Error) -> bool { if let Handle::Pty {ref mut child,..} = *handle { if child.try_wait().unwrap().is_some() { return true; } } panic!("Error: {:?}", err) } #[cfg(target_os = "linux")] pub fn get_handle(command: Command, tty: bool) -> Handle { if tty { return get_tty(command) } get_handle_base(command) } #[cfg(not(target_os = "linux"))] pub fn get_handle(mut command: Command, tty: bool) -> Handle { get_handle_base(command) } fn get_handle_base(mut command: Command) -> Handle { let child = command.stderr(Stdio::piped()) .spawn() .unwrap(); Handle::Stderr(child.stderr.unwrap()) }
{ match *self { Handle::Pty{ref mut file, ..} => file.read(buf), Handle::Stderr(ref mut stderr) => stderr.read(buf) } }
identifier_body
tty.rs
use std::process::{Command, Stdio, ChildStderr, Child}; use std::ptr; use std::io::{Read, Error}; use std::fs::File; #[cfg(target_os = "linux")] pub fn get_tty(mut command: Command) -> Handle { use libc::{self, winsize, c_int, TIOCGWINSZ}; use std::os::unix::io::FromRawFd; use std::fs::File; let mut master: c_int = 0; let mut slave: c_int = 0; let mut win = winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0, }; let res = unsafe { libc::ioctl(0, TIOCGWINSZ, &mut win); libc::openpty(&mut master, &mut slave, ptr::null_mut(), ptr::null(), &win) }; if res < 0 { panic!("Failed to open pty: {}", res); } let child = command.stderr(unsafe { Stdio::from_raw_fd(slave) } ) .spawn() .unwrap(); unsafe { Handle::Pty {child: child, fd: master as usize, file: File::from_raw_fd(master) } } } pub enum Handle { Pty {child: Child, fd: usize, file: File }, Stderr(ChildStderr) } impl Read for Handle { fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> { match *self { Handle::Pty{ref mut file,..} => file.read(buf), Handle::Stderr(ref mut stderr) => stderr.read(buf) } } } pub fn handle_err(handle: &mut Handle, err: &Error) -> bool { if let Handle::Pty {ref mut child,..} = *handle { if child.try_wait().unwrap().is_some() { return true; } } panic!("Error: {:?}", err) } #[cfg(target_os = "linux")] pub fn get_handle(command: Command, tty: bool) -> Handle { if tty { return get_tty(command) } get_handle_base(command) } #[cfg(not(target_os = "linux"))] pub fn get_handle(mut command: Command, tty: bool) -> Handle {
.spawn() .unwrap(); Handle::Stderr(child.stderr.unwrap()) }
get_handle_base(command) } fn get_handle_base(mut command: Command) -> Handle { let child = command.stderr(Stdio::piped())
random_line_split
lib.rs
//! The library allows to send data to carbon (also known as graphite) //! //! #Example //! //! ```ignore //! extern crate rotor; //! extern crate rotor_tools; //! //! use rotor_tools::loop_ext::LoopExt; //! //! let loopinst = rotor::Loop::new(&rotor::Config::new()).instantiate(()); //! let sink = loopinst.add_and_fetch(|scope| { //! connect_ip("127.0.0.1:2003".parse().unwrap(), scope) //! }).unwrap(); //! //! loopinst.run().unwrap(); //! //! // Then somewhere else: //! //! { // Note sender keeps lock on buffer for it's lifetime //! let sender = sink.sender();
//! } //! ``` //! //! If you need to format the metric name, use `format_args!` instead of //! `format!` as the former does not preallocate a buffer: //! ``` //! snd.add_int_at( //! format_args!("servers.{}.metrics.{}", hostname, metric), //! metric_value, timestamp); //! ``` //! extern crate rotor; extern crate rotor_stream; extern crate rotor_tools; extern crate time; extern crate num; #[macro_use] extern crate log; mod sink; mod sender; mod proto; use std::net::SocketAddr; use std::sync::{Arc, Mutex, MutexGuard}; use rotor::{GenericScope, Notifier, Void, Response}; use rotor::mio::tcp::TcpStream; use rotor_stream::{Persistent, ActiveStream}; use rotor_tools::sync::{Mutexed}; /// A state machine object, just add in to the loop pub type Fsm<C, S> = Mutexed<Persistent<proto::CarbonProto<C, S>>>; /// This is a wrapper around the machinery to send data /// /// Use ``sink.sender()`` go to get an actual object you may send to /// /// Note ``sink.sender()`` holds lock on the underlying buffer and doesn't /// send data, until sender is dropped. This is useful for sending data in /// single bulk. #[derive(Clone)] pub struct Sink<C, S>(Arc<Mutex<Persistent<proto::CarbonProto<C, S>>>>, Notifier) where S: ActiveStream; /// The sender object, which has convenience methods to send the data /// /// Note ``Sender()`` holds lock on the underlying buffer and doesn't /// send data, until sender is dropped. This is useful for sending data in /// single bulk. pub struct Sender<'a, C: 'a, S>( MutexGuard<'a, Persistent<proto::CarbonProto<C, S>>>, Option<Notifier>) where S: ActiveStream; /// Connect to the socket by IP address /// /// The method is here while rotor-dns is not matured yet. The better way /// would be to use dns resolving. pub fn connect_ip<S: GenericScope, C>(addr: SocketAddr, scope: &mut S) -> Response<(Fsm<C, TcpStream>, Sink<C, TcpStream>), Void> { Persistent::connect(scope, addr, ()).wrap(|fsm| { let arc = Arc::new(Mutex::new(fsm)); (Mutexed(arc.clone()), Sink(arc, scope.notifier())) }) }
//! sender.add_u64("some.value", 1234);
random_line_split
lib.rs
//! The library allows to send data to carbon (also known as graphite) //! //! #Example //! //! ```ignore //! extern crate rotor; //! extern crate rotor_tools; //! //! use rotor_tools::loop_ext::LoopExt; //! //! let loopinst = rotor::Loop::new(&rotor::Config::new()).instantiate(()); //! let sink = loopinst.add_and_fetch(|scope| { //! connect_ip("127.0.0.1:2003".parse().unwrap(), scope) //! }).unwrap(); //! //! loopinst.run().unwrap(); //! //! // Then somewhere else: //! //! { // Note sender keeps lock on buffer for it's lifetime //! let sender = sink.sender(); //! sender.add_u64("some.value", 1234); //! } //! ``` //! //! If you need to format the metric name, use `format_args!` instead of //! `format!` as the former does not preallocate a buffer: //! ``` //! snd.add_int_at( //! format_args!("servers.{}.metrics.{}", hostname, metric), //! metric_value, timestamp); //! ``` //! extern crate rotor; extern crate rotor_stream; extern crate rotor_tools; extern crate time; extern crate num; #[macro_use] extern crate log; mod sink; mod sender; mod proto; use std::net::SocketAddr; use std::sync::{Arc, Mutex, MutexGuard}; use rotor::{GenericScope, Notifier, Void, Response}; use rotor::mio::tcp::TcpStream; use rotor_stream::{Persistent, ActiveStream}; use rotor_tools::sync::{Mutexed}; /// A state machine object, just add in to the loop pub type Fsm<C, S> = Mutexed<Persistent<proto::CarbonProto<C, S>>>; /// This is a wrapper around the machinery to send data /// /// Use ``sink.sender()`` go to get an actual object you may send to /// /// Note ``sink.sender()`` holds lock on the underlying buffer and doesn't /// send data, until sender is dropped. This is useful for sending data in /// single bulk. #[derive(Clone)] pub struct
<C, S>(Arc<Mutex<Persistent<proto::CarbonProto<C, S>>>>, Notifier) where S: ActiveStream; /// The sender object, which has convenience methods to send the data /// /// Note ``Sender()`` holds lock on the underlying buffer and doesn't /// send data, until sender is dropped. This is useful for sending data in /// single bulk. pub struct Sender<'a, C: 'a, S>( MutexGuard<'a, Persistent<proto::CarbonProto<C, S>>>, Option<Notifier>) where S: ActiveStream; /// Connect to the socket by IP address /// /// The method is here while rotor-dns is not matured yet. The better way /// would be to use dns resolving. pub fn connect_ip<S: GenericScope, C>(addr: SocketAddr, scope: &mut S) -> Response<(Fsm<C, TcpStream>, Sink<C, TcpStream>), Void> { Persistent::connect(scope, addr, ()).wrap(|fsm| { let arc = Arc::new(Mutex::new(fsm)); (Mutexed(arc.clone()), Sink(arc, scope.notifier())) }) }
Sink
identifier_name
compositor_task.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/. */ //! Communication with the compositor task. pub use windowing; pub use constellation::{FrameId, SendableFrameTree}; use compositor; use headless; use windowing::{WindowEvent, WindowMethods}; use azure::azure_hl::{SourceSurfaceMethods, Color}; use geom::point::Point2D; use geom::rect::{Rect, TypedRect}; use geom::size::Size2D; use layers::platform::surface::{NativeCompositingGraphicsContext, NativeGraphicsMetadata}; use layers::layers::LayerBufferSet; use pipeline::CompositionPipeline; use msg::compositor_msg::{Epoch, LayerId, LayerMetadata, ReadyState}; use msg::compositor_msg::{PaintListener, PaintState, ScriptListener, ScrollPolicy}; use msg::constellation_msg::{ConstellationChan, LoadData, PipelineId}; use msg::constellation_msg::{Key, KeyState, KeyModifiers}; use util::cursor::Cursor; use util::geometry::PagePx; use util::memory::MemoryProfilerChan; use util::time::TimeProfilerChan; use std::sync::mpsc::{channel, Sender, Receiver}; use std::fmt::{Error, Formatter, Debug}; use std::rc::Rc; /// Sends messages to the compositor. This is a trait supplied by the port because the method used /// to communicate with the compositor may have to kick OS event loops awake, communicate cross- /// process, and so forth. pub trait CompositorProxy :'static + Send { /// Sends a message to the compositor. fn send(&mut self, msg: Msg); /// Clones the compositor proxy. fn clone_compositor_proxy(&self) -> Box<CompositorProxy+'static+Send>; } /// The port that the compositor receives messages on. As above, this is a trait supplied by the /// Servo port. pub trait CompositorReceiver :'static { /// Receives the next message inbound for the compositor. This must not block. fn try_recv_compositor_msg(&mut self) -> Option<Msg>; /// Synchronously waits for, and returns, the next message inbound for the compositor. fn recv_compositor_msg(&mut self) -> Msg; } /// A convenience implementation of `CompositorReceiver` for a plain old Rust `Receiver`. impl CompositorReceiver for Receiver<Msg> { fn try_recv_compositor_msg(&mut self) -> Option<Msg> { match self.try_recv() { Ok(msg) => Some(msg), Err(_) => None, } } fn recv_compositor_msg(&mut self) -> Msg { self.recv().unwrap() } } /// Implementation of the abstract `ScriptListener` interface. impl ScriptListener for Box<CompositorProxy+'static+Send> { fn set_ready_state(&mut self, pipeline_id: PipelineId, ready_state: ReadyState) { let msg = Msg::ChangeReadyState(pipeline_id, ready_state); self.send(msg); } fn scroll_fragment_point(&mut self, pipeline_id: PipelineId, layer_id: LayerId, point: Point2D<f32>) { self.send(Msg::ScrollFragmentPoint(pipeline_id, layer_id, point)); } fn close(&mut self) { let (chan, port) = channel(); self.send(Msg::Exit(chan)); port.recv().unwrap(); } fn dup(&mut self) -> Box<ScriptListener+'static> { box self.clone_compositor_proxy() as Box<ScriptListener+'static> } fn set_title(&mut self, pipeline_id: PipelineId, title: Option<String>) { self.send(Msg::ChangePageTitle(pipeline_id, title)) } fn send_key_event(&mut self, key: Key, state: KeyState, modifiers: KeyModifiers) { self.send(Msg::KeyEvent(key, state, modifiers)); } } /// Information about each layer that the compositor keeps. #[derive(Copy)] pub struct LayerProperties { pub pipeline_id: PipelineId, pub epoch: Epoch, pub id: LayerId, pub rect: Rect<f32>, pub background_color: Color, pub scroll_policy: ScrollPolicy, } impl LayerProperties { fn new(pipeline_id: PipelineId, epoch: Epoch, metadata: &LayerMetadata) -> LayerProperties { LayerProperties { pipeline_id: pipeline_id, epoch: epoch, id: metadata.id, rect: Rect(Point2D(metadata.position.origin.x as f32, metadata.position.origin.y as f32), Size2D(metadata.position.size.width as f32, metadata.position.size.height as f32)), background_color: metadata.background_color, scroll_policy: metadata.scroll_policy, } } } /// Implementation of the abstract `PaintListener` interface. impl PaintListener for Box<CompositorProxy+'static+Send> { fn get_graphics_metadata(&mut self) -> Option<NativeGraphicsMetadata> { let (chan, port) = channel(); self.send(Msg::GetGraphicsMetadata(chan)); port.recv().unwrap() } fn assign_painted_buffers(&mut self, pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>) { self.send(Msg::AssignPaintedBuffers(pipeline_id, epoch, replies)); } fn initialize_layers_for_pipeline(&mut self, pipeline_id: PipelineId, metadata: Vec<LayerMetadata>, epoch: Epoch) { // FIXME(#2004, pcwalton): This assumes that the first layer determines the page size, and // that all other layers are immediate children of it. This is sufficient to handle // `position: fixed` but will not be sufficient to handle `overflow: scroll` or transforms. let mut first = true; for metadata in metadata.iter() { let layer_properties = LayerProperties::new(pipeline_id, epoch, metadata); if first { self.send(Msg::CreateOrUpdateBaseLayer(layer_properties)); first = false } else { self.send(Msg::CreateOrUpdateDescendantLayer(layer_properties)); } } } fn paint_msg_discarded(&mut self) { self.send(Msg::PaintMsgDiscarded); } fn
(&mut self, pipeline_id: PipelineId, paint_state: PaintState) { self.send(Msg::ChangePaintState(pipeline_id, paint_state)) } } /// Messages from the painting task and the constellation task to the compositor task. pub enum Msg { /// Requests that the compositor shut down. Exit(Sender<()>), /// Informs the compositor that the constellation has completed shutdown. /// Required because the constellation can have pending calls to make /// (e.g. SetFrameTree) at the time that we send it an ExitMsg. ShutdownComplete, /// Requests the compositor's graphics metadata. Graphics metadata is what the painter needs /// to create surfaces that the compositor can see. On Linux this is the X display; on Mac this /// is the pixel format. /// /// The headless compositor returns `None`. GetGraphicsMetadata(Sender<Option<NativeGraphicsMetadata>>), /// Tells the compositor to create the root layer for a pipeline if necessary (i.e. if no layer /// with that ID exists). CreateOrUpdateBaseLayer(LayerProperties), /// Tells the compositor to create a descendant layer for a pipeline if necessary (i.e. if no /// layer with that ID exists). CreateOrUpdateDescendantLayer(LayerProperties), /// Alerts the compositor that the specified layer's origin has changed. SetLayerOrigin(PipelineId, LayerId, Point2D<f32>), /// Scroll a page in a window ScrollFragmentPoint(PipelineId, LayerId, Point2D<f32>), /// Requests that the compositor assign the painted buffers to the given layers. AssignPaintedBuffers(PipelineId, Epoch, Vec<(LayerId, Box<LayerBufferSet>)>), /// Alerts the compositor to the current status of page loading. ChangeReadyState(PipelineId, ReadyState), /// Alerts the compositor to the current status of painting. ChangePaintState(PipelineId, PaintState), /// Alerts the compositor that the current page has changed its title. ChangePageTitle(PipelineId, Option<String>), /// Alerts the compositor that the current page has changed its load data (including URL). ChangePageLoadData(FrameId, LoadData), /// Alerts the compositor that a `PaintMsg` has been discarded. PaintMsgDiscarded, /// Replaces the current frame tree, typically called during main frame navigation. SetFrameTree(SendableFrameTree, Sender<()>, ConstellationChan), /// Requests the compositor to create a root layer for a new frame. CreateRootLayerForPipeline(CompositionPipeline, CompositionPipeline, Option<TypedRect<PagePx, f32>>, Sender<()>), /// Requests the compositor to change a root layer's pipeline and remove all child layers. ChangeLayerPipelineAndRemoveChildren(CompositionPipeline, CompositionPipeline, Sender<()>), /// The load of a page has completed. LoadComplete, /// Indicates that the scrolling timeout with the given starting timestamp has happened and a /// composite should happen. (See the `scrolling` module.) ScrollTimeout(u64), /// Sends an unconsumed key event back to the compositor. KeyEvent(Key, KeyState, KeyModifiers), /// Changes the cursor. SetCursor(Cursor), /// Informs the compositor that the paint task for the given pipeline has exited. PaintTaskExited(PipelineId), } impl Debug for Msg { fn fmt(&self, f: &mut Formatter) -> Result<(),Error> { match *self { Msg::Exit(..) => write!(f, "Exit"), Msg::ShutdownComplete(..) => write!(f, "ShutdownComplete"), Msg::GetGraphicsMetadata(..) => write!(f, "GetGraphicsMetadata"), Msg::CreateOrUpdateBaseLayer(..) => write!(f, "CreateOrUpdateBaseLayer"), Msg::CreateOrUpdateDescendantLayer(..) => write!(f, "CreateOrUpdateDescendantLayer"), Msg::SetLayerOrigin(..) => write!(f, "SetLayerOrigin"), Msg::ScrollFragmentPoint(..) => write!(f, "ScrollFragmentPoint"), Msg::AssignPaintedBuffers(..) => write!(f, "AssignPaintedBuffers"), Msg::ChangeReadyState(..) => write!(f, "ChangeReadyState"), Msg::ChangePaintState(..) => write!(f, "ChangePaintState"), Msg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), Msg::ChangePageLoadData(..) => write!(f, "ChangePageLoadData"), Msg::PaintMsgDiscarded(..) => write!(f, "PaintMsgDiscarded"), Msg::SetFrameTree(..) => write!(f, "SetFrameTree"), Msg::CreateRootLayerForPipeline(..) => write!(f, "CreateRootLayerForPipeline"), Msg::ChangeLayerPipelineAndRemoveChildren(..) => write!(f, "ChangeLayerPipelineAndRemoveChildren"), Msg::LoadComplete => write!(f, "LoadComplete"), Msg::ScrollTimeout(..) => write!(f, "ScrollTimeout"), Msg::KeyEvent(..) => write!(f, "KeyEvent"), Msg::SetCursor(..) => write!(f, "SetCursor"), Msg::PaintTaskExited(..) => write!(f, "PaintTaskExited"), } } } pub struct CompositorTask; impl CompositorTask { /// Creates a graphics context. Platform-specific. /// /// FIXME(pcwalton): Probably could be less platform-specific, using the metadata abstraction. #[cfg(target_os="linux")] pub fn create_graphics_context(native_metadata: &NativeGraphicsMetadata) -> NativeCompositingGraphicsContext { NativeCompositingGraphicsContext::from_display(native_metadata.display) } #[cfg(not(target_os="linux"))] pub fn create_graphics_context(_: &NativeGraphicsMetadata) -> NativeCompositingGraphicsContext { NativeCompositingGraphicsContext::new() } pub fn create<Window>(window: Option<Rc<Window>>, sender: Box<CompositorProxy+Send>, receiver: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: TimeProfilerChan, memory_profiler_chan: MemoryProfilerChan) -> Box<CompositorEventListener +'static> where Window: WindowMethods +'static { match window { Some(window) => { box compositor::IOCompositor::create(window, sender, receiver, constellation_chan.clone(), time_profiler_chan, memory_profiler_chan) as Box<CompositorEventListener> } None => { box headless::NullCompositor::create(receiver, constellation_chan.clone(), time_profiler_chan, memory_profiler_chan) as Box<CompositorEventListener> } } } } pub trait CompositorEventListener { fn handle_event(&mut self, event: WindowEvent) -> bool; fn repaint_synchronously(&mut self); fn shutdown(&mut self); fn pinch_zoom_level(&self) -> f32; /// Requests that the compositor send the title for the main frame as soon as possible. fn get_title_for_main_frame(&self); }
set_paint_state
identifier_name
compositor_task.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/. */ //! Communication with the compositor task. pub use windowing; pub use constellation::{FrameId, SendableFrameTree}; use compositor; use headless; use windowing::{WindowEvent, WindowMethods}; use azure::azure_hl::{SourceSurfaceMethods, Color}; use geom::point::Point2D; use geom::rect::{Rect, TypedRect}; use geom::size::Size2D; use layers::platform::surface::{NativeCompositingGraphicsContext, NativeGraphicsMetadata}; use layers::layers::LayerBufferSet; use pipeline::CompositionPipeline; use msg::compositor_msg::{Epoch, LayerId, LayerMetadata, ReadyState}; use msg::compositor_msg::{PaintListener, PaintState, ScriptListener, ScrollPolicy}; use msg::constellation_msg::{ConstellationChan, LoadData, PipelineId}; use msg::constellation_msg::{Key, KeyState, KeyModifiers}; use util::cursor::Cursor; use util::geometry::PagePx; use util::memory::MemoryProfilerChan; use util::time::TimeProfilerChan; use std::sync::mpsc::{channel, Sender, Receiver}; use std::fmt::{Error, Formatter, Debug}; use std::rc::Rc; /// Sends messages to the compositor. This is a trait supplied by the port because the method used /// to communicate with the compositor may have to kick OS event loops awake, communicate cross- /// process, and so forth. pub trait CompositorProxy :'static + Send { /// Sends a message to the compositor. fn send(&mut self, msg: Msg); /// Clones the compositor proxy. fn clone_compositor_proxy(&self) -> Box<CompositorProxy+'static+Send>; } /// The port that the compositor receives messages on. As above, this is a trait supplied by the /// Servo port. pub trait CompositorReceiver :'static { /// Receives the next message inbound for the compositor. This must not block. fn try_recv_compositor_msg(&mut self) -> Option<Msg>; /// Synchronously waits for, and returns, the next message inbound for the compositor. fn recv_compositor_msg(&mut self) -> Msg; } /// A convenience implementation of `CompositorReceiver` for a plain old Rust `Receiver`. impl CompositorReceiver for Receiver<Msg> { fn try_recv_compositor_msg(&mut self) -> Option<Msg> { match self.try_recv() { Ok(msg) => Some(msg), Err(_) => None, } } fn recv_compositor_msg(&mut self) -> Msg { self.recv().unwrap() } } /// Implementation of the abstract `ScriptListener` interface. impl ScriptListener for Box<CompositorProxy+'static+Send> { fn set_ready_state(&mut self, pipeline_id: PipelineId, ready_state: ReadyState) { let msg = Msg::ChangeReadyState(pipeline_id, ready_state); self.send(msg); } fn scroll_fragment_point(&mut self, pipeline_id: PipelineId, layer_id: LayerId, point: Point2D<f32>) { self.send(Msg::ScrollFragmentPoint(pipeline_id, layer_id, point)); } fn close(&mut self) { let (chan, port) = channel(); self.send(Msg::Exit(chan)); port.recv().unwrap(); } fn dup(&mut self) -> Box<ScriptListener+'static> { box self.clone_compositor_proxy() as Box<ScriptListener+'static> } fn set_title(&mut self, pipeline_id: PipelineId, title: Option<String>) { self.send(Msg::ChangePageTitle(pipeline_id, title)) } fn send_key_event(&mut self, key: Key, state: KeyState, modifiers: KeyModifiers) { self.send(Msg::KeyEvent(key, state, modifiers)); } } /// Information about each layer that the compositor keeps. #[derive(Copy)] pub struct LayerProperties { pub pipeline_id: PipelineId, pub epoch: Epoch, pub id: LayerId, pub rect: Rect<f32>, pub background_color: Color, pub scroll_policy: ScrollPolicy, } impl LayerProperties { fn new(pipeline_id: PipelineId, epoch: Epoch, metadata: &LayerMetadata) -> LayerProperties { LayerProperties { pipeline_id: pipeline_id, epoch: epoch, id: metadata.id, rect: Rect(Point2D(metadata.position.origin.x as f32, metadata.position.origin.y as f32), Size2D(metadata.position.size.width as f32, metadata.position.size.height as f32)), background_color: metadata.background_color, scroll_policy: metadata.scroll_policy, } } } /// Implementation of the abstract `PaintListener` interface. impl PaintListener for Box<CompositorProxy+'static+Send> { fn get_graphics_metadata(&mut self) -> Option<NativeGraphicsMetadata> { let (chan, port) = channel(); self.send(Msg::GetGraphicsMetadata(chan)); port.recv().unwrap() } fn assign_painted_buffers(&mut self, pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>) { self.send(Msg::AssignPaintedBuffers(pipeline_id, epoch, replies)); } fn initialize_layers_for_pipeline(&mut self, pipeline_id: PipelineId, metadata: Vec<LayerMetadata>, epoch: Epoch) { // FIXME(#2004, pcwalton): This assumes that the first layer determines the page size, and // that all other layers are immediate children of it. This is sufficient to handle // `position: fixed` but will not be sufficient to handle `overflow: scroll` or transforms. let mut first = true; for metadata in metadata.iter() { let layer_properties = LayerProperties::new(pipeline_id, epoch, metadata); if first { self.send(Msg::CreateOrUpdateBaseLayer(layer_properties)); first = false } else { self.send(Msg::CreateOrUpdateDescendantLayer(layer_properties)); } } } fn paint_msg_discarded(&mut self) { self.send(Msg::PaintMsgDiscarded); } fn set_paint_state(&mut self, pipeline_id: PipelineId, paint_state: PaintState) { self.send(Msg::ChangePaintState(pipeline_id, paint_state)) } } /// Messages from the painting task and the constellation task to the compositor task. pub enum Msg { /// Requests that the compositor shut down. Exit(Sender<()>), /// Informs the compositor that the constellation has completed shutdown. /// Required because the constellation can have pending calls to make /// (e.g. SetFrameTree) at the time that we send it an ExitMsg. ShutdownComplete, /// Requests the compositor's graphics metadata. Graphics metadata is what the painter needs /// to create surfaces that the compositor can see. On Linux this is the X display; on Mac this /// is the pixel format. /// /// The headless compositor returns `None`. GetGraphicsMetadata(Sender<Option<NativeGraphicsMetadata>>), /// Tells the compositor to create the root layer for a pipeline if necessary (i.e. if no layer /// with that ID exists). CreateOrUpdateBaseLayer(LayerProperties), /// Tells the compositor to create a descendant layer for a pipeline if necessary (i.e. if no /// layer with that ID exists). CreateOrUpdateDescendantLayer(LayerProperties), /// Alerts the compositor that the specified layer's origin has changed. SetLayerOrigin(PipelineId, LayerId, Point2D<f32>), /// Scroll a page in a window ScrollFragmentPoint(PipelineId, LayerId, Point2D<f32>), /// Requests that the compositor assign the painted buffers to the given layers. AssignPaintedBuffers(PipelineId, Epoch, Vec<(LayerId, Box<LayerBufferSet>)>), /// Alerts the compositor to the current status of page loading. ChangeReadyState(PipelineId, ReadyState), /// Alerts the compositor to the current status of painting. ChangePaintState(PipelineId, PaintState), /// Alerts the compositor that the current page has changed its title. ChangePageTitle(PipelineId, Option<String>), /// Alerts the compositor that the current page has changed its load data (including URL). ChangePageLoadData(FrameId, LoadData), /// Alerts the compositor that a `PaintMsg` has been discarded. PaintMsgDiscarded, /// Replaces the current frame tree, typically called during main frame navigation. SetFrameTree(SendableFrameTree, Sender<()>, ConstellationChan), /// Requests the compositor to create a root layer for a new frame. CreateRootLayerForPipeline(CompositionPipeline, CompositionPipeline, Option<TypedRect<PagePx, f32>>, Sender<()>), /// Requests the compositor to change a root layer's pipeline and remove all child layers. ChangeLayerPipelineAndRemoveChildren(CompositionPipeline, CompositionPipeline, Sender<()>), /// The load of a page has completed. LoadComplete, /// Indicates that the scrolling timeout with the given starting timestamp has happened and a /// composite should happen. (See the `scrolling` module.) ScrollTimeout(u64), /// Sends an unconsumed key event back to the compositor. KeyEvent(Key, KeyState, KeyModifiers), /// Changes the cursor. SetCursor(Cursor), /// Informs the compositor that the paint task for the given pipeline has exited. PaintTaskExited(PipelineId), } impl Debug for Msg { fn fmt(&self, f: &mut Formatter) -> Result<(),Error> { match *self { Msg::Exit(..) => write!(f, "Exit"), Msg::ShutdownComplete(..) => write!(f, "ShutdownComplete"), Msg::GetGraphicsMetadata(..) => write!(f, "GetGraphicsMetadata"), Msg::CreateOrUpdateBaseLayer(..) => write!(f, "CreateOrUpdateBaseLayer"), Msg::CreateOrUpdateDescendantLayer(..) => write!(f, "CreateOrUpdateDescendantLayer"), Msg::SetLayerOrigin(..) => write!(f, "SetLayerOrigin"), Msg::ScrollFragmentPoint(..) => write!(f, "ScrollFragmentPoint"), Msg::AssignPaintedBuffers(..) => write!(f, "AssignPaintedBuffers"), Msg::ChangeReadyState(..) => write!(f, "ChangeReadyState"), Msg::ChangePaintState(..) => write!(f, "ChangePaintState"), Msg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), Msg::ChangePageLoadData(..) => write!(f, "ChangePageLoadData"), Msg::PaintMsgDiscarded(..) => write!(f, "PaintMsgDiscarded"), Msg::SetFrameTree(..) => write!(f, "SetFrameTree"), Msg::CreateRootLayerForPipeline(..) => write!(f, "CreateRootLayerForPipeline"), Msg::ChangeLayerPipelineAndRemoveChildren(..) => write!(f, "ChangeLayerPipelineAndRemoveChildren"), Msg::LoadComplete => write!(f, "LoadComplete"), Msg::ScrollTimeout(..) => write!(f, "ScrollTimeout"), Msg::KeyEvent(..) => write!(f, "KeyEvent"), Msg::SetCursor(..) => write!(f, "SetCursor"), Msg::PaintTaskExited(..) => write!(f, "PaintTaskExited"), } } } pub struct CompositorTask; impl CompositorTask { /// Creates a graphics context. Platform-specific. /// /// FIXME(pcwalton): Probably could be less platform-specific, using the metadata abstraction. #[cfg(target_os="linux")] pub fn create_graphics_context(native_metadata: &NativeGraphicsMetadata) -> NativeCompositingGraphicsContext { NativeCompositingGraphicsContext::from_display(native_metadata.display) } #[cfg(not(target_os="linux"))] pub fn create_graphics_context(_: &NativeGraphicsMetadata) -> NativeCompositingGraphicsContext { NativeCompositingGraphicsContext::new() } pub fn create<Window>(window: Option<Rc<Window>>, sender: Box<CompositorProxy+Send>, receiver: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: TimeProfilerChan, memory_profiler_chan: MemoryProfilerChan) -> Box<CompositorEventListener +'static> where Window: WindowMethods +'static
} pub trait CompositorEventListener { fn handle_event(&mut self, event: WindowEvent) -> bool; fn repaint_synchronously(&mut self); fn shutdown(&mut self); fn pinch_zoom_level(&self) -> f32; /// Requests that the compositor send the title for the main frame as soon as possible. fn get_title_for_main_frame(&self); }
{ match window { Some(window) => { box compositor::IOCompositor::create(window, sender, receiver, constellation_chan.clone(), time_profiler_chan, memory_profiler_chan) as Box<CompositorEventListener> } None => { box headless::NullCompositor::create(receiver, constellation_chan.clone(), time_profiler_chan, memory_profiler_chan) as Box<CompositorEventListener> } } }
identifier_body
compositor_task.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/. */ //! Communication with the compositor task. pub use windowing; pub use constellation::{FrameId, SendableFrameTree}; use compositor; use headless; use windowing::{WindowEvent, WindowMethods}; use azure::azure_hl::{SourceSurfaceMethods, Color}; use geom::point::Point2D; use geom::rect::{Rect, TypedRect}; use geom::size::Size2D; use layers::platform::surface::{NativeCompositingGraphicsContext, NativeGraphicsMetadata}; use layers::layers::LayerBufferSet; use pipeline::CompositionPipeline; use msg::compositor_msg::{Epoch, LayerId, LayerMetadata, ReadyState}; use msg::compositor_msg::{PaintListener, PaintState, ScriptListener, ScrollPolicy}; use msg::constellation_msg::{ConstellationChan, LoadData, PipelineId}; use msg::constellation_msg::{Key, KeyState, KeyModifiers}; use util::cursor::Cursor; use util::geometry::PagePx; use util::memory::MemoryProfilerChan; use util::time::TimeProfilerChan; use std::sync::mpsc::{channel, Sender, Receiver}; use std::fmt::{Error, Formatter, Debug};
use std::rc::Rc; /// Sends messages to the compositor. This is a trait supplied by the port because the method used /// to communicate with the compositor may have to kick OS event loops awake, communicate cross- /// process, and so forth. pub trait CompositorProxy :'static + Send { /// Sends a message to the compositor. fn send(&mut self, msg: Msg); /// Clones the compositor proxy. fn clone_compositor_proxy(&self) -> Box<CompositorProxy+'static+Send>; } /// The port that the compositor receives messages on. As above, this is a trait supplied by the /// Servo port. pub trait CompositorReceiver :'static { /// Receives the next message inbound for the compositor. This must not block. fn try_recv_compositor_msg(&mut self) -> Option<Msg>; /// Synchronously waits for, and returns, the next message inbound for the compositor. fn recv_compositor_msg(&mut self) -> Msg; } /// A convenience implementation of `CompositorReceiver` for a plain old Rust `Receiver`. impl CompositorReceiver for Receiver<Msg> { fn try_recv_compositor_msg(&mut self) -> Option<Msg> { match self.try_recv() { Ok(msg) => Some(msg), Err(_) => None, } } fn recv_compositor_msg(&mut self) -> Msg { self.recv().unwrap() } } /// Implementation of the abstract `ScriptListener` interface. impl ScriptListener for Box<CompositorProxy+'static+Send> { fn set_ready_state(&mut self, pipeline_id: PipelineId, ready_state: ReadyState) { let msg = Msg::ChangeReadyState(pipeline_id, ready_state); self.send(msg); } fn scroll_fragment_point(&mut self, pipeline_id: PipelineId, layer_id: LayerId, point: Point2D<f32>) { self.send(Msg::ScrollFragmentPoint(pipeline_id, layer_id, point)); } fn close(&mut self) { let (chan, port) = channel(); self.send(Msg::Exit(chan)); port.recv().unwrap(); } fn dup(&mut self) -> Box<ScriptListener+'static> { box self.clone_compositor_proxy() as Box<ScriptListener+'static> } fn set_title(&mut self, pipeline_id: PipelineId, title: Option<String>) { self.send(Msg::ChangePageTitle(pipeline_id, title)) } fn send_key_event(&mut self, key: Key, state: KeyState, modifiers: KeyModifiers) { self.send(Msg::KeyEvent(key, state, modifiers)); } } /// Information about each layer that the compositor keeps. #[derive(Copy)] pub struct LayerProperties { pub pipeline_id: PipelineId, pub epoch: Epoch, pub id: LayerId, pub rect: Rect<f32>, pub background_color: Color, pub scroll_policy: ScrollPolicy, } impl LayerProperties { fn new(pipeline_id: PipelineId, epoch: Epoch, metadata: &LayerMetadata) -> LayerProperties { LayerProperties { pipeline_id: pipeline_id, epoch: epoch, id: metadata.id, rect: Rect(Point2D(metadata.position.origin.x as f32, metadata.position.origin.y as f32), Size2D(metadata.position.size.width as f32, metadata.position.size.height as f32)), background_color: metadata.background_color, scroll_policy: metadata.scroll_policy, } } } /// Implementation of the abstract `PaintListener` interface. impl PaintListener for Box<CompositorProxy+'static+Send> { fn get_graphics_metadata(&mut self) -> Option<NativeGraphicsMetadata> { let (chan, port) = channel(); self.send(Msg::GetGraphicsMetadata(chan)); port.recv().unwrap() } fn assign_painted_buffers(&mut self, pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>) { self.send(Msg::AssignPaintedBuffers(pipeline_id, epoch, replies)); } fn initialize_layers_for_pipeline(&mut self, pipeline_id: PipelineId, metadata: Vec<LayerMetadata>, epoch: Epoch) { // FIXME(#2004, pcwalton): This assumes that the first layer determines the page size, and // that all other layers are immediate children of it. This is sufficient to handle // `position: fixed` but will not be sufficient to handle `overflow: scroll` or transforms. let mut first = true; for metadata in metadata.iter() { let layer_properties = LayerProperties::new(pipeline_id, epoch, metadata); if first { self.send(Msg::CreateOrUpdateBaseLayer(layer_properties)); first = false } else { self.send(Msg::CreateOrUpdateDescendantLayer(layer_properties)); } } } fn paint_msg_discarded(&mut self) { self.send(Msg::PaintMsgDiscarded); } fn set_paint_state(&mut self, pipeline_id: PipelineId, paint_state: PaintState) { self.send(Msg::ChangePaintState(pipeline_id, paint_state)) } } /// Messages from the painting task and the constellation task to the compositor task. pub enum Msg { /// Requests that the compositor shut down. Exit(Sender<()>), /// Informs the compositor that the constellation has completed shutdown. /// Required because the constellation can have pending calls to make /// (e.g. SetFrameTree) at the time that we send it an ExitMsg. ShutdownComplete, /// Requests the compositor's graphics metadata. Graphics metadata is what the painter needs /// to create surfaces that the compositor can see. On Linux this is the X display; on Mac this /// is the pixel format. /// /// The headless compositor returns `None`. GetGraphicsMetadata(Sender<Option<NativeGraphicsMetadata>>), /// Tells the compositor to create the root layer for a pipeline if necessary (i.e. if no layer /// with that ID exists). CreateOrUpdateBaseLayer(LayerProperties), /// Tells the compositor to create a descendant layer for a pipeline if necessary (i.e. if no /// layer with that ID exists). CreateOrUpdateDescendantLayer(LayerProperties), /// Alerts the compositor that the specified layer's origin has changed. SetLayerOrigin(PipelineId, LayerId, Point2D<f32>), /// Scroll a page in a window ScrollFragmentPoint(PipelineId, LayerId, Point2D<f32>), /// Requests that the compositor assign the painted buffers to the given layers. AssignPaintedBuffers(PipelineId, Epoch, Vec<(LayerId, Box<LayerBufferSet>)>), /// Alerts the compositor to the current status of page loading. ChangeReadyState(PipelineId, ReadyState), /// Alerts the compositor to the current status of painting. ChangePaintState(PipelineId, PaintState), /// Alerts the compositor that the current page has changed its title. ChangePageTitle(PipelineId, Option<String>), /// Alerts the compositor that the current page has changed its load data (including URL). ChangePageLoadData(FrameId, LoadData), /// Alerts the compositor that a `PaintMsg` has been discarded. PaintMsgDiscarded, /// Replaces the current frame tree, typically called during main frame navigation. SetFrameTree(SendableFrameTree, Sender<()>, ConstellationChan), /// Requests the compositor to create a root layer for a new frame. CreateRootLayerForPipeline(CompositionPipeline, CompositionPipeline, Option<TypedRect<PagePx, f32>>, Sender<()>), /// Requests the compositor to change a root layer's pipeline and remove all child layers. ChangeLayerPipelineAndRemoveChildren(CompositionPipeline, CompositionPipeline, Sender<()>), /// The load of a page has completed. LoadComplete, /// Indicates that the scrolling timeout with the given starting timestamp has happened and a /// composite should happen. (See the `scrolling` module.) ScrollTimeout(u64), /// Sends an unconsumed key event back to the compositor. KeyEvent(Key, KeyState, KeyModifiers), /// Changes the cursor. SetCursor(Cursor), /// Informs the compositor that the paint task for the given pipeline has exited. PaintTaskExited(PipelineId), } impl Debug for Msg { fn fmt(&self, f: &mut Formatter) -> Result<(),Error> { match *self { Msg::Exit(..) => write!(f, "Exit"), Msg::ShutdownComplete(..) => write!(f, "ShutdownComplete"), Msg::GetGraphicsMetadata(..) => write!(f, "GetGraphicsMetadata"), Msg::CreateOrUpdateBaseLayer(..) => write!(f, "CreateOrUpdateBaseLayer"), Msg::CreateOrUpdateDescendantLayer(..) => write!(f, "CreateOrUpdateDescendantLayer"), Msg::SetLayerOrigin(..) => write!(f, "SetLayerOrigin"), Msg::ScrollFragmentPoint(..) => write!(f, "ScrollFragmentPoint"), Msg::AssignPaintedBuffers(..) => write!(f, "AssignPaintedBuffers"), Msg::ChangeReadyState(..) => write!(f, "ChangeReadyState"), Msg::ChangePaintState(..) => write!(f, "ChangePaintState"), Msg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), Msg::ChangePageLoadData(..) => write!(f, "ChangePageLoadData"), Msg::PaintMsgDiscarded(..) => write!(f, "PaintMsgDiscarded"), Msg::SetFrameTree(..) => write!(f, "SetFrameTree"), Msg::CreateRootLayerForPipeline(..) => write!(f, "CreateRootLayerForPipeline"), Msg::ChangeLayerPipelineAndRemoveChildren(..) => write!(f, "ChangeLayerPipelineAndRemoveChildren"), Msg::LoadComplete => write!(f, "LoadComplete"), Msg::ScrollTimeout(..) => write!(f, "ScrollTimeout"), Msg::KeyEvent(..) => write!(f, "KeyEvent"), Msg::SetCursor(..) => write!(f, "SetCursor"), Msg::PaintTaskExited(..) => write!(f, "PaintTaskExited"), } } } pub struct CompositorTask; impl CompositorTask { /// Creates a graphics context. Platform-specific. /// /// FIXME(pcwalton): Probably could be less platform-specific, using the metadata abstraction. #[cfg(target_os="linux")] pub fn create_graphics_context(native_metadata: &NativeGraphicsMetadata) -> NativeCompositingGraphicsContext { NativeCompositingGraphicsContext::from_display(native_metadata.display) } #[cfg(not(target_os="linux"))] pub fn create_graphics_context(_: &NativeGraphicsMetadata) -> NativeCompositingGraphicsContext { NativeCompositingGraphicsContext::new() } pub fn create<Window>(window: Option<Rc<Window>>, sender: Box<CompositorProxy+Send>, receiver: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: TimeProfilerChan, memory_profiler_chan: MemoryProfilerChan) -> Box<CompositorEventListener +'static> where Window: WindowMethods +'static { match window { Some(window) => { box compositor::IOCompositor::create(window, sender, receiver, constellation_chan.clone(), time_profiler_chan, memory_profiler_chan) as Box<CompositorEventListener> } None => { box headless::NullCompositor::create(receiver, constellation_chan.clone(), time_profiler_chan, memory_profiler_chan) as Box<CompositorEventListener> } } } } pub trait CompositorEventListener { fn handle_event(&mut self, event: WindowEvent) -> bool; fn repaint_synchronously(&mut self); fn shutdown(&mut self); fn pinch_zoom_level(&self) -> f32; /// Requests that the compositor send the title for the main frame as soon as possible. fn get_title_for_main_frame(&self); }
random_line_split
split_operation_metadata.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use fnv::FnvHashSet; use graphql_ir::{Argument, ConstantValue, Directive, Value}; use interner::{Intern, StringKey}; use lazy_static::lazy_static; lazy_static! { pub static ref DIRECTIVE_SPLIT_OPERATION: StringKey = "__splitOperation".intern(); static ref ARG_DERIVED_FROM: StringKey = "derivedFrom".intern(); static ref ARG_PARENT_SOURCES: StringKey = "parentSources".intern(); static ref ARG_RAW_RESPONSE_TYPE: StringKey = "rawResponseType".intern(); } /// The split operation metadata directive indicates that an operation was split /// out by the compiler from a parent normalization file. pub struct SplitOperationMetadata { /// Name of the fragment that this split operation represents. pub derived_from: StringKey, /// The names of the fragments and operations that included this fragment. /// They are the reason this split operation exist. If they are all removed, /// this file also needs to be removed. pub parent_sources: FnvHashSet<StringKey>, /// Should a @raw_response_type style type be generated. pub raw_response_type: bool, } impl SplitOperationMetadata { pub fn to_directive(&self) -> Directive { let mut arguments = vec![ Argument { name: WithLocation::generated(*ARG_DERIVED_FROM), value: WithLocation::generated(Value::Constant(ConstantValue::String( self.derived_from, ))), }, Argument { name: WithLocation::generated(*ARG_PARENT_SOURCES), value: WithLocation::generated(Value::Constant(ConstantValue::List( self.parent_sources .iter() .cloned() .map(ConstantValue::String) .collect(), ))), }, ]; if self.raw_response_type { arguments.push(Argument { name: WithLocation::generated(*ARG_RAW_RESPONSE_TYPE), value: WithLocation::generated(Value::Constant(ConstantValue::Null())), }); } Directive { name: WithLocation::generated(*DIRECTIVE_SPLIT_OPERATION), arguments, } } } impl From<&Directive> for SplitOperationMetadata { fn from(directive: &Directive) -> Self { debug_assert!(directive.name.item == *DIRECTIVE_SPLIT_OPERATION); let derived_from_arg = directive .arguments .named(*ARG_DERIVED_FROM) .expect("Expected derived_from arg to exist"); let derived_from = derived_from_arg.value.item.expect_string_literal(); let parent_sources_arg = directive .arguments .named(*ARG_PARENT_SOURCES) .expect("Expected parent_sources arg to exist"); let raw_response_type = directive.arguments.named(*ARG_RAW_RESPONSE_TYPE).is_some(); if let Value::Constant(ConstantValue::List(source_definition_names)) = &parent_sources_arg.value.item
else { panic!("Expected parent sources to be a constant of list."); } } }
{ let parent_sources = source_definition_names .iter() .map(|val| { if let ConstantValue::String(name) = val { name } else { panic!("Expected item in the parent sources to be a StringKey.") } }) .cloned() .collect(); Self { derived_from, parent_sources, raw_response_type, } }
conditional_block
split_operation_metadata.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use fnv::FnvHashSet; use graphql_ir::{Argument, ConstantValue, Directive, Value}; use interner::{Intern, StringKey}; use lazy_static::lazy_static; lazy_static! { pub static ref DIRECTIVE_SPLIT_OPERATION: StringKey = "__splitOperation".intern(); static ref ARG_DERIVED_FROM: StringKey = "derivedFrom".intern(); static ref ARG_PARENT_SOURCES: StringKey = "parentSources".intern(); static ref ARG_RAW_RESPONSE_TYPE: StringKey = "rawResponseType".intern(); } /// The split operation metadata directive indicates that an operation was split /// out by the compiler from a parent normalization file. pub struct SplitOperationMetadata { /// Name of the fragment that this split operation represents. pub derived_from: StringKey, /// The names of the fragments and operations that included this fragment. /// They are the reason this split operation exist. If they are all removed, /// this file also needs to be removed. pub parent_sources: FnvHashSet<StringKey>, /// Should a @raw_response_type style type be generated. pub raw_response_type: bool, } impl SplitOperationMetadata { pub fn to_directive(&self) -> Directive { let mut arguments = vec![ Argument { name: WithLocation::generated(*ARG_DERIVED_FROM), value: WithLocation::generated(Value::Constant(ConstantValue::String( self.derived_from, ))), }, Argument { name: WithLocation::generated(*ARG_PARENT_SOURCES), value: WithLocation::generated(Value::Constant(ConstantValue::List( self.parent_sources .iter() .cloned() .map(ConstantValue::String) .collect(), ))), }, ]; if self.raw_response_type { arguments.push(Argument { name: WithLocation::generated(*ARG_RAW_RESPONSE_TYPE), value: WithLocation::generated(Value::Constant(ConstantValue::Null())), }); } Directive { name: WithLocation::generated(*DIRECTIVE_SPLIT_OPERATION), arguments, } } } impl From<&Directive> for SplitOperationMetadata { fn from(directive: &Directive) -> Self { debug_assert!(directive.name.item == *DIRECTIVE_SPLIT_OPERATION); let derived_from_arg = directive .arguments .named(*ARG_DERIVED_FROM) .expect("Expected derived_from arg to exist"); let derived_from = derived_from_arg.value.item.expect_string_literal(); let parent_sources_arg = directive .arguments .named(*ARG_PARENT_SOURCES) .expect("Expected parent_sources arg to exist"); let raw_response_type = directive.arguments.named(*ARG_RAW_RESPONSE_TYPE).is_some(); if let Value::Constant(ConstantValue::List(source_definition_names)) = &parent_sources_arg.value.item { let parent_sources = source_definition_names .iter() .map(|val| { if let ConstantValue::String(name) = val { name } else { panic!("Expected item in the parent sources to be a StringKey.")
Self { derived_from, parent_sources, raw_response_type, } } else { panic!("Expected parent sources to be a constant of list."); } } }
} }) .cloned() .collect();
random_line_split
split_operation_metadata.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use fnv::FnvHashSet; use graphql_ir::{Argument, ConstantValue, Directive, Value}; use interner::{Intern, StringKey}; use lazy_static::lazy_static; lazy_static! { pub static ref DIRECTIVE_SPLIT_OPERATION: StringKey = "__splitOperation".intern(); static ref ARG_DERIVED_FROM: StringKey = "derivedFrom".intern(); static ref ARG_PARENT_SOURCES: StringKey = "parentSources".intern(); static ref ARG_RAW_RESPONSE_TYPE: StringKey = "rawResponseType".intern(); } /// The split operation metadata directive indicates that an operation was split /// out by the compiler from a parent normalization file. pub struct SplitOperationMetadata { /// Name of the fragment that this split operation represents. pub derived_from: StringKey, /// The names of the fragments and operations that included this fragment. /// They are the reason this split operation exist. If they are all removed, /// this file also needs to be removed. pub parent_sources: FnvHashSet<StringKey>, /// Should a @raw_response_type style type be generated. pub raw_response_type: bool, } impl SplitOperationMetadata { pub fn to_directive(&self) -> Directive
arguments.push(Argument { name: WithLocation::generated(*ARG_RAW_RESPONSE_TYPE), value: WithLocation::generated(Value::Constant(ConstantValue::Null())), }); } Directive { name: WithLocation::generated(*DIRECTIVE_SPLIT_OPERATION), arguments, } } } impl From<&Directive> for SplitOperationMetadata { fn from(directive: &Directive) -> Self { debug_assert!(directive.name.item == *DIRECTIVE_SPLIT_OPERATION); let derived_from_arg = directive .arguments .named(*ARG_DERIVED_FROM) .expect("Expected derived_from arg to exist"); let derived_from = derived_from_arg.value.item.expect_string_literal(); let parent_sources_arg = directive .arguments .named(*ARG_PARENT_SOURCES) .expect("Expected parent_sources arg to exist"); let raw_response_type = directive.arguments.named(*ARG_RAW_RESPONSE_TYPE).is_some(); if let Value::Constant(ConstantValue::List(source_definition_names)) = &parent_sources_arg.value.item { let parent_sources = source_definition_names .iter() .map(|val| { if let ConstantValue::String(name) = val { name } else { panic!("Expected item in the parent sources to be a StringKey.") } }) .cloned() .collect(); Self { derived_from, parent_sources, raw_response_type, } } else { panic!("Expected parent sources to be a constant of list."); } } }
{ let mut arguments = vec![ Argument { name: WithLocation::generated(*ARG_DERIVED_FROM), value: WithLocation::generated(Value::Constant(ConstantValue::String( self.derived_from, ))), }, Argument { name: WithLocation::generated(*ARG_PARENT_SOURCES), value: WithLocation::generated(Value::Constant(ConstantValue::List( self.parent_sources .iter() .cloned() .map(ConstantValue::String) .collect(), ))), }, ]; if self.raw_response_type {
identifier_body
split_operation_metadata.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use fnv::FnvHashSet; use graphql_ir::{Argument, ConstantValue, Directive, Value}; use interner::{Intern, StringKey}; use lazy_static::lazy_static; lazy_static! { pub static ref DIRECTIVE_SPLIT_OPERATION: StringKey = "__splitOperation".intern(); static ref ARG_DERIVED_FROM: StringKey = "derivedFrom".intern(); static ref ARG_PARENT_SOURCES: StringKey = "parentSources".intern(); static ref ARG_RAW_RESPONSE_TYPE: StringKey = "rawResponseType".intern(); } /// The split operation metadata directive indicates that an operation was split /// out by the compiler from a parent normalization file. pub struct SplitOperationMetadata { /// Name of the fragment that this split operation represents. pub derived_from: StringKey, /// The names of the fragments and operations that included this fragment. /// They are the reason this split operation exist. If they are all removed, /// this file also needs to be removed. pub parent_sources: FnvHashSet<StringKey>, /// Should a @raw_response_type style type be generated. pub raw_response_type: bool, } impl SplitOperationMetadata { pub fn
(&self) -> Directive { let mut arguments = vec![ Argument { name: WithLocation::generated(*ARG_DERIVED_FROM), value: WithLocation::generated(Value::Constant(ConstantValue::String( self.derived_from, ))), }, Argument { name: WithLocation::generated(*ARG_PARENT_SOURCES), value: WithLocation::generated(Value::Constant(ConstantValue::List( self.parent_sources .iter() .cloned() .map(ConstantValue::String) .collect(), ))), }, ]; if self.raw_response_type { arguments.push(Argument { name: WithLocation::generated(*ARG_RAW_RESPONSE_TYPE), value: WithLocation::generated(Value::Constant(ConstantValue::Null())), }); } Directive { name: WithLocation::generated(*DIRECTIVE_SPLIT_OPERATION), arguments, } } } impl From<&Directive> for SplitOperationMetadata { fn from(directive: &Directive) -> Self { debug_assert!(directive.name.item == *DIRECTIVE_SPLIT_OPERATION); let derived_from_arg = directive .arguments .named(*ARG_DERIVED_FROM) .expect("Expected derived_from arg to exist"); let derived_from = derived_from_arg.value.item.expect_string_literal(); let parent_sources_arg = directive .arguments .named(*ARG_PARENT_SOURCES) .expect("Expected parent_sources arg to exist"); let raw_response_type = directive.arguments.named(*ARG_RAW_RESPONSE_TYPE).is_some(); if let Value::Constant(ConstantValue::List(source_definition_names)) = &parent_sources_arg.value.item { let parent_sources = source_definition_names .iter() .map(|val| { if let ConstantValue::String(name) = val { name } else { panic!("Expected item in the parent sources to be a StringKey.") } }) .cloned() .collect(); Self { derived_from, parent_sources, raw_response_type, } } else { panic!("Expected parent sources to be a constant of list."); } } }
to_directive
identifier_name
test.rs
// Copyright 2017 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. #![feature(extern_types)] #[link(name = "ctest", kind = "static")] extern { type data; fn data_create(magic: u32) -> *mut data; fn data_get(data: *mut data) -> u32; } const MAGIC: u32 = 0xdeadbeef; fn main()
{ unsafe { let data = data_create(MAGIC); assert_eq!(data_get(data), MAGIC); } }
identifier_body
test.rs
// Copyright 2017 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. #![feature(extern_types)] #[link(name = "ctest", kind = "static")] extern { type data; fn data_create(magic: u32) -> *mut data; fn data_get(data: *mut data) -> u32; } const MAGIC: u32 = 0xdeadbeef; fn
() { unsafe { let data = data_create(MAGIC); assert_eq!(data_get(data), MAGIC); } }
main
identifier_name
test.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// 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. #![feature(extern_types)] #[link(name = "ctest", kind = "static")] extern { type data; fn data_create(magic: u32) -> *mut data; fn data_get(data: *mut data) -> u32; } const MAGIC: u32 = 0xdeadbeef; fn main() { unsafe { let data = data_create(MAGIC); assert_eq!(data_get(data), MAGIC); } }
// 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
random_line_split
fnv.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/. */ //! This file stolen wholesale from rustc/src/librustc/util/nodemap.rs pub use std::hash::{Hash, Hasher, Writer}; /// A speedy hash algorithm for node ids and def ids. The hashmap in /// libcollections by default uses SipHash which isn't quite as speedy as we /// want. In the compiler we're not really worried about DOS attempts, so we /// just default to a non-cryptographic hash. /// /// This uses FNV hashing, as described here: /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function #[deriving(Clone)] pub struct FnvHasher; pub struct
(u64); impl Hasher<FnvState> for FnvHasher { fn hash<Sized? T: Hash<FnvState>>(&self, t: &T) -> u64 { let mut state = FnvState(0xcbf29ce484222325); t.hash(&mut state); let FnvState(ret) = state; return ret; } } impl Writer for FnvState { fn write(&mut self, bytes: &[u8]) { let FnvState(mut hash) = *self; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash * 0x100000001b3; } *self = FnvState(hash); } } #[inline(always)] pub fn hash<T: Hash<FnvState>>(t: &T) -> u64 { let s = FnvHasher; s.hash(t) }
FnvState
identifier_name
fnv.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/. */ //! This file stolen wholesale from rustc/src/librustc/util/nodemap.rs pub use std::hash::{Hash, Hasher, Writer}; /// A speedy hash algorithm for node ids and def ids. The hashmap in /// libcollections by default uses SipHash which isn't quite as speedy as we /// want. In the compiler we're not really worried about DOS attempts, so we /// just default to a non-cryptographic hash. /// /// This uses FNV hashing, as described here: /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function #[deriving(Clone)] pub struct FnvHasher; pub struct FnvState(u64); impl Hasher<FnvState> for FnvHasher { fn hash<Sized? T: Hash<FnvState>>(&self, t: &T) -> u64 { let mut state = FnvState(0xcbf29ce484222325); t.hash(&mut state);
let FnvState(ret) = state; return ret; } } impl Writer for FnvState { fn write(&mut self, bytes: &[u8]) { let FnvState(mut hash) = *self; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash * 0x100000001b3; } *self = FnvState(hash); } } #[inline(always)] pub fn hash<T: Hash<FnvState>>(t: &T) -> u64 { let s = FnvHasher; s.hash(t) }
random_line_split
table_caption.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. use crate::block::BlockFlow; use crate::context::LayoutContext; use crate::display_list::{ DisplayListBuildState, StackingContextCollectionFlags, StackingContextCollectionState, }; use crate::flow::{Flow, FlowClass, OpaqueFlow}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use app_units::Au; use euclid::Point2D; use gfx_traits::print_tree::PrintTree; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; #[allow(unsafe_code)] unsafe impl crate::flow::HasBaseFlow for TableCaptionFlow {} /// A table formatting context. #[repr(C)] pub struct TableCaptionFlow { pub block_flow: BlockFlow, } impl TableCaptionFlow { pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow { TableCaptionFlow { block_flow: BlockFlow::from_fragment(fragment), } } } impl Flow for TableCaptionFlow { fn class(&self) -> FlowClass { FlowClass::TableCaption } fn as_mut_block(&mut self) -> &mut BlockFlow { &mut self.block_flow } fn as_block(&self) -> &BlockFlow { &self.block_flow } fn bubble_inline_sizes(&mut self) { self.block_flow.bubble_inline_sizes(); } fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) { debug!( "assign_inline_sizes({}): assigning inline_size for flow", "table_caption" ); self.block_flow.assign_inline_sizes(layout_context); } fn assign_block_size(&mut self, layout_context: &LayoutContext) { debug!("assign_block_size: assigning block_size for table_caption"); self.block_flow.assign_block_size(layout_context); } fn compute_stacking_relative_position(&mut self, layout_context: &LayoutContext) { self.block_flow .compute_stacking_relative_position(layout_context) } fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) { self.block_flow .update_late_computed_inline_position_if_necessary(inline_position) } fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au)
fn build_display_list(&mut self, state: &mut DisplayListBuildState) { debug!("build_display_list_table_caption: same process as block flow"); self.block_flow.build_display_list(state); } fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) { self.block_flow .collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty()); } fn repair_style(&mut self, new_style: &crate::ServoArc<ComputedValues>) { self.block_flow.repair_style(new_style) } fn compute_overflow(&self) -> Overflow { self.block_flow.compute_overflow() } fn contains_roots_of_absolute_flow_tree(&self) -> bool { self.block_flow.contains_roots_of_absolute_flow_tree() } fn is_absolute_containing_block(&self) -> bool { self.block_flow.is_absolute_containing_block() } fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> { self.block_flow.generated_containing_block_size(flow) } fn iterate_through_fragment_border_boxes( &self, iterator: &mut dyn FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D<Au>, ) { self.block_flow.iterate_through_fragment_border_boxes( iterator, level, stacking_context_position, ) } fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } fn print_extra_flow_children(&self, print_tree: &mut PrintTree) { self.block_flow.print_extra_flow_children(print_tree); } } impl fmt::Debug for TableCaptionFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TableCaptionFlow: {:?}", self.block_flow) } }
{ self.block_flow .update_late_computed_block_position_if_necessary(block_position) }
identifier_body
table_caption.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. use crate::block::BlockFlow; use crate::context::LayoutContext; use crate::display_list::{ DisplayListBuildState, StackingContextCollectionFlags, StackingContextCollectionState, }; use crate::flow::{Flow, FlowClass, OpaqueFlow}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use app_units::Au; use euclid::Point2D; use gfx_traits::print_tree::PrintTree; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; #[allow(unsafe_code)] unsafe impl crate::flow::HasBaseFlow for TableCaptionFlow {} /// A table formatting context. #[repr(C)] pub struct TableCaptionFlow { pub block_flow: BlockFlow, } impl TableCaptionFlow { pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow { TableCaptionFlow { block_flow: BlockFlow::from_fragment(fragment), } } } impl Flow for TableCaptionFlow { fn class(&self) -> FlowClass { FlowClass::TableCaption }
} fn as_block(&self) -> &BlockFlow { &self.block_flow } fn bubble_inline_sizes(&mut self) { self.block_flow.bubble_inline_sizes(); } fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) { debug!( "assign_inline_sizes({}): assigning inline_size for flow", "table_caption" ); self.block_flow.assign_inline_sizes(layout_context); } fn assign_block_size(&mut self, layout_context: &LayoutContext) { debug!("assign_block_size: assigning block_size for table_caption"); self.block_flow.assign_block_size(layout_context); } fn compute_stacking_relative_position(&mut self, layout_context: &LayoutContext) { self.block_flow .compute_stacking_relative_position(layout_context) } fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) { self.block_flow .update_late_computed_inline_position_if_necessary(inline_position) } fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) { self.block_flow .update_late_computed_block_position_if_necessary(block_position) } fn build_display_list(&mut self, state: &mut DisplayListBuildState) { debug!("build_display_list_table_caption: same process as block flow"); self.block_flow.build_display_list(state); } fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) { self.block_flow .collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty()); } fn repair_style(&mut self, new_style: &crate::ServoArc<ComputedValues>) { self.block_flow.repair_style(new_style) } fn compute_overflow(&self) -> Overflow { self.block_flow.compute_overflow() } fn contains_roots_of_absolute_flow_tree(&self) -> bool { self.block_flow.contains_roots_of_absolute_flow_tree() } fn is_absolute_containing_block(&self) -> bool { self.block_flow.is_absolute_containing_block() } fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> { self.block_flow.generated_containing_block_size(flow) } fn iterate_through_fragment_border_boxes( &self, iterator: &mut dyn FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D<Au>, ) { self.block_flow.iterate_through_fragment_border_boxes( iterator, level, stacking_context_position, ) } fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } fn print_extra_flow_children(&self, print_tree: &mut PrintTree) { self.block_flow.print_extra_flow_children(print_tree); } } impl fmt::Debug for TableCaptionFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TableCaptionFlow: {:?}", self.block_flow) } }
fn as_mut_block(&mut self) -> &mut BlockFlow { &mut self.block_flow
random_line_split
table_caption.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. use crate::block::BlockFlow; use crate::context::LayoutContext; use crate::display_list::{ DisplayListBuildState, StackingContextCollectionFlags, StackingContextCollectionState, }; use crate::flow::{Flow, FlowClass, OpaqueFlow}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use app_units::Au; use euclid::Point2D; use gfx_traits::print_tree::PrintTree; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; #[allow(unsafe_code)] unsafe impl crate::flow::HasBaseFlow for TableCaptionFlow {} /// A table formatting context. #[repr(C)] pub struct TableCaptionFlow { pub block_flow: BlockFlow, } impl TableCaptionFlow { pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow { TableCaptionFlow { block_flow: BlockFlow::from_fragment(fragment), } } } impl Flow for TableCaptionFlow { fn
(&self) -> FlowClass { FlowClass::TableCaption } fn as_mut_block(&mut self) -> &mut BlockFlow { &mut self.block_flow } fn as_block(&self) -> &BlockFlow { &self.block_flow } fn bubble_inline_sizes(&mut self) { self.block_flow.bubble_inline_sizes(); } fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) { debug!( "assign_inline_sizes({}): assigning inline_size for flow", "table_caption" ); self.block_flow.assign_inline_sizes(layout_context); } fn assign_block_size(&mut self, layout_context: &LayoutContext) { debug!("assign_block_size: assigning block_size for table_caption"); self.block_flow.assign_block_size(layout_context); } fn compute_stacking_relative_position(&mut self, layout_context: &LayoutContext) { self.block_flow .compute_stacking_relative_position(layout_context) } fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) { self.block_flow .update_late_computed_inline_position_if_necessary(inline_position) } fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) { self.block_flow .update_late_computed_block_position_if_necessary(block_position) } fn build_display_list(&mut self, state: &mut DisplayListBuildState) { debug!("build_display_list_table_caption: same process as block flow"); self.block_flow.build_display_list(state); } fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) { self.block_flow .collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty()); } fn repair_style(&mut self, new_style: &crate::ServoArc<ComputedValues>) { self.block_flow.repair_style(new_style) } fn compute_overflow(&self) -> Overflow { self.block_flow.compute_overflow() } fn contains_roots_of_absolute_flow_tree(&self) -> bool { self.block_flow.contains_roots_of_absolute_flow_tree() } fn is_absolute_containing_block(&self) -> bool { self.block_flow.is_absolute_containing_block() } fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> { self.block_flow.generated_containing_block_size(flow) } fn iterate_through_fragment_border_boxes( &self, iterator: &mut dyn FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D<Au>, ) { self.block_flow.iterate_through_fragment_border_boxes( iterator, level, stacking_context_position, ) } fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } fn print_extra_flow_children(&self, print_tree: &mut PrintTree) { self.block_flow.print_extra_flow_children(print_tree); } } impl fmt::Debug for TableCaptionFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TableCaptionFlow: {:?}", self.block_flow) } }
class
identifier_name
fun1.rs
fn sqr(x: f64) -> f64 { x * x } //absolute value fn abs(x: f64) -> f64 { if x > 0.0 { x } else { -x } } //ensure a number always falls in the given range fn clamp(x: f64, x1: f64, x2: f64) -> f64 { if x < x1 { x1 } else if x > x2 { x2 } else { x } } fn
() { let res = sqr(2.0); println!("square is {}", res); let num = -1.0; let abs1 = abs(num); println!("absolute value of {} is {}", num, abs1); let min = 5.0; let max = 18.0; let clamp_min = 1.0; let clamp_max = 99.0; let dont_clamp = 7.0; println!("clamping {}: {}", clamp_min, clamp(clamp_min, min, max)); println!("clamping {}: {}", clamp_max, clamp(clamp_max, min, max)); println!("clamping {}: {}", dont_clamp, clamp(dont_clamp, min, max)); }
main
identifier_name
fun1.rs
fn sqr(x: f64) -> f64 { x * x } //absolute value fn abs(x: f64) -> f64 { if x > 0.0 { x } else
} //ensure a number always falls in the given range fn clamp(x: f64, x1: f64, x2: f64) -> f64 { if x < x1 { x1 } else if x > x2 { x2 } else { x } } fn main() { let res = sqr(2.0); println!("square is {}", res); let num = -1.0; let abs1 = abs(num); println!("absolute value of {} is {}", num, abs1); let min = 5.0; let max = 18.0; let clamp_min = 1.0; let clamp_max = 99.0; let dont_clamp = 7.0; println!("clamping {}: {}", clamp_min, clamp(clamp_min, min, max)); println!("clamping {}: {}", clamp_max, clamp(clamp_max, min, max)); println!("clamping {}: {}", dont_clamp, clamp(dont_clamp, min, max)); }
{ -x }
conditional_block
fun1.rs
fn sqr(x: f64) -> f64 { x * x } //absolute value fn abs(x: f64) -> f64 { if x > 0.0 { x } else { -x } } //ensure a number always falls in the given range fn clamp(x: f64, x1: f64, x2: f64) -> f64 { if x < x1 { x1 } else if x > x2 { x2 } else { x } } fn main()
{ let res = sqr(2.0); println!("square is {}", res); let num = -1.0; let abs1 = abs(num); println!("absolute value of {} is {}", num, abs1); let min = 5.0; let max = 18.0; let clamp_min = 1.0; let clamp_max = 99.0; let dont_clamp = 7.0; println!("clamping {}: {}", clamp_min, clamp(clamp_min, min, max)); println!("clamping {}: {}", clamp_max, clamp(clamp_max, min, max)); println!("clamping {}: {}", dont_clamp, clamp(dont_clamp, min, max)); }
identifier_body
fun1.rs
fn sqr(x: f64) -> f64 { x * x } //absolute value fn abs(x: f64) -> f64 { if x > 0.0 { x } else { -x } } //ensure a number always falls in the given range fn clamp(x: f64, x1: f64, x2: f64) -> f64 { if x < x1 { x1 } else if x > x2 { x2 } else { x } } fn main() { let res = sqr(2.0); println!("square is {}", res); let num = -1.0; let abs1 = abs(num); println!("absolute value of {} is {}", num, abs1);
let dont_clamp = 7.0; println!("clamping {}: {}", clamp_min, clamp(clamp_min, min, max)); println!("clamping {}: {}", clamp_max, clamp(clamp_max, min, max)); println!("clamping {}: {}", dont_clamp, clamp(dont_clamp, min, max)); }
let min = 5.0; let max = 18.0; let clamp_min = 1.0; let clamp_max = 99.0;
random_line_split
commands.rs
use std::collections::VecDeque; use std::sync::{atomic, mpsc, Arc, Condvar, Mutex}; use std::{mem, ptr}; use context::CommandContext; use GliumCreationError; use glutin; const CLOSURES_MAX_SIZE: usize = 64; const MAX_QUEUE_SIZE: usize = 64; pub struct Sender { queue: Arc<Queue>, } pub struct Receiver { queue: Arc<Queue>, closed: atomic::AtomicBool, } struct Queue { queue: Mutex<VecDeque<InternalMessage>>, condvar: Condvar, } pub enum Message { EndFrame, Stop, Execute(Exec), Rebuild(glutin::WindowBuilder<'static>, mpsc::Sender<Result<(), GliumCreationError>>), } pub struct
{ /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), } enum InternalMessage { EndFrame, Stop, Execute { /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), }, Rebuild(glutin::WindowBuilder<'static>, mpsc::Sender<Result<(), GliumCreationError>>), } pub fn channel() -> (Sender, Receiver) { let queue_sender = Arc::new(Queue { queue: Mutex::new(VecDeque::with_capacity(MAX_QUEUE_SIZE)), condvar: Condvar::new(), }); let queue_receiver = queue_sender.clone(); (Sender { queue: queue_sender }, Receiver { queue: queue_receiver, closed: atomic::AtomicBool::new(false) }) } impl Sender { pub fn push<F>(&self, f: F) where F: FnOnce(CommandContext) { // TODO: + Send +'static assert!(mem::size_of::<F>() <= CLOSURES_MAX_SIZE * mem::size_of::<usize>()); fn call_fn<F>(data: [usize; CLOSURES_MAX_SIZE], cmd: CommandContext) where F: FnOnce(CommandContext) { let closure: F = unsafe { ptr::read(data.as_slice().as_ptr() as *const F) }; closure(cmd); } let mut data: [usize; CLOSURES_MAX_SIZE] = unsafe { mem::uninitialized() }; unsafe { ptr::copy_nonoverlapping_memory(data.as_mut_slice().as_mut_ptr() as *mut F, &f, 1); } let message = InternalMessage::Execute { data: data, call_fn: call_fn::<F>, }; { let mut lock = self.queue.queue.lock().unwrap(); loop { if lock.len() >= MAX_QUEUE_SIZE { lock = self.queue.condvar.wait(lock).unwrap(); continue; } lock.push_back(message); self.queue.condvar.notify_one(); break; } } unsafe { mem::forget(f) } } pub fn push_endframe(&self) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::EndFrame); self.queue.condvar.notify_one(); } pub fn push_rebuild(&self, b: glutin::WindowBuilder<'static>, n: mpsc::Sender<Result<(), GliumCreationError>>) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Rebuild(b, n)); self.queue.condvar.notify_one(); } } impl Drop for Sender { fn drop(&mut self) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Stop); self.queue.condvar.notify_one(); } } impl Receiver { pub fn pop(&self) -> Message { let mut lock = self.queue.queue.lock().unwrap(); loop { let msg = lock.pop_front(); self.queue.condvar.notify_one(); match msg { Some(InternalMessage::EndFrame) => return Message::EndFrame, Some(InternalMessage::Execute { data, call_fn }) => return Message::Execute(Exec { data: data, call_fn: call_fn }), Some(InternalMessage::Stop) => { self.closed.store(true, atomic::Ordering::Release); return Message::Stop; }, Some(InternalMessage::Rebuild(a, b)) => { return Message::Rebuild(a, b); }, None => { if self.closed.load(atomic::Ordering::Acquire) { return Message::Stop; } lock = self.queue.condvar.wait(lock).unwrap(); } } } } } impl Exec { pub fn execute(self, ctxt: CommandContext) { let f = self.call_fn; f(self.data, ctxt); } } #[cfg(test)] mod test { use super::{Message, channel}; #[test] fn simple() { let (sender, receiver) = channel(); let (tx, rx) = ::std::sync::mpsc::channel(); sender.push(move |c| { tx.send(5).unwrap(); unsafe { ::std::mem::forget(c) }; }); match receiver.pop() { Message::Execute(f) => f.execute(unsafe { ::std::mem::uninitialized() }), _ => unreachable!() }; assert_eq!(rx.try_recv().unwrap(), 5); } #[test] fn stop_message() { let (_, receiver) = channel(); for _ in (0.. 5) { match receiver.pop() { Message::Stop => (), _ => unreachable!() }; } } }
Exec
identifier_name
commands.rs
use std::collections::VecDeque; use std::sync::{atomic, mpsc, Arc, Condvar, Mutex}; use std::{mem, ptr}; use context::CommandContext; use GliumCreationError; use glutin; const CLOSURES_MAX_SIZE: usize = 64; const MAX_QUEUE_SIZE: usize = 64; pub struct Sender { queue: Arc<Queue>, } pub struct Receiver { queue: Arc<Queue>, closed: atomic::AtomicBool, } struct Queue { queue: Mutex<VecDeque<InternalMessage>>, condvar: Condvar, } pub enum Message { EndFrame, Stop, Execute(Exec), Rebuild(glutin::WindowBuilder<'static>, mpsc::Sender<Result<(), GliumCreationError>>), } pub struct Exec { /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), } enum InternalMessage { EndFrame, Stop, Execute { /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), }, Rebuild(glutin::WindowBuilder<'static>, mpsc::Sender<Result<(), GliumCreationError>>), } pub fn channel() -> (Sender, Receiver) { let queue_sender = Arc::new(Queue { queue: Mutex::new(VecDeque::with_capacity(MAX_QUEUE_SIZE)), condvar: Condvar::new(), }); let queue_receiver = queue_sender.clone(); (Sender { queue: queue_sender }, Receiver { queue: queue_receiver, closed: atomic::AtomicBool::new(false) }) } impl Sender { pub fn push<F>(&self, f: F) where F: FnOnce(CommandContext) { // TODO: + Send +'static assert!(mem::size_of::<F>() <= CLOSURES_MAX_SIZE * mem::size_of::<usize>()); fn call_fn<F>(data: [usize; CLOSURES_MAX_SIZE], cmd: CommandContext) where F: FnOnce(CommandContext) { let closure: F = unsafe { ptr::read(data.as_slice().as_ptr() as *const F) }; closure(cmd); } let mut data: [usize; CLOSURES_MAX_SIZE] = unsafe { mem::uninitialized() }; unsafe { ptr::copy_nonoverlapping_memory(data.as_mut_slice().as_mut_ptr() as *mut F, &f, 1); } let message = InternalMessage::Execute { data: data, call_fn: call_fn::<F>, }; { let mut lock = self.queue.queue.lock().unwrap(); loop { if lock.len() >= MAX_QUEUE_SIZE { lock = self.queue.condvar.wait(lock).unwrap(); continue; } lock.push_back(message); self.queue.condvar.notify_one(); break; } } unsafe { mem::forget(f) } } pub fn push_endframe(&self) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::EndFrame); self.queue.condvar.notify_one(); } pub fn push_rebuild(&self, b: glutin::WindowBuilder<'static>, n: mpsc::Sender<Result<(), GliumCreationError>>) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Rebuild(b, n)); self.queue.condvar.notify_one(); } } impl Drop for Sender { fn drop(&mut self) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Stop); self.queue.condvar.notify_one(); } } impl Receiver { pub fn pop(&self) -> Message { let mut lock = self.queue.queue.lock().unwrap(); loop { let msg = lock.pop_front(); self.queue.condvar.notify_one(); match msg { Some(InternalMessage::EndFrame) => return Message::EndFrame, Some(InternalMessage::Execute { data, call_fn }) => return Message::Execute(Exec { data: data, call_fn: call_fn }), Some(InternalMessage::Stop) => { self.closed.store(true, atomic::Ordering::Release); return Message::Stop; }, Some(InternalMessage::Rebuild(a, b)) => { return Message::Rebuild(a, b); }, None => { if self.closed.load(atomic::Ordering::Acquire) { return Message::Stop; } lock = self.queue.condvar.wait(lock).unwrap(); } } } } } impl Exec { pub fn execute(self, ctxt: CommandContext) { let f = self.call_fn; f(self.data, ctxt); } } #[cfg(test)] mod test { use super::{Message, channel}; #[test] fn simple() { let (sender, receiver) = channel(); let (tx, rx) = ::std::sync::mpsc::channel(); sender.push(move |c| { tx.send(5).unwrap(); unsafe { ::std::mem::forget(c) }; }); match receiver.pop() { Message::Execute(f) => f.execute(unsafe { ::std::mem::uninitialized() }), _ => unreachable!() }; assert_eq!(rx.try_recv().unwrap(), 5); } #[test] fn stop_message() { let (_, receiver) = channel(); for _ in (0.. 5) { match receiver.pop() { Message::Stop => (), _ => unreachable!() }; }
}
}
random_line_split
commands.rs
use std::collections::VecDeque; use std::sync::{atomic, mpsc, Arc, Condvar, Mutex}; use std::{mem, ptr}; use context::CommandContext; use GliumCreationError; use glutin; const CLOSURES_MAX_SIZE: usize = 64; const MAX_QUEUE_SIZE: usize = 64; pub struct Sender { queue: Arc<Queue>, } pub struct Receiver { queue: Arc<Queue>, closed: atomic::AtomicBool, } struct Queue { queue: Mutex<VecDeque<InternalMessage>>, condvar: Condvar, } pub enum Message { EndFrame, Stop, Execute(Exec), Rebuild(glutin::WindowBuilder<'static>, mpsc::Sender<Result<(), GliumCreationError>>), } pub struct Exec { /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), } enum InternalMessage { EndFrame, Stop, Execute { /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), }, Rebuild(glutin::WindowBuilder<'static>, mpsc::Sender<Result<(), GliumCreationError>>), } pub fn channel() -> (Sender, Receiver) { let queue_sender = Arc::new(Queue { queue: Mutex::new(VecDeque::with_capacity(MAX_QUEUE_SIZE)), condvar: Condvar::new(), }); let queue_receiver = queue_sender.clone(); (Sender { queue: queue_sender }, Receiver { queue: queue_receiver, closed: atomic::AtomicBool::new(false) }) } impl Sender { pub fn push<F>(&self, f: F) where F: FnOnce(CommandContext) { // TODO: + Send +'static assert!(mem::size_of::<F>() <= CLOSURES_MAX_SIZE * mem::size_of::<usize>()); fn call_fn<F>(data: [usize; CLOSURES_MAX_SIZE], cmd: CommandContext) where F: FnOnce(CommandContext) { let closure: F = unsafe { ptr::read(data.as_slice().as_ptr() as *const F) }; closure(cmd); } let mut data: [usize; CLOSURES_MAX_SIZE] = unsafe { mem::uninitialized() }; unsafe { ptr::copy_nonoverlapping_memory(data.as_mut_slice().as_mut_ptr() as *mut F, &f, 1); } let message = InternalMessage::Execute { data: data, call_fn: call_fn::<F>, }; { let mut lock = self.queue.queue.lock().unwrap(); loop { if lock.len() >= MAX_QUEUE_SIZE { lock = self.queue.condvar.wait(lock).unwrap(); continue; } lock.push_back(message); self.queue.condvar.notify_one(); break; } } unsafe { mem::forget(f) } } pub fn push_endframe(&self) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::EndFrame); self.queue.condvar.notify_one(); } pub fn push_rebuild(&self, b: glutin::WindowBuilder<'static>, n: mpsc::Sender<Result<(), GliumCreationError>>) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Rebuild(b, n)); self.queue.condvar.notify_one(); } } impl Drop for Sender { fn drop(&mut self)
} impl Receiver { pub fn pop(&self) -> Message { let mut lock = self.queue.queue.lock().unwrap(); loop { let msg = lock.pop_front(); self.queue.condvar.notify_one(); match msg { Some(InternalMessage::EndFrame) => return Message::EndFrame, Some(InternalMessage::Execute { data, call_fn }) => return Message::Execute(Exec { data: data, call_fn: call_fn }), Some(InternalMessage::Stop) => { self.closed.store(true, atomic::Ordering::Release); return Message::Stop; }, Some(InternalMessage::Rebuild(a, b)) => { return Message::Rebuild(a, b); }, None => { if self.closed.load(atomic::Ordering::Acquire) { return Message::Stop; } lock = self.queue.condvar.wait(lock).unwrap(); } } } } } impl Exec { pub fn execute(self, ctxt: CommandContext) { let f = self.call_fn; f(self.data, ctxt); } } #[cfg(test)] mod test { use super::{Message, channel}; #[test] fn simple() { let (sender, receiver) = channel(); let (tx, rx) = ::std::sync::mpsc::channel(); sender.push(move |c| { tx.send(5).unwrap(); unsafe { ::std::mem::forget(c) }; }); match receiver.pop() { Message::Execute(f) => f.execute(unsafe { ::std::mem::uninitialized() }), _ => unreachable!() }; assert_eq!(rx.try_recv().unwrap(), 5); } #[test] fn stop_message() { let (_, receiver) = channel(); for _ in (0.. 5) { match receiver.pop() { Message::Stop => (), _ => unreachable!() }; } } }
{ let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Stop); self.queue.condvar.notify_one(); }
identifier_body
commands.rs
use std::collections::VecDeque; use std::sync::{atomic, mpsc, Arc, Condvar, Mutex}; use std::{mem, ptr}; use context::CommandContext; use GliumCreationError; use glutin; const CLOSURES_MAX_SIZE: usize = 64; const MAX_QUEUE_SIZE: usize = 64; pub struct Sender { queue: Arc<Queue>, } pub struct Receiver { queue: Arc<Queue>, closed: atomic::AtomicBool, } struct Queue { queue: Mutex<VecDeque<InternalMessage>>, condvar: Condvar, } pub enum Message { EndFrame, Stop, Execute(Exec), Rebuild(glutin::WindowBuilder<'static>, mpsc::Sender<Result<(), GliumCreationError>>), } pub struct Exec { /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), } enum InternalMessage { EndFrame, Stop, Execute { /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), }, Rebuild(glutin::WindowBuilder<'static>, mpsc::Sender<Result<(), GliumCreationError>>), } pub fn channel() -> (Sender, Receiver) { let queue_sender = Arc::new(Queue { queue: Mutex::new(VecDeque::with_capacity(MAX_QUEUE_SIZE)), condvar: Condvar::new(), }); let queue_receiver = queue_sender.clone(); (Sender { queue: queue_sender }, Receiver { queue: queue_receiver, closed: atomic::AtomicBool::new(false) }) } impl Sender { pub fn push<F>(&self, f: F) where F: FnOnce(CommandContext) { // TODO: + Send +'static assert!(mem::size_of::<F>() <= CLOSURES_MAX_SIZE * mem::size_of::<usize>()); fn call_fn<F>(data: [usize; CLOSURES_MAX_SIZE], cmd: CommandContext) where F: FnOnce(CommandContext) { let closure: F = unsafe { ptr::read(data.as_slice().as_ptr() as *const F) }; closure(cmd); } let mut data: [usize; CLOSURES_MAX_SIZE] = unsafe { mem::uninitialized() }; unsafe { ptr::copy_nonoverlapping_memory(data.as_mut_slice().as_mut_ptr() as *mut F, &f, 1); } let message = InternalMessage::Execute { data: data, call_fn: call_fn::<F>, }; { let mut lock = self.queue.queue.lock().unwrap(); loop { if lock.len() >= MAX_QUEUE_SIZE { lock = self.queue.condvar.wait(lock).unwrap(); continue; } lock.push_back(message); self.queue.condvar.notify_one(); break; } } unsafe { mem::forget(f) } } pub fn push_endframe(&self) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::EndFrame); self.queue.condvar.notify_one(); } pub fn push_rebuild(&self, b: glutin::WindowBuilder<'static>, n: mpsc::Sender<Result<(), GliumCreationError>>) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Rebuild(b, n)); self.queue.condvar.notify_one(); } } impl Drop for Sender { fn drop(&mut self) { let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Stop); self.queue.condvar.notify_one(); } } impl Receiver { pub fn pop(&self) -> Message { let mut lock = self.queue.queue.lock().unwrap(); loop { let msg = lock.pop_front(); self.queue.condvar.notify_one(); match msg { Some(InternalMessage::EndFrame) => return Message::EndFrame, Some(InternalMessage::Execute { data, call_fn }) => return Message::Execute(Exec { data: data, call_fn: call_fn }), Some(InternalMessage::Stop) => { self.closed.store(true, atomic::Ordering::Release); return Message::Stop; }, Some(InternalMessage::Rebuild(a, b)) => { return Message::Rebuild(a, b); }, None =>
} } } } impl Exec { pub fn execute(self, ctxt: CommandContext) { let f = self.call_fn; f(self.data, ctxt); } } #[cfg(test)] mod test { use super::{Message, channel}; #[test] fn simple() { let (sender, receiver) = channel(); let (tx, rx) = ::std::sync::mpsc::channel(); sender.push(move |c| { tx.send(5).unwrap(); unsafe { ::std::mem::forget(c) }; }); match receiver.pop() { Message::Execute(f) => f.execute(unsafe { ::std::mem::uninitialized() }), _ => unreachable!() }; assert_eq!(rx.try_recv().unwrap(), 5); } #[test] fn stop_message() { let (_, receiver) = channel(); for _ in (0.. 5) { match receiver.pop() { Message::Stop => (), _ => unreachable!() }; } } }
{ if self.closed.load(atomic::Ordering::Acquire) { return Message::Stop; } lock = self.queue.condvar.wait(lock).unwrap(); }
conditional_block
simple.rs
use tracing::Level; mod yak_shave; fn main() { assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); // Global default collector if false
// Local collector { let collector = tracing_subscriber::fmt() .with_max_level(Level::TRACE) .finish(); tracing::collect::with_default(collector, ||{ tracing::info!("This will be logged to stdout"); }); tracing::info!("This will not be logged to stdout"); } }
{ tracing_subscriber::fmt() // enable everything .with_max_level(Level::TRACE) // sets this to be the default, global collector for this application. .init(); let number_of_yaks = 3; // this creates a new event, outside of any spans. tracing::info!(number_of_yaks, "preparing to shave yaks"); let number_shaved = yak_shave::shave_all(number_of_yaks); tracing::info!( all_yaks_shaved = number_shaved == number_of_yaks, "yak shaving completed." ); }
conditional_block
simple.rs
use tracing::Level; mod yak_shave; fn main()
"yak shaving completed." ); } // Local collector { let collector = tracing_subscriber::fmt() .with_max_level(Level::TRACE) .finish(); tracing::collect::with_default(collector, ||{ tracing::info!("This will be logged to stdout"); }); tracing::info!("This will not be logged to stdout"); } }
{ assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); // Global default collector if false { tracing_subscriber::fmt() // enable everything .with_max_level(Level::TRACE) // sets this to be the default, global collector for this application. .init(); let number_of_yaks = 3; // this creates a new event, outside of any spans. tracing::info!(number_of_yaks, "preparing to shave yaks"); let number_shaved = yak_shave::shave_all(number_of_yaks); tracing::info!( all_yaks_shaved = number_shaved == number_of_yaks,
identifier_body
simple.rs
use tracing::Level; mod yak_shave; fn
() { assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); // Global default collector if false { tracing_subscriber::fmt() // enable everything .with_max_level(Level::TRACE) // sets this to be the default, global collector for this application. .init(); let number_of_yaks = 3; // this creates a new event, outside of any spans. tracing::info!(number_of_yaks, "preparing to shave yaks"); let number_shaved = yak_shave::shave_all(number_of_yaks); tracing::info!( all_yaks_shaved = number_shaved == number_of_yaks, "yak shaving completed." ); } // Local collector { let collector = tracing_subscriber::fmt() .with_max_level(Level::TRACE) .finish(); tracing::collect::with_default(collector, ||{ tracing::info!("This will be logged to stdout"); }); tracing::info!("This will not be logged to stdout"); } }
main
identifier_name
simple.rs
use tracing::Level; mod yak_shave; fn main() { assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); // Global default collector if false { tracing_subscriber::fmt() // enable everything
let number_of_yaks = 3; // this creates a new event, outside of any spans. tracing::info!(number_of_yaks, "preparing to shave yaks"); let number_shaved = yak_shave::shave_all(number_of_yaks); tracing::info!( all_yaks_shaved = number_shaved == number_of_yaks, "yak shaving completed." ); } // Local collector { let collector = tracing_subscriber::fmt() .with_max_level(Level::TRACE) .finish(); tracing::collect::with_default(collector, ||{ tracing::info!("This will be logged to stdout"); }); tracing::info!("This will not be logged to stdout"); } }
.with_max_level(Level::TRACE) // sets this to be the default, global collector for this application. .init();
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate compiletest_rs as compiletest; use std::env; use std::path::PathBuf; pub fn
(mode: &'static str) { let mut config = compiletest::default_config(); let cfg_mode = mode.parse().ok().expect("Invalid mode"); config.mode = cfg_mode; config.src_base = PathBuf::from(format!("{}", mode)); let mut base_path = env::current_dir().expect("Current directory is invalid"); base_path.pop(); base_path.pop(); base_path.pop(); let mode = env::var("BUILD_MODE").expect("BUILD_MODE environment variable must be set"); let debug_path = base_path.join(PathBuf::from(format!("target/{}", mode))); let deps_path = base_path.join(PathBuf::from(format!("target/{}/deps", mode))); config.target_rustcflags = Some(format!("-L {} -L {}", debug_path.display(), deps_path.display())); compiletest::run_tests(&config); }
run_mode
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate compiletest_rs as compiletest; use std::env; use std::path::PathBuf; pub fn run_mode(mode: &'static str)
{ let mut config = compiletest::default_config(); let cfg_mode = mode.parse().ok().expect("Invalid mode"); config.mode = cfg_mode; config.src_base = PathBuf::from(format!("{}", mode)); let mut base_path = env::current_dir().expect("Current directory is invalid"); base_path.pop(); base_path.pop(); base_path.pop(); let mode = env::var("BUILD_MODE").expect("BUILD_MODE environment variable must be set"); let debug_path = base_path.join(PathBuf::from(format!("target/{}", mode))); let deps_path = base_path.join(PathBuf::from(format!("target/{}/deps", mode))); config.target_rustcflags = Some(format!("-L {} -L {}", debug_path.display(), deps_path.display())); compiletest::run_tests(&config); }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate compiletest_rs as compiletest; use std::env; use std::path::PathBuf; pub fn run_mode(mode: &'static str) { let mut config = compiletest::default_config(); let cfg_mode = mode.parse().ok().expect("Invalid mode"); config.mode = cfg_mode; config.src_base = PathBuf::from(format!("{}", mode)); let mut base_path = env::current_dir().expect("Current directory is invalid"); base_path.pop(); base_path.pop(); base_path.pop(); let mode = env::var("BUILD_MODE").expect("BUILD_MODE environment variable must be set"); let debug_path = base_path.join(PathBuf::from(format!("target/{}", mode))); let deps_path = base_path.join(PathBuf::from(format!("target/{}/deps", mode)));
compiletest::run_tests(&config); }
config.target_rustcflags = Some(format!("-L {} -L {}", debug_path.display(), deps_path.display()));
random_line_split
filesearch.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. #![allow(non_camel_case_types)] use std::cell::RefCell; use std::os; use std::io::fs; use std::dynamic_lib::DynamicLibrary; use std::collections::HashSet; use myfs = util::fs; pub enum FileMatch { FileMatches, FileDoesntMatch } // A module for searching for libraries // FIXME (#2658): I'm not happy how this module turned out. Should // probably just be folded into cstore. /// Functions with type `pick` take a parent directory as well as /// a file found in that directory. pub type pick<'a> = |path: &Path|: 'a -> FileMatch; pub struct FileSearch<'a> { pub sysroot: &'a Path, pub addl_lib_search_paths: &'a RefCell<HashSet<Path>>, pub triple: &'a str, } impl<'a> FileSearch<'a> { pub fn
(&self, f: |&Path| -> FileMatch) { let mut visited_dirs = HashSet::new(); let mut found = false; debug!("filesearch: searching additional lib search paths [{:?}]", self.addl_lib_search_paths.borrow().len()); for path in self.addl_lib_search_paths.borrow().iter() { match f(path) { FileMatches => found = true, FileDoesntMatch => () } visited_dirs.insert(path.as_vec().to_owned()); } debug!("filesearch: searching lib path"); let tlib_path = make_target_lib_path(self.sysroot, self.triple); if!visited_dirs.contains_equiv(&tlib_path.as_vec()) { match f(&tlib_path) { FileMatches => found = true, FileDoesntMatch => () } } visited_dirs.insert(tlib_path.as_vec().to_owned()); // Try RUST_PATH if!found { let rustpath = rust_path(); for path in rustpath.iter() { let tlib_path = make_rustpkg_lib_path( self.sysroot, path, self.triple); debug!("is {} in visited_dirs? {:?}", tlib_path.display(), visited_dirs.contains_equiv(&tlib_path.as_vec().to_owned())); if!visited_dirs.contains_equiv(&tlib_path.as_vec()) { visited_dirs.insert(tlib_path.as_vec().to_owned()); // Don't keep searching the RUST_PATH if one match turns up -- // if we did, we'd get a "multiple matching crates" error match f(&tlib_path) { FileMatches => { break; } FileDoesntMatch => () } } } } } pub fn get_lib_path(&self) -> Path { make_target_lib_path(self.sysroot, self.triple) } pub fn search(&self, pick: pick) { self.for_each_lib_search_path(|lib_search_path| { debug!("searching {}", lib_search_path.display()); match fs::readdir(lib_search_path) { Ok(files) => { let mut rslt = FileDoesntMatch; fn is_rlib(p: & &Path) -> bool { p.extension_str() == Some("rlib") } // Reading metadata out of rlibs is faster, and if we find both // an rlib and a dylib we only read one of the files of // metadata, so in the name of speed, bring all rlib files to // the front of the search list. let files1 = files.iter().filter(|p| is_rlib(p)); let files2 = files.iter().filter(|p|!is_rlib(p)); for path in files1.chain(files2) { debug!("testing {}", path.display()); let maybe_picked = pick(path); match maybe_picked { FileMatches => { debug!("picked {}", path.display()); rslt = FileMatches; } FileDoesntMatch => { debug!("rejected {}", path.display()); } } } rslt } Err(..) => FileDoesntMatch, } }); } pub fn new(sysroot: &'a Path, triple: &'a str, addl_lib_search_paths: &'a RefCell<HashSet<Path>>) -> FileSearch<'a> { debug!("using sysroot = {}, triple = {}", sysroot.display(), triple); FileSearch { sysroot: sysroot, addl_lib_search_paths: addl_lib_search_paths, triple: triple, } } pub fn add_dylib_search_paths(&self) { self.for_each_lib_search_path(|lib_search_path| { DynamicLibrary::prepend_search_path(lib_search_path); FileDoesntMatch }) } } pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { let mut p = Path::new(find_libdir(sysroot)); assert!(p.is_relative()); p.push(rustlibdir()); p.push(target_triple); p.push("lib"); p } fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { sysroot.join(&relative_target_lib_path(sysroot, target_triple)) } fn make_rustpkg_lib_path(sysroot: &Path, dir: &Path, triple: &str) -> Path { let mut p = dir.join(find_libdir(sysroot)); p.push(triple); p } pub fn get_or_default_sysroot() -> Path { // Follow symlinks. If the resolved path is relative, make it absolute. fn canonicalize(path: Option<Path>) -> Option<Path> { path.and_then(|path| match myfs::realpath(&path) { Ok(canon) => Some(canon), Err(e) => fail!("failed to get realpath: {}", e), }) } match canonicalize(os::self_exe_name()) { Some(mut p) => { p.pop(); p.pop(); p } None => fail!("can't determine value for sysroot") } } #[cfg(windows)] static PATH_ENTRY_SEPARATOR: &'static str = ";"; #[cfg(not(windows))] static PATH_ENTRY_SEPARATOR: &'static str = ":"; /// Returns RUST_PATH as a string, without default paths added pub fn get_rust_path() -> Option<String> { os::getenv("RUST_PATH").map(|x| x.to_string()) } /// Returns the value of RUST_PATH, as a list /// of Paths. Includes default entries for, if they exist: /// $HOME/.rust /// DIR/.rust for any DIR that's the current working directory /// or an ancestor of it pub fn rust_path() -> Vec<Path> { let mut env_rust_path: Vec<Path> = match get_rust_path() { Some(env_path) => { let env_path_components = env_path.as_slice().split_str(PATH_ENTRY_SEPARATOR); env_path_components.map(|s| Path::new(s)).collect() } None => Vec::new() }; let mut cwd = os::getcwd(); // now add in default entries let cwd_dot_rust = cwd.join(".rust"); if!env_rust_path.contains(&cwd_dot_rust) { env_rust_path.push(cwd_dot_rust); } if!env_rust_path.contains(&cwd) { env_rust_path.push(cwd.clone()); } loop { if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } { break } cwd.set_filename(".rust"); if!env_rust_path.contains(&cwd) && cwd.exists() { env_rust_path.push(cwd.clone()); } cwd.pop(); } let h = os::homedir(); for h in h.iter() { let p = h.join(".rust"); if!env_rust_path.contains(&p) && p.exists() { env_rust_path.push(p); } } env_rust_path } // The name of the directory rustc expects libraries to be located. // On Unix should be "lib", on windows "bin" #[cfg(unix)] fn find_libdir(sysroot: &Path) -> String { // FIXME: This is a quick hack to make the rustc binary able to locate // Rust libraries in Linux environments where libraries might be installed // to lib64/lib32. This would be more foolproof by basing the sysroot off // of the directory where librustc is located, rather than where the rustc // binary is. if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() { return primary_libdir_name(); } else { return secondary_libdir_name(); } #[cfg(target_word_size = "64")] fn primary_libdir_name() -> String { "lib64".to_string() } #[cfg(target_word_size = "32")] fn primary_libdir_name() -> String { "lib32".to_string() } fn secondary_libdir_name() -> String { "lib".to_string() } } #[cfg(windows)] fn find_libdir(_sysroot: &Path) -> String { "bin".to_string() } // The name of rustc's own place to organize libraries. // Used to be "rustc", now the default is "rustlib" pub fn rustlibdir() -> String { "rustlib".to_string() }
for_each_lib_search_path
identifier_name
filesearch.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. #![allow(non_camel_case_types)] use std::cell::RefCell; use std::os; use std::io::fs; use std::dynamic_lib::DynamicLibrary; use std::collections::HashSet; use myfs = util::fs; pub enum FileMatch { FileMatches, FileDoesntMatch } // A module for searching for libraries // FIXME (#2658): I'm not happy how this module turned out. Should // probably just be folded into cstore. /// Functions with type `pick` take a parent directory as well as /// a file found in that directory. pub type pick<'a> = |path: &Path|: 'a -> FileMatch; pub struct FileSearch<'a> { pub sysroot: &'a Path, pub addl_lib_search_paths: &'a RefCell<HashSet<Path>>, pub triple: &'a str, } impl<'a> FileSearch<'a> { pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch)
FileDoesntMatch => () } } visited_dirs.insert(tlib_path.as_vec().to_owned()); // Try RUST_PATH if!found { let rustpath = rust_path(); for path in rustpath.iter() { let tlib_path = make_rustpkg_lib_path( self.sysroot, path, self.triple); debug!("is {} in visited_dirs? {:?}", tlib_path.display(), visited_dirs.contains_equiv(&tlib_path.as_vec().to_owned())); if!visited_dirs.contains_equiv(&tlib_path.as_vec()) { visited_dirs.insert(tlib_path.as_vec().to_owned()); // Don't keep searching the RUST_PATH if one match turns up -- // if we did, we'd get a "multiple matching crates" error match f(&tlib_path) { FileMatches => { break; } FileDoesntMatch => () } } } } } pub fn get_lib_path(&self) -> Path { make_target_lib_path(self.sysroot, self.triple) } pub fn search(&self, pick: pick) { self.for_each_lib_search_path(|lib_search_path| { debug!("searching {}", lib_search_path.display()); match fs::readdir(lib_search_path) { Ok(files) => { let mut rslt = FileDoesntMatch; fn is_rlib(p: & &Path) -> bool { p.extension_str() == Some("rlib") } // Reading metadata out of rlibs is faster, and if we find both // an rlib and a dylib we only read one of the files of // metadata, so in the name of speed, bring all rlib files to // the front of the search list. let files1 = files.iter().filter(|p| is_rlib(p)); let files2 = files.iter().filter(|p|!is_rlib(p)); for path in files1.chain(files2) { debug!("testing {}", path.display()); let maybe_picked = pick(path); match maybe_picked { FileMatches => { debug!("picked {}", path.display()); rslt = FileMatches; } FileDoesntMatch => { debug!("rejected {}", path.display()); } } } rslt } Err(..) => FileDoesntMatch, } }); } pub fn new(sysroot: &'a Path, triple: &'a str, addl_lib_search_paths: &'a RefCell<HashSet<Path>>) -> FileSearch<'a> { debug!("using sysroot = {}, triple = {}", sysroot.display(), triple); FileSearch { sysroot: sysroot, addl_lib_search_paths: addl_lib_search_paths, triple: triple, } } pub fn add_dylib_search_paths(&self) { self.for_each_lib_search_path(|lib_search_path| { DynamicLibrary::prepend_search_path(lib_search_path); FileDoesntMatch }) } } pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { let mut p = Path::new(find_libdir(sysroot)); assert!(p.is_relative()); p.push(rustlibdir()); p.push(target_triple); p.push("lib"); p } fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { sysroot.join(&relative_target_lib_path(sysroot, target_triple)) } fn make_rustpkg_lib_path(sysroot: &Path, dir: &Path, triple: &str) -> Path { let mut p = dir.join(find_libdir(sysroot)); p.push(triple); p } pub fn get_or_default_sysroot() -> Path { // Follow symlinks. If the resolved path is relative, make it absolute. fn canonicalize(path: Option<Path>) -> Option<Path> { path.and_then(|path| match myfs::realpath(&path) { Ok(canon) => Some(canon), Err(e) => fail!("failed to get realpath: {}", e), }) } match canonicalize(os::self_exe_name()) { Some(mut p) => { p.pop(); p.pop(); p } None => fail!("can't determine value for sysroot") } } #[cfg(windows)] static PATH_ENTRY_SEPARATOR: &'static str = ";"; #[cfg(not(windows))] static PATH_ENTRY_SEPARATOR: &'static str = ":"; /// Returns RUST_PATH as a string, without default paths added pub fn get_rust_path() -> Option<String> { os::getenv("RUST_PATH").map(|x| x.to_string()) } /// Returns the value of RUST_PATH, as a list /// of Paths. Includes default entries for, if they exist: /// $HOME/.rust /// DIR/.rust for any DIR that's the current working directory /// or an ancestor of it pub fn rust_path() -> Vec<Path> { let mut env_rust_path: Vec<Path> = match get_rust_path() { Some(env_path) => { let env_path_components = env_path.as_slice().split_str(PATH_ENTRY_SEPARATOR); env_path_components.map(|s| Path::new(s)).collect() } None => Vec::new() }; let mut cwd = os::getcwd(); // now add in default entries let cwd_dot_rust = cwd.join(".rust"); if!env_rust_path.contains(&cwd_dot_rust) { env_rust_path.push(cwd_dot_rust); } if!env_rust_path.contains(&cwd) { env_rust_path.push(cwd.clone()); } loop { if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } { break } cwd.set_filename(".rust"); if!env_rust_path.contains(&cwd) && cwd.exists() { env_rust_path.push(cwd.clone()); } cwd.pop(); } let h = os::homedir(); for h in h.iter() { let p = h.join(".rust"); if!env_rust_path.contains(&p) && p.exists() { env_rust_path.push(p); } } env_rust_path } // The name of the directory rustc expects libraries to be located. // On Unix should be "lib", on windows "bin" #[cfg(unix)] fn find_libdir(sysroot: &Path) -> String { // FIXME: This is a quick hack to make the rustc binary able to locate // Rust libraries in Linux environments where libraries might be installed // to lib64/lib32. This would be more foolproof by basing the sysroot off // of the directory where librustc is located, rather than where the rustc // binary is. if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() { return primary_libdir_name(); } else { return secondary_libdir_name(); } #[cfg(target_word_size = "64")] fn primary_libdir_name() -> String { "lib64".to_string() } #[cfg(target_word_size = "32")] fn primary_libdir_name() -> String { "lib32".to_string() } fn secondary_libdir_name() -> String { "lib".to_string() } } #[cfg(windows)] fn find_libdir(_sysroot: &Path) -> String { "bin".to_string() } // The name of rustc's own place to organize libraries. // Used to be "rustc", now the default is "rustlib" pub fn rustlibdir() -> String { "rustlib".to_string() }
{ let mut visited_dirs = HashSet::new(); let mut found = false; debug!("filesearch: searching additional lib search paths [{:?}]", self.addl_lib_search_paths.borrow().len()); for path in self.addl_lib_search_paths.borrow().iter() { match f(path) { FileMatches => found = true, FileDoesntMatch => () } visited_dirs.insert(path.as_vec().to_owned()); } debug!("filesearch: searching lib path"); let tlib_path = make_target_lib_path(self.sysroot, self.triple); if !visited_dirs.contains_equiv(&tlib_path.as_vec()) { match f(&tlib_path) { FileMatches => found = true,
identifier_body
filesearch.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. #![allow(non_camel_case_types)] use std::cell::RefCell; use std::os; use std::io::fs; use std::dynamic_lib::DynamicLibrary; use std::collections::HashSet; use myfs = util::fs; pub enum FileMatch { FileMatches, FileDoesntMatch } // A module for searching for libraries // FIXME (#2658): I'm not happy how this module turned out. Should // probably just be folded into cstore. /// Functions with type `pick` take a parent directory as well as /// a file found in that directory. pub type pick<'a> = |path: &Path|: 'a -> FileMatch; pub struct FileSearch<'a> { pub sysroot: &'a Path, pub addl_lib_search_paths: &'a RefCell<HashSet<Path>>, pub triple: &'a str, } impl<'a> FileSearch<'a> { pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) { let mut visited_dirs = HashSet::new(); let mut found = false; debug!("filesearch: searching additional lib search paths [{:?}]", self.addl_lib_search_paths.borrow().len()); for path in self.addl_lib_search_paths.borrow().iter() { match f(path) { FileMatches => found = true, FileDoesntMatch => () } visited_dirs.insert(path.as_vec().to_owned()); } debug!("filesearch: searching lib path"); let tlib_path = make_target_lib_path(self.sysroot, self.triple); if!visited_dirs.contains_equiv(&tlib_path.as_vec()) { match f(&tlib_path) { FileMatches => found = true, FileDoesntMatch => () } } visited_dirs.insert(tlib_path.as_vec().to_owned()); // Try RUST_PATH if!found { let rustpath = rust_path(); for path in rustpath.iter() { let tlib_path = make_rustpkg_lib_path( self.sysroot, path, self.triple); debug!("is {} in visited_dirs? {:?}", tlib_path.display(), visited_dirs.contains_equiv(&tlib_path.as_vec().to_owned())); if!visited_dirs.contains_equiv(&tlib_path.as_vec()) { visited_dirs.insert(tlib_path.as_vec().to_owned()); // Don't keep searching the RUST_PATH if one match turns up -- // if we did, we'd get a "multiple matching crates" error match f(&tlib_path) { FileMatches => { break; } FileDoesntMatch => () } } } } } pub fn get_lib_path(&self) -> Path { make_target_lib_path(self.sysroot, self.triple) } pub fn search(&self, pick: pick) { self.for_each_lib_search_path(|lib_search_path| { debug!("searching {}", lib_search_path.display()); match fs::readdir(lib_search_path) { Ok(files) => { let mut rslt = FileDoesntMatch; fn is_rlib(p: & &Path) -> bool { p.extension_str() == Some("rlib") } // Reading metadata out of rlibs is faster, and if we find both // an rlib and a dylib we only read one of the files of // metadata, so in the name of speed, bring all rlib files to // the front of the search list. let files1 = files.iter().filter(|p| is_rlib(p)); let files2 = files.iter().filter(|p|!is_rlib(p)); for path in files1.chain(files2) { debug!("testing {}", path.display()); let maybe_picked = pick(path); match maybe_picked { FileMatches => { debug!("picked {}", path.display()); rslt = FileMatches; } FileDoesntMatch => { debug!("rejected {}", path.display()); } } } rslt } Err(..) => FileDoesntMatch, } }); } pub fn new(sysroot: &'a Path, triple: &'a str, addl_lib_search_paths: &'a RefCell<HashSet<Path>>) -> FileSearch<'a> { debug!("using sysroot = {}, triple = {}", sysroot.display(), triple); FileSearch { sysroot: sysroot, addl_lib_search_paths: addl_lib_search_paths, triple: triple, } } pub fn add_dylib_search_paths(&self) { self.for_each_lib_search_path(|lib_search_path| { DynamicLibrary::prepend_search_path(lib_search_path); FileDoesntMatch }) } } pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { let mut p = Path::new(find_libdir(sysroot)); assert!(p.is_relative()); p.push(rustlibdir()); p.push(target_triple); p.push("lib"); p } fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { sysroot.join(&relative_target_lib_path(sysroot, target_triple)) } fn make_rustpkg_lib_path(sysroot: &Path, dir: &Path, triple: &str) -> Path { let mut p = dir.join(find_libdir(sysroot)); p.push(triple); p } pub fn get_or_default_sysroot() -> Path { // Follow symlinks. If the resolved path is relative, make it absolute. fn canonicalize(path: Option<Path>) -> Option<Path> { path.and_then(|path| match myfs::realpath(&path) { Ok(canon) => Some(canon), Err(e) => fail!("failed to get realpath: {}", e), }) }
Some(mut p) => { p.pop(); p.pop(); p } None => fail!("can't determine value for sysroot") } } #[cfg(windows)] static PATH_ENTRY_SEPARATOR: &'static str = ";"; #[cfg(not(windows))] static PATH_ENTRY_SEPARATOR: &'static str = ":"; /// Returns RUST_PATH as a string, without default paths added pub fn get_rust_path() -> Option<String> { os::getenv("RUST_PATH").map(|x| x.to_string()) } /// Returns the value of RUST_PATH, as a list /// of Paths. Includes default entries for, if they exist: /// $HOME/.rust /// DIR/.rust for any DIR that's the current working directory /// or an ancestor of it pub fn rust_path() -> Vec<Path> { let mut env_rust_path: Vec<Path> = match get_rust_path() { Some(env_path) => { let env_path_components = env_path.as_slice().split_str(PATH_ENTRY_SEPARATOR); env_path_components.map(|s| Path::new(s)).collect() } None => Vec::new() }; let mut cwd = os::getcwd(); // now add in default entries let cwd_dot_rust = cwd.join(".rust"); if!env_rust_path.contains(&cwd_dot_rust) { env_rust_path.push(cwd_dot_rust); } if!env_rust_path.contains(&cwd) { env_rust_path.push(cwd.clone()); } loop { if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } { break } cwd.set_filename(".rust"); if!env_rust_path.contains(&cwd) && cwd.exists() { env_rust_path.push(cwd.clone()); } cwd.pop(); } let h = os::homedir(); for h in h.iter() { let p = h.join(".rust"); if!env_rust_path.contains(&p) && p.exists() { env_rust_path.push(p); } } env_rust_path } // The name of the directory rustc expects libraries to be located. // On Unix should be "lib", on windows "bin" #[cfg(unix)] fn find_libdir(sysroot: &Path) -> String { // FIXME: This is a quick hack to make the rustc binary able to locate // Rust libraries in Linux environments where libraries might be installed // to lib64/lib32. This would be more foolproof by basing the sysroot off // of the directory where librustc is located, rather than where the rustc // binary is. if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() { return primary_libdir_name(); } else { return secondary_libdir_name(); } #[cfg(target_word_size = "64")] fn primary_libdir_name() -> String { "lib64".to_string() } #[cfg(target_word_size = "32")] fn primary_libdir_name() -> String { "lib32".to_string() } fn secondary_libdir_name() -> String { "lib".to_string() } } #[cfg(windows)] fn find_libdir(_sysroot: &Path) -> String { "bin".to_string() } // The name of rustc's own place to organize libraries. // Used to be "rustc", now the default is "rustlib" pub fn rustlibdir() -> String { "rustlib".to_string() }
match canonicalize(os::self_exe_name()) {
random_line_split
mod.rs
mod case; mod functions; mod parse; mod splitter; pub(crate) use self::{ parse::parse, splitter::{StatementError, StatementSplitter}, }; use shell::flow_control::Statement; /// Parses a given statement string and return's the corresponding mapped /// `Statement` pub(crate) fn parse_and_validate<'a>(statement: Result<String, StatementError>) -> Statement { match statement { Ok(statement) => parse(statement.as_str()), Err(err) => { eprintln!("ion: {}", err); Statement::Error(-1) } } } /// Splits a string into two, based on a given pattern. We know that the first string will always /// exist, but if the pattern is not found, or no string follows the pattern, then the second /// string will not exist. Useful for splitting the function expression by the "--" pattern. pub(crate) fn split_pattern<'a>(arg: &'a str, pattern: &str) -> (&'a str, Option<&'a str>) { match arg.find(pattern) { Some(pos) => { let args = &arg[..pos].trim(); let comment = &arg[pos + pattern.len()..].trim(); if comment.is_empty() { (args, None) } else { (args, Some(comment)) } } None => (arg, None), } } #[cfg(test)] mod tests { use super::*; #[test] fn statement_pattern_splitting()
}
{ let (args, description) = split_pattern("a:int b:bool -- a comment", "--"); assert_eq!(args, "a:int b:bool"); assert_eq!(description, Some("a comment")); let (args, description) = split_pattern("a --", "--"); assert_eq!(args, "a"); assert_eq!(description, None); let (args, description) = split_pattern("a", "--"); assert_eq!(args, "a"); assert_eq!(description, None); }
identifier_body
mod.rs
mod case; mod functions; mod parse; mod splitter; pub(crate) use self::{ parse::parse, splitter::{StatementError, StatementSplitter}, }; use shell::flow_control::Statement; /// Parses a given statement string and return's the corresponding mapped /// `Statement` pub(crate) fn parse_and_validate<'a>(statement: Result<String, StatementError>) -> Statement { match statement { Ok(statement) => parse(statement.as_str()), Err(err) => { eprintln!("ion: {}", err); Statement::Error(-1) } } } /// Splits a string into two, based on a given pattern. We know that the first string will always /// exist, but if the pattern is not found, or no string follows the pattern, then the second /// string will not exist. Useful for splitting the function expression by the "--" pattern. pub(crate) fn split_pattern<'a>(arg: &'a str, pattern: &str) -> (&'a str, Option<&'a str>) { match arg.find(pattern) { Some(pos) => { let args = &arg[..pos].trim(); let comment = &arg[pos + pattern.len()..].trim(); if comment.is_empty() { (args, None) } else { (args, Some(comment)) } } None => (arg, None), } } #[cfg(test)] mod tests { use super::*; #[test] fn
() { let (args, description) = split_pattern("a:int b:bool -- a comment", "--"); assert_eq!(args, "a:int b:bool"); assert_eq!(description, Some("a comment")); let (args, description) = split_pattern("a --", "--"); assert_eq!(args, "a"); assert_eq!(description, None); let (args, description) = split_pattern("a", "--"); assert_eq!(args, "a"); assert_eq!(description, None); } }
statement_pattern_splitting
identifier_name