hexsha
stringlengths 40
40
| size
int64 4
1.05M
| content
stringlengths 4
1.05M
| avg_line_length
float64 1.33
100
| max_line_length
int64 1
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
e872d13d36b0c772279291813d12e1ed593b8ef0
| 264 |
// variables5.rs
// Make me compile! Execute the command `rustlings hint variables5` if you want a hint :)
fn main() {
let number = "3"; // don't change this line
println!("Number {}", number);
let mut number = 3;
println!("Number {}", number);
}
| 26.4 | 89 | 0.621212 |
f9ba8e82ef7152b1bfb51f2080fe1456f88fdc1f
| 637 |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn view<T>(x: &[T]) -> &[T] {x}
pub fn main() {
let v = vec!(1, 2, 3);
let x = view(&v);
let y = view(x);
assert!((v[0] == x[0]) && (v[0] == y[0]));
}
| 30.333333 | 68 | 0.643642 |
62fe37c1b89900805569160440849e94b68ac527
| 3,813 |
use super::resource_id::{ResourceId};
use std::net::{SocketAddr};
/// Information to identify the remote endpoint.
/// The endpoint is used mainly as a connection identified.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Endpoint {
resource_id: ResourceId,
addr: SocketAddr,
}
impl Endpoint {
/// Creates a new Endpoint to use in non connection oriented protocols.
///
/// For non connection-oriented protocols, as *UDP*, the endpoint can be created manually
/// from a **listener resource** to send messages to different address without
/// creating a connection.
///
/// For connection oriented protocol, creating manually an endpoint is not allowed.
///
/// # Example
/// ```rust
/// use message_io::node::{self, NodeEvent};
/// use message_io::network::{Transport, Endpoint, NetEvent};
///
/// let (handler, listener) = node::split::<()>();
/// handler.signals().send_with_timer((), std::time::Duration::from_secs(1)); //timeout
///
/// let listen_addr = "127.0.0.1:0";
/// let (receiver_id_1, addr_1) = handler.network().listen(Transport::Udp, listen_addr).unwrap();
/// let (receiver_id_2, addr_2) = handler.network().listen(Transport::Udp, listen_addr).unwrap();
/// let (sender_id, _) = handler.network().listen(Transport::Udp, listen_addr).unwrap();
///
/// //addr_1 and addr_2 contain the addresses with the listening ports.
/// handler.network().send(Endpoint::from_listener(sender_id, addr_1), &[23]);
/// handler.network().send(Endpoint::from_listener(sender_id, addr_2), &[42]);
///
/// let (mut msg_1, mut msg_2) = (0, 0);
/// listener.for_each(|event| match event {
/// NodeEvent::Signal(_) => handler.stop(),
/// NodeEvent::Network(net_event) => match net_event {
/// NetEvent::Message(endpoint, message) => match endpoint.resource_id() {
/// id if id == receiver_id_1 => msg_1 = message[0],
/// id if id == receiver_id_2 => msg_2 = message[0],
/// _ => unreachable!(),
/// }
/// _ => unreachable!(),
/// }
/// });
///
/// assert_eq!((msg_1, msg_2), (23, 42));
/// ```
pub fn from_listener(id: ResourceId, addr: SocketAddr) -> Self {
// Only local resources allowed
assert_eq!(id.resource_type(), super::resource_id::ResourceType::Local);
// Only non connection-oriented transport protocols allowed
assert!(!super::transport::Transport::from(id.adapter_id()).is_connection_oriented());
Endpoint::new(id, addr)
}
pub(crate) fn new(resource_id: ResourceId, addr: SocketAddr) -> Self {
Self { resource_id, addr }
}
/// Returns the inner network resource id used by this endpoint.
/// It is not necessary to be unique for each endpoint if some of them shared the resource
/// (an example of this is the different endpoints generated by when you listen by udp).
pub fn resource_id(&self) -> ResourceId {
self.resource_id
}
/// Returns the peer address of the endpoint.
pub fn addr(&self) -> SocketAddr {
self.addr
}
}
impl std::fmt::Display for Endpoint {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} {}", self.resource_id, self.addr)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::network::resource_id::{ResourceType, ResourceIdGenerator};
use crate::network::transport::{Transport};
#[test]
fn from_local_non_connection_oriented() {
let addr = "0.0.0.0:0".parse().unwrap();
let generator = ResourceIdGenerator::new(Transport::Udp.id(), ResourceType::Local);
Endpoint::from_listener(generator.generate(), addr);
}
}
| 38.13 | 101 | 0.619722 |
6776cc5551ccb070e05fa3dfd4ac4080367c79d0
| 17,845 |
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of Open Ethereum.
// Open Ethereum 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.
// Open Ethereum 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 Open Ethereum. If not, see <http://www.gnu.org/licenses/>.
use std::io;
use std::io::{Write, BufReader, BufRead};
use std::time::Duration;
use std::fs::File;
use std::collections::HashSet;
use ethereum_types::{U256, Address};
use journaldb::Algorithm;
use ethcore::client::{DatabaseCompactionProfile, ClientConfig};
use ethcore::miner::{PendingSet, Penalization};
use verification::VerifierType;
use miner::pool::PrioritizationStrategy;
use cache::CacheConfig;
use dir::DatabaseDirectories;
use dir::helpers::replace_home;
use upgrade::{upgrade, upgrade_data_paths};
use sync::{validate_node_url, self};
use db::migrate;
use path;
use ethkey::Password;
use types::{
ids::BlockId,
client_types::Mode,
};
pub fn to_duration(s: &str) -> Result<Duration, String> {
to_seconds(s).map(Duration::from_secs)
}
// TODO: should we bring it back to ethereum-types?
fn clean_0x(s: &str) -> &str {
if s.starts_with("0x") {
&s[2..]
} else {
s
}
}
fn to_seconds(s: &str) -> Result<u64, String> {
let bad = |_| {
format!("{}: Invalid duration given. See parity --help for more information.", s)
};
match s {
"twice-daily" => Ok(12 * 60 * 60),
"half-hourly" => Ok(30 * 60),
"1second" | "1 second" | "second" => Ok(1),
"1minute" | "1 minute" | "minute" => Ok(60),
"hourly" | "1hour" | "1 hour" | "hour" => Ok(60 * 60),
"daily" | "1day" | "1 day" | "day" => Ok(24 * 60 * 60),
x if x.ends_with("seconds") => x[0..x.len() - 7].trim().parse().map_err(bad),
x if x.ends_with("minutes") => x[0..x.len() - 7].trim().parse::<u64>().map_err(bad).map(|x| x * 60),
x if x.ends_with("hours") => x[0..x.len() - 5].trim().parse::<u64>().map_err(bad).map(|x| x * 60 * 60),
x if x.ends_with("days") => x[0..x.len() - 4].trim().parse::<u64>().map_err(bad).map(|x| x * 24 * 60 * 60),
x => x.trim().parse().map_err(bad),
}
}
pub fn to_mode(s: &str, timeout: u64, alarm: u64) -> Result<Mode, String> {
match s {
"active" => Ok(Mode::Active),
"passive" => Ok(Mode::Passive(Duration::from_secs(timeout), Duration::from_secs(alarm))),
"dark" => Ok(Mode::Dark(Duration::from_secs(timeout))),
"offline" => Ok(Mode::Off),
_ => Err(format!("{}: Invalid value for --mode. Must be one of active, passive, dark or offline.", s)),
}
}
pub fn to_block_id(s: &str) -> Result<BlockId, String> {
if s == "latest" {
Ok(BlockId::Latest)
} else if let Ok(num) = s.parse() {
Ok(BlockId::Number(num))
} else if let Ok(hash) = s.parse() {
Ok(BlockId::Hash(hash))
} else {
Err("Invalid block.".into())
}
}
pub fn to_u256(s: &str) -> Result<U256, String> {
if let Ok(decimal) = U256::from_dec_str(s) {
Ok(decimal)
} else if let Ok(hex) = clean_0x(s).parse() {
Ok(hex)
} else {
Err(format!("Invalid numeric value: {}", s))
}
}
pub fn to_pending_set(s: &str) -> Result<PendingSet, String> {
match s {
"cheap" => Ok(PendingSet::AlwaysQueue),
"strict" => Ok(PendingSet::AlwaysSealing),
"lenient" => Ok(PendingSet::SealingOrElseQueue),
other => Err(format!("Invalid pending set value: {:?}", other)),
}
}
pub fn to_queue_strategy(s: &str) -> Result<PrioritizationStrategy, String> {
match s {
"gas_price" => Ok(PrioritizationStrategy::GasPriceOnly),
other => Err(format!("Invalid queue strategy: {}", other)),
}
}
pub fn to_queue_penalization(time: Option<u64>) -> Result<Penalization, String> {
Ok(match time {
Some(threshold_ms) => Penalization::Enabled {
offend_threshold: Duration::from_millis(threshold_ms),
},
None => Penalization::Disabled,
})
}
pub fn to_address(s: Option<String>) -> Result<Address, String> {
match s {
Some(ref a) => clean_0x(a).parse().map_err(|_| format!("Invalid address: {:?}", a)),
None => Ok(Address::zero())
}
}
pub fn to_addresses(s: &Option<String>) -> Result<Vec<Address>, String> {
match *s {
Some(ref adds) if !adds.is_empty() => adds.split(',')
.map(|a| clean_0x(a).parse().map_err(|_| format!("Invalid address: {:?}", a)))
.collect(),
_ => Ok(Vec::new()),
}
}
/// Tries to parse string as a price.
pub fn to_price(s: &str) -> Result<f32, String> {
s.parse::<f32>().map_err(|_| format!("Invalid transaction price {:?} given. Must be a decimal number.", s))
}
pub fn join_set(set: Option<&HashSet<String>>) -> Option<String> {
match set {
Some(s) => Some(s.iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(",")),
None => None
}
}
/// Flush output buffer.
pub fn flush_stdout() {
io::stdout().flush().expect("stdout is flushable; qed");
}
/// Returns default geth ipc path.
pub fn geth_ipc_path(testnet: bool) -> String {
// Windows path should not be hardcoded here.
// Instead it should be a part of path::ethereum
if cfg!(windows) {
return r"\\.\pipe\geth.ipc".to_owned();
}
if testnet {
path::ethereum::with_testnet("geth.ipc").to_str().unwrap().to_owned()
} else {
path::ethereum::with_default("geth.ipc").to_str().unwrap().to_owned()
}
}
/// Formats and returns parity ipc path.
pub fn parity_ipc_path(base: &str, path: &str, shift: u16) -> String {
let mut path = path.to_owned();
if shift != 0 {
path = path.replace("jsonrpc.ipc", &format!("jsonrpc-{}.ipc", shift));
}
replace_home(base, &path)
}
/// Validates and formats bootnodes option.
pub fn to_bootnodes(bootnodes: &Option<String>) -> Result<Vec<String>, String> {
match *bootnodes {
Some(ref x) if !x.is_empty() => x.split(',').map(|s| {
match validate_node_url(s).map(Into::into) {
None => Ok(s.to_owned()),
Some(sync::Error::AddressResolve(_)) => Err(format!("Failed to resolve hostname of a boot node: {}", s)),
Some(_) => Err(format!("Invalid node address format given for a boot node: {}", s)),
}
}).collect(),
Some(_) => Ok(vec![]),
None => Ok(vec![])
}
}
#[cfg(test)]
pub fn default_network_config() -> ::sync::NetworkConfiguration {
use network::NatType;
use sync::{NetworkConfiguration};
use super::network::IpFilter;
NetworkConfiguration {
config_path: Some(replace_home(&::dir::default_data_path(), "$BASE/network")),
net_config_path: None,
listen_address: Some("0.0.0.0:30303".into()),
public_address: None,
udp_port: None,
nat_enabled: true,
nat_type: NatType::Any,
discovery_enabled: true,
boot_nodes: Vec::new(),
use_secret: None,
max_peers: 50,
min_peers: 25,
snapshot_peers: 0,
max_pending_peers: 64,
ip_filter: IpFilter::default(),
reserved_nodes: Vec::new(),
allow_non_reserved: true,
client_version: ::parity_version::version(),
}
}
pub fn to_client_config(
cache_config: &CacheConfig,
spec_name: String,
mode: Mode,
tracing: bool,
fat_db: bool,
compaction: DatabaseCompactionProfile,
name: String,
pruning: Algorithm,
pruning_history: u64,
pruning_memory: usize,
check_seal: bool,
max_round_blocks_to_import: usize,
) -> ClientConfig {
let mut client_config = ClientConfig::default();
let mb = 1024 * 1024;
// in bytes
client_config.blockchain.max_cache_size = cache_config.blockchain() as usize * mb;
// in bytes
client_config.blockchain.pref_cache_size = cache_config.blockchain() as usize * 3 / 4 * mb;
// db cache size, in megabytes
client_config.db_cache_size = Some(cache_config.db_cache_size() as usize);
// db queue cache size, in bytes
client_config.queue.max_mem_use = cache_config.queue() as usize * mb;
// in bytes
client_config.tracing.max_cache_size = cache_config.traces() as usize * mb;
// in bytes
client_config.tracing.pref_cache_size = cache_config.traces() as usize * 3 / 4 * mb;
// in bytes
client_config.state_cache_size = cache_config.state() as usize * mb;
// in bytes
client_config.jump_table_size = cache_config.jump_tables() as usize * mb;
// in bytes
client_config.history_mem = pruning_memory * mb;
client_config.mode = mode;
client_config.tracing.enabled = tracing;
client_config.fat_db = fat_db;
client_config.pruning = pruning;
client_config.history = pruning_history;
client_config.db_compaction = compaction;
client_config.name = name;
client_config.verifier_type = if check_seal { VerifierType::Canon } else { VerifierType::CanonNoSeal };
client_config.spec_name = spec_name;
client_config.max_round_blocks_to_import = max_round_blocks_to_import;
client_config
}
pub fn execute_upgrades(
base_path: &str,
dirs: &DatabaseDirectories,
pruning: Algorithm,
compaction_profile: &DatabaseCompactionProfile
) -> Result<(), String> {
upgrade_data_paths(base_path, dirs, pruning);
match upgrade(&dirs.path) {
Ok(upgrades_applied) if upgrades_applied > 0 => {
debug!("Executed {} upgrade scripts - ok", upgrades_applied);
},
Err(e) => {
return Err(format!("Error upgrading parity data: {:?}", e));
},
_ => {},
}
let client_path = dirs.db_path(pruning);
migrate(&client_path, compaction_profile).map_err(|e| format!("{}", e))
}
/// Prompts user asking for password.
pub fn password_prompt() -> Result<Password, String> {
use rpassword::read_password;
const STDIN_ERROR: &'static str = "Unable to ask for password on non-interactive terminal.";
println!("Please note that password is NOT RECOVERABLE.");
print!("Type password: ");
flush_stdout();
let password = read_password().map_err(|_| STDIN_ERROR.to_owned())?.into();
print!("Repeat password: ");
flush_stdout();
let password_repeat = read_password().map_err(|_| STDIN_ERROR.to_owned())?.into();
if password != password_repeat {
return Err("Passwords do not match!".into());
}
Ok(password)
}
/// Read a password from password file.
pub fn password_from_file(path: String) -> Result<Password, String> {
let passwords = passwords_from_files(&[path])?;
// use only first password from the file
passwords.get(0).map(Password::clone)
.ok_or_else(|| "Password file seems to be empty.".to_owned())
}
/// Reads passwords from files. Treats each line as a separate password.
pub fn passwords_from_files(files: &[String]) -> Result<Vec<Password>, String> {
let passwords = files.iter().map(|filename| {
let file = File::open(filename).map_err(|_| format!("{} Unable to read password file. Ensure it exists and permissions are correct.", filename))?;
let reader = BufReader::new(&file);
let lines = reader.lines()
.filter_map(|l| l.ok())
.map(|pwd| pwd.trim().to_owned().into())
.collect::<Vec<Password>>();
Ok(lines)
}).collect::<Result<Vec<Vec<Password>>, String>>();
Ok(passwords?.into_iter().flat_map(|x| x).collect())
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use std::fs::File;
use std::io::Write;
use std::collections::HashSet;
use tempfile::TempDir;
use ethereum_types::U256;
use ethcore::miner::PendingSet;
use ethkey::Password;
use types::{
ids::BlockId,
client_types::Mode,
};
use super::{to_duration, to_mode, to_block_id, to_u256, to_pending_set, to_address, to_addresses, to_price, geth_ipc_path, to_bootnodes, join_set, password_from_file};
#[test]
fn test_to_duration() {
assert_eq!(to_duration("twice-daily").unwrap(), Duration::from_secs(12 * 60 * 60));
assert_eq!(to_duration("half-hourly").unwrap(), Duration::from_secs(30 * 60));
assert_eq!(to_duration("1second").unwrap(), Duration::from_secs(1));
assert_eq!(to_duration("2seconds").unwrap(), Duration::from_secs(2));
assert_eq!(to_duration("15seconds").unwrap(), Duration::from_secs(15));
assert_eq!(to_duration("1minute").unwrap(), Duration::from_secs(1 * 60));
assert_eq!(to_duration("2minutes").unwrap(), Duration::from_secs(2 * 60));
assert_eq!(to_duration("15minutes").unwrap(), Duration::from_secs(15 * 60));
assert_eq!(to_duration("hourly").unwrap(), Duration::from_secs(60 * 60));
assert_eq!(to_duration("daily").unwrap(), Duration::from_secs(24 * 60 * 60));
assert_eq!(to_duration("1hour").unwrap(), Duration::from_secs(1 * 60 * 60));
assert_eq!(to_duration("2hours").unwrap(), Duration::from_secs(2 * 60 * 60));
assert_eq!(to_duration("15hours").unwrap(), Duration::from_secs(15 * 60 * 60));
assert_eq!(to_duration("1day").unwrap(), Duration::from_secs(1 * 24 * 60 * 60));
assert_eq!(to_duration("2days").unwrap(), Duration::from_secs(2 * 24 *60 * 60));
assert_eq!(to_duration("15days").unwrap(), Duration::from_secs(15 * 24 * 60 * 60));
assert_eq!(to_duration("15 days").unwrap(), Duration::from_secs(15 * 24 * 60 * 60));
assert_eq!(to_duration("2 seconds").unwrap(), Duration::from_secs(2));
}
#[test]
fn test_to_mode() {
assert_eq!(to_mode("active", 0, 0).unwrap(), Mode::Active);
assert_eq!(to_mode("passive", 10, 20).unwrap(), Mode::Passive(Duration::from_secs(10), Duration::from_secs(20)));
assert_eq!(to_mode("dark", 20, 30).unwrap(), Mode::Dark(Duration::from_secs(20)));
assert!(to_mode("other", 20, 30).is_err());
}
#[test]
fn test_to_block_id() {
assert_eq!(to_block_id("latest").unwrap(), BlockId::Latest);
assert_eq!(to_block_id("0").unwrap(), BlockId::Number(0));
assert_eq!(to_block_id("2").unwrap(), BlockId::Number(2));
assert_eq!(to_block_id("15").unwrap(), BlockId::Number(15));
assert_eq!(
to_block_id("9fc84d84f6a785dc1bd5abacfcf9cbdd3b6afb80c0f799bfb2fd42c44a0c224e").unwrap(),
BlockId::Hash("9fc84d84f6a785dc1bd5abacfcf9cbdd3b6afb80c0f799bfb2fd42c44a0c224e".parse().unwrap())
);
}
#[test]
fn test_to_u256() {
assert_eq!(to_u256("0").unwrap(), U256::from(0));
assert_eq!(to_u256("11").unwrap(), U256::from(11));
assert_eq!(to_u256("0x11").unwrap(), U256::from(17));
assert!(to_u256("u").is_err())
}
#[test]
fn test_pending_set() {
assert_eq!(to_pending_set("cheap").unwrap(), PendingSet::AlwaysQueue);
assert_eq!(to_pending_set("strict").unwrap(), PendingSet::AlwaysSealing);
assert_eq!(to_pending_set("lenient").unwrap(), PendingSet::SealingOrElseQueue);
assert!(to_pending_set("othe").is_err());
}
#[test]
fn test_to_address() {
assert_eq!(
to_address(Some("0xD9A111feda3f362f55Ef1744347CDC8Dd9964a41".into())).unwrap(),
"D9A111feda3f362f55Ef1744347CDC8Dd9964a41".parse().unwrap()
);
assert_eq!(
to_address(Some("D9A111feda3f362f55Ef1744347CDC8Dd9964a41".into())).unwrap(),
"D9A111feda3f362f55Ef1744347CDC8Dd9964a41".parse().unwrap()
);
assert_eq!(to_address(None).unwrap(), Default::default());
}
#[test]
fn test_to_addresses() {
let addresses = to_addresses(&Some("0xD9A111feda3f362f55Ef1744347CDC8Dd9964a41,D9A111feda3f362f55Ef1744347CDC8Dd9964a42".into())).unwrap();
assert_eq!(
addresses,
vec![
"D9A111feda3f362f55Ef1744347CDC8Dd9964a41".parse().unwrap(),
"D9A111feda3f362f55Ef1744347CDC8Dd9964a42".parse().unwrap(),
]
);
}
#[test]
fn test_password() {
let tempdir = TempDir::new().unwrap();
let path = tempdir.path().join("file");
let mut file = File::create(&path).unwrap();
file.write_all(b"a bc ").unwrap();
assert_eq!(password_from_file(path.to_str().unwrap().into()).unwrap().as_bytes(), b"a bc");
}
#[test]
fn test_password_multiline() {
let tempdir = TempDir::new().unwrap();
let path = tempdir.path().join("file");
let mut file = File::create(path.as_path()).unwrap();
file.write_all(br#" password with trailing whitespace
those passwords should be
ignored
but the first password is trimmed
"#).unwrap();
assert_eq!(password_from_file(path.to_str().unwrap().into()).unwrap(), Password::from("password with trailing whitespace"));
}
#[test]
fn test_to_price() {
assert_eq!(to_price("1").unwrap(), 1.0);
assert_eq!(to_price("2.3").unwrap(), 2.3);
assert_eq!(to_price("2.33").unwrap(), 2.33);
}
#[test]
#[cfg(windows)]
fn test_geth_ipc_path() {
assert_eq!(geth_ipc_path(true), r"\\.\pipe\geth.ipc".to_owned());
assert_eq!(geth_ipc_path(false), r"\\.\pipe\geth.ipc".to_owned());
}
#[test]
#[cfg(not(windows))]
fn test_geth_ipc_path() {
use path;
assert_eq!(geth_ipc_path(true), path::ethereum::with_testnet("geth.ipc").to_str().unwrap().to_owned());
assert_eq!(geth_ipc_path(false), path::ethereum::with_default("geth.ipc").to_str().unwrap().to_owned());
}
#[test]
fn test_to_bootnodes() {
let one_bootnode = "enode://e731347db0521f3476e6bbbb83375dcd7133a1601425ebd15fd10f3835fd4c304fba6282087ca5a0deeafadf0aa0d4fd56c3323331901c1f38bd181c283e3e35@128.199.55.137:30303";
let two_bootnodes = "enode://e731347db0521f3476e6bbbb83375dcd7133a1601425ebd15fd10f3835fd4c304fba6282087ca5a0deeafadf0aa0d4fd56c3323331901c1f38bd181c283e3e35@128.199.55.137:30303,enode://e731347db0521f3476e6bbbb83375dcd7133a1601425ebd15fd10f3835fd4c304fba6282087ca5a0deeafadf0aa0d4fd56c3323331901c1f38bd181c283e3e35@128.199.55.137:30303";
assert_eq!(to_bootnodes(&Some("".into())), Ok(vec![]));
assert_eq!(to_bootnodes(&None), Ok(vec![]));
assert_eq!(to_bootnodes(&Some(one_bootnode.into())), Ok(vec![one_bootnode.into()]));
assert_eq!(to_bootnodes(&Some(two_bootnodes.into())), Ok(vec![one_bootnode.into(), one_bootnode.into()]));
}
#[test]
fn test_join_set() {
let mut test_set = HashSet::new();
test_set.insert("0x1111111111111111111111111111111111111111".to_string());
test_set.insert("0x0000000000000000000000000000000000000000".to_string());
let res = join_set(Some(&test_set)).unwrap();
assert!(
res == "0x1111111111111111111111111111111111111111,0x0000000000000000000000000000000000000000"
||
res == "0x0000000000000000000000000000000000000000,0x1111111111111111111111111111111111111111"
);
}
}
| 34.449807 | 340 | 0.693584 |
d712c5041267a09fdc3437d7d020e4350c101012
| 5,868 |
#![allow(dead_code)]
//! Utilities for LSP-related boilerplate code.
use std::{error::Error, ops::Range};
use lsp_server::Notification;
use crate::{from_proto, global_state::GlobalState, LspError};
use base_db::line_index::LineIndex;
pub(crate) fn is_cancelled(e: &(dyn Error + 'static)) -> bool {
e.downcast_ref::<salsa::Cancelled>().is_some()
}
pub(crate) fn invalid_params_error(message: String) -> LspError {
LspError {
code: lsp_server::ErrorCode::InvalidParams as i32,
message,
}
}
pub(crate) fn notification_is<N: lsp_types::notification::Notification>(
notification: &Notification,
) -> bool {
notification.method == N::METHOD
}
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum Progress {
Begin,
Report,
End,
}
impl Progress {
pub(crate) fn fraction(done: usize, total: usize) -> f64 {
assert!(done <= total);
done as f64 / total.max(1) as f64
}
}
impl GlobalState {
pub(crate) fn show_message(&mut self, typ: lsp_types::MessageType, message: String) {
let message = message;
self.send_notification::<lsp_types::notification::ShowMessage>(
lsp_types::ShowMessageParams { typ, message },
)
}
pub(crate) fn report_progress(
&mut self,
title: &str,
state: Progress,
message: Option<String>,
fraction: Option<f64>,
) {
/*if !self.config.work_done_progress() {
return;
}*/
let percentage = fraction.map(|f| {
assert!(0.0 <= f && f <= 1.0);
(f * 100.0) as u32
});
let token = lsp_types::ProgressToken::String(format!("rustAnalyzer/{}", title));
let work_done_progress = match state {
Progress::Begin => {
self.send_request::<lsp_types::request::WorkDoneProgressCreate>(
lsp_types::WorkDoneProgressCreateParams {
token: token.clone(),
},
|_, _| (),
);
lsp_types::WorkDoneProgress::Begin(lsp_types::WorkDoneProgressBegin {
title: title.into(),
cancellable: None,
message,
percentage,
})
}
Progress::Report => {
lsp_types::WorkDoneProgress::Report(lsp_types::WorkDoneProgressReport {
cancellable: None,
message,
percentage,
})
}
Progress::End => {
lsp_types::WorkDoneProgress::End(lsp_types::WorkDoneProgressEnd { message })
}
};
self.send_notification::<lsp_types::notification::Progress>(lsp_types::ProgressParams {
token,
value: lsp_types::ProgressParamsValue::WorkDone(work_done_progress),
});
}
}
pub(crate) fn apply_document_changes(
old_text: &mut String,
content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>,
) {
let mut line_index = LineIndex::new(old_text);
// The changes we got must be applied sequentially, but can cross lines so we
// have to keep our line index updated.
// Some clients (e.g. Code) sort the ranges in reverse. As an optimization, we
// remember the last valid line in the index and only rebuild it if needed.
// The VFS will normalize the end of lines to `\n`.
enum IndexValid {
All,
UpToLineExclusive(u32),
}
impl IndexValid {
fn covers(&self, line: u32) -> bool {
match *self {
IndexValid::UpToLineExclusive(to) => to > line,
_ => true,
}
}
}
let mut index_valid = IndexValid::All;
for change in content_changes {
match change.range {
Some(range) => {
if !index_valid.covers(range.end.line) {
line_index = LineIndex::new(old_text);
}
index_valid = IndexValid::UpToLineExclusive(range.start.line);
let range = from_proto::text_range(&line_index, range);
old_text.replace_range(Range::<usize>::from(range), &change.text);
}
None => {
*old_text = change.text;
index_valid = IndexValid::UpToLineExclusive(0);
}
}
}
}
/// Checks that the edits inside the completion and the additional edits do not overlap.
/// LSP explicitly forbids the additional edits to overlap both with the main edit and themselves.
pub(crate) fn all_edits_are_disjoint(
completion: &lsp_types::CompletionItem,
additional_edits: &[lsp_types::TextEdit],
) -> bool {
let mut edit_ranges = Vec::new();
match completion.text_edit.as_ref() {
Some(lsp_types::CompletionTextEdit::Edit(edit)) => {
edit_ranges.push(edit.range);
}
Some(lsp_types::CompletionTextEdit::InsertAndReplace(edit)) => {
let replace = edit.replace;
let insert = edit.insert;
if replace.start != insert.start
|| insert.start > insert.end
|| insert.end > replace.end
{
// insert has to be a prefix of replace but it is not
return false;
}
edit_ranges.push(replace);
}
None => {}
}
if let Some(additional_changes) = completion.additional_text_edits.as_ref() {
edit_ranges.extend(additional_changes.iter().map(|edit| edit.range));
};
edit_ranges.extend(additional_edits.iter().map(|edit| edit.range));
edit_ranges.sort_by_key(|range| (range.start, range.end));
edit_ranges
.iter()
.zip(edit_ranges.iter().skip(1))
.all(|(previous, next)| previous.end <= next.start)
}
| 33.152542 | 98 | 0.571234 |
f472be2292a5c28a1606ffc603ea5f7ddf19694b
| 2,494 |
// Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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.
#![feature(test)]
extern crate rand;
extern crate test;
extern crate cgmath;
use rand::{IsaacRng, Rng};
use std::ops::*;
use test::Bencher;
use cgmath::*;
#[path="common/macros.rs"]
#[macro_use] mod macros;
bench_binop!(_bench_matrix2_mul_m, Matrix2<f32>, Matrix2<f32>, mul);
bench_binop!(_bench_matrix3_mul_m, Matrix3<f32>, Matrix3<f32>, mul);
bench_binop!(_bench_matrix4_mul_m, Matrix4<f32>, Matrix4<f32>, mul);
bench_binop!(_bench_matrix2_add_m, Matrix2<f32>, Matrix2<f32>, add);
bench_binop!(_bench_matrix3_add_m, Matrix3<f32>, Matrix3<f32>, add);
bench_binop!(_bench_matrix4_add_m, Matrix4<f32>, Matrix4<f32>, add);
bench_binop!(_bench_matrix2_sub_m, Matrix2<f32>, Matrix2<f32>, sub);
bench_binop!(_bench_matrix3_sub_m, Matrix3<f32>, Matrix3<f32>, sub);
bench_binop!(_bench_matrix4_sub_m, Matrix4<f32>, Matrix4<f32>, sub);
bench_binop!(_bench_matrix2_mul_v, Matrix2<f32>, Vector2<f32>, mul);
bench_binop!(_bench_matrix3_mul_v, Matrix3<f32>, Vector3<f32>, mul);
bench_binop!(_bench_matrix4_mul_v, Matrix4<f32>, Vector4<f32>, mul);
bench_binop!(_bench_matrix2_mul_s, Matrix2<f32>, f32, mul);
bench_binop!(_bench_matrix3_mul_s, Matrix3<f32>, f32, mul);
bench_binop!(_bench_matrix4_mul_s, Matrix4<f32>, f32, mul);
bench_binop!(_bench_matrix2_div_s, Matrix2<f32>, f32, div);
bench_binop!(_bench_matrix3_div_s, Matrix3<f32>, f32, div);
bench_binop!(_bench_matrix4_div_s, Matrix4<f32>, f32, div);
bench_unop!(_bench_matrix2_invert, Matrix2<f32>, invert);
bench_unop!(_bench_matrix3_invert, Matrix3<f32>, invert);
bench_unop!(_bench_matrix4_invert, Matrix4<f32>, invert);
bench_unop!(_bench_matrix2_transpose, Matrix2<f32>, transpose);
bench_unop!(_bench_matrix3_transpose, Matrix3<f32>, transpose);
bench_unop!(_bench_matrix4_transpose, Matrix4<f32>, transpose);
| 40.225806 | 80 | 0.768244 |
03a3a2291450582713855899058acde5c683e295
| 10,092 |
//! Area is a `Ui` that has no parent, it floats on the background.
//! It has no frame or own size. It is potentially movable.
//! It is the foundation for windows and popups.
use std::{fmt::Debug, hash::Hash};
use crate::*;
/// State that is persisted between frames
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
pub(crate) struct State {
/// Last known pos
pub pos: Pos2,
/// Last know size. Used for catching clicks.
pub size: Vec2,
/// If false, clicks goes straight through to what is behind us.
/// Good for tooltips etc.
pub interactable: bool,
}
impl State {
pub fn rect(&self) -> Rect {
Rect::from_min_size(self.pos, self.size)
}
}
/// An area on the screen that can be moved by dragging.
///
/// This forms the base of the [`Window`] container.
///
/// ```
/// # let mut ctx = egui::CtxRef::default();
/// # ctx.begin_frame(Default::default());
/// # let ctx = &ctx;
/// egui::Area::new("my_area")
/// .fixed_pos(egui::pos2(32.0, 32.0))
/// .show(ctx, |ui| {
/// ui.label("Floating text!");
/// });
#[derive(Clone, Copy, Debug)]
pub struct Area {
pub(crate) id: Id,
movable: bool,
interactable: bool,
order: Order,
default_pos: Option<Pos2>,
new_pos: Option<Pos2>,
}
impl Area {
pub fn new(id_source: impl Hash) -> Self {
Self {
id: Id::new(id_source),
movable: true,
interactable: true,
order: Order::Middle,
default_pos: None,
new_pos: None,
}
}
pub fn id(mut self, id: Id) -> Self {
self.id = id;
self
}
pub fn layer(&self) -> LayerId {
LayerId::new(self.order, self.id)
}
/// moveable by dragging the area?
pub fn movable(mut self, movable: bool) -> Self {
self.movable = movable;
self.interactable |= movable;
self
}
pub fn is_movable(&self) -> bool {
self.movable
}
/// If false, clicks goes straight through to what is behind us.
/// Good for tooltips etc.
pub fn interactable(mut self, interactable: bool) -> Self {
self.interactable = interactable;
self.movable &= interactable;
self
}
/// `order(Order::Foreground)` for an Area that should always be on top
pub fn order(mut self, order: Order) -> Self {
self.order = order;
self
}
pub fn default_pos(mut self, default_pos: impl Into<Pos2>) -> Self {
self.default_pos = Some(default_pos.into());
self
}
/// Positions the window and prevents it from being moved
pub fn fixed_pos(mut self, fixed_pos: impl Into<Pos2>) -> Self {
let fixed_pos = fixed_pos.into();
self.new_pos = Some(fixed_pos);
self.movable = false;
self
}
/// Positions the window but you can still move it.
pub fn current_pos(mut self, current_pos: impl Into<Pos2>) -> Self {
let current_pos = current_pos.into();
self.new_pos = Some(current_pos);
self
}
}
pub(crate) struct Prepared {
layer_id: LayerId,
state: State,
movable: bool,
}
impl Area {
pub(crate) fn begin(self, ctx: &CtxRef) -> Prepared {
let Area {
id,
movable,
order,
interactable,
default_pos,
new_pos,
} = self;
let layer_id = LayerId::new(order, id);
let state = ctx.memory().areas.get(id).cloned();
let mut state = state.unwrap_or_else(|| State {
pos: default_pos.unwrap_or_else(|| automatic_area_position(ctx)),
size: Vec2::zero(),
interactable,
});
state.pos = new_pos.unwrap_or(state.pos);
state.pos = ctx.round_pos_to_pixels(state.pos);
Prepared {
layer_id,
state,
movable,
}
}
pub fn show(self, ctx: &CtxRef, add_contents: impl FnOnce(&mut Ui)) -> Response {
let prepared = self.begin(ctx);
let mut content_ui = prepared.content_ui(ctx);
add_contents(&mut content_ui);
prepared.end(ctx, content_ui)
}
pub fn show_open_close_animation(&self, ctx: &CtxRef, frame: &Frame, is_open: bool) {
// must be called first so animation managers know the latest state
let visibility_factor = ctx.animate_bool(self.id.with("close_animation"), is_open);
if is_open {
// we actually only show close animations.
// when opening a window we show it right away.
return;
}
if visibility_factor <= 0.0 {
return;
}
let layer_id = LayerId::new(self.order, self.id);
let area_rect = ctx.memory().areas.get(self.id).map(|area| area.rect());
if let Some(area_rect) = area_rect {
let clip_rect = ctx.available_rect();
let painter = Painter::new(ctx.clone(), layer_id, clip_rect);
// shrinkage: looks kinda a bad on its own
// let area_rect =
// Rect::from_center_size(area_rect.center(), visibility_factor * area_rect.size());
let frame = frame.multiply_with_opacity(visibility_factor);
painter.add(frame.paint(area_rect));
}
}
}
impl Prepared {
pub(crate) fn state(&self) -> &State {
&self.state
}
pub(crate) fn state_mut(&mut self) -> &mut State {
&mut self.state
}
pub(crate) fn content_ui(&self, ctx: &CtxRef) -> Ui {
let max_rect = Rect::from_min_size(self.state.pos, Vec2::infinity());
let shadow_radius = ctx.style().visuals.window_shadow.extrusion; // hacky
let mut clip_rect = max_rect
.expand(ctx.style().visuals.clip_rect_margin)
.expand(shadow_radius)
.intersect(ctx.input().screen_rect);
// Windows are constrained to central area,
// (except in rare cases where they don't fit).
// Adjust clip rect so we don't cast shadows on side panels:
let central_area = ctx.available_rect();
let is_within_central_area = central_area.contains(self.state.pos);
if is_within_central_area {
clip_rect = clip_rect.intersect(central_area);
}
Ui::new(
ctx.clone(),
self.layer_id,
self.layer_id.id,
max_rect,
clip_rect,
)
}
#[allow(clippy::needless_pass_by_value)] // intentional to swallow up `content_ui`.
pub(crate) fn end(self, ctx: &CtxRef, content_ui: Ui) -> Response {
let Prepared {
layer_id,
mut state,
movable,
} = self;
state.size = content_ui.min_rect().size();
let interact_id = layer_id.id.with("move");
let sense = if movable {
Sense::click_and_drag()
} else {
Sense::click() // allow clicks to bring to front
};
let move_response = ctx.interact(
Rect::everything(),
ctx.style().spacing.item_spacing,
layer_id,
interact_id,
state.rect(),
sense,
);
if move_response.active && movable {
state.pos += ctx.input().mouse.delta;
}
state.pos = ctx.constrain_window_rect(state.rect()).min;
if (move_response.active || move_response.clicked)
|| mouse_pressed_on_area(ctx, layer_id)
|| !ctx.memory().areas.visible_last_frame(&layer_id)
{
ctx.memory().areas.move_to_top(layer_id);
ctx.request_repaint();
}
ctx.memory().areas.set_state(layer_id, state);
move_response
}
}
fn mouse_pressed_on_area(ctx: &Context, layer_id: LayerId) -> bool {
if let Some(mouse_pos) = ctx.input().mouse.pos {
ctx.input().mouse.pressed && ctx.layer_id_at(mouse_pos) == Some(layer_id)
} else {
false
}
}
fn automatic_area_position(ctx: &Context) -> Pos2 {
let mut existing: Vec<Rect> = ctx
.memory()
.areas
.visible_windows()
.into_iter()
.map(State::rect)
.collect();
existing.sort_by_key(|r| r.left().round() as i32);
let available_rect = ctx.available_rect();
let spacing = 16.0;
let left = available_rect.left() + spacing;
let top = available_rect.top() + spacing;
if existing.is_empty() {
return pos2(left, top);
}
// Separate existing rectangles into columns:
let mut column_bbs = vec![existing[0]];
for &rect in &existing {
let current_column_bb = column_bbs.last_mut().unwrap();
if rect.left() < current_column_bb.right() {
// same column
*current_column_bb = current_column_bb.union(rect);
} else {
// new column
column_bbs.push(rect);
}
}
{
// Look for large spaces between columns (empty columns):
let mut x = left;
for col_bb in &column_bbs {
let available = col_bb.left() - x;
if available >= 300.0 {
return pos2(x, top);
}
x = col_bb.right() + spacing;
}
}
// Find first column with some available space at the bottom of it:
for col_bb in &column_bbs {
if col_bb.bottom() < available_rect.center().y {
return pos2(col_bb.left(), col_bb.bottom() + spacing);
}
}
// Maybe we can fit a new column?
let rightmost = column_bbs.last().unwrap().right();
if rightmost + 200.0 < available_rect.right() {
return pos2(rightmost + spacing, top);
}
// Ok, just put us in the column with the most space at the bottom:
let mut best_pos = pos2(left, column_bbs[0].bottom() + spacing);
for col_bb in &column_bbs {
let col_pos = pos2(col_bb.left(), col_bb.bottom() + spacing);
if col_pos.y < best_pos.y {
best_pos = col_pos;
}
}
best_pos
}
| 29 | 100 | 0.571344 |
293772d76609a712053ba0894cbae404d0429f21
| 2,934 |
use core;
use std::error::Error;
use std::ffi::CStr;
use std::io;
use std::str;
use libc::{c_int, c_char, size_t};
pub fn last_os_error() -> core::Error {
from_raw_os_error(errno())
}
pub fn from_raw_os_error(errno: i32) -> core::Error {
use libc::{EBUSY, EISDIR, ELOOP, ENOTDIR, ENOENT, ENODEV, ENXIO, EACCES, EINVAL, ENAMETOOLONG, EINTR, EWOULDBLOCK};
let kind = match errno {
EBUSY | EISDIR | ELOOP | ENOTDIR | ENOENT | ENODEV | ENXIO | EACCES => core::ErrorKind::NoDevice,
EINVAL | ENAMETOOLONG => core::ErrorKind::InvalidInput,
EINTR => core::ErrorKind::Io(io::ErrorKind::Interrupted),
EWOULDBLOCK => core::ErrorKind::Io(io::ErrorKind::WouldBlock),
_ => core::ErrorKind::Io(io::ErrorKind::Other),
};
core::Error::new(kind, error_string(errno))
}
pub fn from_io_error(io_error: io::Error) -> core::Error {
match io_error.raw_os_error() {
Some(errno) => from_raw_os_error(errno),
None => {
let description = io_error.description().to_string();
core::Error::new(core::ErrorKind::Io(io_error.kind()), description)
}
}
}
// the rest of this module is borrowed from libstd
const TMPBUF_SZ: usize = 128;
pub fn errno() -> i32 {
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __error() -> *const c_int; }
__error()
}
#[cfg(target_os = "bitrig")]
fn errno_location() -> *const c_int {
extern {
fn __errno() -> *const c_int;
}
unsafe {
__errno()
}
}
#[cfg(target_os = "dragonfly")]
unsafe fn errno_location() -> *const c_int {
extern { fn __dfly_error() -> *const c_int; }
__dfly_error()
}
#[cfg(target_os = "openbsd")]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno() -> *const c_int; }
__errno()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno_location() -> *const c_int; }
__errno_location()
}
unsafe {
(*errno_location()) as i32
}
}
pub fn error_string(errno: i32) -> String {
#[cfg(target_os = "linux")]
extern {
#[link_name = "__xpg_strerror_r"]
fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int;
}
#[cfg(not(target_os = "linux"))]
extern {
fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int;
}
let mut buf = [0 as c_char; TMPBUF_SZ];
let p = buf.as_mut_ptr();
unsafe {
if strerror_r(errno as c_int, p, buf.len() as size_t) < 0 {
panic!("strerror_r failure");
}
let p = p as *const _;
str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
}
}
| 27.420561 | 119 | 0.578732 |
097d2ddbe7abbdcce6b73015164e81eddf666fae
| 2,620 |
mod add_super_final_state;
mod all_pairs_shortest_distance;
mod arc_map;
mod arc_sort;
mod arc_sum;
pub(crate) mod arc_unique;
mod closure;
pub mod compose;
mod concat;
mod condense;
mod connect;
mod determinize;
pub(crate) mod dfs_visit;
pub(crate) mod dynamic_fst;
mod encode;
mod factor_weight;
mod fst_convert;
mod inversion;
mod isomorphic;
mod minimize;
mod partition;
mod projection;
mod push;
mod queue;
mod relabel_pairs;
mod replace;
mod reverse;
mod reweight;
mod rm_epsilon;
mod rm_final_epsilon;
mod shortest_distance;
mod shortest_path;
mod state_sort;
mod top_sort;
mod union;
mod weight_convert;
/// Module that provides different structures implementing the `Queue` trait.
pub mod queues;
/// Function objects to restrict which arcs are traversed in an FST.
pub mod arc_filters;
/// Module that provides structures implementing the `ArcMapper` trait.
pub mod arc_mappers;
pub(crate) mod visitors;
#[allow(unused)]
pub(crate) mod cache;
#[allow(unused)]
pub(crate) mod factor_iterators;
/// Module that provides structures implementing the `WeightConverter` trait.
pub mod weight_converters;
/// Functions to compare / sort the Arcs of an FST.
pub mod arc_compares {
pub use super::arc_sort::{ilabel_compare, olabel_compare};
pub use super::isomorphic::arc_compare;
}
pub use self::{
add_super_final_state::add_super_final_state,
all_pairs_shortest_distance::all_pairs_shortest_distance,
arc_map::{arc_map, ArcMapper, FinalArc, MapFinalAction},
arc_sort::arc_sort,
arc_sum::arc_sum,
arc_unique::arc_unique,
closure::{closure, ClosureFst, ClosureType},
compose::compose,
concat::{concat, ConcatFst},
condense::condense,
connect::connect,
determinize::{determinize, determinize_with_distance, DeterminizeType},
encode::{decode, encode},
fst_convert::{fst_convert, fst_convert_from_ref},
inversion::invert,
isomorphic::isomorphic,
minimize::minimize,
projection::{project, ProjectType},
push::{push, push_weights, PushType},
queue::{Queue, QueueType},
relabel_pairs::relabel_pairs,
replace::{replace, ReplaceFst},
reverse::reverse,
reweight::{reweight, ReweightType},
rm_epsilon::{rm_epsilon, RmEpsilonFst},
rm_final_epsilon::rm_final_epsilon,
shortest_distance::shortest_distance,
shortest_path::shortest_path,
state_sort::state_sort,
top_sort::top_sort,
union::{union, UnionFst},
weight_convert::{weight_convert, WeightConverter},
};
pub use self::factor_weight::{
factor_weight, FactorIterator, FactorWeightFst, FactorWeightOptions, FactorWeightType,
};
| 25.686275 | 90 | 0.75458 |
22fee902aea262546694649e6edb2532858cc31b
| 15,057 |
use std::mem;
use crate::deriving;
use syntax::ast::{self, Ident};
use syntax::attr;
use syntax::source_map::{ExpnInfo, MacroAttribute, hygiene, respan};
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::ext::expand::ExpansionConfig;
use syntax::ext::hygiene::Mark;
use syntax::mut_visit::MutVisitor;
use syntax::parse::ParseSess;
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax::symbol::keywords;
use syntax::visit::{self, Visitor};
use syntax_pos::{Span, DUMMY_SP};
const PROC_MACRO_KINDS: [&str; 3] = ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
struct ProcMacroDerive {
trait_name: ast::Name,
function_name: Ident,
span: Span,
attrs: Vec<ast::Name>,
}
struct ProcMacroDef {
function_name: Ident,
span: Span,
}
struct CollectProcMacros<'a> {
derives: Vec<ProcMacroDerive>,
attr_macros: Vec<ProcMacroDef>,
bang_macros: Vec<ProcMacroDef>,
in_root: bool,
handler: &'a errors::Handler,
is_proc_macro_crate: bool,
is_test_crate: bool,
}
pub fn modify(sess: &ParseSess,
resolver: &mut dyn (::syntax::ext::base::Resolver),
mut krate: ast::Crate,
is_proc_macro_crate: bool,
has_proc_macro_decls: bool,
is_test_crate: bool,
num_crate_types: usize,
handler: &errors::Handler) -> ast::Crate {
let ecfg = ExpansionConfig::default("proc_macro".to_string());
let mut cx = ExtCtxt::new(sess, ecfg, resolver);
let (derives, attr_macros, bang_macros) = {
let mut collect = CollectProcMacros {
derives: Vec::new(),
attr_macros: Vec::new(),
bang_macros: Vec::new(),
in_root: true,
handler,
is_proc_macro_crate,
is_test_crate,
};
if has_proc_macro_decls || is_proc_macro_crate {
visit::walk_crate(&mut collect, &krate);
}
(collect.derives, collect.attr_macros, collect.bang_macros)
};
if !is_proc_macro_crate {
return krate
}
if num_crate_types > 1 {
handler.err("cannot mix `proc-macro` crate type with others");
}
if is_test_crate {
return krate;
}
krate.module.items.push(mk_decls(&mut cx, &derives, &attr_macros, &bang_macros));
krate
}
pub fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(kind))
}
impl<'a> CollectProcMacros<'a> {
fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
self.handler.span_err(sp,
"`proc-macro` crate types cannot \
export any items other than functions \
tagged with `#[proc_macro_derive]` currently");
}
}
fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
// Once we've located the `#[proc_macro_derive]` attribute, verify
// that it's of the form `#[proc_macro_derive(Foo)]` or
// `#[proc_macro_derive(Foo, attributes(A, ..))]`
let list = match attr.meta_item_list() {
Some(list) => list,
None => return,
};
if list.len() != 1 && list.len() != 2 {
self.handler.span_err(attr.span,
"attribute must have either one or two arguments");
return
}
let trait_attr = match list[0].meta_item() {
Some(meta_item) => meta_item,
_ => {
self.handler.span_err(list[0].span(), "not a meta item");
return
}
};
let trait_ident = match trait_attr.ident() {
Some(trait_ident) if trait_attr.is_word() => trait_ident,
_ => {
self.handler.span_err(trait_attr.span, "must only be one word");
return
}
};
if !trait_ident.can_be_raw() {
self.handler.span_err(trait_attr.span,
&format!("`{}` cannot be a name of derive macro", trait_ident));
}
if deriving::is_builtin_trait(trait_ident.name) {
self.handler.span_err(trait_attr.span,
"cannot override a built-in derive macro");
}
let attributes_attr = list.get(1);
let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
if !attr.check_name("attributes") {
self.handler.span_err(attr.span(), "second argument must be `attributes`")
}
attr.meta_item_list().unwrap_or_else(|| {
self.handler.span_err(attr.span(),
"attribute must be of form: `attributes(foo, bar)`");
&[]
}).into_iter().filter_map(|attr| {
let attr = match attr.meta_item() {
Some(meta_item) => meta_item,
_ => {
self.handler.span_err(attr.span(), "not a meta item");
return None;
}
};
let ident = match attr.ident() {
Some(ident) if attr.is_word() => ident,
_ => {
self.handler.span_err(attr.span, "must only be one word");
return None;
}
};
if !ident.can_be_raw() {
self.handler.span_err(
attr.span,
&format!("`{}` cannot be a name of derive helper attribute", ident),
);
}
Some(ident.name)
}).collect()
} else {
Vec::new()
};
if self.in_root && item.vis.node.is_pub() {
self.derives.push(ProcMacroDerive {
span: item.span,
trait_name: trait_ident.name,
function_name: item.ident,
attrs: proc_attrs,
});
} else {
let msg = if !self.in_root {
"functions tagged with `#[proc_macro_derive]` must \
currently reside in the root of the crate"
} else {
"functions tagged with `#[proc_macro_derive]` must be `pub`"
};
self.handler.span_err(item.span, msg);
}
}
fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
if self.in_root && item.vis.node.is_pub() {
self.attr_macros.push(ProcMacroDef {
span: item.span,
function_name: item.ident,
});
} else {
let msg = if !self.in_root {
"functions tagged with `#[proc_macro_attribute]` must \
currently reside in the root of the crate"
} else {
"functions tagged with `#[proc_macro_attribute]` must be `pub`"
};
self.handler.span_err(item.span, msg);
}
}
fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
if self.in_root && item.vis.node.is_pub() {
self.bang_macros.push(ProcMacroDef {
span: item.span,
function_name: item.ident,
});
} else {
let msg = if !self.in_root {
"functions tagged with `#[proc_macro]` must \
currently reside in the root of the crate"
} else {
"functions tagged with `#[proc_macro]` must be `pub`"
};
self.handler.span_err(item.span, msg);
}
}
}
impl<'a> Visitor<'a> for CollectProcMacros<'a> {
fn visit_item(&mut self, item: &'a ast::Item) {
if let ast::ItemKind::MacroDef(..) = item.node {
if self.is_proc_macro_crate && attr::contains_name(&item.attrs, "macro_export") {
let msg =
"cannot export macro_rules! macros from a `proc-macro` crate type currently";
self.handler.span_err(item.span, msg);
}
}
// First up, make sure we're checking a bare function. If we're not then
// we're just not interested in this item.
//
// If we find one, try to locate a `#[proc_macro_derive]` attribute on
// it.
let is_fn = match item.node {
ast::ItemKind::Fn(..) => true,
_ => false,
};
let mut found_attr: Option<&'a ast::Attribute> = None;
for attr in &item.attrs {
if is_proc_macro_attr(&attr) {
if let Some(prev_attr) = found_attr {
let msg = if attr.path.segments[0].ident.name ==
prev_attr.path.segments[0].ident.name {
format!("Only one `#[{}]` attribute is allowed on any given function",
attr.path)
} else {
format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
to the same function", attr.path, prev_attr.path)
};
self.handler.struct_span_err(attr.span, &msg)
.span_note(prev_attr.span, "Previous attribute here")
.emit();
return;
}
found_attr = Some(attr);
}
}
let attr = match found_attr {
None => {
self.check_not_pub_in_root(&item.vis, item.span);
let prev_in_root = mem::replace(&mut self.in_root, false);
visit::walk_item(self, item);
self.in_root = prev_in_root;
return;
},
Some(attr) => attr,
};
if !is_fn {
let msg = format!("the `#[{}]` attribute may only be used on bare functions",
attr.path);
self.handler.span_err(attr.span, &msg);
return;
}
if self.is_test_crate {
return;
}
if !self.is_proc_macro_crate {
let msg = format!("the `#[{}]` attribute is only usable with crates of the \
`proc-macro` crate type", attr.path);
self.handler.span_err(attr.span, &msg);
return;
}
if attr.check_name("proc_macro_derive") {
self.collect_custom_derive(item, attr);
} else if attr.check_name("proc_macro_attribute") {
self.collect_attr_proc_macro(item);
} else if attr.check_name("proc_macro") {
self.collect_bang_proc_macro(item);
};
let prev_in_root = mem::replace(&mut self.in_root, false);
visit::walk_item(self, item);
self.in_root = prev_in_root;
}
fn visit_mac(&mut self, mac: &'a ast::Mac) {
visit::walk_mac(self, mac)
}
}
// Creates a new module which looks like:
//
// mod $gensym {
// extern crate proc_macro;
//
// use proc_macro::bridge::client::ProcMacro;
//
// #[rustc_proc_macro_decls]
// static DECLS: &[ProcMacro] = &[
// ProcMacro::custom_derive($name_trait1, &[], ::$name1);
// ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
// // ...
// ];
// }
fn mk_decls(
cx: &mut ExtCtxt<'_>,
custom_derives: &[ProcMacroDerive],
custom_attrs: &[ProcMacroDef],
custom_macros: &[ProcMacroDef],
) -> P<ast::Item> {
let mark = Mark::fresh(Mark::root());
mark.set_expn_info(ExpnInfo {
call_site: DUMMY_SP,
def_site: None,
format: MacroAttribute(Symbol::intern("proc_macro")),
allow_internal_unstable: Some(vec![
Symbol::intern("rustc_attrs"),
Symbol::intern("proc_macro_internals"),
].into()),
allow_internal_unsafe: false,
local_inner_macros: false,
edition: hygiene::default_edition(),
});
let span = DUMMY_SP.apply_mark(mark);
let proc_macro = Ident::from_str("proc_macro");
let krate = cx.item(span,
proc_macro,
Vec::new(),
ast::ItemKind::ExternCrate(None));
let bridge = Ident::from_str("bridge");
let client = Ident::from_str("client");
let proc_macro_ty = Ident::from_str("ProcMacro");
let custom_derive = Ident::from_str("custom_derive");
let attr = Ident::from_str("attr");
let bang = Ident::from_str("bang");
let crate_kw = Ident::with_empty_ctxt(keywords::Crate.name());
let decls = {
let local_path = |sp: Span, name| {
cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![crate_kw, name]))
};
let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
proc_macro, bridge, client, proc_macro_ty, method,
]));
custom_derives.iter().map(|cd| {
cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
cx.expr_str(cd.span, cd.trait_name),
cx.expr_vec_slice(
span,
cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
),
local_path(cd.span, cd.function_name),
])
}).chain(custom_attrs.iter().map(|ca| {
cx.expr_call(span, proc_macro_ty_method_path(attr), vec![
cx.expr_str(ca.span, ca.function_name.name),
local_path(ca.span, ca.function_name),
])
})).chain(custom_macros.iter().map(|cm| {
cx.expr_call(span, proc_macro_ty_method_path(bang), vec![
cx.expr_str(cm.span, cm.function_name.name),
local_path(cm.span, cm.function_name),
])
})).collect()
};
let decls_static = cx.item_static(
span,
Ident::from_str("_DECLS"),
cx.ty_rptr(span,
cx.ty(span, ast::TyKind::Slice(
cx.ty_path(cx.path(span,
vec![proc_macro, bridge, client, proc_macro_ty])))),
None, ast::Mutability::Immutable),
ast::Mutability::Immutable,
cx.expr_vec_slice(span, decls),
).map(|mut i| {
let attr = cx.meta_word(span, Symbol::intern("rustc_proc_macro_decls"));
i.attrs.push(cx.attribute(span, attr));
i.vis = respan(span, ast::VisibilityKind::Public);
i
});
let module = cx.item_mod(
span,
span,
ast::Ident::with_empty_ctxt(Symbol::gensym("decls")),
vec![],
vec![krate, decls_static],
).map(|mut i| {
i.vis = respan(span, ast::VisibilityKind::Public);
i
});
cx.monotonic_expander().flat_map_item(module).pop().unwrap()
}
| 34.773672 | 98 | 0.525071 |
1e97e3c2b243b9ae0fdc692356d4f11d8ef1d28d
| 1,280 |
#![no_std]
/// Reexport `fugit`
pub use fugit::*;
/// Provides non-blocking `CountDown` timing capabilities
pub trait Timer<const TIMER_HZ: u32> {
/// An error that might happen during waiting
type Error: core::fmt::Debug;
/// Return current time `Instant`
fn now(&mut self) -> TimerInstantU32<TIMER_HZ>;
/// Start timer with a `duration`
fn start(&mut self, duration: TimerDurationU32<TIMER_HZ>) -> Result<(), Self::Error>;
/// Tries to stop this timer.
/// An error will be returned if the timer has already been canceled or was never started.
/// An error is also returned if the timer is not `Periodic` and has already expired.
fn cancel(&mut self) -> Result<(), Self::Error>;
/// Wait until timer `duration` has expired.
/// Must return `nb::Error::WouldBlock` if timer `duration` is not yet over.
/// Must return `OK(())` as soon as timer `duration` has expired.
fn wait(&mut self) -> nb::Result<(), Self::Error>;
}
/// Provides blocking `Delay`
pub trait Delay<const TIMER_HZ: u32> {
/// An error that might happen during waiting
type Error: core::fmt::Debug;
/// Wait until timer `duration` has expired.
fn delay(&mut self, duration: TimerDurationU32<TIMER_HZ>) -> Result<(), Self::Error>;
}
| 35.555556 | 94 | 0.660938 |
ed39ee03be15020e942c9077a0853fe973152d8b
| 946 |
// iterators1.rs
//
// Make me compile by filling in the `???`s
//
// When performing operations on elements within a collection, iterators are essential.
// This module helps you get familiar with the structure of using an iterator and
// how to go through elements within an iterable collection.
//
// Execute `rustlings hint iterators1` for hints :D
fn main() {
let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"];
let mut my_iterable_fav_fruits = my_fav_fruits.iter(); //Step 1
assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // Step 2
assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // Step 2.1
assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry"));
assert_eq!(my_iterable_fav_fruits.next(), None); // Step 3
}
| 41.130435 | 89 | 0.705074 |
5d0d81667eaee65f3f171db2714a0c7bcf2fbc36
| 39,655 |
pub use root::*;
const _: () = ::planus::check_version_compatibility("planus-0.3.0");
#[no_implicit_prelude]
mod root {
pub mod my_game {
pub mod sample {
#[derive(
Copy,
Clone,
Debug,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
::serde::Serialize,
::serde::Deserialize,
)]
#[repr(i8)]
pub enum Color {
Red = 0,
Green = 1,
Blue = 2,
}
impl ::core::convert::TryFrom<i8> for Color {
type Error = ::planus::errors::UnknownEnumTagKind;
fn try_from(
value: i8,
) -> ::core::result::Result<Self, ::planus::errors::UnknownEnumTagKind>
{
#[allow(clippy::match_single_binding)]
match value {
0 => ::core::result::Result::Ok(Color::Red),
1 => ::core::result::Result::Ok(Color::Green),
2 => ::core::result::Result::Ok(Color::Blue),
_ => ::core::result::Result::Err(::planus::errors::UnknownEnumTagKind {
tag: value as i128,
}),
}
}
}
impl ::core::convert::From<Color> for i8 {
fn from(value: Color) -> Self {
value as i8
}
}
impl ::planus::Primitive for Color {
const ALIGNMENT: usize = 1;
const SIZE: usize = 1;
}
impl ::planus::WriteAsPrimitive<Color> for Color {
#[inline]
fn write<const N: usize>(
&self,
cursor: ::planus::Cursor<'_, N>,
buffer_position: u32,
) {
(*self as i8).write(cursor, buffer_position);
}
}
impl ::planus::WriteAs<Color> for Color {
type Prepared = Self;
#[inline]
fn prepare(&self, _builder: &mut ::planus::Builder) -> Color {
*self
}
}
impl ::planus::WriteAsDefault<Color, Color> for Color {
type Prepared = Self;
#[inline]
fn prepare(
&self,
_builder: &mut ::planus::Builder,
default: &Color,
) -> ::core::option::Option<Color> {
if self == default {
::core::option::Option::None
} else {
::core::option::Option::Some(*self)
}
}
}
impl ::planus::WriteAsOptional<Color> for Color {
type Prepared = Self;
#[inline]
fn prepare(
&self,
_builder: &mut ::planus::Builder,
) -> ::core::option::Option<Color> {
::core::option::Option::Some(*self)
}
}
impl<'buf> ::planus::TableRead<'buf> for Color {
fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'buf>,
offset: usize,
) -> ::core::result::Result<Self, ::planus::errors::ErrorKind> {
let n: i8 = ::planus::TableRead::from_buffer(buffer, offset)?;
::core::result::Result::Ok(::core::convert::TryInto::try_into(n)?)
}
}
impl<'buf> ::planus::VectorReadInner<'buf> for Color {
type Error = ::planus::errors::UnknownEnumTag;
const STRIDE: usize = 1;
#[inline]
unsafe fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'buf>,
offset: usize,
) -> ::core::result::Result<Self, ::planus::errors::UnknownEnumTag>
{
let value = <i8 as ::planus::VectorRead>::from_buffer(buffer, offset);
let value: ::core::result::Result<Self, _> =
::core::convert::TryInto::try_into(value);
value.map_err(|error_kind| {
error_kind.with_error_location(
"Color",
"VectorRead::from_buffer",
buffer.offset_from_start,
)
})
}
}
impl<'buf> ::planus::VectorWrite<Color> for Color {
const STRIDE: usize = 1;
type Value = Self;
fn prepare(&self, _builder: &mut ::planus::Builder) -> Self::Value {
*self
}
#[inline]
unsafe fn write_values(
values: &[Self],
bytes: *mut ::core::mem::MaybeUninit<u8>,
buffer_position: u32,
) {
let bytes = bytes as *mut [::core::mem::MaybeUninit<u8>; 1];
for (i, v) in ::core::iter::Iterator::enumerate(values.iter()) {
::planus::WriteAsPrimitive::write(
v,
::planus::Cursor::new(&mut *bytes.add(i)),
buffer_position - i as u32,
);
}
}
}
#[derive(
Clone,
Debug,
PartialEq,
PartialOrd,
Eq,
Ord,
Hash,
::serde::Serialize,
::serde::Deserialize,
)]
pub enum Equipment {
Weapon(::planus::alloc::boxed::Box<self::Weapon>),
}
impl Equipment {
pub fn create_weapon(
builder: &mut ::planus::Builder,
value: impl ::planus::WriteAsOffset<self::Weapon>,
) -> ::planus::UnionOffset<Self> {
::planus::UnionOffset::new(1, value.prepare(builder).downcast())
}
}
impl ::planus::WriteAsUnion<Equipment> for Equipment {
fn prepare(&self, builder: &mut ::planus::Builder) -> ::planus::UnionOffset<Self> {
match self {
Self::Weapon(value) => Self::create_weapon(builder, value),
}
}
}
impl ::planus::WriteAsOptionalUnion<Equipment> for Equipment {
fn prepare(
&self,
builder: &mut ::planus::Builder,
) -> ::core::option::Option<::planus::UnionOffset<Self>> {
::core::option::Option::Some(::planus::WriteAsUnion::prepare(self, builder))
}
}
#[derive(Copy, Clone, Debug)]
pub enum EquipmentRef<'a> {
Weapon(self::WeaponRef<'a>),
}
impl<'a> ::core::convert::TryFrom<EquipmentRef<'a>> for Equipment {
type Error = ::planus::Error;
fn try_from(value: EquipmentRef<'a>) -> ::planus::Result<Self> {
::core::result::Result::Ok(match value {
EquipmentRef::Weapon(value) => {
Equipment::Weapon(::planus::alloc::boxed::Box::new(
::core::convert::TryFrom::try_from(value)?,
))
}
})
}
}
impl<'a> ::planus::TableReadUnion<'a> for EquipmentRef<'a> {
fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'a>,
field_offset: usize,
tag: u8,
) -> ::core::result::Result<Self, ::planus::errors::ErrorKind> {
match tag {
1 => ::core::result::Result::Ok(Self::Weapon(
::planus::TableRead::from_buffer(buffer, field_offset)?,
)),
_ => ::core::result::Result::Err(
::planus::errors::ErrorKind::UnknownUnionTag { tag },
),
}
}
}
#[derive(
Copy,
Clone,
Debug,
PartialEq,
PartialOrd,
Default,
::serde::Serialize,
::serde::Deserialize,
)]
pub struct Vec3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl ::planus::Primitive for Vec3 {
const ALIGNMENT: usize = 4;
const SIZE: usize = 12;
}
#[allow(clippy::identity_op)]
impl ::planus::WriteAsPrimitive<Vec3> for Vec3 {
fn write<const N: usize>(
&self,
cursor: ::planus::Cursor<'_, N>,
buffer_position: u32,
) {
let (cur, cursor) = cursor.split::<4, 8>();
self.x.write(cur, buffer_position - 0);
let (cur, cursor) = cursor.split::<4, 4>();
self.y.write(cur, buffer_position - 4);
let (cur, cursor) = cursor.split::<4, 0>();
self.z.write(cur, buffer_position - 8);
cursor.finish([]);
}
}
impl ::planus::WriteAs<Vec3> for Vec3 {
type Prepared = Self;
fn prepare(&self, _builder: &mut ::planus::Builder) -> Self {
*self
}
}
impl ::planus::WriteAsOptional<Vec3> for Vec3 {
type Prepared = Self;
fn prepare(
&self,
_builder: &mut ::planus::Builder,
) -> ::core::option::Option<Self> {
::core::option::Option::Some(*self)
}
}
#[derive(Copy, Clone)]
pub struct Vec3Ref<'a>(::planus::ArrayWithStartOffset<'a, 12>);
impl<'a> Vec3Ref<'a> {
pub fn x(&self) -> f32 {
let buffer = self.0.advance_as_array::<4>(0).unwrap();
f32::from_le_bytes(*buffer.as_array())
}
pub fn y(&self) -> f32 {
let buffer = self.0.advance_as_array::<4>(4).unwrap();
f32::from_le_bytes(*buffer.as_array())
}
pub fn z(&self) -> f32 {
let buffer = self.0.advance_as_array::<4>(8).unwrap();
f32::from_le_bytes(*buffer.as_array())
}
}
impl<'a> ::core::fmt::Debug for Vec3Ref<'a> {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
let mut f = f.debug_struct("Vec3Ref");
f.field("x", &self.x());
f.field("y", &self.y());
f.field("z", &self.z());
f.finish()
}
}
impl<'a> ::core::convert::TryFrom<Vec3Ref<'a>> for Vec3 {
type Error = ::planus::Error;
#[allow(unreachable_code)]
fn try_from(value: Vec3Ref<'a>) -> ::planus::Result<Self> {
::core::result::Result::Ok(Vec3 {
x: value.x(),
y: value.y(),
z: value.z(),
})
}
}
impl<'a> ::planus::TableRead<'a> for Vec3Ref<'a> {
fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'a>,
offset: usize,
) -> ::core::result::Result<Self, ::planus::errors::ErrorKind> {
let buffer = buffer.advance_as_array::<12>(offset)?;
::core::result::Result::Ok(Self(buffer))
}
}
impl<'a> ::planus::VectorRead<'a> for Vec3Ref<'a> {
const STRIDE: usize = 12;
unsafe fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'a>,
offset: usize,
) -> Self {
Self(buffer.unchecked_advance_as_array(offset))
}
}
impl ::planus::VectorWrite<Vec3> for Vec3 {
const STRIDE: usize = 12;
type Value = Vec3;
fn prepare(&self, _builder: &mut ::planus::Builder) -> Self::Value {
*self
}
#[inline]
unsafe fn write_values(
values: &[Vec3],
bytes: *mut ::core::mem::MaybeUninit<u8>,
buffer_position: u32,
) {
let bytes = bytes as *mut [::core::mem::MaybeUninit<u8>; 12];
for (i, v) in ::core::iter::Iterator::enumerate(values.iter()) {
::planus::WriteAsPrimitive::write(
v,
::planus::Cursor::new(&mut *bytes.add(i)),
buffer_position - (12 * i) as u32,
);
}
}
}
#[derive(
Clone, Debug, PartialEq, PartialOrd, ::serde::Serialize, ::serde::Deserialize,
)]
pub struct Monster {
pub pos: ::core::option::Option<self::Vec3>,
pub mana: i16,
pub hp: i16,
pub name: ::core::option::Option<::planus::alloc::string::String>,
pub inventory: ::core::option::Option<::planus::alloc::vec::Vec<u8>>,
pub color: self::Color,
pub weapons: ::core::option::Option<::planus::alloc::vec::Vec<self::Weapon>>,
pub equipped: ::core::option::Option<self::Equipment>,
pub path: ::core::option::Option<::planus::alloc::vec::Vec<self::Vec3>>,
}
#[allow(clippy::derivable_impls)]
impl ::core::default::Default for Monster {
fn default() -> Self {
Self {
pos: ::core::default::Default::default(),
mana: 150,
hp: 100,
name: ::core::default::Default::default(),
inventory: ::core::default::Default::default(),
color: self::Color::Blue,
weapons: ::core::default::Default::default(),
equipped: ::core::default::Default::default(),
path: ::core::default::Default::default(),
}
}
}
impl Monster {
#[allow(clippy::too_many_arguments)]
pub fn create(
builder: &mut ::planus::Builder,
pos: impl ::planus::WriteAsOptional<self::Vec3>,
mana: impl ::planus::WriteAsDefault<i16, i16>,
hp: impl ::planus::WriteAsDefault<i16, i16>,
name: impl ::planus::WriteAsOptional<::planus::Offset<::core::primitive::str>>,
inventory: impl ::planus::WriteAsOptional<::planus::Offset<[u8]>>,
color: impl ::planus::WriteAsDefault<self::Color, self::Color>,
weapons: impl ::planus::WriteAsOptional<
::planus::Offset<[::planus::Offset<self::Weapon>]>,
>,
equipped: impl ::planus::WriteAsOptionalUnion<self::Equipment>,
path: impl ::planus::WriteAsOptional<::planus::Offset<[self::Vec3]>>,
) -> ::planus::Offset<Self> {
let prepared_pos = pos.prepare(builder);
let prepared_mana = mana.prepare(builder, &150);
let prepared_hp = hp.prepare(builder, &100);
let prepared_name = name.prepare(builder);
let prepared_inventory = inventory.prepare(builder);
let prepared_color = color.prepare(builder, &self::Color::Blue);
let prepared_weapons = weapons.prepare(builder);
let prepared_equipped = equipped.prepare(builder);
let prepared_path = path.prepare(builder);
let mut table_writer =
::planus::table_writer::TableWriter::<24, 39>::new(builder);
if prepared_pos.is_some() {
table_writer.calculate_size::<self::Vec3>(2);
}
if prepared_mana.is_some() {
table_writer.calculate_size::<i16>(4);
}
if prepared_hp.is_some() {
table_writer.calculate_size::<i16>(6);
}
if prepared_name.is_some() {
table_writer.calculate_size::<::planus::Offset<str>>(8);
}
if prepared_inventory.is_some() {
table_writer.calculate_size::<::planus::Offset<[u8]>>(12);
}
if prepared_color.is_some() {
table_writer.calculate_size::<self::Color>(14);
}
if prepared_weapons.is_some() {
table_writer
.calculate_size::<::planus::Offset<[::planus::Offset<self::Weapon>]>>(
16,
);
}
if prepared_equipped.is_some() {
table_writer.calculate_size::<u8>(18);
table_writer.calculate_size::<::planus::Offset<self::Equipment>>(20);
}
if prepared_path.is_some() {
table_writer.calculate_size::<::planus::Offset<[self::Vec3]>>(22);
}
table_writer.finish_calculating();
unsafe {
if let ::core::option::Option::Some(prepared_pos) = prepared_pos {
table_writer.write::<_, _, 12>(0, &prepared_pos);
}
if let ::core::option::Option::Some(prepared_name) = prepared_name {
table_writer.write::<_, _, 4>(3, &prepared_name);
}
if let ::core::option::Option::Some(prepared_inventory) = prepared_inventory
{
table_writer.write::<_, _, 4>(5, &prepared_inventory);
}
if let ::core::option::Option::Some(prepared_weapons) = prepared_weapons {
table_writer.write::<_, _, 4>(7, &prepared_weapons);
}
if let ::core::option::Option::Some(prepared_equipped) = prepared_equipped {
table_writer.write::<_, _, 4>(9, &prepared_equipped.offset());
}
if let ::core::option::Option::Some(prepared_path) = prepared_path {
table_writer.write::<_, _, 4>(10, &prepared_path);
}
if let ::core::option::Option::Some(prepared_mana) = prepared_mana {
table_writer.write::<_, _, 2>(1, &prepared_mana);
}
if let ::core::option::Option::Some(prepared_hp) = prepared_hp {
table_writer.write::<_, _, 2>(2, &prepared_hp);
}
if let ::core::option::Option::Some(prepared_color) = prepared_color {
table_writer.write::<_, _, 1>(6, &prepared_color);
}
if let ::core::option::Option::Some(prepared_equipped) = prepared_equipped {
table_writer.write::<_, _, 1>(8, &prepared_equipped.tag());
}
}
table_writer.finish()
}
}
impl ::planus::WriteAs<::planus::Offset<Monster>> for Monster {
type Prepared = ::planus::Offset<Self>;
fn prepare(&self, builder: &mut ::planus::Builder) -> ::planus::Offset<Monster> {
::planus::WriteAsOffset::prepare(self, builder)
}
}
impl ::planus::WriteAsOptional<::planus::Offset<Monster>> for Monster {
type Prepared = ::planus::Offset<Self>;
fn prepare(
&self,
builder: &mut ::planus::Builder,
) -> ::core::option::Option<::planus::Offset<Monster>> {
::core::option::Option::Some(::planus::WriteAsOffset::prepare(self, builder))
}
}
impl ::planus::WriteAsOffset<Monster> for Monster {
fn prepare(&self, builder: &mut ::planus::Builder) -> ::planus::Offset<Monster> {
Monster::create(
builder,
&self.pos,
&self.mana,
&self.hp,
&self.name,
&self.inventory,
&self.color,
&self.weapons,
&self.equipped,
&self.path,
)
}
}
#[derive(Copy, Clone)]
pub struct MonsterRef<'a>(::planus::table_reader::Table<'a>);
impl<'a> MonsterRef<'a> {
pub fn pos(&self) -> ::planus::Result<::core::option::Option<self::Vec3Ref<'a>>> {
self.0.access(0, "Monster", "pos")
}
pub fn mana(&self) -> ::planus::Result<i16> {
::core::result::Result::Ok(self.0.access(1, "Monster", "mana")?.unwrap_or(150))
}
pub fn hp(&self) -> ::planus::Result<i16> {
::core::result::Result::Ok(self.0.access(2, "Monster", "hp")?.unwrap_or(100))
}
pub fn name(
&self,
) -> ::planus::Result<::core::option::Option<&'a ::core::primitive::str>>
{
self.0.access(3, "Monster", "name")
}
pub fn inventory(
&self,
) -> ::planus::Result<::core::option::Option<::planus::Vector<'a, u8>>>
{
self.0.access(5, "Monster", "inventory")
}
pub fn color(&self) -> ::planus::Result<self::Color> {
::core::result::Result::Ok(
self.0
.access(6, "Monster", "color")?
.unwrap_or(self::Color::Blue),
)
}
pub fn weapons(
&self,
) -> ::planus::Result<
::core::option::Option<
::planus::Vector<'a, ::planus::Result<self::WeaponRef<'a>>>,
>,
> {
self.0.access(7, "Monster", "weapons")
}
pub fn equipped(
&self,
) -> ::planus::Result<::core::option::Option<self::EquipmentRef<'a>>>
{
self.0.access_union(8, "Monster", "equipped")
}
pub fn path(
&self,
) -> ::planus::Result<::core::option::Option<::planus::Vector<'a, self::Vec3Ref<'a>>>>
{
self.0.access(10, "Monster", "path")
}
}
impl<'a> ::core::fmt::Debug for MonsterRef<'a> {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
let mut f = f.debug_struct("MonsterRef");
if let ::core::option::Option::Some(pos) = self.pos().transpose() {
f.field("pos", &pos);
}
f.field("mana", &self.mana());
f.field("hp", &self.hp());
if let ::core::option::Option::Some(name) = self.name().transpose() {
f.field("name", &name);
}
if let ::core::option::Option::Some(inventory) = self.inventory().transpose() {
f.field("inventory", &inventory);
}
f.field("color", &self.color());
if let ::core::option::Option::Some(weapons) = self.weapons().transpose() {
f.field("weapons", &weapons);
}
if let ::core::option::Option::Some(equipped) = self.equipped().transpose() {
f.field("equipped", &equipped);
}
if let ::core::option::Option::Some(path) = self.path().transpose() {
f.field("path", &path);
}
f.finish()
}
}
impl<'a> ::core::convert::TryFrom<MonsterRef<'a>> for Monster {
type Error = ::planus::Error;
#[allow(unreachable_code)]
fn try_from(value: MonsterRef<'a>) -> ::planus::Result<Self> {
::core::result::Result::Ok(Self {
pos: if let ::core::option::Option::Some(pos) = value.pos()? {
::core::option::Option::Some(::core::convert::TryInto::try_into(pos)?)
} else {
::core::option::Option::None
},
mana: ::core::convert::TryInto::try_into(value.mana()?)?,
hp: ::core::convert::TryInto::try_into(value.hp()?)?,
name: if let ::core::option::Option::Some(name) = value.name()? {
::core::option::Option::Some(::core::convert::TryInto::try_into(name)?)
} else {
::core::option::Option::None
},
inventory: if let ::core::option::Option::Some(inventory) =
value.inventory()?
{
::core::option::Option::Some(inventory.to_vec()?)
} else {
::core::option::Option::None
},
color: ::core::convert::TryInto::try_into(value.color()?)?,
weapons: if let ::core::option::Option::Some(weapons) = value.weapons()? {
::core::option::Option::Some(weapons.to_vec_result()?)
} else {
::core::option::Option::None
},
equipped: if let ::core::option::Option::Some(equipped) =
value.equipped()?
{
::core::option::Option::Some(::core::convert::TryInto::try_into(
equipped,
)?)
} else {
::core::option::Option::None
},
path: if let ::core::option::Option::Some(path) = value.path()? {
::core::option::Option::Some(path.to_vec()?)
} else {
::core::option::Option::None
},
})
}
}
impl<'a> ::planus::TableRead<'a> for MonsterRef<'a> {
fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'a>,
offset: usize,
) -> ::core::result::Result<Self, ::planus::errors::ErrorKind> {
::core::result::Result::Ok(Self(::planus::table_reader::Table::from_buffer(
buffer, offset,
)?))
}
}
impl<'a> ::planus::VectorReadInner<'a> for MonsterRef<'a> {
type Error = ::planus::Error;
const STRIDE: usize = 4;
unsafe fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'a>,
offset: usize,
) -> ::planus::Result<Self> {
::planus::TableRead::from_buffer(buffer, offset).map_err(|error_kind| {
error_kind.with_error_location(
"[MonsterRef]",
"get",
buffer.offset_from_start,
)
})
}
}
impl ::planus::VectorWrite<::planus::Offset<Monster>> for Monster {
type Value = ::planus::Offset<Monster>;
const STRIDE: usize = 4;
fn prepare(&self, builder: &mut ::planus::Builder) -> Self::Value {
::planus::WriteAs::prepare(self, builder)
}
#[inline]
unsafe fn write_values(
values: &[::planus::Offset<Monster>],
bytes: *mut ::core::mem::MaybeUninit<u8>,
buffer_position: u32,
) {
let bytes = bytes as *mut [::core::mem::MaybeUninit<u8>; 4];
for (i, v) in ::core::iter::Iterator::enumerate(values.iter()) {
::planus::WriteAsPrimitive::write(
v,
::planus::Cursor::new(&mut *bytes.add(i)),
buffer_position - (Self::STRIDE * i) as u32,
);
}
}
}
impl<'a> ::planus::ReadAsRoot<'a> for MonsterRef<'a> {
fn read_as_root(slice: &'a [u8]) -> ::planus::Result<Self> {
::planus::TableRead::from_buffer(
::planus::SliceWithStartOffset {
buffer: slice,
offset_from_start: 0,
},
0,
)
.map_err(|error_kind| {
error_kind.with_error_location("[MonsterRef]", "read_as_root", 0)
})
}
}
#[derive(
Clone,
Debug,
PartialEq,
PartialOrd,
Eq,
Ord,
Hash,
::serde::Serialize,
::serde::Deserialize,
)]
pub struct Weapon {
pub name: ::core::option::Option<::planus::alloc::string::String>,
pub damage: i16,
}
#[allow(clippy::derivable_impls)]
impl ::core::default::Default for Weapon {
fn default() -> Self {
Self {
name: ::core::default::Default::default(),
damage: 0,
}
}
}
impl Weapon {
#[allow(clippy::too_many_arguments)]
pub fn create(
builder: &mut ::planus::Builder,
name: impl ::planus::WriteAsOptional<::planus::Offset<::core::primitive::str>>,
damage: impl ::planus::WriteAsDefault<i16, i16>,
) -> ::planus::Offset<Self> {
let prepared_name = name.prepare(builder);
let prepared_damage = damage.prepare(builder, &0);
let mut table_writer =
::planus::table_writer::TableWriter::<6, 6>::new(builder);
if prepared_name.is_some() {
table_writer.calculate_size::<::planus::Offset<str>>(2);
}
if prepared_damage.is_some() {
table_writer.calculate_size::<i16>(4);
}
table_writer.finish_calculating();
unsafe {
if let ::core::option::Option::Some(prepared_name) = prepared_name {
table_writer.write::<_, _, 4>(0, &prepared_name);
}
if let ::core::option::Option::Some(prepared_damage) = prepared_damage {
table_writer.write::<_, _, 2>(1, &prepared_damage);
}
}
table_writer.finish()
}
}
impl ::planus::WriteAs<::planus::Offset<Weapon>> for Weapon {
type Prepared = ::planus::Offset<Self>;
fn prepare(&self, builder: &mut ::planus::Builder) -> ::planus::Offset<Weapon> {
::planus::WriteAsOffset::prepare(self, builder)
}
}
impl ::planus::WriteAsOptional<::planus::Offset<Weapon>> for Weapon {
type Prepared = ::planus::Offset<Self>;
fn prepare(
&self,
builder: &mut ::planus::Builder,
) -> ::core::option::Option<::planus::Offset<Weapon>> {
::core::option::Option::Some(::planus::WriteAsOffset::prepare(self, builder))
}
}
impl ::planus::WriteAsOffset<Weapon> for Weapon {
fn prepare(&self, builder: &mut ::planus::Builder) -> ::planus::Offset<Weapon> {
Weapon::create(builder, &self.name, &self.damage)
}
}
#[derive(Copy, Clone)]
pub struct WeaponRef<'a>(::planus::table_reader::Table<'a>);
impl<'a> WeaponRef<'a> {
pub fn name(
&self,
) -> ::planus::Result<::core::option::Option<&'a ::core::primitive::str>>
{
self.0.access(0, "Weapon", "name")
}
pub fn damage(&self) -> ::planus::Result<i16> {
::core::result::Result::Ok(self.0.access(1, "Weapon", "damage")?.unwrap_or(0))
}
}
impl<'a> ::core::fmt::Debug for WeaponRef<'a> {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
let mut f = f.debug_struct("WeaponRef");
if let ::core::option::Option::Some(name) = self.name().transpose() {
f.field("name", &name);
}
f.field("damage", &self.damage());
f.finish()
}
}
impl<'a> ::core::convert::TryFrom<WeaponRef<'a>> for Weapon {
type Error = ::planus::Error;
#[allow(unreachable_code)]
fn try_from(value: WeaponRef<'a>) -> ::planus::Result<Self> {
::core::result::Result::Ok(Self {
name: if let ::core::option::Option::Some(name) = value.name()? {
::core::option::Option::Some(::core::convert::TryInto::try_into(name)?)
} else {
::core::option::Option::None
},
damage: ::core::convert::TryInto::try_into(value.damage()?)?,
})
}
}
impl<'a> ::planus::TableRead<'a> for WeaponRef<'a> {
fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'a>,
offset: usize,
) -> ::core::result::Result<Self, ::planus::errors::ErrorKind> {
::core::result::Result::Ok(Self(::planus::table_reader::Table::from_buffer(
buffer, offset,
)?))
}
}
impl<'a> ::planus::VectorReadInner<'a> for WeaponRef<'a> {
type Error = ::planus::Error;
const STRIDE: usize = 4;
unsafe fn from_buffer(
buffer: ::planus::SliceWithStartOffset<'a>,
offset: usize,
) -> ::planus::Result<Self> {
::planus::TableRead::from_buffer(buffer, offset).map_err(|error_kind| {
error_kind.with_error_location(
"[WeaponRef]",
"get",
buffer.offset_from_start,
)
})
}
}
impl ::planus::VectorWrite<::planus::Offset<Weapon>> for Weapon {
type Value = ::planus::Offset<Weapon>;
const STRIDE: usize = 4;
fn prepare(&self, builder: &mut ::planus::Builder) -> Self::Value {
::planus::WriteAs::prepare(self, builder)
}
#[inline]
unsafe fn write_values(
values: &[::planus::Offset<Weapon>],
bytes: *mut ::core::mem::MaybeUninit<u8>,
buffer_position: u32,
) {
let bytes = bytes as *mut [::core::mem::MaybeUninit<u8>; 4];
for (i, v) in ::core::iter::Iterator::enumerate(values.iter()) {
::planus::WriteAsPrimitive::write(
v,
::planus::Cursor::new(&mut *bytes.add(i)),
buffer_position - (Self::STRIDE * i) as u32,
);
}
}
}
impl<'a> ::planus::ReadAsRoot<'a> for WeaponRef<'a> {
fn read_as_root(slice: &'a [u8]) -> ::planus::Result<Self> {
::planus::TableRead::from_buffer(
::planus::SliceWithStartOffset {
buffer: slice,
offset_from_start: 0,
},
0,
)
.map_err(|error_kind| {
error_kind.with_error_location("[WeaponRef]", "read_as_root", 0)
})
}
}
}
}
}
| 40.671795 | 102 | 0.403329 |
5bc907ad78cbb0ea8663f9c85c5c6e744d18d3e2
| 5,506 |
// Generated from definition io.k8s.api.storage.v1.VolumeAttachmentSource
/// VolumeAttachmentSource represents a volume that should be attached. Right now only PersistenVolumes can be attached via external attacher, in future we may allow also inline volumes in pods. Exactly one member can be set.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VolumeAttachmentSource {
/// Name of the persistent volume to attach.
pub persistent_volume_name: Option<String>,
}
impl<'de> crate::serde::Deserialize<'de> for VolumeAttachmentSource {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_persistent_volume_name,
Other,
}
impl<'de> crate::serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: crate::serde::de::Error {
Ok(match v {
"persistentVolumeName" => Field::Key_persistent_volume_name,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = VolumeAttachmentSource;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("VolumeAttachmentSource")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: crate::serde::de::MapAccess<'de> {
let mut value_persistent_volume_name: Option<String> = None;
while let Some(key) = crate::serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_persistent_volume_name => value_persistent_volume_name = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: crate::serde::de::IgnoredAny = crate::serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(VolumeAttachmentSource {
persistent_volume_name: value_persistent_volume_name,
})
}
}
deserializer.deserialize_struct(
"VolumeAttachmentSource",
&[
"persistentVolumeName",
],
Visitor,
)
}
}
impl crate::serde::Serialize for VolumeAttachmentSource {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: crate::serde::Serializer {
let mut state = serializer.serialize_struct(
"VolumeAttachmentSource",
self.persistent_volume_name.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.persistent_volume_name {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "persistentVolumeName", value)?;
}
crate::serde::ser::SerializeStruct::end(state)
}
}
#[cfg(feature = "schemars")]
impl crate::schemars::JsonSchema for VolumeAttachmentSource {
fn schema_name() -> String {
"io.k8s.api.storage.v1.VolumeAttachmentSource".to_owned()
}
fn json_schema(__gen: &mut crate::schemars::gen::SchemaGenerator) -> crate::schemars::schema::Schema {
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("VolumeAttachmentSource represents a volume that should be attached. Right now only PersistenVolumes can be attached via external attacher, in future we may allow also inline volumes in pods. Exactly one member can be set.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Object))),
object: Some(Box::new(crate::schemars::schema::ObjectValidation {
properties: IntoIterator::into_iter([
(
"persistentVolumeName".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Name of the persistent volume to attach.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
..Default::default()
}),
),
]).collect(),
..Default::default()
})),
..Default::default()
})
}
}
| 45.131148 | 270 | 0.561569 |
222bbe4f32509a730b07d9d14f09c84b3687e1b4
| 1,203 |
use crate::{
client::Client,
error::Error,
request::{Request, TryIntoRequest},
response::ResponseFuture,
routing::Route,
};
use twilight_model::{
id::{marker::GuildMarker, Id},
invite::WelcomeScreen,
};
/// Get the guild's welcome screen.
#[must_use = "requests must be configured and executed"]
pub struct GetGuildWelcomeScreen<'a> {
guild_id: Id<GuildMarker>,
http: &'a Client,
}
impl<'a> GetGuildWelcomeScreen<'a> {
pub(crate) const fn new(http: &'a Client, guild_id: Id<GuildMarker>) -> Self {
Self { guild_id, http }
}
/// Execute the request, returning a future resolving to a [`Response`].
///
/// [`Response`]: crate::response::Response
pub fn exec(self) -> ResponseFuture<WelcomeScreen> {
let http = self.http;
match self.try_into_request() {
Ok(request) => http.request(request),
Err(source) => ResponseFuture::error(source),
}
}
}
impl TryIntoRequest for GetGuildWelcomeScreen<'_> {
fn try_into_request(self) -> Result<Request, Error> {
Ok(Request::from_route(&Route::GetGuildWelcomeScreen {
guild_id: self.guild_id.get(),
}))
}
}
| 26.733333 | 82 | 0.624273 |
21b210e4647b09ff5b5fb1fcd36a8b9d189b1df1
| 9,571 |
//! Mutex (Spin, SpinNoIrq, Thread)
//!
//! Modified from spin::mutex.
//!
//! 一个可替换底层支持的锁框架。
//!
//! # 在此框架下实现了以下几种锁
//!
//! * `SpinLock`: 自旋锁。
//! 等价于`spin::Mutex`,相当于Linux中的`spin_lock`。
//! 当获取锁失败时,忙等待。
//! 由于没有禁用内核抢占和中断,在单处理器上使用可能发生死锁。
//!
//! * `SpinNoIrqLock`: 禁止中断的自旋锁。
//! 相当于Linux中的`spin_lock_irqsave`。
//! 在尝试获取锁之前禁用中断,在try_lock失败/解锁时恢复之前的中断状态。
//! 可被用于中断处理中,不会发生死锁。
//!
//! * `ThreadLock`: 线程调度锁。
//! 等价于`std::sync::Mutex`,依赖于`thread`模块提供线程调度支持。
//! 在获取锁失败时,将自己加入等待队列,让出CPU;在解锁时,唤醒一个等待队列中的线程。
//!
//! # 实现方法
//!
//! 由一个struct提供底层支持,它impl trait `MutexSupport`,并嵌入`Mutex`中。
//! `MutexSupport`提供了若干接口,它们会在操作锁的不同时间点被调用。
//! 注意这个接口实际是取了几种实现的并集,并不是很通用。
use super::Condvar;
use crate::arch::interrupt;
use crate::processor;
use core::cell::UnsafeCell;
use core::fmt;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicBool, AtomicU8, Ordering};
pub type SpinLock<T> = Mutex<T, Spin>;
pub type SpinNoIrqLock<T> = Mutex<T, SpinNoIrq>;
pub type SleepLock<T> = Mutex<T, Condvar>;
pub struct Mutex<T: ?Sized, S: MutexSupport> {
lock: AtomicBool,
support: MaybeUninit<S>,
support_initialization: AtomicU8, // 0 = uninitialized, 1 = initializing, 2 = initialized
user: UnsafeCell<(usize, usize)>, // (cid, tid)
data: UnsafeCell<T>,
}
/// A guard to which the protected data can be accessed
///
/// When the guard falls out of scope it will release the lock.
pub struct MutexGuard<'a, T: ?Sized + 'a, S: MutexSupport + 'a> {
pub(super) mutex: &'a Mutex<T, S>,
support_guard: S::GuardData,
}
// Same unsafe impls as `std::sync::Mutex`
unsafe impl<T: ?Sized + Send, S: MutexSupport> Sync for Mutex<T, S> {}
unsafe impl<T: ?Sized + Send, S: MutexSupport> Send for Mutex<T, S> {}
impl<T, S: MutexSupport> Mutex<T, S> {
/// Creates a new spinlock wrapping the supplied data.
///
/// May be used statically:
///
/// ```
/// #![feature(const_fn)]
/// use spin;
///
/// static MUTEX: spin::Mutex<()> = spin::Mutex::new(());
///
/// fn demo() {
/// let lock = MUTEX.lock();
/// // do something with lock
/// drop(lock);
/// }
/// ```
pub const fn new(user_data: T) -> Mutex<T, S> {
Mutex {
lock: AtomicBool::new(false),
data: UnsafeCell::new(user_data),
support: MaybeUninit::uninit(),
support_initialization: AtomicU8::new(0),
user: UnsafeCell::new((0, 0)),
}
}
/// Consumes this mutex, returning the underlying data.
pub fn into_inner(self) -> T {
// We know statically that there are no outstanding references to
// `self` so there's no need to lock.
let Mutex { data, .. } = self;
data.into_inner()
}
}
impl<T: ?Sized, S: MutexSupport> Mutex<T, S> {
fn obtain_lock(&self) {
while self.lock.compare_and_swap(false, true, Ordering::Acquire) != false {
let mut try_count = 0;
// Wait until the lock looks unlocked before retrying
while self.lock.load(Ordering::Relaxed) {
unsafe { &*self.support.as_ptr() }.cpu_relax();
try_count += 1;
if try_count == 0x100000 {
let (cid, tid) = unsafe { *self.user.get() };
error!(
"Mutex: deadlock detected! locked by cpu {} thread {} @ {:?}",
cid, tid, self as *const Self
);
}
}
}
let cid = crate::arch::cpu::id();
let tid = processor().tid_option().unwrap_or(0);
unsafe { self.user.get().write((cid, tid)) };
}
/// Locks the spinlock and returns a guard.
///
/// The returned value may be dereferenced for data access
/// and the lock will be dropped when the guard falls out of scope.
///
/// ```
/// let mylock = spin::Mutex::new(0);
/// {
/// let mut data = mylock.lock();
/// // The lock is now locked and the data can be accessed
/// *data += 1;
/// // The lock is implicitly dropped
/// }
///
/// ```
pub fn lock(&self) -> MutexGuard<T, S> {
let support_guard = S::before_lock();
self.ensure_support();
self.obtain_lock();
MutexGuard {
mutex: self,
support_guard,
}
}
pub fn ensure_support(&self) {
let initialization = self.support_initialization.load(Ordering::Relaxed);
if initialization == 2 {
return;
};
if initialization == 1
|| self
.support_initialization
.compare_and_swap(0, 1, Ordering::Acquire)
!= 0
{
// Wait for another thread to initialize
while self.support_initialization.load(Ordering::Acquire) == 1 {
core::sync::atomic::spin_loop_hint();
}
} else {
// My turn to initialize
(unsafe { core::ptr::write(self.support.as_ptr() as *mut _, S::new()) });
self.support_initialization.store(2, Ordering::Release);
}
}
/// Force unlock the spinlock.
///
/// This is *extremely* unsafe if the lock is not held by the current
/// thread. However, this can be useful in some instances for exposing the
/// lock to FFI that doesn't know how to deal with RAII.
///
/// If the lock isn't held, this is a no-op.
pub unsafe fn force_unlock(&self) {
self.lock.store(false, Ordering::Release);
}
/// Tries to lock the mutex. If it is already locked, it will return None. Otherwise it returns
/// a guard within Some.
pub fn try_lock(&self) -> Option<MutexGuard<T, S>> {
let support_guard = S::before_lock();
if self.lock.compare_and_swap(false, true, Ordering::Acquire) == false {
Some(MutexGuard {
mutex: self,
support_guard,
})
} else {
None
}
}
}
impl<T: ?Sized + fmt::Debug, S: MutexSupport + fmt::Debug> fmt::Debug for Mutex<T, S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.try_lock() {
Some(guard) => write!(
f,
"Mutex {{ data: {:?}, support: {:?} }}",
&*guard, self.support
),
None => write!(f, "Mutex {{ <locked>, support: {:?} }}", self.support),
}
}
}
impl<T: ?Sized + Default, S: MutexSupport> Default for Mutex<T, S> {
fn default() -> Mutex<T, S> {
Mutex::new(Default::default())
}
}
impl<'a, T: ?Sized, S: MutexSupport> Deref for MutexGuard<'a, T, S> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.mutex.data.get() }
}
}
impl<'a, T: ?Sized, S: MutexSupport> DerefMut for MutexGuard<'a, T, S> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.mutex.data.get() }
}
}
impl<'a, T: ?Sized, S: MutexSupport> Drop for MutexGuard<'a, T, S> {
/// The dropping of the MutexGuard will release the lock it was created from.
fn drop(&mut self) {
self.mutex.lock.store(false, Ordering::Release);
unsafe { &*self.mutex.support.as_ptr() }.after_unlock();
}
}
/// Low-level support for mutex
pub trait MutexSupport {
type GuardData;
fn new() -> Self;
/// Called when failing to acquire the lock
fn cpu_relax(&self);
/// Called before lock() & try_lock()
fn before_lock() -> Self::GuardData;
/// Called when MutexGuard dropping
fn after_unlock(&self);
}
/// Spin lock
#[derive(Debug)]
pub struct Spin;
impl MutexSupport for Spin {
type GuardData = ();
fn new() -> Self {
Spin
}
fn cpu_relax(&self) {
unsafe {
#[cfg(target_arch = "x86_64")]
asm!("pause" :::: "volatile");
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64", target_arch = "mips"))]
asm!("nop" :::: "volatile");
#[cfg(target_arch = "aarch64")]
asm!("yield" :::: "volatile");
}
}
fn before_lock() -> Self::GuardData {}
fn after_unlock(&self) {}
}
/// Spin & no-interrupt lock
#[derive(Debug)]
pub struct SpinNoIrq;
/// Contains RFLAGS before disable interrupt, will auto restore it when dropping
pub struct FlagsGuard(usize);
impl Drop for FlagsGuard {
fn drop(&mut self) {
unsafe { interrupt::restore(self.0) };
}
}
impl FlagsGuard {
pub fn no_irq_region() -> Self {
Self(unsafe { interrupt::disable_and_store() })
}
}
impl MutexSupport for SpinNoIrq {
type GuardData = FlagsGuard;
fn new() -> Self {
SpinNoIrq
}
fn cpu_relax(&self) {
unsafe {
#[cfg(target_arch = "x86_64")]
asm!("pause" :::: "volatile");
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64", target_arch = "mips"))]
asm!("nop" :::: "volatile");
#[cfg(target_arch = "aarch64")]
asm!("yield" :::: "volatile");
}
}
fn before_lock() -> Self::GuardData {
FlagsGuard(unsafe { interrupt::disable_and_store() })
}
fn after_unlock(&self) {}
}
impl MutexSupport for Condvar {
type GuardData = ();
fn new() -> Self {
Condvar::new()
}
fn cpu_relax(&self) {
self._wait();
}
fn before_lock() -> Self::GuardData {}
fn after_unlock(&self) {
self.notify_one();
}
}
| 29.449231 | 99 | 0.553547 |
1c8060697241bc64c2800e7588ebd5b41d4c52e6
| 2,242 |
#![doc = "generated by AutoRust 0.1.0"]
#[cfg(feature = "1.6")]
mod v1_6;
use azure_core::setters;
#[cfg(feature = "1.6")]
pub use v1_6::{models, operations, API_VERSION};
pub fn config(
http_client: std::sync::Arc<dyn azure_core::HttpClient>,
token_credential: Box<dyn azure_core::TokenCredential>,
) -> OperationConfigBuilder {
OperationConfigBuilder {
api_version: None,
http_client,
base_path: None,
token_credential,
token_credential_resource: None,
}
}
pub struct OperationConfigBuilder {
api_version: Option<String>,
http_client: std::sync::Arc<dyn azure_core::HttpClient>,
base_path: Option<String>,
token_credential: Box<dyn azure_core::TokenCredential>,
token_credential_resource: Option<String>,
}
impl OperationConfigBuilder {
setters! { api_version : String => Some (api_version) , base_path : String => Some (base_path) , token_credential_resource : String => Some (token_credential_resource) , }
pub fn build(self) -> OperationConfig {
OperationConfig {
api_version: self.api_version.unwrap_or(API_VERSION.to_owned()),
http_client: self.http_client,
base_path: self.base_path.unwrap_or("https://management.azure.com".to_owned()),
token_credential: Some(self.token_credential),
token_credential_resource: self.token_credential_resource.unwrap_or("https://management.azure.com/".to_owned()),
}
}
}
pub struct OperationConfig {
api_version: String,
http_client: std::sync::Arc<dyn azure_core::HttpClient>,
base_path: String,
token_credential: Option<Box<dyn azure_core::TokenCredential>>,
token_credential_resource: String,
}
impl OperationConfig {
pub fn api_version(&self) -> &str {
self.api_version.as_str()
}
pub fn http_client(&self) -> &dyn azure_core::HttpClient {
self.http_client.as_ref()
}
pub fn base_path(&self) -> &str {
self.base_path.as_str()
}
pub fn token_credential(&self) -> Option<&dyn azure_core::TokenCredential> {
self.token_credential.as_deref()
}
pub fn token_credential_resource(&self) -> &str {
self.token_credential_resource.as_str()
}
}
| 36.16129 | 175 | 0.68198 |
e9d3bc274035ec5c6e6df7e00ae219aefa8e1a6e
| 1,982 |
pub mod item;
use crate::error::FeedError;
use self::item::{FeedItem, Item, Source};
use std::{cmp::Reverse, io::BufRead};
#[derive(Debug)]
pub enum Feed {
Rss(rss::Channel),
Atom(atom_syndication::Feed),
}
impl<'a> Feed {
pub fn read_from<R>(reader: R) -> Result<Self, FeedError>
where
R: BufRead + Copy,
{
let feed = match rss::Channel::read_from(reader) {
Ok(channel) => Self::Rss(channel),
Err(e) => match e {
rss::Error::InvalidStartTag => {
let feed = atom_syndication::Feed::read_from(reader)?;
Self::Atom(feed)
}
_ => return Err(e.into()),
},
};
Ok(feed)
}
pub fn title(&self) -> &str {
match self {
Feed::Rss(c) => &c.title,
Feed::Atom(f) => &f.title.value,
}
}
pub fn link(&self) -> Option<&str> {
match self {
Feed::Rss(c) => Some(c.link()),
Feed::Atom(f) => f
.links()
.iter()
.find(|s| s.rel() == "alternate")
.map(|s| s.href()),
}
}
pub fn items(&'a self) -> Vec<Item<'a>> {
let source: Source<'a> = Source {
title: self.title(),
url: self.link(),
};
let mut items: Vec<Item<'a>> = match self {
Feed::Rss(c) => c
.items()
.iter()
.map(|v| Item::Rss {
source: source.clone(),
item: v,
})
.collect(),
Feed::Atom(f) => f
.entries()
.iter()
.map(|v| Item::Atom {
source: source.clone(),
entry: v,
})
.collect(),
};
items.sort_unstable_by_key(|v| Reverse(v.date()));
items
}
}
| 24.170732 | 74 | 0.401615 |
3a598e2db947cfd68540ad0ae5f1214c8ec72995
| 7,048 |
use super::impact_with_leaf_octant;
use crate::{OctreeDbvt, OctreeDbvtVisitor, VoxelImpact};
use building_blocks_core::prelude::*;
use building_blocks_storage::prelude::VisitStatus;
use core::hash::Hash;
use nalgebra::{self as na, zero, Isometry3, Translation3, UnitQuaternion};
use ncollide3d::{
bounding_volume::{BoundingVolume, HasBoundingVolume, AABB},
query::{time_of_impact, DefaultTOIDispatcher, Ray, TOIStatus, TOI},
shape::{Ball, Cuboid},
};
/// The impact of a ball with an `OctreeDbvt`.
pub type VoxelBallImpact = VoxelImpact<TOI<f32>>;
/// Casts a ball of `radius` along `ray` and returns the coordinates of the first voxel that intersects the ball. Voxels are
/// modeled as axis-aligned bounding boxes (AABBs).
///
/// `ray.dir` is the velocity vector of the ball, and any collisions that would occur after `max_toi` will not be considered.
///
/// `predicate` can be used to filter voxels by returning `false`.
pub fn cast_ball_at_voxels<K>(
octree: &OctreeDbvt<K>,
radius: f32,
ray: Ray<f32>,
max_toi: f32,
predicate: impl Fn(Point3i) -> bool,
) -> Option<VoxelBallImpact>
where
K: Eq + Hash,
{
let mut visitor = VoxelSBallCast::new(radius, ray, max_toi, predicate);
octree.visit(&mut visitor);
visitor.earliest_impact
}
struct VoxelSBallCast<F> {
earliest_impact: Option<VoxelImpact<TOI<f32>>>,
ball: Ball<f32>,
ball_start_isom: Isometry3<f32>,
ray: Ray<f32>,
max_toi: f32,
ball_path_aabb: AABB<f32>,
predicate: F,
}
impl<F> VoxelSBallCast<F> {
fn new(radius: f32, ray: Ray<f32>, max_toi: f32, predicate: F) -> Self {
let ball = Ball::new(radius);
let start = ray.origin;
let end = ray.point_at(max_toi);
let ball_start_isom =
Isometry3::from_parts(Translation3::from(start.coords), UnitQuaternion::identity());
let ball_end_isom =
Isometry3::from_parts(Translation3::from(end.coords), UnitQuaternion::identity());
// Make an AABB that bounds the ball through its entire path.
let ball_start_aabb: AABB<f32> = ball.bounding_volume(&ball_start_isom);
let ball_end_aabb: AABB<f32> = ball.bounding_volume(&ball_end_isom);
let ball_path_aabb = ball_start_aabb.merged(&ball_end_aabb);
Self {
earliest_impact: None,
ball,
ball_start_isom,
ray,
max_toi,
ball_path_aabb,
predicate,
}
}
fn earliest_toi(&self) -> f32 {
self.earliest_impact
.as_ref()
.map(|i| i.impact.toi)
.unwrap_or(std::f32::INFINITY)
}
}
impl<F> OctreeDbvtVisitor for VoxelSBallCast<F>
where
F: Fn(Point3i) -> bool,
{
fn visit(&mut self, aabb: &AABB<f32>, octant: Option<&Octant>, is_leaf: bool) -> VisitStatus {
if !self.ball_path_aabb.intersects(aabb) {
// The ball couldn't intersect any voxels in this AABB, because it doesn't even intersect the AABB that bounds the
// ball's path.
return VisitStatus::Stop;
}
if let Some(octant) = octant {
// Cast a ball at this octant.
let octant_extent = Extent3i::from(*octant);
let voxel_velocity = na::Vector3::zeros();
let target_distance = 0.0;
if let Some(impact) = time_of_impact(
&DefaultTOIDispatcher,
&self.ball_start_isom,
&self.ray.dir,
&self.ball,
&extent3i_cuboid_transform(&octant_extent),
&voxel_velocity,
&extent3i_cuboid(&octant_extent),
self.max_toi,
target_distance,
)
// Unsupported shape queries return Err
.unwrap()
{
if impact.status != TOIStatus::Converged {
// Something bad happened with the TOI algorithm. Let's just keep going down this branch and hope it gets
// better. If we're at a leaf, we won't consider this a legitimate impact.
return VisitStatus::Continue;
}
if is_leaf && impact.toi < self.earliest_toi() {
// The contact point is the center of the ball plus the ball's "local witness."
let contact = self.ray.point_at(impact.toi) + impact.witness1.coords;
let point = impact_with_leaf_octant(&octant, &contact, &impact.normal2);
if (self.predicate)(point) {
self.earliest_impact = Some(VoxelImpact { point, impact });
}
}
} else {
// The ball won't intersect this octant.
return VisitStatus::Stop;
}
}
VisitStatus::Continue
}
}
fn extent3i_cuboid(e: &Extent3i) -> Cuboid<f32> {
Cuboid::new(half_extent(e.shape))
}
fn extent3i_cuboid_transform(e: &Extent3i) -> Isometry3<f32> {
let min = na::Point3::from(Point3f::from(e.minimum));
let center = min + half_extent(e.shape);
Isometry3::new(center.coords, zero())
}
fn half_extent(shape: Point3i) -> na::Vector3<f32> {
na::Vector3::from(Point3f::from(shape)) / 2.0
}
// ████████╗███████╗███████╗████████╗
// ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝
// ██║ █████╗ ███████╗ ██║
// ██║ ██╔══╝ ╚════██║ ██║
// ██║ ███████╗███████║ ██║
// ╚═╝ ╚══════╝╚══════╝ ╚═╝
#[cfg(test)]
mod tests {
use super::*;
use crate::collision::test_util::*;
use ncollide3d::na;
#[test]
fn ball_cast_hits_expected_voxel() {
let bvt = bvt_with_voxels_filled(&[PointN([0, 0, 0]), PointN([0, 15, 0])]);
// Cast ball at the corners.
let start = na::Point3::new(-1.0, -1.0, -1.0);
let radius = 0.5;
let ray = Ray::new(start, na::Point3::new(0.5, 0.5, 0.5) - start);
let result = cast_ball_at_voxels(&bvt, radius, ray, std::f32::INFINITY, |_| true).unwrap();
assert_eq!(result.point, PointN([0, 0, 0]));
let ray = Ray::new(start, na::Point3::new(0.0, 15.5, 0.0) - start);
let result = cast_ball_at_voxels(&bvt, radius, ray, std::f32::INFINITY, |_| true).unwrap();
assert_eq!(result.point, PointN([0, 15, 0]));
// Cast into the middle where we shouldn't hit anything.
let ray = Ray::new(start, na::Point3::new(0.0, 3.0, 0.0) - start);
let result = cast_ball_at_voxels(&bvt, radius, ray, std::f32::INFINITY, |_| true);
assert!(result.is_none());
}
#[test]
fn ball_cast_hits_expected_voxel_for_collapsed_leaf() {
let bvt = bvt_with_all_voxels_filled();
let start = na::Point3::new(-1.0, -1.0, -1.0);
let radius = 0.5;
let ray = Ray::new(start, na::Point3::new(0.5, 0.5, 0.5) - start);
let result = cast_ball_at_voxels(&bvt, radius, ray, std::f32::INFINITY, |_| true).unwrap();
assert_eq!(result.point, PointN([0, 0, 0]));
}
}
| 34.213592 | 126 | 0.577611 |
89006477f8878e96112ea0a31d44e37def65eefb
| 12,666 |
// Copyright 2019 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.
use crate::connect;
use crate::connection::BootstrapGroupMaker;
use crate::context::ctx;
pub fn start() {
let (proxies, event_tx): (Vec<_>, _) = ctx(|c| {
(
c.bootstrap_cache
.peers()
.iter()
.rev()
.chain(c.bootstrap_cache.hard_coded_contacts().iter())
.cloned()
.collect(),
c.event_tx.clone(),
)
});
let maker = BootstrapGroupMaker::new(event_tx);
for proxy in proxies {
let _ = connect::connect_to(proxy, None, Some(&maker));
}
}
#[cfg(test)]
mod tests {
use crate::test_utils::new_random_qp2p;
use crate::{Builder, Config, Event, NodeInfo, OurType, QuicP2p};
use crossbeam_channel as mpmc;
use std::collections::{HashSet, VecDeque};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
use std::thread;
use std::time::Duration;
use unwrap::unwrap;
// Try to bootstrap to 4 different peer sequentially. Use an artificial delay for 3 of the peers.
// Make sure in the end we have only one bootstrapped connection (all other connections are
// supposed to be dropped).
#[test]
fn bootstrap_to_only_one_node_with_delays() {
test_bootstrap_to_multiple_peers(4, Some(10));
}
// Try to bootstrap to 4 different peer at once.
// Make sure in the end we have only one bootstrapped connection (all other connections are
// supposed to be dropped).
#[test]
fn bootstrap_to_only_one_node_without_delays() {
test_bootstrap_to_multiple_peers(4, None);
}
fn test_bootstrap_to_multiple_peers(num_conns: u64, delay_ms: Option<u64>) {
let mut bs_nodes = Vec::with_capacity(num_conns as usize);
let mut bs_peer_addrs = HashSet::with_capacity(num_conns as usize);
let mut hcc_contacts = HashSet::with_capacity(num_conns as usize);
// Spin up 4 peers that we'll use for hardcoded contacts.
for i in 0..num_conns {
let (mut qp2p, rx) = new_random_qp2p(false, Default::default());
if let Some(delay_ms) = delay_ms {
qp2p.set_connect_delay(i * delay_ms);
}
let ci_info = unwrap!(qp2p.our_connection_info());
assert!(bs_peer_addrs.insert(ci_info.peer_addr));
assert!(hcc_contacts.insert(ci_info));
bs_nodes.push((rx, qp2p));
}
// Create a client and bootstrap to 4 of the peers we created previously.
let (mut qp2p0, rx0) = new_random_qp2p(false, hcc_contacts);
qp2p0.bootstrap();
match unwrap!(rx0.recv()) {
Event::BootstrappedTo { node, .. } => {
assert!(bs_peer_addrs.contains(&node.peer_addr));
}
ev => panic!("Unexpected event: {:?}", ev),
}
thread::sleep(Duration::from_millis(if let Some(delay_ms) = delay_ms {
num_conns * delay_ms + delay_ms
} else {
100
}));
// We expect only 1 bootstrap connection to succeed.
let conns_count = unwrap!(qp2p0.connections(|c| {
c.iter()
.filter(|(_pa, conn)| conn.to_peer.is_established())
.count()
}));
assert_eq!(conns_count, 1);
}
// Try to bootstrap to hardcoded contacts and cached peers at once.
// Bootstrap cache should be prioritised in this case.
#[test]
fn bootstrap_prioritise_cache() {
// Total number of nodes (half for hardcoded contacts, half for the bootstrap cache).
const NODES_COUNT: u64 = 8;
// Initialise nodes for the bootstrap cache and for hardcoded contacts
let mut hcc_nodes = Vec::with_capacity(NODES_COUNT as usize / 2);
let mut bootstrap_cache_nodes = Vec::with_capacity(NODES_COUNT as usize / 2);
for _i in 0..(NODES_COUNT / 2) {
let (qp2p, rx) = test_node();
bootstrap_cache_nodes.push((qp2p, rx));
let (qp2p, rx) = test_node();
hcc_nodes.push((qp2p, rx));
}
let bootstrap_cache: VecDeque<NodeInfo> = bootstrap_cache_nodes
.iter_mut()
.map(|(node, _)| unwrap!(node.our_connection_info()))
.collect();
let hard_coded_contacts: HashSet<NodeInfo> = hcc_nodes
.iter_mut()
.map(|(node, _)| unwrap!(node.our_connection_info()))
.collect();
// Waiting for all nodes to start
let (ev_tx, ev_rx) = mpmc::unbounded();
let mut bootstrapping_node = unwrap!(Builder::new(ev_tx)
.with_config(Config {
port: Some(0),
ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
hard_coded_contacts: hard_coded_contacts.clone(),
our_type: OurType::Client,
..Default::default()
})
.with_proxies(bootstrap_cache.clone(), true,)
.build());
bootstrapping_node.bootstrap();
for event in ev_rx.iter() {
if let Event::BootstrappedTo { .. } = event {
let attempted_conns = unwrap!(bootstrapping_node.attempted_connections());
assert_eq!(
&attempted_conns[0..(NODES_COUNT as usize / 2)],
bootstrap_cache
.iter()
.map(|node| node.peer_addr)
.rev()
.collect::<Vec<_>>()
.as_slice()
);
break;
}
}
}
// Test that bootstrap fails after a handshake timeout if none of the peers
// that we're bootstrapping to have responded.
#[test]
fn bootstrap_failure() {
let (mut bootstrap_node, _rx) = test_node();
bootstrap_node.set_connect_delay(100);
let bootstrap_ci = unwrap!(bootstrap_node.our_connection_info());
let mut hcc = HashSet::with_capacity(1);
assert!(hcc.insert(bootstrap_ci.clone()));
let (ev_tx, ev_rx) = mpmc::unbounded();
let mut bootstrap_client = unwrap!(Builder::new(ev_tx)
.with_config(Config {
port: Some(0),
ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
hard_coded_contacts: hcc,
our_type: OurType::Node,
idle_timeout_msec: Some(30),
..Default::default()
})
.with_proxies(Default::default(), true)
.build());
bootstrap_client.bootstrap();
match unwrap!(ev_rx.recv()) {
Event::BootstrapFailure => (),
ev => {
panic!("Unexpected event: {:?}", ev);
}
}
}
#[test]
fn node_will_attempt_hard_coded_contacts() {
let (mut peer1, _) = test_node();
let peer1_conn_info = unwrap!(peer1.our_connection_info());
let (mut peer2, ev_rx) = {
let mut hcc = HashSet::new();
assert!(hcc.insert(peer1_conn_info.clone()));
test_peer_with_hcc(hcc, OurType::Node)
};
peer2.bootstrap();
let peer2_conn_info = unwrap!(peer2.our_connection_info());
for event in ev_rx.iter() {
if let Event::BootstrappedTo { node } = event {
assert_eq!(node, peer1_conn_info);
break;
}
}
let is_peer1_state_valid = unwrap!(peer1.connections(move |c| {
c[&peer2_conn_info.peer_addr].from_peer.is_established()
&& c[&peer2_conn_info.peer_addr].to_peer.is_established()
}));
assert!(is_peer1_state_valid);
let is_peer2_state_valid = unwrap!(peer2.connections(move |c| {
c[&peer1_conn_info.peer_addr].to_peer.is_established()
&& c[&peer1_conn_info.peer_addr].from_peer.is_established()
}));
assert!(is_peer2_state_valid);
}
#[test]
fn client_will_attempt_hard_coded_contacts() {
let (mut peer1, _) = test_node();
let peer1_conn_info = unwrap!(peer1.our_connection_info());
let (mut peer2, ev_rx) = {
let mut hcc = HashSet::new();
assert!(hcc.insert(peer1_conn_info.clone()));
test_peer_with_hcc(hcc, OurType::Client)
};
peer2.bootstrap();
let peer2_conn_info = unwrap!(peer2.our_connection_info());
for event in ev_rx.iter() {
if let Event::BootstrappedTo { node } = event {
assert_eq!(node, peer1_conn_info);
break;
}
}
let is_peer1_state_valid = unwrap!(peer1.connections(move |c| {
c[&peer2_conn_info.peer_addr].from_peer.is_established()
&& c[&peer2_conn_info.peer_addr].to_peer.is_not_needed()
}));
assert!(is_peer1_state_valid);
let is_peer2_state_valid = unwrap!(peer2.connections(move |c| {
c[&peer1_conn_info.peer_addr].to_peer.is_established()
&& c[&peer1_conn_info.peer_addr].from_peer.is_not_needed()
}));
assert!(is_peer2_state_valid);
}
#[test]
fn node_will_attempt_cached_peers() {
let (mut peer1, _) = test_node();
let peer1_conn_info = unwrap!(peer1.our_connection_info());
let (mut peer2, ev_rx) = test_peer_with_bootstrap_cache(vec![peer1_conn_info.clone()]);
peer2.bootstrap();
for event in ev_rx.iter() {
if let Event::BootstrappedTo { node } = event {
assert_eq!(node, peer1_conn_info);
break;
}
}
}
#[test]
fn node_will_report_failure_when_bootstrap_cache_and_hard_coded_contacts_are_empty() {
let (mut peer, ev_rx) = test_node();
peer.bootstrap();
for event in ev_rx.iter() {
if let Event::BootstrapFailure = event {
break;
}
}
}
#[test]
fn node_will_report_failure_when_bootstrap_cache_and_hard_coded_contacts_are_invalid() {
let dummy_peer_info = NodeInfo {
peer_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 37692)),
peer_cert_der: vec![1, 2, 3],
};
let (mut peer, ev_rx) = {
let mut hcc = HashSet::new();
assert!(hcc.insert(dummy_peer_info.clone()));
test_peer_with_hcc(hcc, OurType::Node)
};
peer.bootstrap();
for event in ev_rx.iter() {
if let Event::BootstrapFailure = event {
break;
}
}
}
fn test_peer_with_bootstrap_cache(
mut cached_peers: Vec<NodeInfo>,
) -> (QuicP2p, mpmc::Receiver<Event>) {
let cached_peers: VecDeque<_> = cached_peers.drain(..).collect();
let (ev_tx, ev_rx) = mpmc::unbounded();
let builder = Builder::new(ev_tx)
.with_config(Config {
port: Some(0),
ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
..Default::default()
})
.with_proxies(cached_peers, true);
(unwrap!(builder.build()), ev_rx)
}
/// Constructs a `QuicP2p` node with some sane defaults for testing.
fn test_node() -> (QuicP2p, mpmc::Receiver<Event>) {
test_peer_with_hcc(Default::default(), OurType::Node)
}
/// Construct a `QuicP2p` instance with optional set of hardcoded contacts.
fn test_peer_with_hcc(
hard_coded_contacts: HashSet<NodeInfo>,
our_type: OurType,
) -> (QuicP2p, mpmc::Receiver<Event>) {
let (ev_tx, ev_rx) = mpmc::unbounded();
let builder = Builder::new(ev_tx)
.with_config(Config {
port: Some(0),
ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
hard_coded_contacts,
our_type,
..Default::default()
})
// Make sure we start with an empty cache. Otherwise, we might get into unexpected state.
.with_proxies(Default::default(), true);
(unwrap!(builder.build()), ev_rx)
}
}
| 35.183333 | 101 | 0.574451 |
90deff7c70ec6e7f22635954f0bd8902261a35bb
| 15,052 |
/* heatmap - High performance heatmap creation in C.
*
* The MIT License (MIT)
*
* Copyright (c) 2013 Lucas Beyer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include "lodepng.h"
#include "heatmap.h"
#include "colorschemes/gray.h"
#include "colorschemes/Blues.h"
#include "colorschemes/BrBG.h"
#include "colorschemes/BuGn.h"
#include "colorschemes/BuPu.h"
#include "colorschemes/GnBu.h"
#include "colorschemes/Greens.h"
#include "colorschemes/Greys.h"
#include "colorschemes/Oranges.h"
#include "colorschemes/OrRd.h"
#include "colorschemes/PiYG.h"
#include "colorschemes/PRGn.h"
#include "colorschemes/PuBuGn.h"
#include "colorschemes/PuBu.h"
#include "colorschemes/PuOr.h"
#include "colorschemes/PuRd.h"
#include "colorschemes/Purples.h"
#include "colorschemes/RdBu.h"
#include "colorschemes/RdGy.h"
#include "colorschemes/RdPu.h"
#include "colorschemes/RdYlBu.h"
#include "colorschemes/RdYlGn.h"
#include "colorschemes/Reds.h"
#include "colorschemes/Spectral.h"
#include "colorschemes/YlGnBu.h"
#include "colorschemes/YlGn.h"
#include "colorschemes/YlOrBr.h"
#include "colorschemes/YlOrRd.h"
// Too bad C++ doesn't have nice mad reflection skillz!
std::map<std::string, const heatmap_colorscheme_t*> g_schemes = {
{"b2w", heatmap_cs_b2w},
{"b2w_opaque", heatmap_cs_b2w_opaque},
{"w2b", heatmap_cs_w2b},
{"w2b_opaque", heatmap_cs_w2b_opaque},
{"Blues_discrete", heatmap_cs_Blues_discrete},
{"Blues_soft", heatmap_cs_Blues_soft},
{"Blues_mixed", heatmap_cs_Blues_mixed},
{"Blues_mixed_exp", heatmap_cs_Blues_mixed_exp},
{"BrBG_discrete", heatmap_cs_BrBG_discrete},
{"BrBG_soft", heatmap_cs_BrBG_soft},
{"BrBG_mixed", heatmap_cs_BrBG_mixed},
{"BrBG_mixed_exp", heatmap_cs_BrBG_mixed_exp},
{"BuGn_discrete", heatmap_cs_BuGn_discrete},
{"BuGn_soft", heatmap_cs_BuGn_soft},
{"BuGn_mixed", heatmap_cs_BuGn_mixed},
{"BuGn_mixed_exp", heatmap_cs_BuGn_mixed_exp},
{"BuPu_discrete", heatmap_cs_BuPu_discrete},
{"BuPu_soft", heatmap_cs_BuPu_soft},
{"BuPu_mixed", heatmap_cs_BuPu_mixed},
{"BuPu_mixed_exp", heatmap_cs_BuPu_mixed_exp},
{"GnBu_discrete", heatmap_cs_GnBu_discrete},
{"GnBu_soft", heatmap_cs_GnBu_soft},
{"GnBu_mixed", heatmap_cs_GnBu_mixed},
{"GnBu_mixed_exp", heatmap_cs_GnBu_mixed_exp},
{"Greens_discrete", heatmap_cs_Greens_discrete},
{"Greens_soft", heatmap_cs_Greens_soft},
{"Greens_mixed", heatmap_cs_Greens_mixed},
{"Greens_mixed_exp", heatmap_cs_Greens_mixed_exp},
{"Greys_discrete", heatmap_cs_Greys_discrete},
{"Greys_soft", heatmap_cs_Greys_soft},
{"Greys_mixed", heatmap_cs_Greys_mixed},
{"Greys_mixed_exp", heatmap_cs_Greys_mixed_exp},
{"Oranges_discrete", heatmap_cs_Oranges_discrete},
{"Oranges_soft", heatmap_cs_Oranges_soft},
{"Oranges_mixed", heatmap_cs_Oranges_mixed},
{"Oranges_mixed_exp", heatmap_cs_Oranges_mixed_exp},
{"OrRd_discrete", heatmap_cs_OrRd_discrete},
{"OrRd_soft", heatmap_cs_OrRd_soft},
{"OrRd_mixed", heatmap_cs_OrRd_mixed},
{"OrRd_mixed_exp", heatmap_cs_OrRd_mixed_exp},
{"PiYG_discrete", heatmap_cs_PiYG_discrete},
{"PiYG_soft", heatmap_cs_PiYG_soft},
{"PiYG_mixed", heatmap_cs_PiYG_mixed},
{"PiYG_mixed_exp", heatmap_cs_PiYG_mixed_exp},
{"PRGn_discrete", heatmap_cs_PRGn_discrete},
{"PRGn_soft", heatmap_cs_PRGn_soft},
{"PRGn_mixed", heatmap_cs_PRGn_mixed},
{"PRGn_mixed_exp", heatmap_cs_PRGn_mixed_exp},
{"PuBuGn_discrete", heatmap_cs_PuBuGn_discrete},
{"PuBuGn_soft", heatmap_cs_PuBuGn_soft},
{"PuBuGn_mixed", heatmap_cs_PuBuGn_mixed},
{"PuBuGn_mixed_exp", heatmap_cs_PuBuGn_mixed_exp},
{"PuBu_discrete", heatmap_cs_PuBu_discrete},
{"PuBu_soft", heatmap_cs_PuBu_soft},
{"PuBu_mixed", heatmap_cs_PuBu_mixed},
{"PuBu_mixed_exp", heatmap_cs_PuBu_mixed_exp},
{"PuOr_discrete", heatmap_cs_PuOr_discrete},
{"PuOr_soft", heatmap_cs_PuOr_soft},
{"PuOr_mixed", heatmap_cs_PuOr_mixed},
{"PuOr_mixed_exp", heatmap_cs_PuOr_mixed_exp},
{"PuRd_discrete", heatmap_cs_PuRd_discrete},
{"PuRd_soft", heatmap_cs_PuRd_soft},
{"PuRd_mixed", heatmap_cs_PuRd_mixed},
{"PuRd_mixed_exp", heatmap_cs_PuRd_mixed_exp},
{"Purples_discrete", heatmap_cs_Purples_discrete},
{"Purples_soft", heatmap_cs_Purples_soft},
{"Purples_mixed", heatmap_cs_Purples_mixed},
{"Purples_mixed_exp", heatmap_cs_Purples_mixed_exp},
{"RdBu_discrete", heatmap_cs_RdBu_discrete},
{"RdBu_soft", heatmap_cs_RdBu_soft},
{"RdBu_mixed", heatmap_cs_RdBu_mixed},
{"RdBu_mixed_exp", heatmap_cs_RdBu_mixed_exp},
{"RdGy_discrete", heatmap_cs_RdGy_discrete},
{"RdGy_soft", heatmap_cs_RdGy_soft},
{"RdGy_mixed", heatmap_cs_RdGy_mixed},
{"RdGy_mixed_exp", heatmap_cs_RdGy_mixed_exp},
{"RdPu_discrete", heatmap_cs_RdPu_discrete},
{"RdPu_soft", heatmap_cs_RdPu_soft},
{"RdPu_mixed", heatmap_cs_RdPu_mixed},
{"RdPu_mixed_exp", heatmap_cs_RdPu_mixed_exp},
{"RdYlBu_discrete", heatmap_cs_RdYlBu_discrete},
{"RdYlBu_soft", heatmap_cs_RdYlBu_soft},
{"RdYlBu_mixed", heatmap_cs_RdYlBu_mixed},
{"RdYlBu_mixed_exp", heatmap_cs_RdYlBu_mixed_exp},
{"RdYlGn_discrete", heatmap_cs_RdYlGn_discrete},
{"RdYlGn_soft", heatmap_cs_RdYlGn_soft},
{"RdYlGn_mixed", heatmap_cs_RdYlGn_mixed},
{"RdYlGn_mixed_exp", heatmap_cs_RdYlGn_mixed_exp},
{"Reds_discrete", heatmap_cs_Reds_discrete},
{"Reds_soft", heatmap_cs_Reds_soft},
{"Reds_mixed", heatmap_cs_Reds_mixed},
{"Reds_mixed_exp", heatmap_cs_Reds_mixed_exp},
{"Spectral_discrete", heatmap_cs_Spectral_discrete},
{"Spectral_soft", heatmap_cs_Spectral_soft},
{"Spectral_mixed", heatmap_cs_Spectral_mixed},
{"Spectral_mixed_exp", heatmap_cs_Spectral_mixed_exp},
{"YlGnBu_discrete", heatmap_cs_YlGnBu_discrete},
{"YlGnBu_soft", heatmap_cs_YlGnBu_soft},
{"YlGnBu_mixed", heatmap_cs_YlGnBu_mixed},
{"YlGnBu_mixed_exp", heatmap_cs_YlGnBu_mixed_exp},
{"YlGn_discrete", heatmap_cs_YlGn_discrete},
{"YlGn_soft", heatmap_cs_YlGn_soft},
{"YlGn_mixed", heatmap_cs_YlGn_mixed},
{"YlGn_mixed_exp", heatmap_cs_YlGn_mixed_exp},
{"YlOrBr_discrete", heatmap_cs_YlOrBr_discrete},
{"YlOrBr_soft", heatmap_cs_YlOrBr_soft},
{"YlOrBr_mixed", heatmap_cs_YlOrBr_mixed},
{"YlOrBr_mixed_exp", heatmap_cs_YlOrBr_mixed_exp},
{"YlOrRd_discrete", heatmap_cs_YlOrRd_discrete},
{"YlOrRd_soft", heatmap_cs_YlOrRd_soft},
{"YlOrRd_mixed", heatmap_cs_YlOrRd_mixed},
{"YlOrRd_mixed_exp", heatmap_cs_YlOrRd_mixed_exp},
};
int main(int argc, char* argv[])
{
clock_t start, mid, mid2, end;
start = clock();
if(argc == 2 && std::string(argv[1]) == "-l") {
for(auto& scheme : g_schemes) {
std::cout << " " << scheme.first << std::endl;
}
return 0;
}
#ifdef FIT_IMAGE
if(argc < 6 || 7 < argc) {
#else
if(argc < 8 || 9 < argc) {
#endif
std::cerr << std::endl << "Invalid number of arguments!" << std::endl;
std::cout << "Usage:" << std::endl;
#ifdef FIT_IMAGE
std::cout << " " << argv[0] << " image_width image_height num_data_cols num_data_rows csv_data_filename [colorscheme]" << std::endl;
#else
std::cout << " " << argv[0] << " image_width image_height tile_ratio_x tile_ratio_y num_data_cols num_data_rows csv_data_filename [colorscheme]" << std::endl;
#endif
std::cout << std::endl;
std::cout << " To get a list of available colorschemes, run" << std::endl;
std::cout << " " << argv[0] << " -l" << std::endl;
std::cout << " The default colorscheme is Spectral_mixed." << std::endl << std::endl;
return 1;
}
const unsigned image_width = atoi(argv[1]), image_height = atoi(argv[2]);
#ifdef FIT_IMAGE
const unsigned num_data_cols = atoi(argv[3]);
const unsigned num_data_rows = atoi(argv[4]);
const char* csv_path = argv[5];
if (image_width < num_data_cols || image_height < num_data_rows) {
std::cerr << std::endl << "Image dimensions must be at least the dimensions of the data." << std::endl;
std::cout << "Specifically, the following must be true: " << std::endl;
std::cout << " image_width > num_data_cols" << std::endl;
std::cout << " image_height > num_data_rows" << std::endl << std::endl;
return 1;
}
// Calculate appropriate sizing for tile
unsigned tile_width = (int) (image_width / (num_data_cols));
// std::cerr << "tile_width: " << tile_width << std::endl;
unsigned tile_height = (int) (image_height / (num_data_rows));
// std::cerr << "tile_height: " << tile_height << std::endl;
if(argc >= 7 && g_schemes.find(argv[6]) == g_schemes.end()) {
std::cerr << "Unknown colorscheme. Run " << argv[0] << " -l for a list of valid ones." << std::endl;
return 1;
}
const heatmap_colorscheme_t* colorscheme = argc == 7 ? g_schemes[argv[6]] : heatmap_cs_default;
#else
const unsigned tile_ratio_x = argc >= 8 ? atoi(argv[3]) : 1;
const unsigned tile_ratio_y = argc >= 8 ? atoi(argv[4]) : 1;
const unsigned num_data_cols = argc >= 8 ? atoi(argv[5]) : atoi(argv[3]);
const unsigned num_data_rows = argc >= 8 ? atoi(argv[6]) : atoi(argv[4]);
const char* csv_path = argv[7];
if (image_width < (tile_ratio_x * num_data_cols) || image_height < (tile_ratio_y * num_data_rows)) {
std::cerr << std::endl << "Image dimensions are not enough to accomodate tile dimensions and amount of data." << std::endl;
std::cout << "Specifically, the following must be true: " << std::endl;
std::cout << " image_width >= (tile_ratio_x * num_data_cols)" << std::endl;
std::cout << " image_height >= (tile_ratio_y * num_data_rows)" << std::endl << std::endl;
return 1;
}
// Calculate appropiate sizing for tile
unsigned max_x_scaling_factor = (int) (image_width / (num_data_cols * tile_ratio_x));
// std::cerr << "max_x_scaling_factor: " << max_x_scaling_factor << std::endl;
unsigned max_y_scaling_factor = (int) (image_height / (num_data_rows * tile_ratio_y));
// std::cerr << "max_y_scaling_factor: " << max_y_scaling_factor << std::endl;
unsigned scaling_factor = std::min(max_x_scaling_factor,max_y_scaling_factor);
// std::cerr << "scaling_factor: " << scaling_factor << std::endl;
unsigned tile_width = scaling_factor * tile_ratio_x;
// std::cerr << "tile_width: " << tile_width << std::endl;
unsigned tile_height = scaling_factor * tile_ratio_y;
// std::cerr << "tile_height: " << tile_height << std::endl;
if(argc >= 9 && g_schemes.find(argv[8]) == g_schemes.end()) {
std::cerr << "Unknown colorscheme. Run " << argv[0] << " -l for a list of valid ones." << std::endl;
return 1;
}
const heatmap_colorscheme_t* colorscheme = argc == 9 ? g_schemes[argv[8]] : heatmap_cs_default;
#endif
std::ifstream ifile;
ifile.open(csv_path);
if(!ifile) {
std::cerr << "CSV file does not exist at given filepath" << std::endl;
return 1;
}
unsigned updated_image_width = tile_width * num_data_cols;
// std::cerr << "updated_image_width: " << updated_image_width << std::endl;
unsigned updated_image_height = tile_height * num_data_rows;
// std::cerr << "updated_image_height: " << updated_image_height << std::endl;
heatmap_t* hm = heatmap_new(updated_image_width, updated_image_height);
heatmap_stamp_t* tile = heatmap_stamp_gen(tile_width, tile_height);
unsigned int x, y;
float weight;
unsigned int row_num = 0;
std::ifstream data(csv_path);
std::string line;
while(std::getline(data,line))
{
std::stringstream lineStream(line);
std::string cell;
if (row_num == 0){
row_num += 1;
continue;
}
y = (row_num - 0.5) * tile_height;
int col_num = 0;
while(std::getline(lineStream,cell,','))
{
if (col_num == 0){
col_num += 1;
continue;
}
x = (col_num - 0.5) * tile_width;
weight = std::stof(cell);
if(x < updated_image_width && y < updated_image_height) {
heatmap_add_weighted_point_with_stamp(hm, x, y, weight, tile);
} else {
std::cerr << "Warning: Skipping out-of-bound input coordinate: (" << x << "," << y << ")." << std::endl;
}
col_num += 1;
}
row_num += 1;
}
heatmap_stamp_free(tile);
std::vector<unsigned char> image(updated_image_width*updated_image_height*4);
heatmap_render_to(hm, colorscheme, &image[0]);
heatmap_free(hm);
std::vector<unsigned char> png;
mid = clock();
double time_taken_1 = double(mid - start) / double(CLOCKS_PER_SEC);
mid2 = clock();
if(unsigned error = lodepng::encode(png, image, updated_image_width, updated_image_height)) {
std::cerr << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
return 1;
}
// lodepng::save_file(png, output_png_name);
std::cout.write((char*)&png[0], png.size());
end = clock();
double time_taken_2 = double(end - mid2) / double(CLOCKS_PER_SEC);
double time_taken_overall = time_taken_1 + time_taken_2;
std::cerr << "Overall time taken by program is : " << std::fixed
<< time_taken_overall << std::setprecision(5);
std::cerr << " sec " << std::endl;
std::cerr << "Without png generation (first half) : " << std::fixed
<< time_taken_1 << std::setprecision(5);
std::cerr << " sec " << std::endl;
std::cerr << "PNG generation (second half) : " << std::fixed
<< time_taken_2 << std::setprecision(5);
std::cerr << " sec " << std::endl;
return 0;
}
| 40.902174 | 167 | 0.674661 |
bbcab9c0560e0fa55352bc19fe011e17622ed25b
| 330 |
use std::rc::Rc;
use pentago::board;
use pentago::board::Board;
#[derive(Debug, Clone)]
pub struct Game {
pub victory: u8,
pub board: Board
}
impl Game {
pub fn new(dim: u8, length: u8, victory: u8) -> Game {
Game {
victory: victory,
board: Board::new(dim, length)
}
}
}
| 16.5 | 58 | 0.548485 |
38a98107e3e3872acd4c6075ad413dd983b252f2
| 1,816 |
use crate::device::RCC;
use crate::rcc::rst;
use crate::rcc::RccExt;
/// Peripheral Reset
///
/// The X peripheral and all its associated configuration registers are placed in
/// the reset condition. The reset is effective via the RCC peripheral reset
/// system.
pub trait Reset {
fn reset(&self, rcc: &mut RCC);
}
macro_rules! impl_reset {
($PER:ty, $REG:expr) => (
impl Reset for $PER {
fn reset(&self, rcc: &mut RCC) {
rcc.periph_reset_pulse($REG);// проверить
}
}
)
}
use crate::device::CAN1;
use crate::device::{I2C1,I2C2};
use crate::device::{SPI1,SPI2,SPI3};
use crate::device::{TIM1,
TIM2,
TIM3,
TIM4,
TIM5,
TIM6,
TIM7,
TIM8,
TIM9,
TIM10,
TIM11,
TIM12,
TIM13,
TIM14};
impl_reset!(CAN1, rst::CAN1);
//impl_reset!(CAN2, rst::CAN2);
impl_reset!(I2C1, rst::I2C1);
impl_reset!(I2C2, rst::I2C2);
//impl_reset!(I2C3, rst::I2C3);
//impl_reset!(I2C4, rst::I2C4);
impl_reset!(SPI1, rst::SPI1);
impl_reset!(SPI2, rst::SPI2);
impl_reset!(SPI3, rst::SPI3);
//impl_reset!(SPI4, rst::SPI4);
//impl_reset!(SPI5, rst::SPI5);
//impl_reset!(SPI6, rst::SPI6);
impl_reset!(TIM1, rst::TIM1);
impl_reset!(TIM2, rst::TIM2);
impl_reset!(TIM3, rst::TIM3);
impl_reset!(TIM4, rst::TIM4);
impl_reset!(TIM5, rst::TIM5);
impl_reset!(TIM6, rst::TIM6);
impl_reset!(TIM7, rst::TIM7);
impl_reset!(TIM8, rst::TIM8);
impl_reset!(TIM9, rst::TIM9);
impl_reset!(TIM10, rst::TIM10);
impl_reset!(TIM11, rst::TIM11);
impl_reset!(TIM12, rst::TIM12);
impl_reset!(TIM13, rst::TIM13);
impl_reset!(TIM14, rst::TIM14);
| 25.222222 | 81 | 0.564978 |
87a360f3dcb43125b3bc0f9499946ea472e03af2
| 2,004 |
use crate::info_extractor::{InputStructType, SerializerType, TraitItemMethodInfo};
use quote::quote;
use syn::export::TokenStream2;
impl TraitItemMethodInfo {
/// Generate code that wraps the method.
pub fn method_wrapper(&self) -> TokenStream2 {
let ident = &self.attr_sig_info.ident;
let ident_byte_str = &self.ident_byte_str;
let pat_type_list = self.attr_sig_info.pat_type_list();
let has_input_args = self.attr_sig_info.input_args().next().is_some();
let struct_decl;
let constructor;
let value_ser = if !has_input_args {
struct_decl = TokenStream2::new();
constructor = TokenStream2::new();
quote! {let args = vec![]; }
} else {
struct_decl = self.attr_sig_info.input_struct(InputStructType::Serialization);
let constructor_call = self.attr_sig_info.constructor_expr();
constructor = quote! {let args = #constructor_call;};
match self.attr_sig_info.result_serializer {
SerializerType::JSON => quote! {
let args = near_sdk::serde_json::to_vec(&args).expect("Failed to serialize the cross contract args using JSON.");
},
SerializerType::Borsh => quote! {
let args = near_sdk::borsh::BorshSerialize::try_to_vec(&args).expect("Failed to serialize the cross contract args using Borsh.");
},
}
};
quote! {
pub fn #ident<T: ToString>(#pat_type_list __account_id: &T, __balance: near_sdk::Balance, __gas: near_sdk::Gas) -> near_sdk::Promise {
#struct_decl
#constructor
#value_ser
near_sdk::Promise::new(__account_id.to_string())
.function_call(
#ident_byte_str.to_vec(),
args,
__balance,
__gas,
)
}
}
}
}
| 42.638298 | 149 | 0.572355 |
3a626908f5d5f245540714f3e8b7cfa57182640c
| 7,791 |
use crate::platform::math::f32::abs;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// [`Colors`](Color) can be used to describe what [`Color`] to use for
/// visualizing backgrounds, texts, lines and various other elements that are
/// being shown. They are stored as RGBA [`Colors`](Color) with 32-bit floating
/// point numbers ranging from 0.0 to 1.0 per channel.
#[derive(Debug, Copy, Clone, Default, PartialEq)]
#[repr(C)]
pub struct Color {
/// The red component (0 - 1) of the [`Color`].
pub red: f32,
/// The green component (0 - 1) of the [`Color`].
pub green: f32,
/// The blue component (0 - 1) of the [`Color`].
pub blue: f32,
/// The alpha component (0 - 1) of the [`Color`].
pub alpha: f32,
}
impl Color {
/// Creates a new [`Color`] from red (0 - 1), green (0 - 1), blue (0 - 1)
/// and alpha (0 - 1) components.
pub const fn rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
/// Creates a new [`Color`] from red, green, blue and alpha byte components.
pub fn rgba8(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
const RECIP_255: f32 = 1.0 / 255.0;
Self {
red: RECIP_255 * red as f32,
green: RECIP_255 * green as f32,
blue: RECIP_255 * blue as f32,
alpha: RECIP_255 * alpha as f32,
}
}
/// Converts the [`Color`] into red, green, blue and alpha byte components.
pub fn to_rgba8(&self) -> [u8; 4] {
[
(255.0 * self.red + 0.5) as u8,
(255.0 * self.green + 0.5) as u8,
(255.0 * self.blue + 0.5) as u8,
(255.0 * self.alpha + 0.5) as u8,
]
}
/// Creates a new transparent [`Color`].
pub const fn transparent() -> Self {
Self {
red: 0.0,
green: 0.0,
blue: 0.0,
alpha: 0.0,
}
}
/// Creates a new white [`Color`].
pub const fn white() -> Self {
Self {
red: 1.0,
green: 1.0,
blue: 1.0,
alpha: 1.0,
}
}
/// Creates a new black [`Color`].
pub const fn black() -> Self {
Self {
red: 0.0,
green: 0.0,
blue: 0.0,
alpha: 1.0,
}
}
/// Converts the [`Color`] into an array of red (0 - 1), green (0 - 1), blue
/// (0 - 1) and alpha (0 - 1).
pub const fn to_array(&self) -> [f32; 4] {
[self.red, self.green, self.blue, self.alpha]
}
/// Creates a new [`Color`] by providing the hue (0 - 360), saturation (0 -
/// 1), lightness (0 - 1) and alpha (0 - 1) for it.
pub fn hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Self {
const RECIP_60: f32 = 1.0 / 60.0;
let c = (1.0 - abs(2.0 * lightness - 1.0)) * saturation;
let x = c * (1.0 - abs((hue * RECIP_60) % 2.0 - 1.0));
let m = lightness - 0.5 * c;
let (red, green, blue) = if hue < 60.0 {
(m + c, m + x, m)
} else if hue < 120.0 {
(m + x, m + c, m)
} else if hue < 180.0 {
(m, m + c, m + x)
} else if hue < 240.0 {
(m, m + x, m + c)
} else if hue < 300.0 {
(m + x, m, m + c)
} else {
(m + c, m, m + x)
};
Self {
red,
green,
blue,
alpha,
}
}
/// Creates a new [`Color`] by providing the hue (0 - 360), saturation (0 -
/// 1), value (0 - 1) and alpha (0 - 1) for it.
pub fn hsva(hue: f32, saturation: f32, value: f32, alpha: f32) -> Self {
const RECIP_60: f32 = 1.0 / 60.0;
let c = value * saturation;
let x = c * (1.0 - abs((hue * RECIP_60) % 2.0 - 1.0));
let m = value - c;
let (red, green, blue) = if hue < 60.0 {
(m + c, m + x, m)
} else if hue < 120.0 {
(m + x, m + c, m)
} else if hue < 180.0 {
(m, m + c, m + x)
} else if hue < 240.0 {
(m, m + x, m + c)
} else if hue < 300.0 {
(m + x, m, m + c)
} else {
(m + c, m, m + x)
};
Self {
red,
green,
blue,
alpha,
}
}
/// Converts the [`Color`] into hue (0 - 360), saturation (0 - 1), value (0
/// - 1) and alpha (0 - 1).
pub fn to_hsva(&self) -> [f32; 4] {
let [r, g, b, a] = self.to_array();
let (shift, max, diff, min) = if r > g {
if r > b {
if b > g {
(360.0, r, g - b, g)
} else {
(0.0, r, g - b, b)
}
} else {
(240.0, b, r - g, g)
}
} else if b > g {
(240.0, b, r - g, r)
} else {
(120.0, g, b - r, if r > b { b } else { r })
};
let delta = max - min;
let hue = if delta == 0.0 {
0.0
} else {
60.0 * diff / delta + shift
};
let saturation = if max == 0.0 { 0.0 } else { delta / max };
let value = max;
[hue, saturation, value, a]
}
}
impl From<[f32; 4]> for Color {
fn from([red, green, blue, alpha]: [f32; 4]) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
}
impl From<Color> for [f32; 4] {
fn from(c: Color) -> Self {
c.to_array()
}
}
impl From<[u8; 4]> for Color {
fn from([red, green, blue, alpha]: [u8; 4]) -> Self {
Self::rgba8(red, green, blue, alpha)
}
}
impl Serialize for Color {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.to_array().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Color {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let rgba = <[f32; 4]>::deserialize(deserializer)?;
Ok(rgba.into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[allow(clippy::float_cmp)]
#[test]
fn to_hsva() {
assert_eq!(
Color::from([1.0, 0.0, 0.0, 1.0]).to_hsva(),
[0.0, 1.0, 1.0, 1.0],
);
assert_eq!(
Color::from([1.0, 1.0, 0.0, 1.0]).to_hsva(),
[60.0, 1.0, 1.0, 1.0],
);
assert_eq!(
Color::from([0.0, 1.0, 0.0, 1.0]).to_hsva(),
[120.0, 1.0, 1.0, 1.0],
);
assert_eq!(
Color::from([0.0, 1.0, 1.0, 1.0]).to_hsva(),
[180.0, 1.0, 1.0, 1.0],
);
assert_eq!(
Color::from([0.0, 0.0, 1.0, 1.0]).to_hsva(),
[240.0, 1.0, 1.0, 1.0],
);
assert_eq!(
Color::from([1.0, 0.0, 1.0, 1.0]).to_hsva(),
[300.0, 1.0, 1.0, 1.0],
);
}
#[test]
fn from_hsva() {
assert_eq!(Color::hsva(0.0, 1.0, 1.0, 1.0).to_rgba8(), [255, 0, 0, 255]);
assert_eq!(
Color::hsva(60.0, 1.0, 1.0, 1.0).to_rgba8(),
[255, 255, 0, 255],
);
assert_eq!(
Color::hsva(120.0, 1.0, 1.0, 1.0).to_rgba8(),
[0, 255, 0, 255],
);
assert_eq!(
Color::hsva(180.0, 1.0, 1.0, 1.0).to_rgba8(),
[0, 255, 255, 255],
);
assert_eq!(
Color::hsva(240.0, 1.0, 1.0, 1.0).to_rgba8(),
[0, 0, 255, 255],
);
assert_eq!(
Color::hsva(300.0, 1.0, 1.0, 1.0).to_rgba8(),
[255, 0, 255, 255],
);
}
}
| 27.052083 | 81 | 0.427288 |
89336faaffc3e011b427f3f0890afd6223b88466
| 959 |
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use defmt::*;
use embassy::executor::Spawner;
use embassy_nrf::{interrupt, uarte, Peripherals};
use defmt_rtt as _; // global logger
use panic_probe as _;
#[embassy::main]
async fn main(_spawner: Spawner, p: Peripherals) {
let mut config = uarte::Config::default();
config.parity = uarte::Parity::EXCLUDED;
config.baudrate = uarte::Baudrate::BAUD115200;
let irq = interrupt::take!(UARTE0_UART0);
let mut uart = uarte::UarteWithIdle::new(
p.UARTE0, p.TIMER0, p.PPI_CH0, p.PPI_CH1, irq, p.P0_08, p.P0_06, config,
);
info!("uarte initialized!");
// Message must be in SRAM
let mut buf = [0; 8];
buf.copy_from_slice(b"Hello!\r\n");
unwrap!(uart.write(&buf).await);
info!("wrote hello in uart!");
loop {
info!("reading...");
let n = unwrap!(uart.read_until_idle(&mut buf).await);
info!("got {} bytes", n);
}
}
| 25.236842 | 80 | 0.629823 |
187c0600867baddb7c7228a168b4830a8dd4670d
| 4,685 |
use std::collections::HashSet;
use std::iter::FromIterator;
use tokio::prelude::*;
use futures::Future;
use hash::Blake2bHash;
use network_messages::{
Message,
GetBlockProofMessage,
BlockProofMessage,
GetTransactionReceiptsMessage,
GetTransactionsProofMessage,
TransactionReceiptsMessage,
TransactionsProofMessage,
GetAccountsProofMessage,
AccountsProofMessage,
GetAccountsTreeChunkMessage,
AccountsTreeChunkMessage,
AccountsTreeChunkData,
};
use network::connection::close_type::CloseType;
use crate::consensus_agent::ConsensusAgent;
impl ConsensusAgent {
pub(super) fn on_get_chain_proof(&self) {
trace!("[GET-CHAIN-PROOF] from {}", self.peer.peer_address());
if !self.state.write().chain_proof_limit.note_single() {
warn!("Rejecting GetChainProof message - rate-limit exceeded");
self.peer.channel.close(CloseType::RateLimitExceeded);
return;
}
let chain_proof = self.blockchain.get_chain_proof();
self.peer.channel.send_or_close(Message::ChainProof(Box::new(chain_proof)));
}
pub(super) fn on_get_block_proof(&self, msg: GetBlockProofMessage) {
trace!("[GET-BLOCK-PROOF] from {}", self.peer.peer_address());
if !self.state.write().block_proof_limit.note_single() {
warn!("Rejecting GetBlockProof message - rate-limit exceeded");
self.peer.channel.send_or_close(BlockProofMessage::empty());
return;
}
let block_proof = self.blockchain.get_block_proof(&msg.block_hash_to_prove, &msg.known_block_hash);
self.peer.channel.send_or_close(BlockProofMessage::new(block_proof));
}
pub(super) fn on_get_transaction_receipts(&self, msg: GetTransactionReceiptsMessage) {
trace!("[GET-TRANSACTION-RECEIPTS] from {}", self.peer.peer_address());
if !self.state.write().transaction_receipts_limit.note_single() {
warn!("Rejecting GetTransactionReceipts message - rate-limit exceeded");
self.peer.channel.send_or_close(TransactionReceiptsMessage::empty());
return;
}
let limit: usize = TransactionReceiptsMessage::RECEIPTS_MAX_COUNT / 2;
let receipts = self.blockchain.get_transaction_receipts_by_address(&msg.address, limit, limit);
self.peer.channel.send_or_close(TransactionReceiptsMessage::new(receipts));
}
pub(super) fn on_get_transactions_proof(&self, msg: GetTransactionsProofMessage) {
trace!("[GET-TRANSACTIONS-PROOF] from {}", self.peer.peer_address());
if !self.state.write().transactions_proof_limit.note_single() {
warn!("Rejecting GetTransactionsProofMessage message - rate-limit exceeded");
self.peer.channel.send_or_close(TransactionsProofMessage::new(msg.block_hash, None));
return;
}
let addresses = HashSet::from_iter(msg.addresses);
let proof = self.blockchain.get_transactions_proof(&msg.block_hash, &addresses);
self.peer.channel.send_or_close(TransactionsProofMessage::new(msg.block_hash, proof));
}
pub(super) fn on_get_accounts_proof(&self, msg: GetAccountsProofMessage) {
trace!("[GET-ACCOUNTS-PROOF] from {}", self.peer.peer_address());
if !self.state.write().accounts_proof_limit.note_single() {
warn!("Rejecting GetAccountsProof message - rate-limit exceeded");
self.peer.channel.send_or_close(AccountsProofMessage::new(msg.block_hash, None));
return;
}
// TODO: This is a deviation from the JavaScript client. If the given hash is the 0 hash, assume the current head.
let mut hash = msg.block_hash;
if hash == Blake2bHash::default() {
hash = self.blockchain.head_hash();
}
let proof = self.blockchain.get_accounts_proof(&hash, &msg.addresses);
self.peer.channel.send_or_close(AccountsProofMessage::new(hash, proof));
}
pub(super) fn on_get_accounts_tree_chunk(&self, msg: GetAccountsTreeChunkMessage) {
trace!("[GET-ACCOUNTS-TREE-CHUNK] from {}", self.peer.peer_address());
let get_chunk_future = self.accounts_chunk_cache.get_chunk(&msg.block_hash, &msg.start_prefix);
let peer = self.peer.clone();
let future = get_chunk_future.then(move |chunk_res| {
let chunk_opt = chunk_res.unwrap_or(None).map(AccountsTreeChunkData::Serialized);
peer.channel.send_or_close(Message::AccountsTreeChunk(Box::new(AccountsTreeChunkMessage { block_hash: msg.block_hash, chunk: chunk_opt })));
future::ok::<(), ()>(())
});
tokio::spawn(future);
}
}
| 43.785047 | 152 | 0.684525 |
5dbd3606fcc756e451bd879e6ad8411acc29676d
| 10,199 |
extern crate clap;
extern crate dirs;
extern crate libfund;
use std::error::Error;
use std::io;
use std::path::PathBuf;
use clap::ArgMatches;
pub struct Config {
pub configdir: PathBuf,
pub fundfile: PathBuf,
pub command: String,
pub fund_name: Option<String>,
pub transfer_name: Option<String>,
pub field: Option<String>,
pub amount: Option<i32>,
pub goal: Option<i32>,
}
impl Config {
pub fn new(matches: &ArgMatches) -> Result<Config, Box<Error + Send + Sync>> {
let configdir = match dirs::config_dir() {
Some(mut path) => {
path.push(PathBuf::from(r"fund"));
path
}
None => return Err(From::from("can't find config directory")),
};
let mut fundfile = match dirs::data_dir() {
Some(data_dir) => data_dir,
None => return Err(From::from("can't use this directory")),
};
fundfile.push("fund/fund");
if let Some(path) = matches.value_of("fundfile") {
fundfile = PathBuf::from(path);
}
let mut command = String::from(matches.subcommand().0);
let mut fund_name = None;
let mut amount = None;
let mut goal = None;
let mut transfer_name = None;
let mut field = None;
match matches.subcommand() {
("new", Some(new_matches)) => {
fund_name = new_matches.value_of("name");
amount = new_matches.value_of("amount");
goal = new_matches.value_of("goal");
}
("deposit", Some(deposit_matches)) => {
fund_name = deposit_matches.value_of("name");
amount = deposit_matches.value_of("amount");
}
("spend", Some(spend_matches)) => {
fund_name = spend_matches.value_of("name");
amount = spend_matches.value_of("amount");
}
("info", Some(list_matches)) => {
fund_name = list_matches.value_of("name");
}
("transfer", Some(list_matches)) => {
fund_name = list_matches.value_of("from_name");
transfer_name = list_matches.value_of("to_name");
amount = list_matches.value_of("amount");
}
("rename", Some(list_matches)) => {
fund_name = list_matches.value_of("old_name");
transfer_name = list_matches.value_of("new_name");
}
("set", Some(list_matches)) => {
fund_name = list_matches.value_of("name");
amount = list_matches.value_of("amount");
field = list_matches.value_of("field");
}
("", None) => command = String::from("info"),
_ => unreachable!(),
}
let fund_name = fund_name.and_then(|x| Some(String::from(x)));
let transfer_name = transfer_name.and_then(|x| Some(String::from(x)));
let field = field.and_then(|x| Some(String::from(x)));
let amount = amount.map_or(Ok(None), |x| x.replace(".", "").parse::<i32>().map(Some))?;
let goal = goal.map_or(Ok(None), |x| x.replace(".", "").parse::<i32>().map(Some))?;
Ok(Config {
configdir,
fundfile,
command,
fund_name,
transfer_name,
field,
amount,
goal,
})
}
}
pub fn run(config: Config) -> Result<(), libfund::FundManagerError> {
let mut funds = libfund::FundManager::load(&config.fundfile)?;
match config.command.as_str() {
"info" => match config.fund_name {
Some(name) => print_fund(&funds, &name)?,
None => print_all(&funds),
},
"new" => match config.fund_name {
Some(name) => {
let mut fund = libfund::Fund::new();
if let Some(amount) = config.amount {
fund.with_amount(amount);
}
if let Some(goal) = config.goal {
fund.with_goal(goal);
}
let fund = fund.build();
funds.add_fund(&name, fund)?;
print_fund(&funds, &name)?;
}
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"can't create a new struct with no name",
)))
}
},
"spend" => match config.fund_name {
Some(name) => match config.amount {
Some(amount) => {
funds.fund_mut(&name)?.spend(amount);
print_fund(&funds, &name)?;
}
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply an amount to spend",
)))
}
},
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply a fund to spend from",
)))
}
},
"deposit" => match config.fund_name {
Some(name) => match config.amount {
Some(amount) => {
funds.fund_mut(&name)?.deposit(amount);
print_fund(&funds, &name)?;
}
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply an amount to deposit",
)))
}
},
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply a fund to deposit to",
)))
}
},
"transfer" => match config.fund_name {
Some(name) => match config.transfer_name {
Some(transfer_name) => match config.amount {
Some(amount) => {
funds.fund_mut(&name)?.spend(amount);
funds.fund_mut(&transfer_name)?.deposit(amount);
print_fund(&funds, &name)?;
print_fund(&funds, &transfer_name)?;
}
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply an amount to transfer",
)))
}
},
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply a fund to transfer to",
)))
}
},
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply a fund to transfer from",
)))
}
},
"rename" => match config.fund_name {
Some(name) => match config.transfer_name {
Some(transfer_name) => {
funds.rename(&name, &transfer_name)?;
print_fund(&funds, &transfer_name)?;
}
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply a new unique name",
)))
}
},
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please supply the name of the fund to rename",
)))
}
},
"set" => match config.fund_name {
Some(name) => match config.amount {
Some(amount) => match config.field {
Some(field) => {
match field.as_str() {
"amount" => funds.fund_mut(&name)?.amount = amount,
"goal" => funds.fund_mut(&name)?.goal = amount,
_ => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid field name",
)))
}
};
print_fund(&funds, &name)?;
}
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please provide a field name",
)))
}
},
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please provide an amount",
)))
}
},
None => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"please provide a fund name",
)))
}
},
_ => {
return Err(From::from(io::Error::new(
io::ErrorKind::InvalidInput,
"not a valid command",
)))
}
}
funds.save(&config.fundfile)?;
Ok(())
}
pub fn print_fund(funds: &libfund::FundManager, name: &str) -> Result<(), libfund::FundNotFoundError> {
let fund = funds.fund(name)?;
let mut name = String::from(name);
name.push(':');
println!("{:>10} {}", name, fund);
Ok(())
}
pub fn print_all(funds: &libfund::FundManager) {
for fund in funds.into_iter() {
let mut name = fund.0.to_owned();
name.push(':');
println!("{:>10} {}", name, fund.1)
}
}
| 36.038869 | 103 | 0.434062 |
ef71854f3e1c70a863d608e3fa64985b3ded6d29
| 103,830 |
use std::fmt;
// A module to parse HTTP request
// HTTP Header
pub struct Header<'a> {
// In Rust, str is a slice of String
// String is valid UTF-8
key: &'a str,
// colon storage ": "
colon: &'a str,
// Notice that specification allows for values that may not be
// valid ASCII, nor UTF-8
value: &'a [u8],
}
pub struct Request<'a> {
// "GET" or "POST"
pub method: &'a str,
// path is String,so that it can be modified
pub path: String,
// "HTTP/1.1"
pub version: &'a str,
// TODO: maybe HashMap is better
pub headers: Vec<Header<'a>>,
// easy way to get host without searching headers
pub host: &'a str,
// may not be valid UTF-8
pub body: &'a [u8],
}
impl<'a> Request<'a> {
// replace host and url with another host
pub fn modify_host(&mut self, host: &'a str) {
// skip "/" in "http://" and find next /
// we use it as start index of path
let url = self.path[7..].find("/");
match url {
Some(url) => {
self.path = format!("http://{}/{}", host, &self.path[url + 7..]);
}
// None show that url dont have "/" after "http://""
None => {
self.path = format!("http://{}/", host);
}
}
// this program use self.host to crate request
// not self.headers["Host"]
// buf we still need to change "Host" in headers
// if not so,web server will send 400 back
self.host = host;
for i in 0..self.headers.len() {
if self.headers[i].key == "Host" {
self.headers[i].value = host.as_bytes();
}
}
}
pub fn parse(buf: &'a [u8]) -> Result<Request<'a>, String> {
// first, find position of body
let (body_pos, body) = match find(buf, b"\r\n\r\n") {
Some(pos) => (pos, &buf[pos + 4..]),
None => (buf.len(), &buf[buf.len()..]),
};
// header include all HTTP message header, include first line
let header = &buf[..body_pos];
// split it by Line break "\r\n" and return a iterator
let mut iter = split(header, b"\r\n");
// find first line and covert it from &[u8] to str
let first_line = iter.next().ok_or("http massage change line with \\r\\n")?;
let first_line = std::str::from_utf8(first_line)
.map_err(|_| "Http message first line contain invalid utf-8")?;
// split first line by space
let mut first_line_iter = first_line.split(" ");
// find method path and version
let method = first_line_iter
.next()
.ok_or("http massage start with method")?;
let path = first_line_iter
.next()
.ok_or("http massage have path")?
.to_string();
let version = first_line_iter.next().ok_or("http massage have version")?;
// find Host in headers
let mut host = None;
let headers = iter
//map header string to struct Header
.map(|x| {
let colon_pos = find(x, b":").expect("http header use : split k&v");
let key = std::str::from_utf8(&x[..colon_pos])
.expect("Header key contain invalid utf-8")
.trim();
let colon = std::str::from_utf8(&x[colon_pos..colon_pos + 1])
.expect("Header colon contain invalid utf-8");
// find Host in headers
if key == "Host" {
host = Some(
std::str::from_utf8(&x[colon_pos + 1..])
.expect("Host contain invalid utf-8")
.trim(),
)
}
// prevent upgrade HTTP to HTTPS
if key == "Upgrade-Insecure-Requests" {
return None;
}
Some(Header {
key,
colon,
value: trim(&x[colon_pos + 1..]),
})
})
// filter that None
.filter(|x| x.is_some())
// unwrap some in option
.map(|x| x.expect("impossible"))
// collect to Vec<Header>
.collect();
// return Err when don't find host
let host = host.ok_or("dont know host")?;
Ok(Request {
method,
path,
version,
headers,
host,
body,
})
}
// write pain text HTTP request
pub fn write<T>(&self, f: &mut T) -> std::io::Result<()>
where
T: std::io::Write,
{
write!(f, "{} {} {}\r\n", self.method, self.path, self.version)?;
for header in &self.headers {
write!(f, "{}{} ", header.key, header.colon)?;
f.write(header.value)?;
f.write(b"\r\n")?;
}
f.write(b"\r\n")?;
if self.body.len() > 0 {
f.write(self.body)?;
f.write(b"\r\n")?;
}
Ok(())
}
}
// display HTTP request message
impl<'a> fmt::Display for Request<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "START HTTP REQUEST\n")?;
write!(f, "{} {} {}\r\n", self.method, self.path, self.version)?;
for header in &self.headers {
write!(f, "{}{} ", header.key, header.colon)?;
if let Ok(value_str) = std::str::from_utf8(header.value) {
write!(f, "{}\r\n", value_str)?;
} else {
write!(f, "[invalid utf8 key]\r\n")?;
}
}
write!(f, "\r\n")?;
if self.body.len() > 0 {
if let Ok(body_str) = std::str::from_utf8(self.body) {
write!(f, "{}", body_str)?;
} else {
write!(f, "[invalid utf8 body]")?;
}
}
write!(f, "END HTTP REQUEST")
}
}
// some tools for [u8]
// split for [u8]
struct U8SplitIter<'a> {
buf: &'a [u8],
pat: &'static [u8],
pos: usize,
}
impl<'a> Iterator for U8SplitIter<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
let next_pos = find(&self.buf[self.pos..], self.pat);
match next_pos {
Some(next_pos) => {
let last_pos = self.pos;
self.pos += next_pos + self.pat.len();
Some(&self.buf[last_pos..last_pos + next_pos])
}
None => {
if self.pos < self.buf.len() {
let last_pos = self.pos;
self.pos = self.buf.len();
Some(&self.buf[last_pos..])
} else {
None
}
}
}
}
}
fn find(buf: &[u8], pat: &[u8]) -> Option<usize> {
assert!(pat.len() > 0);
for i in 0..buf.len() {
for j in 0..pat.len() {
if buf[i + j] != pat[j] {
break;
} else {
if j == pat.len() - 1 {
return Some(i);
}
}
}
}
None
}
fn split<'a>(buf: &'a [u8], pat: &'static [u8]) -> U8SplitIter<'a> {
U8SplitIter { buf, pat, pos: 0 }
}
// trim space in [u8]
fn trim<'a>(buf: &'a [u8]) -> &'a [u8] {
for i in 0..buf.len() {
if buf[i] != ' ' as u8 {
return &buf[i..];
}
}
&buf[buf.len()..]
}
// ************TEST*************//
// this is a macro to test Request
macro_rules! req {
($name:ident, $buf:expr, |$arg:ident| $body:expr) => {
#[test]
fn $name() {
let req = Request::parse($buf.as_ref()).unwrap();
fn assert_closure($arg: Request) {
$body
}
assert_closure(req);
}
};
}
// copy from rust crate **httparse**
// see https://github.com/seanmonstar/httparse/blob/master/tests/uri.rs
req! {
urltest_001,
"GET /bar;par?b HTTP/1.1\r\nHost: foo\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/bar;par?b");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo");
}
}
req! {
urltest_002,
"GET /x HTTP/1.1\r\nHost: test\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/x");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"test");
}
}
req! {
urltest_003,
"GET /x HTTP/1.1\r\nHost: test\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/x");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"test");
}
}
req! {
urltest_004,
"GET /foo/foo.com HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/foo.com");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_005,
"GET /foo/:foo.com HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:foo.com");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_006,
"GET /foo/foo.com HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/foo.com");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
/*
req! {
urltest_007,
"GET foo.com HTTP/1.1\r\nHost: \r\n\r\n",
Err(Error::Version),
|_r| {}
}
*/
req! {
urltest_008,
"GET /%20b%20?%20d%20 HTTP/1.1\r\nHost: f\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%20b%20?%20d%20");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"f");
}
}
/*
req! {
urltest_009,
"GET x x HTTP/1.1\r\nHost: \r\n\r\n",
Err(Error::Version),
|_r| {}
}
*/
req! {
urltest_010,
"GET /c HTTP/1.1\r\nHost: f\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"f");
}
}
req! {
urltest_011,
"GET /c HTTP/1.1\r\nHost: f\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"f");
}
}
req! {
urltest_012,
"GET /c HTTP/1.1\r\nHost: f\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"f");
}
}
req! {
urltest_013,
"GET /c HTTP/1.1\r\nHost: f\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"f");
}
}
req! {
urltest_014,
"GET /c HTTP/1.1\r\nHost: f\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"f");
}
}
req! {
urltest_015,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_016,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_017,
"GET /foo/:foo.com/ HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:foo.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_018,
"GET /foo/:foo.com/ HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:foo.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_019,
"GET /foo/: HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_020,
"GET /foo/:a HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:a");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_021,
"GET /foo/:/ HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_022,
"GET /foo/:/ HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_023,
"GET /foo/: HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_024,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_025,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_026,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_027,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_028,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_029,
"GET /foo/:23 HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:23");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_030,
"GET /:23 HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/:23");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_031,
"GET /foo/:: HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/::");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_032,
"GET /foo/::23 HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/::23");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_033,
"GET /d HTTP/1.1\r\nHost: c\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/d");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"c");
}
}
req! {
urltest_034,
"GET /foo/:@c:29 HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/:@c:29");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_035,
"GET //@ HTTP/1.1\r\nHost: foo.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "//@");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo.com");
}
}
req! {
urltest_036,
"GET /b:c/[email protected]/ HTTP/1.1\r\nHost: a\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/b:c/[email protected]/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"a");
}
}
req! {
urltest_037,
"GET /bar.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/bar.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_038,
"GET /////// HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "///////");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_039,
"GET ///////bar.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "///////bar.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_040,
"GET //:///// HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "//://///");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_041,
"GET /foo HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_042,
"GET /bar HTTP/1.1\r\nHost: foo\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo");
}
}
req! {
urltest_043,
"GET /path;a??e HTTP/1.1\r\nHost: foo\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/path;a??e");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo");
}
}
req! {
urltest_044,
"GET /abcd?efgh?ijkl HTTP/1.1\r\nHost: foo\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/abcd?efgh?ijkl");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo");
}
}
req! {
urltest_045,
"GET /abcd HTTP/1.1\r\nHost: foo\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/abcd");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo");
}
}
req! {
urltest_046,
"GET /foo/[61:24:74]:98 HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/[61:24:74]:98");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_047,
"GET /foo/[61:27]/:foo HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/[61:27]/:foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_048,
"GET /example.com/ HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_049,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_050,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_051,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_052,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_053,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_054,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_055,
"GET /foo/example.com/ HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_056,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_057,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_058,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_059,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_060,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_061,
"GET /a/b/c HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/a/b/c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_062,
"GET /a/%20/c HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/a/%20/c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_063,
"GET /a%2fc HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/a%2fc");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_064,
"GET /a/%2f/c HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/a/%2f/c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_065,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_066,
"GET text/html,test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "text/html,test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_067,
"GET 1234567890 HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "1234567890");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_068,
"GET /c:/foo/bar.html HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c:/foo/bar.html");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_069,
"GET /c:////foo/bar.html HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c:////foo/bar.html");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_070,
"GET /C:/foo/bar HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_071,
"GET /C:/foo/bar HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_072,
"GET /C:/foo/bar HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_073,
"GET /file HTTP/1.1\r\nHost: server\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/file");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"server");
}
}
req! {
urltest_074,
"GET /file HTTP/1.1\r\nHost: server\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/file");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"server");
}
}
req! {
urltest_075,
"GET /file HTTP/1.1\r\nHost: server\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/file");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"server");
}
}
req! {
urltest_076,
"GET /foo/bar.txt HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar.txt");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_077,
"GET /home/me HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/home/me");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_078,
"GET /test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_079,
"GET /test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_080,
"GET /tmp/mock/test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/tmp/mock/test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_081,
"GET /tmp/mock/test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/tmp/mock/test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_082,
"GET /foo HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_083,
"GET /.foo HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/.foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_084,
"GET /foo/ HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_085,
"GET /foo/ HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_086,
"GET /foo/ HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_087,
"GET /foo/ HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_088,
"GET /foo/..bar HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/..bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_089,
"GET /foo/ton HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/ton");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_090,
"GET /a HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/a");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_091,
"GET /ton HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/ton");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_092,
"GET /foo/ HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_093,
"GET /foo/%2e%2 HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/%2e%2");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_094,
"GET /%2e.bar HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%2e.bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_095,
"GET // HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "//");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_096,
"GET /foo/ HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_097,
"GET /foo/bar/ HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_098,
"GET /foo HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_099,
"GET /%20foo HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%20foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_100,
"GET /foo% HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo%");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_101,
"GET /foo%2 HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo%2");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_102,
"GET /foo%2zbar HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo%2zbar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_103,
"GET /foo%2%C3%82%C2%A9zbar HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo%2%C3%82%C2%A9zbar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_104,
"GET /foo%41%7a HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo%41%7a");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_105,
"GET /foo%C2%91%91 HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo%C2%91%91");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_106,
"GET /foo%00%51 HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo%00%51");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_107,
"GET /(%28:%3A%29) HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/(%28:%3A%29)");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_108,
"GET /%3A%3a%3C%3c HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%3A%3a%3C%3c");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_109,
"GET /foobar HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foobar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_110,
"GET //foo//bar HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "//foo//bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_111,
"GET /%7Ffp3%3Eju%3Dduvgw%3Dd HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%7Ffp3%3Eju%3Dduvgw%3Dd");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_112,
"GET /@asdf%40 HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/@asdf%40");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_113,
"GET /%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_114,
"GET /%E2%80%A5/foo HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%E2%80%A5/foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_115,
"GET /%EF%BB%BF/foo HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%EF%BB%BF/foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_116,
"GET /%E2%80%AE/foo/%E2%80%AD/bar HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%E2%80%AE/foo/%E2%80%AD/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_117,
"GET /foo?bar=baz HTTP/1.1\r\nHost: www.google.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo?bar=baz");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.google.com");
}
}
req! {
urltest_118,
"GET /foo?bar=baz HTTP/1.1\r\nHost: www.google.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo?bar=baz");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.google.com");
}
}
req! {
urltest_119,
"GET test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_120,
"GET /foo%2Ehtml HTTP/1.1\r\nHost: www\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo%2Ehtml");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www");
}
}
req! {
urltest_121,
"GET /foo/html HTTP/1.1\r\nHost: www\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/html");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www");
}
}
req! {
urltest_122,
"GET /foo HTTP/1.1\r\nHost: www.google.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.google.com");
}
}
req! {
urltest_123,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_124,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_125,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_126,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_127,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_128,
"GET /example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_129,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_130,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_131,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_132,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_133,
"GET example.com/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "example.com/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_134,
"GET /test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test.txt");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.example.com");
}
}
req! {
urltest_135,
"GET /test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test.txt");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.example.com");
}
}
req! {
urltest_136,
"GET /test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test.txt");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.example.com");
}
}
req! {
urltest_137,
"GET /test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test.txt");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.example.com");
}
}
req! {
urltest_138,
"GET /aaa/test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/aaa/test.txt");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.example.com");
}
}
req! {
urltest_139,
"GET /test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test.txt");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.example.com");
}
}
req! {
urltest_140,
"GET /%E4%B8%AD/test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%E4%B8%AD/test.txt");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"www.example.com");
}
}
req! {
urltest_141,
"GET /... HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/...");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_142,
"GET /a HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/a");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_143,
"GET /%EF%BF%BD?%EF%BF%BD HTTP/1.1\r\nHost: x\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%EF%BF%BD?%EF%BF%BD");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"x");
}
}
req! {
urltest_144,
"GET /bar HTTP/1.1\r\nHost: example.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.com");
}
}
req! {
urltest_145,
"GET test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_146,
"GET [email protected] HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "[email protected]");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_147,
"GET, HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, ",");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_148,
"GET blank HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "blank");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_149,
"GET test?test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "test?test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_150,
"GET /%60%7B%7D?`{} HTTP/1.1\r\nHost: h\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/%60%7B%7D?`{}");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"h");
}
}
req! {
urltest_151,
"GET /?%27 HTTP/1.1\r\nHost: host\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/?%27");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"host");
}
}
req! {
urltest_152,
"GET /?' HTTP/1.1\r\nHost: host\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/?'");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"host");
}
}
req! {
urltest_153,
"GET /some/path HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/some/path");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_154,
"GET /smth HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/smth");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_155,
"GET /some/path HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/some/path");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_156,
"GET /pa/i HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pa/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_157,
"GET /i HTTP/1.1\r\nHost: ho\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"ho");
}
}
req! {
urltest_158,
"GET /pa/i HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pa/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_159,
"GET /i HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_160,
"GET /i HTTP/1.1\r\nHost: ho\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"ho");
}
}
req! {
urltest_161,
"GET /i HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_162,
"GET /i HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_163,
"GET /i HTTP/1.1\r\nHost: ho\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"ho");
}
}
req! {
urltest_164,
"GET /i HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_165,
"GET /pa/pa?i HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pa/pa?i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_166,
"GET /pa?i HTTP/1.1\r\nHost: ho\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pa?i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"ho");
}
}
req! {
urltest_167,
"GET /pa/pa?i HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pa/pa?i");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_168,
"GET sd HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "sd");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_169,
"GET sd/sd HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "sd/sd");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_170,
"GET /pa/pa HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pa/pa");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_171,
"GET /pa HTTP/1.1\r\nHost: ho\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pa");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"ho");
}
}
req! {
urltest_172,
"GET /pa/pa HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pa/pa");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_173,
"GET /x HTTP/1.1\r\nHost: %C3%B1\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/x");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"%C3%B1");
}
}
/*
req! {
urltest_174,
"GET \\.\\./ HTTP/1.1\r\nHost: \r\n\r\n",
Err(Error::Token),
|_r| {}
}
*/
req! {
urltest_175,
"GET :[email protected] HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, ":[email protected]");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_176,
"GET %NBD HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "%NBD");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_177,
"GET %1G HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "%1G");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_178,
"GET /relative_import.html HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/relative_import.html");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"127.0.0.1");
}
}
req! {
urltest_179,
"GET /?foo=%7B%22abc%22 HTTP/1.1\r\nHost: facebook.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/?foo=%7B%22abc%22");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"facebook.com");
}
}
req! {
urltest_180,
"GET /[email protected] HTTP/1.1\r\nHost: localhost\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/[email protected]");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"localhost");
}
}
req! {
urltest_181,
"GET /path?query HTTP/1.1\r\nHost: host\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/path?query");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"host");
}
}
req! {
urltest_182,
"GET /foo/bar?a=b&c=d HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar?a=b&c=d");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_183,
"GET /foo/bar??a=b&c=d HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar??a=b&c=d");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_184,
"GET /foo/bar HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_185,
"GET /baz?qux HTTP/1.1\r\nHost: foo.bar\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/baz?qux");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo.bar");
}
}
req! {
urltest_186,
"GET /baz?qux HTTP/1.1\r\nHost: foo.bar\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/baz?qux");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo.bar");
}
}
req! {
urltest_187,
"GET /baz?qux HTTP/1.1\r\nHost: foo.bar\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/baz?qux");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo.bar");
}
}
req! {
urltest_188,
"GET /baz?qux HTTP/1.1\r\nHost: foo.bar\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/baz?qux");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo.bar");
}
}
req! {
urltest_189,
"GET /baz?qux HTTP/1.1\r\nHost: foo.bar\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/baz?qux");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foo.bar");
}
}
req! {
urltest_190,
"GET /C%3A/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C%3A/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_191,
"GET /C%7C/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C%7C/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_192,
"GET /C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/pix/submit.gif HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/pix/submit.gif");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_193,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_194,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_195,
"GET /d: HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/d:");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_196,
"GET /d:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/d:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_197,
"GET /test?test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_198,
"GET /test?test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_199,
"GET /test?x HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?x");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_200,
"GET /test?x HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?x");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_201,
"GET /test?test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_202,
"GET /test?test HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_203,
"GET /?fox HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/?fox");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_204,
"GET /localhost//cat HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/localhost//cat");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_205,
"GET /localhost//cat HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/localhost//cat");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_206,
"GET /mouse HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/mouse");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_207,
"GET /pig HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pig");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_208,
"GET /pig HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pig");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_209,
"GET /pig HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/pig");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_210,
"GET /localhost//pig HTTP/1.1\r\nHost: lion\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/localhost//pig");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"lion");
}
}
req! {
urltest_211,
"GET /rooibos HTTP/1.1\r\nHost: tea\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/rooibos");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"tea");
}
}
req! {
urltest_212,
"GET /?chai HTTP/1.1\r\nHost: tea\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/?chai");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"tea");
}
}
req! {
urltest_213,
"GET /C: HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_214,
"GET /C: HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_215,
"GET /C: HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_216,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_217,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_218,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_219,
"GET /dir/C HTTP/1.1\r\nHost: host\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/dir/C");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"host");
}
}
req! {
urltest_220,
"GET /dir/C|a HTTP/1.1\r\nHost: host\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/dir/C|a");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"host");
}
}
req! {
urltest_221,
"GET /c:/foo/bar HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c:/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_222,
"GET /c:/foo/bar HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c:/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_223,
"GET /c:/foo/bar HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c:/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_224,
"GET /c:/foo/bar HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/c:/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_225,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_226,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_227,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_228,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_229,
"GET /C:/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/C:/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_230,
"GET /?q=v HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/?q=v");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_231,
"GET ?x HTTP/1.1\r\nHost: %C3%B1\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "?x");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"%C3%B1");
}
}
req! {
urltest_232,
"GET ?x HTTP/1.1\r\nHost: %C3%B1\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "?x");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"%C3%B1");
}
}
req! {
urltest_233,
"GET // HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "//");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_234,
"GET //x/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "//x/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_235,
"GET /someconfig;mode=netascii HTTP/1.1\r\nHost: foobar.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/someconfig;mode=netascii");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"foobar.com");
}
}
req! {
urltest_236,
"GET /Index.ut2 HTTP/1.1\r\nHost: 10.10.10.10\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/Index.ut2");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"10.10.10.10");
}
}
req! {
urltest_237,
"GET /0?baz=bam&qux=baz HTTP/1.1\r\nHost: somehost\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/0?baz=bam&qux=baz");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"somehost");
}
}
req! {
urltest_238,
"GET /sup HTTP/1.1\r\nHost: host\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/sup");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"host");
}
}
req! {
urltest_239,
"GET /foo/bar.git HTTP/1.1\r\nHost: github.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar.git");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"github.com");
}
}
req! {
urltest_240,
"GET /channel?passwd HTTP/1.1\r\nHost: myserver.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/channel?passwd");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"myserver.com");
}
}
req! {
urltest_241,
"GET /foo.bar.org?type=TXT HTTP/1.1\r\nHost: fw.example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo.bar.org?type=TXT");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"fw.example.org");
}
}
req! {
urltest_242,
"GET /ou=People,o=JNDITutorial HTTP/1.1\r\nHost: localhost\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/ou=People,o=JNDITutorial");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"localhost");
}
}
req! {
urltest_243,
"GET /foo/bar HTTP/1.1\r\nHost: github.com\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"github.com");
}
}
req! {
urltest_244,
"GET ietf:rfc:2648 HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "ietf:rfc:2648");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_245,
"GET [email protected],2001:foo/bar HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "[email protected],2001:foo/bar");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_246,
"GET /path HTTP/1.1\r\nHost: H%4fSt\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/path");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"H%4fSt");
}
}
req! {
urltest_247,
"GET https://example.com:443/ HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "https://example.com:443/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_248,
"GET d3958f5c-0777-0845-9dcf-2cb28783acaf HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "d3958f5c-0777-0845-9dcf-2cb28783acaf");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_249,
"GET /test?%22 HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?%22");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_250,
"GET /test HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_251,
"GET /test?%3C HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?%3C");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_252,
"GET /test?%3E HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?%3E");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_253,
"GET /test?%E2%8C%A3 HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?%E2%8C%A3");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_254,
"GET /test?%23%23 HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?%23%23");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_255,
"GET /test?%GH HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?%GH");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_256,
"GET /test?a HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?a");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_257,
"GET /test?a HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?a");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
req! {
urltest_258,
"GET /test-a-colon-slash.html HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test-a-colon-slash.html");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_259,
"GET /test-a-colon-slash-slash.html HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test-a-colon-slash-slash.html");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_260,
"GET /test-a-colon-slash-b.html HTTP/1.1\r\nHost: \r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test-a-colon-slash-b.html");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"");
}
}
req! {
urltest_261,
"GET /test-a-colon-slash-slash-b.html HTTP/1.1\r\nHost: b\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test-a-colon-slash-slash-b.html");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"b");
}
}
req! {
urltest_262,
"GET /test?a HTTP/1.1\r\nHost: example.org\r\n\r\n",
|req| {
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test?a");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(req.headers.len(), 1);
assert_eq!(req.headers[0].key, "Host");
assert_eq!(req.headers[0].value, b"example.org");
}
}
| 28.384363 | 121 | 0.528123 |
6ace3a2e0b49dfdf349997baf1da14fe675c9d9b
| 4,215 |
use crate::profile::profile_change_history::ProfileChangeHistory;
use crate::{
EventIdentifier, KeyAttributes, OckamError, Profile, ProfileChange, ProfileChangeEvent,
ProfileChangeProof, ProfileChangeType, ProfileEventAttributes, Signature, SignatureType,
PROFILE_CHANGE_CURRENT_VERSION,
};
use ockam_vault_core::{
Secret, SecretAttributes, SecretPersistence, SecretType, CURVE25519_SECRET_LENGTH,
};
use serde::{Deserialize, Serialize};
use serde_big_array::big_array;
use std::ops::Deref;
big_array! { BigArray; }
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RotateKeyChangeData {
key_attributes: KeyAttributes,
public_key: Vec<u8>,
}
impl RotateKeyChangeData {
pub fn key_attributes(&self) -> &KeyAttributes {
&self.key_attributes
}
pub fn public_key(&self) -> &[u8] {
self.public_key.as_slice()
}
}
impl RotateKeyChangeData {
pub fn new(key_attributes: KeyAttributes, public_key: Vec<u8>) -> Self {
RotateKeyChangeData {
key_attributes,
public_key,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RotateKeyChange {
data: RotateKeyChangeData,
#[serde(with = "BigArray")]
self_signature: [u8; 64],
#[serde(with = "BigArray")]
prev_signature: [u8; 64],
}
impl RotateKeyChange {
pub fn data(&self) -> &RotateKeyChangeData {
&self.data
}
pub fn self_signature(&self) -> &[u8; 64] {
&self.self_signature
}
pub fn prev_signature(&self) -> &[u8; 64] {
&self.prev_signature
}
}
impl RotateKeyChange {
pub fn new(
data: RotateKeyChangeData,
self_signature: [u8; 64],
prev_signature: [u8; 64],
) -> Self {
RotateKeyChange {
data,
self_signature,
prev_signature,
}
}
}
impl Profile {
pub(crate) fn rotate_key_event(
&self,
key_attributes: KeyAttributes,
attributes: Option<ProfileEventAttributes>,
root_key: &Secret,
) -> ockam_core::Result<ProfileChangeEvent> {
let attributes = attributes.unwrap_or(ProfileEventAttributes::new());
let prev_event_id = self.change_history.get_last_event_id()?;
let last_event_in_chain = self.change_history.find_last_key_event(&key_attributes)?;
let mut v = self.vault.lock().unwrap();
let last_key_in_chain = ProfileChangeHistory::get_secret_key_from_event(
&key_attributes,
last_event_in_chain,
v.deref(),
)?;
// TODO: Should be customisable
let secret_attributes = SecretAttributes {
stype: SecretType::Curve25519,
persistence: SecretPersistence::Persistent,
length: CURVE25519_SECRET_LENGTH,
};
let secret_key = v.secret_generate(secret_attributes)?;
let public_key = v.secret_public_key_get(&secret_key)?.as_ref().to_vec();
let data = RotateKeyChangeData::new(key_attributes, public_key);
let data_binary = serde_bare::to_vec(&data).map_err(|_| OckamError::BareError)?;
let data_hash = v.sha256(data_binary.as_slice())?;
let self_signature = v.sign(&secret_key, &data_hash)?;
let prev_signature = v.sign(&last_key_in_chain, &data_hash)?;
let change = RotateKeyChange::new(data, self_signature, prev_signature);
let profile_change = ProfileChange::new(
PROFILE_CHANGE_CURRENT_VERSION,
prev_event_id,
attributes.clone(),
ProfileChangeType::RotateKey(change),
);
let changes = vec![profile_change];
let changes_binary = serde_bare::to_vec(&changes).map_err(|_| OckamError::BareError)?;
let event_id = v.sha256(&changes_binary)?;
let event_id = EventIdentifier::from_hash(event_id);
let signature = v.sign(root_key, event_id.as_ref())?;
// TODO: Find root key and sign with it
let proof =
ProfileChangeProof::Signature(Signature::new(SignatureType::RootSign, signature));
let signed_change_event = ProfileChangeEvent::new(event_id, changes, proof);
Ok(signed_change_event)
}
}
| 31.222222 | 94 | 0.653381 |
ff7b3c5d371cec5cb5bc39bf274a1469edb4d5f3
| 27,875 |
use super::helpers;
use spirv::{Op, Word};
pub(super) enum Signedness {
Unsigned = 0,
Signed = 1,
}
pub(super) enum SampleLod {
Explicit,
Implicit,
}
pub(super) struct Case {
pub value: Word,
pub label_id: Word,
}
impl super::Instruction {
//
// Debug Instructions
//
pub(super) fn source(source_language: spirv::SourceLanguage, version: u32) -> Self {
let mut instruction = Self::new(Op::Source);
instruction.add_operand(source_language as u32);
instruction.add_operands(helpers::bytes_to_words(&version.to_le_bytes()));
instruction
}
pub(super) fn name(target_id: Word, name: &str) -> Self {
let mut instruction = Self::new(Op::Name);
instruction.add_operand(target_id);
instruction.add_operands(helpers::string_to_words(name));
instruction
}
pub(super) fn member_name(target_id: Word, member: Word, name: &str) -> Self {
let mut instruction = Self::new(Op::MemberName);
instruction.add_operand(target_id);
instruction.add_operand(member);
instruction.add_operands(helpers::string_to_words(name));
instruction
}
//
// Annotation Instructions
//
pub(super) fn decorate(
target_id: Word,
decoration: spirv::Decoration,
operands: &[Word],
) -> Self {
let mut instruction = Self::new(Op::Decorate);
instruction.add_operand(target_id);
instruction.add_operand(decoration as u32);
for operand in operands {
instruction.add_operand(*operand)
}
instruction
}
pub(super) fn member_decorate(
target_id: Word,
member_index: Word,
decoration: spirv::Decoration,
operands: &[Word],
) -> Self {
let mut instruction = Self::new(Op::MemberDecorate);
instruction.add_operand(target_id);
instruction.add_operand(member_index);
instruction.add_operand(decoration as u32);
for operand in operands {
instruction.add_operand(*operand)
}
instruction
}
//
// Extension Instructions
//
pub(super) fn extension(name: &str) -> Self {
let mut instruction = Self::new(Op::Extension);
instruction.add_operands(helpers::string_to_words(name));
instruction
}
pub(super) fn ext_inst_import(id: Word, name: &str) -> Self {
let mut instruction = Self::new(Op::ExtInstImport);
instruction.set_result(id);
instruction.add_operands(helpers::string_to_words(name));
instruction
}
pub(super) fn ext_inst(
set_id: Word,
op: spirv::GLOp,
result_type_id: Word,
id: Word,
operands: &[Word],
) -> Self {
let mut instruction = Self::new(Op::ExtInst);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(set_id);
instruction.add_operand(op as u32);
for operand in operands {
instruction.add_operand(*operand)
}
instruction
}
//
// Mode-Setting Instructions
//
pub(super) fn memory_model(
addressing_model: spirv::AddressingModel,
memory_model: spirv::MemoryModel,
) -> Self {
let mut instruction = Self::new(Op::MemoryModel);
instruction.add_operand(addressing_model as u32);
instruction.add_operand(memory_model as u32);
instruction
}
pub(super) fn entry_point(
execution_model: spirv::ExecutionModel,
entry_point_id: Word,
name: &str,
interface_ids: &[Word],
) -> Self {
let mut instruction = Self::new(Op::EntryPoint);
instruction.add_operand(execution_model as u32);
instruction.add_operand(entry_point_id);
instruction.add_operands(helpers::string_to_words(name));
for interface_id in interface_ids {
instruction.add_operand(*interface_id);
}
instruction
}
pub(super) fn execution_mode(
entry_point_id: Word,
execution_mode: spirv::ExecutionMode,
args: &[Word],
) -> Self {
let mut instruction = Self::new(Op::ExecutionMode);
instruction.add_operand(entry_point_id);
instruction.add_operand(execution_mode as u32);
for arg in args {
instruction.add_operand(*arg);
}
instruction
}
pub(super) fn capability(capability: spirv::Capability) -> Self {
let mut instruction = Self::new(Op::Capability);
instruction.add_operand(capability as u32);
instruction
}
//
// Type-Declaration Instructions
//
pub(super) fn type_void(id: Word) -> Self {
let mut instruction = Self::new(Op::TypeVoid);
instruction.set_result(id);
instruction
}
pub(super) fn type_bool(id: Word) -> Self {
let mut instruction = Self::new(Op::TypeBool);
instruction.set_result(id);
instruction
}
pub(super) fn type_int(id: Word, width: Word, signedness: Signedness) -> Self {
let mut instruction = Self::new(Op::TypeInt);
instruction.set_result(id);
instruction.add_operand(width);
instruction.add_operand(signedness as u32);
instruction
}
pub(super) fn type_float(id: Word, width: Word) -> Self {
let mut instruction = Self::new(Op::TypeFloat);
instruction.set_result(id);
instruction.add_operand(width);
instruction
}
pub(super) fn type_vector(
id: Word,
component_type_id: Word,
component_count: crate::VectorSize,
) -> Self {
let mut instruction = Self::new(Op::TypeVector);
instruction.set_result(id);
instruction.add_operand(component_type_id);
instruction.add_operand(component_count as u32);
instruction
}
pub(super) fn type_matrix(
id: Word,
column_type_id: Word,
column_count: crate::VectorSize,
) -> Self {
let mut instruction = Self::new(Op::TypeMatrix);
instruction.set_result(id);
instruction.add_operand(column_type_id);
instruction.add_operand(column_count as u32);
instruction
}
pub(super) fn type_image(
id: Word,
sampled_type_id: Word,
dim: spirv::Dim,
arrayed: bool,
image_class: crate::ImageClass,
) -> Self {
let mut instruction = Self::new(Op::TypeImage);
instruction.set_result(id);
instruction.add_operand(sampled_type_id);
instruction.add_operand(dim as u32);
let (depth, multi, sampled) = match image_class {
crate::ImageClass::Sampled { kind: _, multi } => (false, multi, true),
crate::ImageClass::Depth { multi } => (true, multi, true),
crate::ImageClass::Storage { .. } => (false, false, false),
};
instruction.add_operand(depth as u32);
instruction.add_operand(arrayed as u32);
instruction.add_operand(multi as u32);
instruction.add_operand(if sampled { 1 } else { 2 });
let format = match image_class {
crate::ImageClass::Storage { format, .. } => match format {
crate::StorageFormat::R8Unorm => spirv::ImageFormat::R8,
crate::StorageFormat::R8Snorm => spirv::ImageFormat::R8Snorm,
crate::StorageFormat::R8Uint => spirv::ImageFormat::R8ui,
crate::StorageFormat::R8Sint => spirv::ImageFormat::R8i,
crate::StorageFormat::R16Uint => spirv::ImageFormat::R16ui,
crate::StorageFormat::R16Sint => spirv::ImageFormat::R16i,
crate::StorageFormat::R16Float => spirv::ImageFormat::R16f,
crate::StorageFormat::Rg8Unorm => spirv::ImageFormat::Rg8,
crate::StorageFormat::Rg8Snorm => spirv::ImageFormat::Rg8Snorm,
crate::StorageFormat::Rg8Uint => spirv::ImageFormat::Rg8ui,
crate::StorageFormat::Rg8Sint => spirv::ImageFormat::Rg8i,
crate::StorageFormat::R32Uint => spirv::ImageFormat::R32ui,
crate::StorageFormat::R32Sint => spirv::ImageFormat::R32i,
crate::StorageFormat::R32Float => spirv::ImageFormat::R32f,
crate::StorageFormat::Rg16Uint => spirv::ImageFormat::Rg16ui,
crate::StorageFormat::Rg16Sint => spirv::ImageFormat::Rg16i,
crate::StorageFormat::Rg16Float => spirv::ImageFormat::Rg16f,
crate::StorageFormat::Rgba8Unorm => spirv::ImageFormat::Rgba8,
crate::StorageFormat::Rgba8Snorm => spirv::ImageFormat::Rgba8Snorm,
crate::StorageFormat::Rgba8Uint => spirv::ImageFormat::Rgba8ui,
crate::StorageFormat::Rgba8Sint => spirv::ImageFormat::Rgba8i,
crate::StorageFormat::Rgb10a2Unorm => spirv::ImageFormat::Rgb10a2ui,
crate::StorageFormat::Rg11b10Float => spirv::ImageFormat::R11fG11fB10f,
crate::StorageFormat::Rg32Uint => spirv::ImageFormat::Rg32ui,
crate::StorageFormat::Rg32Sint => spirv::ImageFormat::Rg32i,
crate::StorageFormat::Rg32Float => spirv::ImageFormat::Rg32f,
crate::StorageFormat::Rgba16Uint => spirv::ImageFormat::Rgba16ui,
crate::StorageFormat::Rgba16Sint => spirv::ImageFormat::Rgba16i,
crate::StorageFormat::Rgba16Float => spirv::ImageFormat::Rgba16f,
crate::StorageFormat::Rgba32Uint => spirv::ImageFormat::Rgba32ui,
crate::StorageFormat::Rgba32Sint => spirv::ImageFormat::Rgba32i,
crate::StorageFormat::Rgba32Float => spirv::ImageFormat::Rgba32f,
},
_ => spirv::ImageFormat::Unknown,
};
instruction.add_operand(format as u32);
instruction
}
pub(super) fn type_sampler(id: Word) -> Self {
let mut instruction = Self::new(Op::TypeSampler);
instruction.set_result(id);
instruction
}
pub(super) fn type_sampled_image(id: Word, image_type_id: Word) -> Self {
let mut instruction = Self::new(Op::TypeSampledImage);
instruction.set_result(id);
instruction.add_operand(image_type_id);
instruction
}
pub(super) fn type_array(id: Word, element_type_id: Word, length_id: Word) -> Self {
let mut instruction = Self::new(Op::TypeArray);
instruction.set_result(id);
instruction.add_operand(element_type_id);
instruction.add_operand(length_id);
instruction
}
pub(super) fn type_runtime_array(id: Word, element_type_id: Word) -> Self {
let mut instruction = Self::new(Op::TypeRuntimeArray);
instruction.set_result(id);
instruction.add_operand(element_type_id);
instruction
}
pub(super) fn type_struct(id: Word, member_ids: &[Word]) -> Self {
let mut instruction = Self::new(Op::TypeStruct);
instruction.set_result(id);
for member_id in member_ids {
instruction.add_operand(*member_id)
}
instruction
}
pub(super) fn type_pointer(
id: Word,
storage_class: spirv::StorageClass,
type_id: Word,
) -> Self {
let mut instruction = Self::new(Op::TypePointer);
instruction.set_result(id);
instruction.add_operand(storage_class as u32);
instruction.add_operand(type_id);
instruction
}
pub(super) fn type_function(id: Word, return_type_id: Word, parameter_ids: &[Word]) -> Self {
let mut instruction = Self::new(Op::TypeFunction);
instruction.set_result(id);
instruction.add_operand(return_type_id);
for parameter_id in parameter_ids {
instruction.add_operand(*parameter_id);
}
instruction
}
//
// Constant-Creation Instructions
//
pub(super) fn constant_null(result_type_id: Word, id: Word) -> Self {
let mut instruction = Self::new(Op::ConstantNull);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction
}
pub(super) fn constant_true(result_type_id: Word, id: Word) -> Self {
let mut instruction = Self::new(Op::ConstantTrue);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction
}
pub(super) fn constant_false(result_type_id: Word, id: Word) -> Self {
let mut instruction = Self::new(Op::ConstantFalse);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction
}
pub(super) fn constant(result_type_id: Word, id: Word, values: &[Word]) -> Self {
let mut instruction = Self::new(Op::Constant);
instruction.set_type(result_type_id);
instruction.set_result(id);
for value in values {
instruction.add_operand(*value);
}
instruction
}
pub(super) fn constant_composite(
result_type_id: Word,
id: Word,
constituent_ids: &[Word],
) -> Self {
let mut instruction = Self::new(Op::ConstantComposite);
instruction.set_type(result_type_id);
instruction.set_result(id);
for constituent_id in constituent_ids {
instruction.add_operand(*constituent_id);
}
instruction
}
//
// Memory Instructions
//
pub(super) fn variable(
result_type_id: Word,
id: Word,
storage_class: spirv::StorageClass,
initializer_id: Option<Word>,
) -> Self {
let mut instruction = Self::new(Op::Variable);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(storage_class as u32);
if let Some(initializer_id) = initializer_id {
instruction.add_operand(initializer_id);
}
instruction
}
pub(super) fn load(
result_type_id: Word,
id: Word,
pointer_id: Word,
memory_access: Option<spirv::MemoryAccess>,
) -> Self {
let mut instruction = Self::new(Op::Load);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(pointer_id);
if let Some(memory_access) = memory_access {
instruction.add_operand(memory_access.bits());
}
instruction
}
pub(super) fn atomic_load(
result_type_id: Word,
id: Word,
pointer_id: Word,
scope_id: Word,
semantics_id: Word,
) -> Self {
let mut instruction = Self::new(Op::AtomicLoad);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(pointer_id);
instruction.add_operand(scope_id);
instruction.add_operand(semantics_id);
instruction
}
pub(super) fn store(
pointer_id: Word,
value_id: Word,
memory_access: Option<spirv::MemoryAccess>,
) -> Self {
let mut instruction = Self::new(Op::Store);
instruction.add_operand(pointer_id);
instruction.add_operand(value_id);
if let Some(memory_access) = memory_access {
instruction.add_operand(memory_access.bits());
}
instruction
}
pub(super) fn atomic_store(
pointer_id: Word,
scope_id: Word,
semantics_id: Word,
value_id: Word,
) -> Self {
let mut instruction = Self::new(Op::AtomicStore);
instruction.add_operand(pointer_id);
instruction.add_operand(scope_id);
instruction.add_operand(semantics_id);
instruction.add_operand(value_id);
instruction
}
pub(super) fn access_chain(
result_type_id: Word,
id: Word,
base_id: Word,
index_ids: &[Word],
) -> Self {
let mut instruction = Self::new(Op::AccessChain);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(base_id);
for index_id in index_ids {
instruction.add_operand(*index_id);
}
instruction
}
pub(super) fn array_length(
result_type_id: Word,
id: Word,
structure_id: Word,
array_member: Word,
) -> Self {
let mut instruction = Self::new(Op::ArrayLength);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(structure_id);
instruction.add_operand(array_member);
instruction
}
//
// Function Instructions
//
pub(super) fn function(
return_type_id: Word,
id: Word,
function_control: spirv::FunctionControl,
function_type_id: Word,
) -> Self {
let mut instruction = Self::new(Op::Function);
instruction.set_type(return_type_id);
instruction.set_result(id);
instruction.add_operand(function_control.bits());
instruction.add_operand(function_type_id);
instruction
}
pub(super) fn function_parameter(result_type_id: Word, id: Word) -> Self {
let mut instruction = Self::new(Op::FunctionParameter);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction
}
pub(super) fn function_end() -> Self {
Self::new(Op::FunctionEnd)
}
pub(super) fn function_call(
result_type_id: Word,
id: Word,
function_id: Word,
argument_ids: &[Word],
) -> Self {
let mut instruction = Self::new(Op::FunctionCall);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(function_id);
for argument_id in argument_ids {
instruction.add_operand(*argument_id);
}
instruction
}
//
// Image Instructions
//
pub(super) fn sampled_image(
result_type_id: Word,
id: Word,
image: Word,
sampler: Word,
) -> Self {
let mut instruction = Self::new(Op::SampledImage);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(image);
instruction.add_operand(sampler);
instruction
}
pub(super) fn image_sample(
result_type_id: Word,
id: Word,
lod: SampleLod,
sampled_image: Word,
coordinates: Word,
depth_ref: Option<Word>,
) -> Self {
let op = match (lod, depth_ref) {
(SampleLod::Explicit, None) => Op::ImageSampleExplicitLod,
(SampleLod::Implicit, None) => Op::ImageSampleImplicitLod,
(SampleLod::Explicit, Some(_)) => Op::ImageSampleDrefExplicitLod,
(SampleLod::Implicit, Some(_)) => Op::ImageSampleDrefImplicitLod,
};
let mut instruction = Self::new(op);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(sampled_image);
instruction.add_operand(coordinates);
if let Some(dref) = depth_ref {
instruction.add_operand(dref);
}
instruction
}
pub(super) fn image_fetch_or_read(
op: Op,
result_type_id: Word,
id: Word,
image: Word,
coordinates: Word,
) -> Self {
let mut instruction = Self::new(op);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(image);
instruction.add_operand(coordinates);
instruction
}
pub(super) fn image_write(image: Word, coordinates: Word, value: Word) -> Self {
let mut instruction = Self::new(Op::ImageWrite);
instruction.add_operand(image);
instruction.add_operand(coordinates);
instruction.add_operand(value);
instruction
}
pub(super) fn image_query(op: Op, result_type_id: Word, id: Word, image: Word) -> Self {
let mut instruction = Self::new(op);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(image);
instruction
}
//
// Conversion Instructions
//
pub(super) fn unary(op: Op, result_type_id: Word, id: Word, value: Word) -> Self {
let mut instruction = Self::new(op);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(value);
instruction
}
//
// Composite Instructions
//
pub(super) fn composite_construct(
result_type_id: Word,
id: Word,
constituent_ids: &[Word],
) -> Self {
let mut instruction = Self::new(Op::CompositeConstruct);
instruction.set_type(result_type_id);
instruction.set_result(id);
for constituent_id in constituent_ids {
instruction.add_operand(*constituent_id);
}
instruction
}
pub(super) fn composite_extract(
result_type_id: Word,
id: Word,
composite_id: Word,
indices: &[Word],
) -> Self {
let mut instruction = Self::new(Op::CompositeExtract);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(composite_id);
for index in indices {
instruction.add_operand(*index);
}
instruction
}
pub(super) fn vector_extract_dynamic(
result_type_id: Word,
id: Word,
vector_id: Word,
index_id: Word,
) -> Self {
let mut instruction = Self::new(Op::VectorExtractDynamic);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(vector_id);
instruction.add_operand(index_id);
instruction
}
pub(super) fn vector_shuffle(
result_type_id: Word,
id: Word,
v1_id: Word,
v2_id: Word,
components: &[Word],
) -> Self {
let mut instruction = Self::new(Op::VectorShuffle);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(v1_id);
instruction.add_operand(v2_id);
for &component in components {
instruction.add_operand(component);
}
instruction
}
//
// Arithmetic Instructions
//
pub(super) fn binary(
op: Op,
result_type_id: Word,
id: Word,
operand_1: Word,
operand_2: Word,
) -> Self {
let mut instruction = Self::new(op);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(operand_1);
instruction.add_operand(operand_2);
instruction
}
pub(super) fn relational(op: Op, result_type_id: Word, id: Word, expr_id: Word) -> Self {
let mut instruction = Self::new(op);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(expr_id);
instruction
}
pub(super) fn atomic_binary(
op: Op,
result_type_id: Word,
id: Word,
pointer: Word,
scope_id: Word,
semantics_id: Word,
value: Word,
) -> Self {
let mut instruction = Self::new(op);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(pointer);
instruction.add_operand(scope_id);
instruction.add_operand(semantics_id);
instruction.add_operand(value);
instruction
}
//
// Bit Instructions
//
//
// Relational and Logical Instructions
//
//
// Derivative Instructions
//
pub(super) fn derivative(op: Op, result_type_id: Word, id: Word, expr_id: Word) -> Self {
let mut instruction = Self::new(op);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(expr_id);
instruction
}
//
// Control-Flow Instructions
//
pub(super) fn phi(
result_type_id: Word,
result_id: Word,
var_parent_pairs: &[(Word, Word)],
) -> Self {
let mut instruction = Self::new(Op::Phi);
instruction.add_operand(result_type_id);
instruction.add_operand(result_id);
for &(variable, parent) in var_parent_pairs {
instruction.add_operand(variable);
instruction.add_operand(parent);
}
instruction
}
pub(super) fn selection_merge(
merge_id: Word,
selection_control: spirv::SelectionControl,
) -> Self {
let mut instruction = Self::new(Op::SelectionMerge);
instruction.add_operand(merge_id);
instruction.add_operand(selection_control.bits());
instruction
}
pub(super) fn loop_merge(
merge_id: Word,
continuing_id: Word,
selection_control: spirv::SelectionControl,
) -> Self {
let mut instruction = Self::new(Op::LoopMerge);
instruction.add_operand(merge_id);
instruction.add_operand(continuing_id);
instruction.add_operand(selection_control.bits());
instruction
}
pub(super) fn label(id: Word) -> Self {
let mut instruction = Self::new(Op::Label);
instruction.set_result(id);
instruction
}
pub(super) fn branch(id: Word) -> Self {
let mut instruction = Self::new(Op::Branch);
instruction.add_operand(id);
instruction
}
// TODO Branch Weights not implemented.
pub(super) fn branch_conditional(
condition_id: Word,
true_label: Word,
false_label: Word,
) -> Self {
let mut instruction = Self::new(Op::BranchConditional);
instruction.add_operand(condition_id);
instruction.add_operand(true_label);
instruction.add_operand(false_label);
instruction
}
pub(super) fn switch(selector_id: Word, default_id: Word, cases: &[Case]) -> Self {
let mut instruction = Self::new(Op::Switch);
instruction.add_operand(selector_id);
instruction.add_operand(default_id);
for case in cases {
instruction.add_operand(case.value);
instruction.add_operand(case.label_id);
}
instruction
}
pub(super) fn select(
result_type_id: Word,
id: Word,
condition_id: Word,
accept_id: Word,
reject_id: Word,
) -> Self {
let mut instruction = Self::new(Op::Select);
instruction.add_operand(result_type_id);
instruction.add_operand(id);
instruction.add_operand(condition_id);
instruction.add_operand(accept_id);
instruction.add_operand(reject_id);
instruction
}
pub(super) fn kill() -> Self {
Self::new(Op::Kill)
}
pub(super) fn return_void() -> Self {
Self::new(Op::Return)
}
pub(super) fn return_value(value_id: Word) -> Self {
let mut instruction = Self::new(Op::ReturnValue);
instruction.add_operand(value_id);
instruction
}
//
// Atomic Instructions
//
//
// Primitive Instructions
//
// Barriers
pub(super) fn control_barrier(
exec_scope_id: Word,
mem_scope_id: Word,
semantics_id: Word,
) -> Self {
let mut instruction = Self::new(Op::ControlBarrier);
instruction.add_operand(exec_scope_id);
instruction.add_operand(mem_scope_id);
instruction.add_operand(semantics_id);
instruction
}
}
| 30.233189 | 97 | 0.606709 |
67259a8a36d23944a631f6a904347599b1711591
| 18,323 |
use crate::cx::*;
#[derive(Clone)]
pub enum Wrapping {
Char,
Word,
Line,
None,
Ellipsis(f32)
}
#[derive(Clone, Copy)]
pub struct TextStyle {
pub font: Font,
pub font_size: f32,
pub brightness: f32,
pub curve: f32,
pub line_spacing: f32,
pub top_drop: f32,
pub height_factor: f32,
}
impl Default for TextStyle {
fn default() -> Self {
TextStyle {
font: Font::default(),
font_size: 8.0,
brightness: 1.0,
curve: 0.6,
line_spacing: 1.4,
top_drop: 1.1,
height_factor: 1.3,
}
}
}
#[derive(Clone)]
pub struct Text {
pub text_style: TextStyle,
pub shader: Shader,
pub color: Color,
pub z: f32,
pub wrapping: Wrapping,
pub font_scale: f32,
}
impl Text {
pub fn new(cx: &mut Cx) -> Self {
Self {
text_style: TextStyle::default(),
shader: cx.add_shader(Self::def_text_shader(), "TextAtlas"),
z: 0.0,
wrapping: Wrapping::Word,
color: pick!(white).get(cx),
font_scale: 1.0,
}
}
fn geom()->Vec2Id{uid!()}
pub fn font_tc() -> Vec4Id {uid!()}
pub fn color() -> ColorId {uid!()}
pub fn x() -> FloatId {uid!()}
pub fn y() -> FloatId {uid!()}
pub fn w() -> FloatId {uid!()}
pub fn h() -> FloatId {uid!()}
pub fn z() -> FloatId {uid!()}
pub fn base_x() -> FloatId {uid!()}
pub fn base_y() -> FloatId {uid!()}
pub fn font_size() -> FloatId {uid!()}
pub fn marker() -> FloatId {uid!()}
pub fn char_offset() -> FloatId {uid!()}
pub fn brightness() -> FloatId {uid!()}
pub fn curve() -> FloatId {uid!()}
pub fn texturez() -> Texture2dId {uid!()}
pub fn def_text_shader() -> ShaderGen {
// lets add the draw shader lib
let mut sg = Cx::shader_defs(ShaderGen::new());
sg.geometry.add_quad_2d();
sg.compose(shader!{"
geometry geom: Self::geom();
texture texturez: Self::texturez();
instance font_tc: Self::font_tc();
instance color: Self::color();
instance x: Self::x();
instance y: Self::y();
instance w: Self::w();
instance h: Self::h();
instance z: Self::z();
instance base_x: Self::base_x();
instance base_y: Self::base_y();
instance font_size: Self::font_size();
instance char_offset: Self::char_offset();
instance marker: Self::marker();
varying tex_coord1: vec2;
varying tex_coord2: vec2;
varying tex_coord3: vec2;
varying clipped: vec2;
//let rect: vec4<Varying>;
uniform brightness: Self::brightness();
uniform curve: Self::curve();
fn get_color() -> vec4 {
return color;
}
fn pixel() -> vec4 {
let dx = dFdx(vec2(tex_coord1.x * 2048.0, 0.)).x;
let dp = 1.0 / 2048.0;
// basic hardcoded mipmapping so it stops 'swimming' in VR
// mipmaps are stored in red/green/blue channel
let s = 1.0;
if dx > 7.0 {
s = 0.7;
}
else if dx > 2.75 {
s = (
sample2d(texturez, tex_coord3.xy + vec2(0., 0.)).z
+ sample2d(texturez, tex_coord3.xy + vec2(dp, 0.)).z
+ sample2d(texturez, tex_coord3.xy + vec2(0., dp)).z
+ sample2d(texturez, tex_coord3.xy + vec2(dp, dp)).z
) * 0.25;
}
else if dx > 1.75 {
s = sample2d(texturez, tex_coord3.xy).z;
}
else if dx > 1.3 {
s = sample2d(texturez, tex_coord2.xy).y;
}
else {
s = sample2d(texturez, tex_coord1.xy).x;
}
s = pow(s, curve);
let col = get_color();//color!(white);//get_color();
return vec4(s * col.rgb * brightness * col.a, s * col.a);
}
fn vertex() -> vec4 {
let min_pos = vec2(x, y);
let max_pos = vec2(x + w, y - h);
clipped = clamp(
mix(min_pos, max_pos, geom) - draw_scroll.xy,
draw_clip.xy,
draw_clip.zw
);
let normalized: vec2 = (clipped - min_pos + draw_scroll.xy) / vec2(w, -h);
//rect = vec4(min_pos.x, min_pos.y, max_pos.x, max_pos.y) - draw_scroll.xyxy;
tex_coord1 = mix(
font_tc.xy,
font_tc.zw,
normalized.xy
);
tex_coord2 = mix(
font_tc.xy,
font_tc.xy + (font_tc.zw - font_tc.xy) * 0.75,
normalized.xy
);
tex_coord3 = mix(
font_tc.xy,
font_tc.xy + (font_tc.zw - font_tc.xy) * 0.6,
normalized.xy
);
return camera_projection * (camera_view * (view_transform * vec4(clipped.x, clipped.y, z + draw_zbias, 1.)));
}
"})
}
pub fn begin_text(&mut self, cx: &mut Cx) -> AlignedInstance {
//let font_id = self.font.font_id.unwrap();
let inst = cx.new_instance(&self.shader, 0);
let aligned = cx.align_instance(inst);
let text_style = &self.text_style;
let brightness = text_style.brightness;
let curve = text_style.curve;
if aligned.inst.need_uniforms_now(cx) {
aligned.inst.push_uniform_texture_2d_id(cx, cx.fonts_atlas.texture_id);
aligned.inst.push_uniform_float(cx, brightness);
aligned.inst.push_uniform_float(cx, curve);
}
return aligned
}
pub fn add_text<F>(&mut self, cx: &mut Cx, geom_x: f32, geom_y: f32, char_offset: usize, aligned: &mut AlignedInstance, chunk: &[char], mut char_callback: F)
where F: FnMut(char, usize, f32, f32) -> f32
{
if geom_x.is_nan() || geom_y.is_nan(){
return
}
let text_style = &self.text_style;
let mut geom_x = geom_x;
let mut char_offset = char_offset;
let font_id = text_style.font.font_id.unwrap();
let cxfont = &mut cx.fonts[font_id];
let dpi_factor = cx.current_dpi_factor;
//let geom_y = (geom_y * dpi_factor).floor() / dpi_factor;
let atlas_page_id = cxfont.get_atlas_page_id(dpi_factor, text_style.font_size);
let font = &mut cxfont.font_loaded.as_ref().unwrap();
let font_size_logical = text_style.font_size * 96.0 / (72.0 * font.units_per_em);
let font_size_pixels = font_size_logical * dpi_factor;
let atlas_page = &mut cxfont.atlas_pages[atlas_page_id];
let instance = {
let cxview = &mut cx.views[aligned.inst.view_id];
let draw_call = &mut cxview.draw_calls[aligned.inst.draw_call_id];
&mut draw_call.instance
};
for wc in chunk {
let unicode = *wc as usize;
let glyph_id = font.char_code_to_glyph_index_map[unicode];
if glyph_id >= font.glyphs.len() {
println!("GLYPHID OUT OF BOUNDS {} {} len is {}", unicode, glyph_id, font.glyphs.len());
continue;
}
let glyph = &font.glyphs[glyph_id];
let advance = glyph.horizontal_metrics.advance_width * font_size_logical * self.font_scale;
// snap width/height to pixel granularity
let w = ((glyph.bounds.p_max.x - glyph.bounds.p_min.x) * font_size_pixels).ceil() + 1.0;
let h = ((glyph.bounds.p_max.y - glyph.bounds.p_min.y) * font_size_pixels).ceil() + 1.0;
// this one needs pixel snapping
let min_pos_x = geom_x + font_size_logical * glyph.bounds.p_min.x;
let min_pos_y = geom_y - font_size_logical * glyph.bounds.p_min.y + text_style.font_size * text_style.top_drop;
// compute subpixel shift
let subpixel_x_fract = min_pos_x - (min_pos_x * dpi_factor).floor() / dpi_factor;
let subpixel_y_fract = min_pos_y - (min_pos_y * dpi_factor).floor() / dpi_factor;
// scale and snap it
let scaled_min_pos_x = geom_x + font_size_logical * self.font_scale * glyph.bounds.p_min.x - subpixel_x_fract;
let scaled_min_pos_y = geom_y - font_size_logical * self.font_scale * glyph.bounds.p_min.y + text_style.font_size * self.font_scale * text_style.top_drop - subpixel_y_fract;
// only use a subpixel id for small fonts
let subpixel_id = if text_style.font_size>32.0 {
0
}
else { // subtle 64 index subpixel id
((subpixel_y_fract * 7.0) as usize) << 3 |
(subpixel_x_fract * 7.0) as usize
};
let tc = if let Some(tc) = &atlas_page.atlas_glyphs[glyph_id][subpixel_id] {
//println!("{} {} {} {}", tc.tx1,tc.tx2,tc.ty1,tc.ty2);
tc
}
else {
// see if we can fit it
// allocate slot
cx.fonts_atlas.atlas_todo.push(CxFontsAtlasTodo {
subpixel_x_fract,
subpixel_y_fract,
font_id,
atlas_page_id,
glyph_id,
subpixel_id
});
atlas_page.atlas_glyphs[glyph_id][subpixel_id] = Some(
cx.fonts_atlas.alloc_atlas_glyph(&cxfont.path, w, h)
);
atlas_page.atlas_glyphs[glyph_id][subpixel_id].as_ref().unwrap()
};
// give the callback a chance to do things
let marker = char_callback(*wc, char_offset, geom_x, advance);
let data = [
tc.tx1,
tc.ty1,
tc.tx2,
tc.ty2,
self.color.r, // color
self.color.g,
self.color.b,
self.color.a,
scaled_min_pos_x,
scaled_min_pos_y,
w * self.font_scale / dpi_factor,
h * self.font_scale / dpi_factor,
self.z + 0.00001 * min_pos_x, //slight z-bias so we don't get z-fighting with neighbouring chars overlap a bit
geom_x,
geom_y,
text_style.font_size,
char_offset as f32, // char_offset
marker, // marker
];
instance.extend_from_slice(&data);
// !TODO make sure a derived shader adds 'empty' values here.
geom_x += advance;
char_offset += 1;
aligned.inst.instance_count += 1;
}
}
pub fn end_text(&mut self, cx: &mut Cx, aligned: &AlignedInstance) -> Area {
cx.update_aligned_instance_count(aligned);
aligned.inst.into()
}
pub fn draw_text(&mut self, cx: &mut Cx, text: &str) -> Area {
let mut aligned = self.begin_text(cx);
let mut chunk = Vec::new();
let mut width = 0.0;
let mut elipct = 0;
let text_style = &self.text_style;
let font_size = text_style.font_size;
let line_spacing = text_style.line_spacing;
let height_factor = text_style.height_factor;
let mut iter = text.chars().peekable();
let font_id = text_style.font.font_id.unwrap();
let font_size_logical = text_style.font_size * 96.0 / (72.0 * cx.fonts[font_id].font_loaded.as_ref().unwrap().units_per_em);
while let Some(c) = iter.next() {
let last = iter.peek().is_none();
let mut emit = last;
let mut newline = false;
let slot = if c < '\u{10000}' {
cx.fonts[font_id].font_loaded.as_ref().unwrap().char_code_to_glyph_index_map[c as usize]
} else {
0
};
if c == '\n' {
emit = true;
newline = true;
}
if slot != 0 {
let glyph = &cx.fonts[font_id].font_loaded.as_ref().unwrap().glyphs[slot];
width += glyph.horizontal_metrics.advance_width * font_size_logical * self.font_scale;
match self.wrapping {
Wrapping::Char => {
chunk.push(c);
emit = true
},
Wrapping::Word => {
chunk.push(c);
if c == ' ' || c == '\t' || c == ',' || c == '\n' {
emit = true;
}
},
Wrapping::Line => {
chunk.push(c);
if c == 10 as char || c == 13 as char {
emit = true;
}
newline = true;
},
Wrapping::None => {
chunk.push(c);
},
Wrapping::Ellipsis(ellipsis_width) => {
if width>ellipsis_width { // output ...
if elipct < 3 {
chunk.push('.');
elipct += 1;
}
}
else {
chunk.push(c)
}
}
}
}
if emit {
let height = font_size * height_factor * self.font_scale;
let geom = cx.walk_turtle(Walk {
width: Width::Fix(width),
height: Height::Fix(height),
margin: Margin::zero()
});
self.add_text(cx, geom.x, geom.y, 0, &mut aligned, &chunk, | _, _, _, _ | {0.0});
width = 0.0;
chunk.truncate(0);
if newline {
cx.turtle_new_line_min_height(font_size * line_spacing * self.font_scale);
}
}
}
self.end_text(cx, &aligned)
}
// looks up text with the behavior of a text selection mouse cursor
pub fn find_closest_offset(&self, cx: &Cx, area: &Area, pos: Vec2) -> usize {
let scroll_pos = area.get_scroll_pos(cx);
let spos = Vec2 {x: pos.x + scroll_pos.x, y: pos.y + scroll_pos.y};
let x_o = area.get_instance_offset(cx, Self::base_x().into()).unwrap();
let y_o = area.get_instance_offset(cx, Self::base_y().into()).unwrap();
let w_o = area.get_instance_offset(cx, Self::w().into()).unwrap();
let font_size_o = area.get_instance_offset(cx, Self::font_size().into()).unwrap();
let char_offset_o = area.get_instance_offset(cx, Self::char_offset().into()).unwrap();
let read = area.get_read_ref(cx);
let text_style = &self.text_style;
let line_spacing = text_style.line_spacing;
let mut index = 0;
if let Some(read) = read {
while index < read.count {
let y = read.buffer[read.offset + y_o + index * read.slots];
let font_size = read.buffer[read.offset + font_size_o + index * read.slots];
if y + font_size * line_spacing > spos.y { // alright lets find our next x
while index < read.count {
let x = read.buffer[read.offset + x_o + index * read.slots];
let y = read.buffer[read.offset + y_o + index * read.slots];
//let font_size = read.buffer[read.offset + font_size_o + index* read.slots];
let w = read.buffer[read.offset + w_o + index * read.slots];
if x > spos.x + w * 0.5 || y > spos.y {
let prev_index = if index == 0 {0}else {index - 1};
let prev_x = read.buffer[read.offset + x_o + prev_index * read.slots];
let prev_w = read.buffer[read.offset + w_o + prev_index * read.slots];
if index < read.count - 1 && prev_x > spos.x + prev_w { // fix newline jump-back
return read.buffer[read.offset + char_offset_o + index * read.slots] as usize;
}
return read.buffer[read.offset + char_offset_o + prev_index * read.slots] as usize;
}
index += 1;
}
}
index += 1;
}
if read.count == 0 {
return 0
}
return read.buffer[read.offset + char_offset_o + (read.count - 1) * read.slots] as usize;
}
return 0
}
pub fn get_monospace_base(&self, cx: &Cx) -> Vec2 {
let font_id = self.text_style.font.font_id.unwrap();
let font = cx.fonts[font_id].font_loaded.as_ref().unwrap();
let slot = font.char_code_to_glyph_index_map[33];
let glyph = &font.glyphs[slot];
//let font_size = if let Some(font_size) = font_size{font_size}else{self.font_size};
Vec2 {
x: glyph.horizontal_metrics.advance_width * (96.0 / (72.0 * font.units_per_em)),
y: self.text_style.line_spacing
}
}
}
| 38.902335 | 185 | 0.478961 |
c1ec5ff54d70aab72660d127d2975c194b79afad
| 3,026 |
use chrono::{Utc, Datelike};
use std::fs;
use std::fs::OpenOptions;
use std::sync::mpsc::Sender;
use std::sync::mpsc::Receiver;
use std::io::{Write, LineWriter};
use crate::utils::extension::Logging;
use crate::utils::extension::TimeLogged;
use core::fmt;
static LOGS_FOLDER: &str = "./logs";
#[derive(Copy, Debug, Clone, PartialEq)]
pub enum LoggerLevel { DEBUG = 1, INFO = 2, ERROR = 3 }
impl fmt::Display for LoggerLevel {
fn fmt(&self, format: &mut fmt::Formatter) -> fmt::Result {
match *self {
LoggerLevel::DEBUG => write!(format, "DEBUG"),
LoggerLevel::INFO => write!(format, "INFO"),
LoggerLevel::ERROR => write!(format, "ERROR")
}
}
}
impl LoggerLevel {
pub(crate) fn from_i32(value: i32) -> LoggerLevel {
match value {
1 => LoggerLevel::DEBUG,
2 => LoggerLevel::INFO,
3 => LoggerLevel::ERROR,
_ => panic!("Unknown value: {}", value)
}
}
}
pub struct LoggerWriter {}
impl LoggerWriter {
pub fn run(receiver: Receiver<String>) {
fs::create_dir_all(LOGS_FOLDER).expect("Couldn't create log folder!");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(LoggerWriter::log_name())
.expect("Couldn't create log file!");
let mut line_writer = LineWriter::new(file);
for received in receiver {
line_writer.write_all(received.as_bytes()).expect("Error writing log!");
}
}
fn log_name() -> String {
let now = Utc::now();
let mut buffer: String = String::new();
buffer.push_str(LOGS_FOLDER);
buffer.push_str("/");
buffer.push_str(now.year().to_string().as_str());
if now.month() < 10 {
buffer.push_str("0");
buffer.push_str(now.month().to_string().as_str());
} else {
buffer.push_str(now.month().to_string().as_str());
}
if now.day() < 10 {
buffer.push_str("0");
buffer.push_str(now.day().to_string().as_str());
} else {
buffer.push_str(now.day().to_string().as_str());
}
buffer.push_str(".log");
return buffer;
}
}
#[derive(Clone)]
pub struct Logger {
sender: Sender<String>,
logger_level: LoggerLevel,
}
impl Logger {
pub fn new(sender: Sender<String>, logger_level: LoggerLevel) -> Logger {
Logger { sender, logger_level }
}
pub fn debug(&self, message: String) {
if self.logger_level == LoggerLevel::DEBUG {
self.sender.log(format!("[DEBUG] {}\n", message.time_logged()));
}
}
pub fn info(&self, message: String) {
if self.logger_level != LoggerLevel::ERROR {
self.sender.log(format!("[INFO] {}\n", message.time_logged()));
}
}
pub fn error(&self, message: String) {
self.sender.log(format!("[ERROR] {}\n", message.time_logged()));
}
}
| 28.018519 | 84 | 0.562789 |
8a5ec9098fa3b23df42305b0af961f3cc2ddf4f4
| 5,332 |
use bzip2::bufread::BzDecoder;
use log::*;
use safecoin_client::rpc_client::RpcClient;
use solana_net_utils::parse_host;
use solana_notifier::Notifier;
use solana_sdk::{
clock::{Epoch, Slot},
genesis_config::GenesisConfig,
timing::duration_as_ms,
};
use std::{
fs::File,
io,
net::SocketAddr,
path::Path,
thread::sleep,
time::{Duration, Instant},
};
use tar::Archive;
const GENESIS_ARCHIVE_NAME: &str = "genesis.tar.bz2";
/// Inspired by solana_local_cluster::cluster_tests
fn slots_to_secs(num_slots: u64, genesis_config: &GenesisConfig) -> u64 {
let poh_config = &genesis_config.poh_config;
let ticks_per_slot = genesis_config.ticks_per_slot;
let num_ticks_to_sleep = num_slots as f64 * ticks_per_slot as f64;
let num_ticks_per_second = (1000 / duration_as_ms(&poh_config.target_tick_duration)) as f64;
((num_ticks_to_sleep + num_ticks_per_second - 1.0) / num_ticks_per_second) as u64
}
fn sleep_n_slots(num_slots: u64, genesis_config: &GenesisConfig) {
let secs = slots_to_secs(num_slots, genesis_config);
let mins = secs / 60;
let hours = mins / 60;
if hours >= 5 {
debug!("Sleeping for {} slots ({} hours)", num_slots, hours);
} else if mins >= 5 {
debug!("Sleeping for {} slots ({} minutes)", num_slots, mins);
} else if secs > 0 {
debug!("Sleeping for {} slots ({} seconds)", num_slots, secs);
}
sleep(Duration::from_secs(secs));
}
/// Sleep until the target epoch has started or bail if cluster is stuck
pub fn sleep_until_epoch(
rpc_client: &RpcClient,
notifier: &Notifier,
genesis_config: &GenesisConfig,
mut current_slot: Slot,
target_epoch: Epoch,
) {
let target_slot = genesis_config
.epoch_schedule
.get_first_slot_in_epoch(target_epoch);
info!(
"sleep_until_epoch() target_epoch: {}, target_slot: {}",
target_epoch, target_slot
);
loop {
let sleep_slots = target_slot.saturating_sub(current_slot);
if sleep_slots == 0 {
break;
}
sleep_n_slots(sleep_slots.max(50), genesis_config);
let latest_slot = rpc_client.get_slot().unwrap_or_else(|err| {
bail(
notifier,
&format!("Error: Could not fetch current slot: {}", err),
);
});
if current_slot == latest_slot {
bail(
notifier,
&format!("Error: Slot did not advance from {}", current_slot),
);
} else {
current_slot = latest_slot;
}
}
}
pub fn is_host(string: String) -> Result<(), String> {
parse_host(&string)?;
Ok(())
}
pub fn bail(notifier: &Notifier, msg: &str) -> ! {
notifier.send(msg);
sleep(Duration::from_secs(30)); // Wait for notifications to send
std::process::exit(1);
}
/// Inspired by safecoin_validator::download_tar_bz2
pub fn download_genesis(rpc_addr: &SocketAddr, download_path: &Path) -> Result<(), String> {
let archive_name = GENESIS_ARCHIVE_NAME;
let archive_path = download_path.join(archive_name);
let url = format!("http://{}/{}", rpc_addr, archive_name);
let download_start = Instant::now();
debug!("Downloading genesis ({})...", url);
let client = reqwest::blocking::Client::new();
let mut response = client
.get(url.as_str())
.send()
.and_then(|response| response.error_for_status())
.map_err(|err| format!("Unable to get: {:?}", err))?;
let download_size = {
response
.headers()
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|content_length| content_length.to_str().ok())
.and_then(|content_length| content_length.parse().ok())
.unwrap_or(0)
};
let mut file = File::create(&archive_path)
.map_err(|err| format!("Unable to create {:?}: {:?}", archive_path, err))?;
io::copy(&mut response, &mut file)
.map_err(|err| format!("Unable to write {:?}: {:?}", archive_path, err))?;
debug!(
"Downloaded genesis ({} bytes) in {:?}",
download_size,
Instant::now().duration_since(download_start),
);
debug!("Extracting genesis ({})...", archive_name);
let extract_start = Instant::now();
let tar_bz2 = File::open(&archive_path)
.map_err(|err| format!("Unable to open {}: {:?}", archive_name, err))?;
let tar = BzDecoder::new(io::BufReader::new(tar_bz2));
let mut archive = Archive::new(tar);
archive
.unpack(download_path)
.map_err(|err| format!("Unable to unpack {}: {:?}", archive_name, err))?;
debug!(
"Extracted {} in {:?}",
archive_name,
Instant::now().duration_since(extract_start)
);
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_slots_to_secs() {
let mut genesis_config = GenesisConfig::default();
genesis_config.poh_config.target_tick_duration = Duration::from_millis(500);
genesis_config.ticks_per_slot = 10;
assert_eq!(slots_to_secs(2, &genesis_config), 10);
genesis_config.ticks_per_slot = 1;
assert_eq!(slots_to_secs(1, &genesis_config), 1);
genesis_config.ticks_per_slot = 0;
assert_eq!(slots_to_secs(10, &genesis_config), 0);
}
}
| 31.550296 | 96 | 0.618342 |
3a700317a320c5b78a041cf989b0b11772f4b1a3
| 10,690 |
#[cfg(feature = "parallel")]
mod stepped {
use crate::parallel::num_threads;
/// An iterator adaptor to allow running computations using [`in_parallel()`][crate::parallel::in_parallel()] in a step-wise manner, see the [module docs][crate::parallel]
/// for details.
pub struct Stepwise<Reduce: super::Reduce> {
/// This field is first to assure it's dropped first and cause threads that are dropped next to stop their loops
/// as sending results fails when the receiver is dropped.
receive_result: std::sync::mpsc::Receiver<Reduce::Input>,
/// `join()` will be called on these guards to assure every thread tries to send through a closed channel. When
/// that happens, they break out of their loops.
_threads: Vec<std::thread::JoinHandle<()>>,
/// The reducer is called only in the thread using the iterator, dropping it has no side effects.
reducer: Option<Reduce>,
}
impl<Reduce: super::Reduce> Drop for Stepwise<Reduce> {
fn drop(&mut self) {
let (_, sink) = std::sync::mpsc::channel();
drop(std::mem::replace(&mut self.receive_result, sink));
let mut last_err = None;
for handle in std::mem::take(&mut self._threads) {
if let Err(err) = handle.join() {
last_err = Some(err);
};
}
if let Some(thread_err) = last_err {
std::panic::resume_unwind(thread_err);
}
}
}
impl<Reduce: super::Reduce> Stepwise<Reduce> {
/// Instantiate a new iterator and start working in threads.
/// For a description of parameters, see [`in_parallel()`][crate::parallel::in_parallel()].
pub fn new<InputIter, ThreadStateFn, ConsumeFn, I, O, S>(
input: InputIter,
thread_limit: Option<usize>,
new_thread_state: ThreadStateFn,
consume: ConsumeFn,
reducer: Reduce,
) -> Self
where
InputIter: Iterator<Item = I> + Send + 'static,
ThreadStateFn: Fn(usize) -> S + Send + Clone + 'static,
ConsumeFn: Fn(I, &mut S) -> O + Send + Clone + 'static,
Reduce: super::Reduce<Input = O> + 'static,
I: Send + 'static,
O: Send + 'static,
{
let num_threads = num_threads(thread_limit);
let mut threads = Vec::with_capacity(num_threads + 1);
let receive_result = {
let (send_input, receive_input) = crossbeam_channel::bounded::<I>(num_threads);
let (send_result, receive_result) = std::sync::mpsc::sync_channel::<O>(num_threads);
for thread_id in 0..num_threads {
let handle = std::thread::spawn({
let send_result = send_result.clone();
let receive_input = receive_input.clone();
let new_thread_state = new_thread_state.clone();
let consume = consume.clone();
move || {
let mut state = new_thread_state(thread_id);
for item in receive_input {
if send_result.send(consume(item, &mut state)).is_err() {
break;
}
}
}
});
threads.push(handle);
}
threads.push(std::thread::spawn(move || {
for item in input {
if send_input.send(item).is_err() {
break;
}
}
}));
receive_result
};
Stepwise {
_threads: threads,
receive_result,
reducer: Some(reducer),
}
}
/// Consume the iterator by finishing its iteration and calling [`Reduce::finalize()`][crate::parallel::Reduce::finalize()].
pub fn finalize(mut self) -> Result<Reduce::Output, Reduce::Error> {
for value in self.by_ref() {
drop(value?);
}
self.reducer
.take()
.expect("this is the last call before consumption")
.finalize()
}
}
impl<Reduce: super::Reduce> Iterator for Stepwise<Reduce> {
type Item = Result<Reduce::FeedProduce, Reduce::Error>;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
self.receive_result
.recv()
.ok()
.and_then(|input| self.reducer.as_mut().map(|r| r.feed(input)))
}
}
impl<R: super::Reduce> super::Finalize for Stepwise<R> {
type Reduce = R;
fn finalize(
self,
) -> Result<
<<Self as super::Finalize>::Reduce as super::Reduce>::Output,
<<Self as super::Finalize>::Reduce as super::Reduce>::Error,
> {
Stepwise::finalize(self)
}
}
}
#[cfg(not(feature = "parallel"))]
mod stepped {
/// An iterator adaptor to allow running computations using [`in_parallel()`][crate::parallel::in_parallel()] in a step-wise manner, see the [module docs][crate::parallel]
/// for details.
pub struct Stepwise<InputIter, ConsumeFn, ThreadState, Reduce> {
input: InputIter,
consume: ConsumeFn,
thread_state: ThreadState,
reducer: Reduce,
}
impl<InputIter, ConsumeFn, Reduce, I, O, S> Stepwise<InputIter, ConsumeFn, S, Reduce>
where
InputIter: Iterator<Item = I>,
ConsumeFn: Fn(I, &mut S) -> O,
Reduce: super::Reduce<Input = O>,
{
/// Instantiate a new iterator.
/// For a description of parameters, see [`in_parallel()`][crate::parallel::in_parallel()].
pub fn new<ThreadStateFn>(
input: InputIter,
_thread_limit: Option<usize>,
new_thread_state: ThreadStateFn,
consume: ConsumeFn,
reducer: Reduce,
) -> Self
where
ThreadStateFn: Fn(usize) -> S,
{
Stepwise {
input,
consume,
thread_state: new_thread_state(0),
reducer,
}
}
/// Consume the iterator by finishing its iteration and calling [`Reduce::finalize()`][crate::parallel::Reduce::finalize()].
pub fn finalize(mut self) -> Result<Reduce::Output, Reduce::Error> {
for value in self.by_ref() {
drop(value?);
}
self.reducer.finalize()
}
}
impl<InputIter, ConsumeFn, ThreadState, Reduce, I, O> Iterator for Stepwise<InputIter, ConsumeFn, ThreadState, Reduce>
where
InputIter: Iterator<Item = I>,
ConsumeFn: Fn(I, &mut ThreadState) -> O,
Reduce: super::Reduce<Input = O>,
{
type Item = Result<Reduce::FeedProduce, Reduce::Error>;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
self.input
.next()
.map(|input| self.reducer.feed((self.consume)(input, &mut self.thread_state)))
}
}
impl<InputIter, ConsumeFn, R, I, O, S> super::Finalize for Stepwise<InputIter, ConsumeFn, S, R>
where
InputIter: Iterator<Item = I>,
ConsumeFn: Fn(I, &mut S) -> O,
R: super::Reduce<Input = O>,
{
type Reduce = R;
fn finalize(
self,
) -> Result<
<<Self as super::Finalize>::Reduce as super::Reduce>::Output,
<<Self as super::Finalize>::Reduce as super::Reduce>::Error,
> {
Stepwise::finalize(self)
}
}
}
use std::marker::PhantomData;
pub use stepped::Stepwise;
/// An trait for aggregating items commonly produced in threads into a single result, without itself
/// needing to be thread safe.
pub trait Reduce {
/// The type fed to the reducer in the [`feed()`][Reduce::feed()] method.
///
/// It's produced by a function that may run on multiple threads.
type Input;
/// The type produced in Ok(…) by [`feed()`][Reduce::feed()].
/// Most reducers by nature use `()` here as the value is in the aggregation.
/// However, some may use it to collect statistics only and return their Input
/// in some form as a result here for [`Stepwise`] to be useful.
type FeedProduce;
/// The type produced once by the [`finalize()`][Reduce::finalize()] method.
///
/// For traditional reducers, this is the value produced by the entire operation.
/// For those made for step-wise iteration this may be aggregated statistics.
type Output;
/// The error type to use for all methods of this trait.
type Error;
/// Called each time a new `item` was produced in order to aggregate it into the final result.
///
/// If an `Error` is returned, the entire operation will be stopped.
fn feed(&mut self, item: Self::Input) -> Result<Self::FeedProduce, Self::Error>;
/// Called once once all items where passed to `feed()`, producing the final `Output` of the operation or an `Error`.
fn finalize(self) -> Result<Self::Output, Self::Error>;
}
/// An identity reducer for those who want to use [`Stepwise`] or [`in_parallel()`][crate::parallel::in_parallel()]
/// without the use of non-threaded reduction of products created in threads.
pub struct IdentityWithResult<Input, Error> {
_input: PhantomData<Input>,
_error: PhantomData<Error>,
}
impl<Input, Error> Default for IdentityWithResult<Input, Error> {
fn default() -> Self {
IdentityWithResult {
_input: Default::default(),
_error: Default::default(),
}
}
}
impl<Input, Error> Reduce for IdentityWithResult<Input, Error> {
type Input = Result<Input, Self::Error>;
type FeedProduce = Input;
type Output = ();
type Error = Error;
fn feed(&mut self, item: Self::Input) -> Result<Self::FeedProduce, Self::Error> {
item
}
fn finalize(self) -> Result<Self::Output, Self::Error> {
Ok(())
}
}
/// A trait reflecting the `finalize()` method of [`Reduce`] implementations
pub trait Finalize {
/// An implementation of [`Reduce`]
type Reduce: self::Reduce;
/// Similar to the [`Reduce::finalize()`] method
fn finalize(
self,
) -> Result<<<Self as Finalize>::Reduce as self::Reduce>::Output, <<Self as Finalize>::Reduce as self::Reduce>::Error>;
}
| 38.178571 | 175 | 0.556688 |
1c575cf2e8cc2a309e314d0e9afb3d0efc1e91e6
| 7,603 |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
cluster::Cluster,
cluster_swarm::ClusterSwarm,
experiments::{Context, Experiment, ExperimentParam},
instance,
instance::Instance,
stats,
tx_emitter::EmitJobRequest,
util::unix_timestamp_now,
};
use anyhow::Result;
use async_trait::async_trait;
use futures::{future::try_join_all, join};
use libra_logger::info;
use serde_json::Value;
use std::{
collections::HashSet,
fmt::{Display, Error, Formatter},
time::Duration,
};
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
pub struct PerformanceBenchmarkParams {
#[structopt(
long,
default_value = "0",
help = "Percent of nodes which should be down"
)]
pub percent_nodes_down: usize,
#[structopt(long, help = "Whether benchmark should perform trace")]
pub trace: bool,
#[structopt(
long,
default_value = Box::leak(format!("{}", DEFAULT_BENCH_DURATION).into_boxed_str()),
help = "Duration of an experiment in seconds"
)]
pub duration: u64,
}
pub struct PerformanceBenchmark {
down_validators: Vec<Instance>,
up_validators: Vec<Instance>,
up_fullnodes: Vec<Instance>,
percent_nodes_down: usize,
duration: Duration,
trace: bool,
}
pub const DEFAULT_BENCH_DURATION: u64 = 120;
impl PerformanceBenchmarkParams {
pub fn new_nodes_down(percent_nodes_down: usize) -> Self {
Self {
percent_nodes_down,
duration: DEFAULT_BENCH_DURATION,
trace: false,
}
}
}
impl ExperimentParam for PerformanceBenchmarkParams {
type E = PerformanceBenchmark;
fn build(self, cluster: &Cluster) -> Self::E {
let all_fullnode_instances = cluster.fullnode_instances();
let num_nodes = cluster.validator_instances().len();
let nodes_down = (num_nodes * self.percent_nodes_down) / 100;
let (down, up) = cluster.split_n_validators_random(nodes_down);
let up_validators = up.into_validator_instances();
let up_fullnodes: Vec<_> = up_validators
.iter()
.filter_map(|val| {
all_fullnode_instances
.iter()
.find(|x| val.validator_index() == x.validator_index())
.cloned()
})
.collect();
Self::E {
down_validators: down.into_validator_instances(),
up_validators,
up_fullnodes,
percent_nodes_down: self.percent_nodes_down,
duration: Duration::from_secs(self.duration),
trace: self.trace,
}
}
}
#[async_trait]
impl Experiment for PerformanceBenchmark {
fn affected_validators(&self) -> HashSet<String> {
instance::instancelist_to_set(&self.down_validators)
}
async fn run(&mut self, context: &mut Context<'_>) -> Result<()> {
let instance_configs = instance::instance_configs(&self.down_validators)?;
let futures: Vec<_> = instance_configs
.into_iter()
.map(|ic| context.cluster_swarm.delete_node(ic.clone()))
.collect();
try_join_all(futures).await?;
let buffer = Duration::from_secs(60);
let window = self.duration + buffer * 2;
let emit_job_request = if context.emit_to_validator {
EmitJobRequest::for_instances(
self.up_validators.clone(),
context.global_emit_job_request,
)
} else {
EmitJobRequest::for_instances(
self.up_fullnodes.clone(),
context.global_emit_job_request,
)
};
let emit_txn = context.tx_emitter.emit_txn_for(window, emit_job_request);
let trace_tail = &context.trace_tail;
let trace_delay = buffer;
let trace = self.trace;
let capture_trace = async move {
if trace {
tokio::time::delay_for(trace_delay).await;
Some(trace_tail.capture_trace(Duration::from_secs(5)).await)
} else {
None
}
};
let (stats, trace) = join!(emit_txn, capture_trace);
let stats = stats?;
if let Some(trace) = trace {
info!("Traced {} events", trace.len());
let mut events = vec![];
for (node, mut event) in trace {
// This could be done more elegantly, but for now this will do
event
.json
.as_object_mut()
.unwrap()
.insert("peer".to_string(), Value::String(node));
events.push(event);
}
events.sort_by_key(|k| k.timestamp);
let node =
debug_interface::libra_trace::random_node(&events[..], "json-rpc::submit", "txn::")
.expect("No trace node found");
info!("Tracing {}", node);
debug_interface::libra_trace::trace_node(&events[..], &node);
}
let end = unix_timestamp_now() - buffer;
let start = end - window + 2 * buffer;
let avg_txns_per_block = stats::avg_txns_per_block(&context.prometheus, start, end)?;
let avg_latency_client = stats.latency / stats.committed;
let p90_latency = stats.latency_buckets.percentile(9, 10);
let avg_tps = stats.committed / window.as_secs();
info!(
"Link to dashboard : {}",
context.prometheus.link_to_dashboard(start, end)
);
info!(
"Tx status from client side: txn {}, avg latency {}",
stats.committed as u64, avg_latency_client
);
let instance_configs = instance::instance_configs(&self.down_validators)?;
let futures: Vec<_> = instance_configs
.into_iter()
.map(|ic| context.cluster_swarm.upsert_node(ic.clone(), false))
.collect();
try_join_all(futures).await?;
let submitted_txn = stats.submitted;
let expired_txn = stats.expired;
context
.report
.report_metric(&self, "submitted_txn", submitted_txn as f64);
context
.report
.report_metric(&self, "expired_txn", expired_txn as f64);
context
.report
.report_metric(&self, "avg_txns_per_block", avg_txns_per_block as f64);
context
.report
.report_metric(&self, "avg_tps", avg_tps as f64);
context
.report
.report_metric(&self, "avg_latency", avg_latency_client as f64);
context
.report
.report_metric(&self, "p90_latency", p90_latency as f64);
info!("avg_txns_per_block: {}", avg_txns_per_block);
let expired_text = if expired_txn == 0 {
"no expired txns".to_string()
} else {
format!("(!) expired {} out of {} txns", expired_txn, submitted_txn)
};
context.report.report_text(format!(
"{} : {:.0} TPS, {:.1} ms latency, {:.1} ms p90 latency, {}",
self, avg_tps, avg_latency_client, p90_latency, expired_text
));
Ok(())
}
fn deadline(&self) -> Duration {
Duration::from_secs(600)
}
}
impl Display for PerformanceBenchmark {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
if self.percent_nodes_down == 0 {
write!(f, "all up")
} else {
write!(f, "{}% down", self.percent_nodes_down)
}
}
}
| 34.716895 | 99 | 0.580297 |
bfa2e362f171ebd56603038a2e69ac8f240aaa4c
| 792 |
// Copyright © 2015-2017 winapi-rs developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
//! QoS definitions for NDIS components.
use shared::minwindef::ULONG;
pub type SERVICETYPE = ULONG;
STRUCT!{struct FLOWSPEC {
TokenRate: ULONG,
TokenBucketSize: ULONG,
PeakBandwidth: ULONG,
Latency: ULONG,
DelayVariation: ULONG,
ServiceType: SERVICETYPE,
MaxSduSize: ULONG,
MinimumPolicedSize: ULONG,
}}
pub type PFLOWSPEC = *mut FLOWSPEC;
pub type LPFLOWSPEC = *mut FLOWSPEC;
| 36 | 92 | 0.736111 |
ab69072dfa07607845dd6aa3fb5a693af7258e0b
| 34,139 |
use either::Either;
use llvm_ir::instruction;
use llvm_ir::terminator;
use llvm_ir::Constant;
use llvm_ir::HasDebugLoc;
use llvm_ir::IntPredicate;
use llvm_ir::Module;
use llvm_ir::Name;
use llvm_ir::Operand;
use llvm_ir::Type;
use llvm_ir::Typed;
use std::convert::TryInto;
use std::ops::Deref;
use std::path::Path;
use std::sync::{Arc, RwLock};
fn init_logging() {
// capture log messages with test harness
let _ = env_logger::builder().is_test(true).try_init();
}
#[test]
fn hellobc() {
init_logging();
let path = Path::new("tests/basic_bc/hello.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(module.name, "tests/basic_bc/hello.bc");
assert_eq!(module.source_file_name, "hello.c");
assert_eq!(module.target_triple, Some("x86_64-apple-macosx10.14.0".to_owned()));
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
assert_eq!(func.name, "main");
assert_eq!(func.parameters.len(), 0);
assert_eq!(func.is_var_arg, false);
assert_eq!(func.return_type, Type::IntegerType { bits: 32 });
assert_eq!(func.basic_blocks.len(), 1);
let bb = &func.basic_blocks[0];
assert_eq!(bb.name, Name::Number(0));
assert_eq!(bb.instrs.len(), 0);
let ret: &terminator::Ret = &bb
.term
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Terminator should be a Ret but is {:?}", &bb.term));
assert_eq!(
ret.return_operand,
Some(Operand::ConstantOperand(Constant::Int {
bits: 32,
value: 0
}))
);
// this file was compiled without debuginfo, so nothing should have a debugloc
assert_eq!(func.debugloc, None);
assert_eq!(ret.debugloc, None);
}
// this test relates to the version of the file compiled with debuginfo
#[test]
fn hellobcg() {
init_logging();
let path = Path::new("tests/basic_bc/hello.bc-g");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(module.name, "tests/basic_bc/hello.bc-g");
assert_eq!(module.source_file_name, "hello.c");
let debug_filename = "hello.c";
let debug_directory = Some("/Users/craig/llvm-ir/tests/basic_bc".to_owned());
let func = &module.functions[0];
assert_eq!(func.name, "main");
let debugloc = func.get_debug_loc().as_ref().expect("Expected main() to have a debugloc");
assert_eq!(debugloc.line, 3);
assert_eq!(debugloc.col, None);
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(debugloc.directory, debug_directory);
let bb = &func.basic_blocks[0];
let ret: &terminator::Ret = &bb.term.clone().try_into().unwrap_or_else(|_| panic!("Terminator should be a Ret but is {:?}", &bb.term));
let debugloc = ret.get_debug_loc().as_ref().expect("expected the Ret to have a debugloc");
assert_eq!(debugloc.line, 4);
assert_eq!(debugloc.col, Some(3));
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(debugloc.directory, debug_directory);
}
#[test]
#[allow(clippy::cognitive_complexity)]
fn loopbc() {
init_logging();
let path = Path::new("tests/basic_bc/loop.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
// get function and check info on it
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
assert_eq!(func.name, "loop");
assert_eq!(func.parameters.len(), 2);
assert_eq!(func.is_var_arg, false);
assert_eq!(func.return_type, Type::VoidType);
assert_eq!(
func.get_type(),
Type::FuncType {
result_type: Box::new(Type::VoidType),
param_types: vec![Type::i32(), Type::i32()],
is_var_arg: false,
}
);
assert_eq!(module.get_func_by_name("loop"), Some(func));
// get parameters and check info on them
let param0 = &func.parameters[0];
let param1 = &func.parameters[1];
assert_eq!(param0.name, Name::Number(0));
assert_eq!(param1.name, Name::Number(1));
assert_eq!(param0.ty, Type::i32());
assert_eq!(param1.ty, Type::i32());
assert_eq!(param0.get_type(), Type::i32());
assert_eq!(param1.get_type(), Type::i32());
// get basic blocks and check their names
assert_eq!(func.basic_blocks.len(), 6);
let bb2 = &func.basic_blocks[0];
let bb7 = &func.basic_blocks[1];
let bb10 = &func.basic_blocks[2];
let bb14 = &func.basic_blocks[3];
let bb19 = &func.basic_blocks[4];
let bb22 = &func.basic_blocks[5];
assert_eq!(bb2.name, Name::Number(2));
assert_eq!(bb7.name, Name::Number(7));
assert_eq!(bb10.name, Name::Number(10));
assert_eq!(bb14.name, Name::Number(14));
assert_eq!(bb19.name, Name::Number(19));
assert_eq!(bb22.name, Name::Number(22));
assert_eq!(func.get_bb_by_name(&Name::Number(2)), Some(bb2));
assert_eq!(func.get_bb_by_name(&Name::Number(19)), Some(bb19));
// check details about the instructions in basic block %2
let alloca: &instruction::Alloca = &bb2.instrs[0]
.clone()
.try_into()
.expect("Should be an alloca");
assert_eq!(alloca.dest, Name::Number(3));
let allocated_type = Type::ArrayType {
element_type: Box::new(Type::i32()),
num_elements: 10,
};
assert_eq!(alloca.allocated_type, allocated_type);
assert_eq!(
alloca.num_elements,
Operand::ConstantOperand(Constant::Int { bits: 32, value: 1 }) // One element, which is an array of 10 elements. Not 10 elements, each of which are i32.
);
assert_eq!(alloca.alignment, 16);
assert_eq!(alloca.get_type(), Type::pointer_to(allocated_type.clone()));
assert_eq!(alloca.num_elements.get_type(), Type::i32());
let bitcast: &instruction::BitCast = &bb2.instrs[1]
.clone()
.try_into()
.expect("Should be a bitcast");
assert_eq!(bitcast.dest, Name::Number(4));
assert_eq!(bitcast.to_type, Type::pointer_to(Type::i8()));
assert_eq!(
bitcast.operand,
Operand::LocalOperand {
name: Name::Number(3),
ty: Type::pointer_to(allocated_type.clone())
}
);
assert_eq!(bitcast.get_type(), Type::pointer_to(Type::i8()));
assert_eq!(bitcast.operand.get_type(), Type::pointer_to(allocated_type.clone()));
let lifetimestart: &instruction::Call =
&bb2.instrs[2].clone().try_into().expect("Should be a call");
if let Either::Right(Operand::ConstantOperand(Constant::GlobalReference { ref name, ref ty } )) = lifetimestart.function {
assert_eq!(lifetimestart.function.get_type(), Type::pointer_to(ty.clone())); // lifetimestart.function should be a constant function pointer
assert_eq!(*name, Name::Name("llvm.lifetime.start.p0i8".to_owned()));
if let Type::FuncType { ref result_type, ref param_types, ref is_var_arg } = *ty {
assert_eq!(**result_type, Type::VoidType);
assert_eq!(*param_types, vec![Type::i64(), Type::pointer_to(Type::i8())]);
assert_eq!(*is_var_arg, false);
} else {
panic!("lifetimestart.function has unexpected type {:?}", ty);
}
} else {
panic!(
"lifetimestart.function not a GlobalReference as expected; it is actually {:?}",
&lifetimestart.function
);
}
let arg0 = &lifetimestart.arguments.get(0).expect("Expected an argument 0");
let arg1 = &lifetimestart.arguments.get(1).expect("Expected an argument 1");
assert_eq!(arg0.0, Operand::ConstantOperand(Constant::Int { bits: 64, value: 40 } ));
assert_eq!(arg1.0, Operand::LocalOperand { name: Name::Number(4), ty: Type::pointer_to(Type::i8()) } );
assert_eq!(arg0.1, vec![]); // should have no parameter attributes
assert_eq!(arg1.1.len(), 1); // should have one parameter attribute
assert_eq!(lifetimestart.dest, None);
let memset: &instruction::Call = &bb2.instrs[3].clone().try_into().expect("Should be a call");
if let Either::Right(Operand::ConstantOperand(Constant::GlobalReference { ref name, ref ty })) = memset.function {
assert_eq!(*name, Name::Name("llvm.memset.p0i8.i64".to_owned()));
if let Type::FuncType { ref result_type, ref param_types, ref is_var_arg } = *ty {
assert_eq!(**result_type, Type::VoidType);
assert_eq!(*param_types, vec![Type::pointer_to(Type::i8()), Type::i8(), Type::i64(), Type::bool()]);
assert_eq!(*is_var_arg, false);
} else {
panic!("memset.function has unexpected type {:?}", ty);
}
} else {
panic!(
"memset.function not a GlobalReference as expected; it is actually {:?}",
memset.function
);
}
assert_eq!(memset.arguments.len(), 4);
assert_eq!(memset.arguments[0].0, Operand::LocalOperand { name: Name::Number(4), ty: Type::pointer_to(Type::i8()) } );
assert_eq!(memset.arguments[1].0, Operand::ConstantOperand(Constant::Int { bits: 8, value: 0 } ));
assert_eq!(memset.arguments[2].0, Operand::ConstantOperand(Constant::Int { bits: 64, value: 40 } ));
assert_eq!(memset.arguments[3].0, Operand::ConstantOperand(Constant::Int { bits: 1, value: 1 } ));
assert_eq!(memset.arguments[0].1.len(), 2); // should have two parameter attributes
let add: &instruction::Add = &bb2.instrs[4].clone().try_into().expect("Should be an add");
assert_eq!(add.operand0, Operand::LocalOperand { name: Name::Number(1), ty: Type::i32() } );
assert_eq!(add.operand1, Operand::ConstantOperand(Constant::Int { bits: 32, value: 0x0000_0000_FFFF_FFFF }));
assert_eq!(add.dest, Name::Number(5));
assert_eq!(add.get_type(), Type::i32());
let icmp: &instruction::ICmp = &bb2.instrs[5].clone().try_into().expect("Should be an icmp");
assert_eq!(icmp.predicate, IntPredicate::ULT);
assert_eq!(icmp.operand0, Operand::LocalOperand { name: Name::Number(5), ty: Type::i32() } );
assert_eq!(icmp.operand1, Operand::ConstantOperand(Constant::Int { bits: 32, value: 10 }));
assert_eq!(icmp.get_type(), Type::bool());
let condbr: &terminator::CondBr = &bb2.term.clone().try_into().expect("Should be a condbr");
assert_eq!(condbr.condition, Operand::LocalOperand { name: Name::Number(6), ty: Type::bool() } );
assert_eq!(condbr.true_dest, Name::Number(7));
assert_eq!(condbr.false_dest, Name::Number(22));
assert_eq!(condbr.get_type(), Type::VoidType);
// check details about certain instructions in basic block %7
let sext: &instruction::SExt = &bb7.instrs[1].clone().try_into().expect("Should be a SExt");
assert_eq!(sext.operand, Operand::LocalOperand { name: Name::Number(1), ty: Type::i32() } );
assert_eq!(sext.to_type, Type::i64());
assert_eq!(sext.dest, Name::Number(9));
assert_eq!(sext.get_type(), Type::i64());
let br: &terminator::Br = &bb7.term.clone().try_into().expect("Should be a Br");
assert_eq!(br.dest, Name::Number(10));
// check details about certain instructions in basic block %10
let phi: &instruction::Phi = &bb10.instrs[0].clone().try_into().expect("Should be a Phi");
assert_eq!(phi.dest, Name::Number(11));
assert_eq!(phi.to_type, Type::i64());
assert_eq!(
phi.incoming_values,
vec![
(
Operand::ConstantOperand(Constant::Int { bits: 64, value: 0 }),
Name::Number(7)
),
(
Operand::LocalOperand { name: Name::Number(20), ty: Type::i64() },
Name::Number(19)
),
]
);
let gep: &instruction::GetElementPtr =
&bb10.instrs[1].clone().try_into().expect("Should be a gep");
assert_eq!(
gep.address,
Operand::LocalOperand {
name: Name::Number(3),
ty: Type::pointer_to(allocated_type.clone())
}
);
assert_eq!(gep.dest, Name::Number(12));
assert_eq!(gep.in_bounds, true);
assert_eq!(
gep.indices,
vec![
Operand::ConstantOperand(Constant::Int { bits: 64, value: 0 }),
Operand::LocalOperand {
name: Name::Number(11),
ty: Type::i64()
},
]
);
assert_eq!(gep.get_type(), Type::pointer_to(Type::i32()));
let store: &instruction::Store = &bb10.instrs[2]
.clone()
.try_into()
.expect("Should be a store");
assert_eq!(store.address, Operand::LocalOperand { name: Name::Number(12), ty: Type::pointer_to(Type::i32()) });
assert_eq!(store.value, Operand::LocalOperand { name: Name::Number(8), ty: Type::i32() });
assert_eq!(store.volatile, true);
assert_eq!(store.alignment, 4);
assert_eq!(store.get_type(), Type::VoidType);
assert_eq!(bb10.instrs[2].is_atomic(), false);
// and finally other instructions of types we haven't seen yet
let load: &instruction::Load = &bb14.instrs[2].clone().try_into().expect("Should be a load");
assert_eq!(load.address, Operand::LocalOperand { name: Name::Number(16), ty: Type::pointer_to(Type::i32()) });
assert_eq!(load.dest, Name::Number(17));
assert_eq!(load.volatile, true);
assert_eq!(load.alignment, 4);
assert_eq!(load.get_type(), Type::i32());
assert_eq!(bb14.instrs[2].is_atomic(), false);
let ret: &terminator::Ret = &bb22.term.clone().try_into().expect("Should be a ret");
assert_eq!(ret.return_operand, None);
assert_eq!(ret.get_type(), Type::VoidType);
}
#[test]
fn switchbc() {
init_logging();
let path = Path::new("tests/basic_bc/switch.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
assert_eq!(func.name, "has_a_switch");
let bb = &func.basic_blocks[0];
let switch: &terminator::Switch = &bb.term.clone().try_into().expect("Should be a switch");
assert_eq!(switch.operand, Operand::LocalOperand { name: Name::Number(0), ty: Type::i32() });
assert_eq!(switch.dests.len(), 9);
assert_eq!(switch.dests[0], (Constant::Int { bits: 32, value: 0 }, Name::Number(12)));
assert_eq!(switch.dests[1], (Constant::Int { bits: 32, value: 1 }, Name::Number(2)));
assert_eq!(switch.dests[2], (Constant::Int { bits: 32, value: 13 }, Name::Number(3)));
assert_eq!(switch.dests[3], (Constant::Int { bits: 32, value: 26 }, Name::Number(4)));
assert_eq!(switch.dests[4], (Constant::Int { bits: 32, value: 33 }, Name::Number(5)));
assert_eq!(switch.dests[5], (Constant::Int { bits: 32, value: 142 }, Name::Number(6)));
assert_eq!(switch.dests[6], (Constant::Int { bits: 32, value: 1678 }, Name::Number(7)));
assert_eq!(switch.dests[7], (Constant::Int { bits: 32, value: 88 }, Name::Number(8)));
assert_eq!(switch.dests[8], (Constant::Int { bits: 32, value: 101 }, Name::Number(9)));
assert_eq!(switch.default_dest, Name::Number(10));
let phibb = &func
.get_bb_by_name(&Name::Number(12))
.expect("Failed to find bb %12");
let phi: &instruction::Phi = &phibb.instrs[0].clone().try_into().expect("Should be a phi");
assert_eq!(phi.incoming_values.len(), 10);
}
#[test]
fn variablesbc() {
init_logging();
let path = Path::new("tests/basic_bc/variables.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(module.global_vars.len(), 1);
let var = &module.global_vars[0];
assert_eq!(var.name, Name::Name("global".to_owned()));
assert_eq!(var.is_constant, false);
assert_eq!(var.ty, Type::pointer_to(Type::i32()));
assert_eq!(var.initializer, Some(Constant::Int { bits: 32, value: 5 }));
assert_eq!(var.alignment, 4);
assert!(var.get_debug_loc().is_none()); // this file was compiled without debuginfo
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
assert_eq!(func.name, "variables");
let bb = &func.basic_blocks[0];
let store: &instruction::Store = &bb.instrs[2].clone().try_into().expect("Should be a store");
assert_eq!(store.address, Operand::LocalOperand { name: Name::Number(3), ty: Type::pointer_to(Type::i32()) });
assert_eq!(store.get_type(), Type::VoidType);
let load: &instruction::Load = &bb.instrs[8].clone().try_into().expect("Should be a load");
assert_eq!(load.address, Operand::LocalOperand { name: Name::Number(4), ty: Type::pointer_to(Type::i32()) });
assert_eq!(load.get_type(), Type::i32());
let global_load: &instruction::Load = &bb.instrs[14].clone().try_into().expect("Should be a load");
assert_eq!(global_load.address, Operand::ConstantOperand(Constant::GlobalReference { name: Name::Name("global".to_owned()), ty: Type::i32() }));
assert_eq!(global_load.get_type(), Type::i32());
let global_store: &instruction::Store = &bb.instrs[16].clone().try_into().expect("Should be a store");
assert_eq!(global_store.address, Operand::ConstantOperand(Constant::GlobalReference { name: Name::Name("global".to_owned()), ty: Type::i32() }));
assert_eq!(global_store.get_type(), Type::VoidType);
}
// this test relates to the version of the file compiled with debuginfo
#[test]
fn variablesbcg() {
init_logging();
let path = Path::new("tests/basic_bc/variables.bc-g");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let debug_filename = "variables.c";
let debug_directory = Some("/Users/craig/llvm-ir/tests/basic_bc".to_owned());
// really all we want to check is the debugloc of the global variable.
// other debuginfo stuff is covered in other tests
assert_eq!(module.global_vars.len(), 1);
let var = &module.global_vars[0];
assert_eq!(var.name, Name::from("global"));
let debugloc = var.get_debug_loc().as_ref().expect("expected the global to have a debugloc");
assert_eq!(debugloc.line, 5);
assert_eq!(debugloc.col, None); // only `Instruction`s and `Terminator`s get column numbers
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(debugloc.directory, debug_directory);
}
#[test]
fn rustbc() {
// This tests against the checked-in rust.bc, which was generated from the checked-in rust.rs with rustc 1.39.0
init_logging();
let path = Path::new("tests/basic_bc/rust.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let func = module.get_func_by_name("_ZN4rust9rust_loop17h3ed0672b8cf44eb1E").expect("Failed to find function");
assert_eq!(func.parameters.len(), 3);
assert_eq!(func.parameters[0].name, Name::from("a"));
assert_eq!(func.parameters[1].name, Name::from("b"));
assert_eq!(func.parameters[2].name, Name::from("v"));
assert_eq!(func.parameters[0].ty, Type::i64());
assert_eq!(func.parameters[1].ty, Type::i64());
assert_eq!(func.parameters[2].ty, Type::pointer_to(Type::NamedStructType { name: "alloc::vec::Vec<isize>".to_owned(), ty: None })); // we don't actually expect ty to be `None`, but named structs should compare equal as long as their names are the same
let startbb = func.get_bb_by_name(&Name::from("start")).expect("Failed to find bb 'start'");
let alloca_iter: &instruction::Alloca = &startbb.instrs[5].clone().try_into().expect("Should be an alloca");
assert_eq!(alloca_iter.dest, Name::from("iter"));
let alloca_sum: &instruction::Alloca = &startbb.instrs[6].clone().try_into().expect("Should be an alloca");
assert_eq!(alloca_sum.dest, Name::from("sum"));
let store: &instruction::Store = &startbb.instrs[7].clone().try_into().expect("Should be a store");
assert_eq!(store.address, Operand::LocalOperand { name: Name::from("sum"), ty: Type::pointer_to(Type::i64()) });
let call: &instruction::Call = &startbb.instrs[8].clone().try_into().expect("Should be a call");
let param_type = Type::pointer_to(Type::NamedStructType { name: "alloc::vec::Vec<isize>".to_owned(), ty: None }); // we don't actually expect ty to be `None`, but named structs should compare equal as long as their names are the same
let ret_type = Type::StructType { is_packed: false, element_types: vec![
Type::pointer_to(Type::ArrayType { element_type: Box::new(Type::i64()), num_elements: 0 }),
Type::i64(),
]};
if let Either::Right(Operand::ConstantOperand(Constant::GlobalReference { ref name, ref ty })) = call.function {
assert_eq!(name, &Name::from("_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E"));
match ty {
Type::FuncType { result_type, param_types, is_var_arg } => {
assert_eq!(**result_type, ret_type);
assert_eq!(param_types[0], param_type);
assert_eq!(*is_var_arg, false);
},
_ => panic!("Expected called global to have FuncType, but got {:?}", ty),
}
assert_eq!(call.get_type(), ret_type);
} else {
panic!(
"call.function not a GlobalReference as expected; it is actually {:?}",
call.function
);
}
assert_eq!(call.arguments.len(), 1);
assert_eq!(call.arguments[0].0, Operand::LocalOperand {
name: Name::from("v"),
ty: param_type,
});
assert_eq!(call.dest, Some(Name::Number(0)));
// this file was compiled without debuginfo, so nothing should have a debugloc
assert!(func.get_debug_loc().is_none());
assert!(alloca_iter.get_debug_loc().is_none());
assert!(alloca_sum.get_debug_loc().is_none());
assert!(store.get_debug_loc().is_none());
assert!(call.get_debug_loc().is_none());
}
// this test relates to the version of the file compiled with debuginfo
#[test]
fn rustbcg() {
init_logging();
let path = Path::new("tests/basic_bc/rust.bc-g");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let debug_filename = "rust.rs";
let debug_directory = Some("/Users/craig/llvm-ir/tests/basic_bc".to_owned());
let func = module.get_func_by_name("_ZN4rust9rust_loop17h3ed0672b8cf44eb1E").expect("Failed to find function");
let debugloc = func.get_debug_loc().as_ref().expect("Expected function to have a debugloc");
assert_eq!(debugloc.line, 3);
assert_eq!(debugloc.col, None);
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(debugloc.directory, debug_directory);
let startbb = func.get_bb_by_name(&Name::from("start")).expect("Failed to find bb 'start'");
// the first 17 instructions in the function should not have debuglocs - they are just setting up the stack frame
for i in 0..17 {
assert!(startbb.instrs[i].get_debug_loc().is_none());
}
let store_debugloc = startbb.instrs[31].get_debug_loc().as_ref().expect("Expected this store to have a debugloc");
assert_eq!(store_debugloc.line, 4);
assert_eq!(store_debugloc.col, Some(18));
assert_eq!(store_debugloc.filename, debug_filename);
assert_eq!(store_debugloc.directory, debug_directory);
let call_debugloc = startbb.instrs[33].get_debug_loc().as_ref().expect("Expected this call to have a debugloc");
assert_eq!(call_debugloc.line, 5);
assert_eq!(call_debugloc.col, Some(13));
assert_eq!(call_debugloc.filename, debug_filename);
assert_eq!(call_debugloc.directory, debug_directory);
}
#[test]
fn simple_linked_list() {
init_logging();
let path = Path::new("tests/basic_bc/linkedlist.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let structty: Arc<RwLock<Type>> = module
.named_struct_types
.get("struct.SimpleLinkedList")
.unwrap_or_else(|| {
let names: Vec<_> = module.named_struct_types.keys().collect();
panic!(
"Failed to find struct.SimpleLinkedList in named_struct_types; have names {:?}",
names
)
})
.as_ref()
.expect("SimpleLinkedList should not be an opaque type")
.clone();
if let Type::StructType { element_types, .. } = structty.read().unwrap().deref() {
assert_eq!(element_types.len(), 2);
assert_eq!(element_types[0], Type::i32());
if let Type::PointerType { pointee_type, .. } = &element_types[1] {
if let Type::NamedStructType { ref name, ref ty } = **pointee_type {
assert_eq!(name, "struct.SimpleLinkedList");
let ty: Arc<RwLock<Type>> = ty
.as_ref()
.expect("Inner type should not be opaque")
.upgrade()
.expect("Failed to upgrade weak ref");
assert_eq!(ty.read().unwrap().deref(), structty.read().unwrap().deref()); // the type should be truly recursive, in that the pointed-to type should be the same as the original type
} else {
panic!(
"Expected pointee type to be a NamedStructType, got {:?}",
pointee_type
);
}
} else {
panic!(
"Expected inner type to be a PointerType, got {:?}",
element_types[1]
);
}
} else {
panic!(
"Expected SimpleLinkedList to be a StructType, got {:?}",
structty
);
}
let func = module
.get_func_by_name("simple_linked_list")
.expect("Failed to find function");
let alloca: &instruction::Alloca = &func.basic_blocks[0].instrs[1]
.clone()
.try_into()
.expect("Should be an alloca");
if let Type::NamedStructType { ref name, ref ty } = alloca.allocated_type {
assert_eq!(name, "struct.SimpleLinkedList");
let inner_ty: Arc<RwLock<Type>> = ty
.as_ref()
.expect("Allocated type should not be opaque")
.upgrade()
.expect("Failed to upgrade weak ref");
assert_eq!(inner_ty.read().unwrap().deref(), structty.read().unwrap().deref()); // this should be exactly the same struct type as when we accessed it through the module above
} else {
panic!(
"Expected alloca.allocated_type to be a NamedStructType, got {:?}",
alloca.allocated_type
);
}
let structty: &Option<Arc<RwLock<Type>>> = &module
.named_struct_types
.get("struct.SomeOpaqueStruct")
.unwrap_or_else(|| {
let names: Vec<_> = module.named_struct_types.keys().collect();
panic!(
"Failed to find struct.SomeOpaqueStruct in named_struct_types; have names {:?}",
names
)
});
assert!(structty.is_none(), "SomeOpaqueStruct should be an opaque type");
let func = module
.get_func_by_name("takes_opaque_struct")
.expect("Failed to find function");
let paramty = &func.parameters[0].ty;
match paramty {
Type::PointerType { pointee_type, .. } => match &**pointee_type {
Type::NamedStructType { ref name, ref ty } => {
assert_eq!(name, "struct.SomeOpaqueStruct");
assert!(ty.is_none(), "SomeOpaqueStruct should be an opaque type");
},
ty => panic!("Expected parameter type to be pointer to named struct, but got pointer to {:?}", ty),
},
_ => panic!("Expected parameter type to be pointer type, but got {:?}", paramty),
};
}
// this test relates to the version of the file compiled with debuginfo
#[test]
fn simple_linked_list_g() {
init_logging();
let path = Path::new("tests/basic_bc/linkedlist.bc-g");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let debug_filename = "linkedlist.c";
let debug_directory = Some("/Users/craig/llvm-ir/tests/basic_bc".to_owned());
let func = module.get_func_by_name("simple_linked_list").expect("Failed to find function");
let debugloc = func.get_debug_loc().as_ref().expect("expected simple_linked_list to have a debugloc");
assert_eq!(debugloc.line, 8);
assert_eq!(debugloc.col, None);
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(debugloc.directory, debug_directory);
// the first seven instructions shouldn't have debuglocs - they are just setting up the stack frame
for i in 0..7 {
assert!(func.basic_blocks[0].instrs[i].get_debug_loc().is_none());
}
// the eighth instruction should have a debugloc
let debugloc = func.basic_blocks[0].instrs[7].get_debug_loc().as_ref().expect("expected this instruction to have a debugloc");
assert_eq!(debugloc.line, 8);
assert_eq!(debugloc.col, Some(28));
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(debugloc.directory, debug_directory);
// the tenth instruction should have a different debugloc
let debugloc = func.basic_blocks[0].instrs[9].get_debug_loc().as_ref().expect("expected this instruction to have a debugloc");
assert_eq!(debugloc.line, 9);
assert_eq!(debugloc.col, Some(34));
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(debugloc.directory, debug_directory);
}
#[test]
fn indirectly_recursive_type() {
init_logging();
let path = Path::new("tests/basic_bc/linkedlist.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let aty: Arc<RwLock<Type>> = module
.named_struct_types
.get("struct.NodeA")
.unwrap_or_else(|| {
let names: Vec<_> = module.named_struct_types.keys().collect();
panic!(
"Failed to find struct.NodeA in named_struct_types; have names {:?}",
names
)
})
.as_ref()
.expect("NodeA should not be an opaque type")
.clone();
let bty: Arc<RwLock<Type>> = module
.named_struct_types
.get("struct.NodeB")
.unwrap_or_else(|| {
let names: Vec<_> = module.named_struct_types.keys().collect();
panic!(
"Failed to find struct.NodeB in named_struct_types; have names {:?}",
names
)
})
.as_ref()
.expect("NodeB should not be an opaque type")
.clone();
if let Type::StructType { element_types, .. } = aty.read().unwrap().deref() {
assert_eq!(element_types.len(), 2);
assert_eq!(element_types[0], Type::i32());
if let Type::PointerType { pointee_type, .. } = &element_types[1] {
if let Type::NamedStructType { ref name, ref ty } = **pointee_type {
assert_eq!(name, "struct.NodeB");
let ty: Arc<RwLock<Type>> = ty
.as_ref()
.expect("Inner type should not be opaque")
.upgrade()
.expect("Failed to upgrade weak ref");
assert_eq!(ty.read().unwrap().deref(), bty.read().unwrap().deref());
} else {
panic!(
"Expected pointee type to be a NamedStructType, got {:?}",
**pointee_type
);
}
} else {
panic!(
"Expected inner type to be a PointerType, got {:?}",
element_types[1]
);
}
} else {
panic!("Expected NodeA to be a StructType, got {:?}", aty);
}
if let Type::StructType { element_types, .. } = bty.read().unwrap().deref() {
assert_eq!(element_types.len(), 2);
assert_eq!(element_types[0], Type::i32());
if let Type::PointerType { pointee_type, .. } = &element_types[1] {
if let Type::NamedStructType { ref name, ref ty } = **pointee_type {
assert_eq!(name, "struct.NodeA");
let ty: Arc<RwLock<Type>> = ty
.as_ref()
.expect("Inner type should not be opaque")
.upgrade()
.expect("Failed to upgrade weak ref");
assert_eq!(ty.read().unwrap().deref(), aty.read().unwrap().deref());
} else {
panic!(
"Expected pointee type to be a NamedStructType, got {:?}",
**pointee_type
);
}
} else {
panic!(
"Expected inner type to be a PointerType, got {:?}",
element_types[1]
);
}
} else {
panic!("Expected NodeB to be a StructType, got {:?}", bty);
}
let func = module
.get_func_by_name("indirectly_recursive_type")
.expect("Failed to find function");
let alloca_a: &instruction::Alloca = &func.basic_blocks[0].instrs[1]
.clone()
.try_into()
.expect("Should be an alloca");
let alloca_b: &instruction::Alloca = &func.basic_blocks[0].instrs[2]
.clone()
.try_into()
.expect("Should be an alloca");
if let Type::NamedStructType { ref name, ref ty } = alloca_a.allocated_type {
assert_eq!(name, "struct.NodeA");
let inner_ty: Arc<RwLock<Type>> = ty
.as_ref()
.expect("Allocated type should not be opaque")
.upgrade()
.expect("Failed to upgrade weak ref");
assert_eq!(inner_ty.read().unwrap().deref(), aty.read().unwrap().deref()); // this should be exactly the same struct type as when we accessed it through the module above
} else {
panic!(
"Expected alloca_a.allocated_type to be a NamedStructType, got {:?}",
alloca_a.allocated_type
);
}
if let Type::NamedStructType { ref name, ref ty } = alloca_b.allocated_type {
assert_eq!(name, "struct.NodeB");
let inner_ty: Arc<RwLock<Type>> = ty
.as_ref()
.expect("Allocated type should not be opaque")
.upgrade()
.expect("Failed to upgrade weak ref");
assert_eq!(inner_ty.read().unwrap().deref(), bty.read().unwrap().deref());
} else {
panic!(
"Expected alloca_b.allocated_type to be a NamedStructType, got {:?}",
alloca_b.allocated_type
);
}
}
| 45.762735 | 256 | 0.622192 |
61211acc0b06bf9c7df118661bd3d8e6ea0bdb87
| 4,412 |
use crate::addon::{AddonID, AddonSlug};
use crate::addon::files::AddonFile;
use crate::addon::local::{LocalAddon, UpdateOpt};
use crate::addon::rtm::ReleaseTypeMode;
use crate::api::API;
use crate::conf::Repo;
use super::deps::collect_deps;
use super::incompat::*;
use crate::{Op, error, warn, unwrap_result_error};
pub fn install_mod(
// install this specific AddonFile
addon_id: AddonID,
install: AddonFile,
force_incompat: bool, //install even if incompat
// write back to LocalAddon
i_slug: AddonSlug,
i_name: String,
channel: ReleaseTypeMode,
update_opt: UpdateOpt,
manually_installed: bool,
version_blacklist: Option<String>,
// oof
o: &Op,
api: &API,
repo: &mut Repo,
) -> bool {
// if current mod installed, add to delete_sched
// iterate required deps of to install file recursively and if not already installed, collect to install_sched, choose the latest version matching channel
// - only deps that aren't installed are now installed
// - TODO what if dep's LocalAddon still exists?
// do check_incompatibility_2 with install_sched
// now handle --force to override incompatibilities and noop
// attempt to install all addons in install_sched, collect finalizers
// - on deps will softly derive from "our" LocalParams and existing LocalAddon (if removed but not purged) TODO how
// - on "this" addon, "our" LocalParams will replace the ones of existing LocalAddon
// run install finalizers and delete_sched
let mut install_queue = vec![];
let mut finalizer_queue = vec![];
collect_deps(
&repo.addons,
api,
install.dependencies.iter_required(),
&repo.conf.game_version,
channel,
update_opt,
&version_blacklist,
&mut install_queue,
);
let incompat = check_incompatibility_3(
&install_queue,
&repo.addons,
);
if !incompat.is_empty() {
if !force_incompat {
error!("Incompatible addons:{}",o.suffix());
} else {
warn!("Installing addons with incompatibilities:{}",o.suffix());
}
for i in incompat {
eprintln!("\t{} => {}{}",i.from.slug,i.to.slug,o.suffix());
}
if !force_incompat {
std::process::exit(1);
}
}
let mut modified = false;
for i in install_queue {
eprintln!(
"Install: {} ({}){}",
i.slug,
i.installed.as_ref().unwrap().file_name,
o.suffix()
);
if i.installed.as_ref().unwrap().has_install_script {
warn!(
"Installing {}: Install Scripts are currently unsupported",
i.slug
);
}
if !o.noop {
let finalizer = unwrap_result_error!(
i.installed.as_ref().unwrap().download(&repo.conf,api),
|e|"Failed to install addon: {}",e
);
finalizer_queue.push(finalizer);
repo.addons.insert(i.id,i);
modified = true;
}
}
eprintln!(
"Install: {} ({}){}",
i_slug,
install.file_name,
o.suffix()
);
let mut set_new = None;
if !o.noop {
let finalizer = unwrap_result_error!(
install.download(&repo.conf,api),
|e|"Failed to install addon: {}",e
);
finalizer_queue.push(finalizer);
set_new = Some(LocalAddon {
id: addon_id,
slug: i_slug,
name: i_name,
channel,
update_opt,
manually_installed,
version_blacklist,
installed: Some(install),
});
}
if let Some(addon) = repo.addons.get_mut(&addon_id) {
if let Some(installed) = &mut addon.installed {
eprintln!(
"Remove previous version: {}{}",
installed.file_name,
o.suffix()
);
if !o.noop {
unwrap_result_error!(installed.remove(),|e|"Failed to remove addon: {}",e);
addon.installed = None;
modified = true;
}
}
}
if let Some(new) = set_new {
repo.addons.insert(addon_id,new);
modified = true;
}
for f in finalizer_queue {
f.finalize();
}
modified
}
| 28.282051 | 158 | 0.56233 |
dea873f838fe6514f0df6144fde96d7bcc9e0b0a
| 2,956 |
use crate::ics23_commitment::commitment::CommitmentProof;
use crate::Height;
use serde_derive::{Deserialize, Serialize};
/// Structure comprising proofs in a message. Proofs are typically present in messages for
/// handshake protocols, e.g., ICS3 connection (open) handshake or ICS4 channel (open and close)
/// handshake, as well as for ICS4 packets, timeouts, and acknowledgements.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Proofs {
object_proof: CommitmentProof,
client_proof: Option<CommitmentProof>,
consensus_proof: Option<ConsensusProof>,
/// Height for the proofs above. When creating these proofs, the chain was at `height`.
height: Height,
}
impl Proofs {
pub fn new(
object_proof: CommitmentProof,
client_proof: Option<CommitmentProof>,
consensus_proof: Option<ConsensusProof>,
height: Height,
) -> Result<Self, String> {
if height.is_zero() {
return Err("Proofs height cannot be zero".to_string());
}
if object_proof.is_empty() {
return Err("Object proof cannot be empty".to_string());
}
Ok(Self {
object_proof,
client_proof,
consensus_proof,
height,
})
}
/// Getter for the consensus_proof field of this proof. Intuitively, this is a proof that a
/// client on the source chain stores a consensus state for the destination chain.
pub fn consensus_proof(&self) -> Option<ConsensusProof> {
self.consensus_proof.clone()
}
/// Getter for the height field of this proof (i.e., the consensus height where this proof was
/// created).
pub fn height(&self) -> Height {
self.height
}
/// Getter for the object-specific proof (e.g., proof for connection state or channel state).
pub fn object_proof(&self) -> &CommitmentProof {
&self.object_proof
}
/// Getter for the client_proof.
pub fn client_proof(&self) -> &Option<CommitmentProof> {
&self.client_proof
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConsensusProof {
proof: CommitmentProof,
height: Height,
}
impl ConsensusProof {
pub fn new(consensus_proof: CommitmentProof, consensus_height: Height) -> Result<Self, String> {
if consensus_height.is_zero() {
return Err("Consensus height cannot be zero".to_string());
}
if consensus_proof.is_empty() {
return Err("Proof cannot be empty".to_string());
}
Ok(Self {
proof: consensus_proof,
height: consensus_height,
})
}
/// Getter for the height field of this consensus proof.
pub fn height(&self) -> Height {
self.height
}
/// Getter for the proof (CommitmentProof) field of this consensus proof.
pub fn proof(&self) -> &CommitmentProof {
&self.proof
}
}
| 31.446809 | 100 | 0.644452 |
dd02d0cf1e7014afac05861114bf214d08d46883
| 8,153 |
use super::*;
use crate::AxisScale;
use itertools::Itertools;
use plotters::coord::{AsRangedCoord, Shift};
use std::cmp::Ordering;
use std::path::Path;
const NUM_COLORS: usize = 8;
static COMPARISON_COLORS: [RGBColor; NUM_COLORS] = [
RGBColor(178, 34, 34),
RGBColor(46, 139, 87),
RGBColor(0, 139, 139),
RGBColor(255, 215, 0),
RGBColor(0, 0, 139),
RGBColor(220, 20, 60),
RGBColor(139, 0, 139),
RGBColor(0, 255, 127),
];
pub fn line_comparison(
formatter: &dyn ValueFormatter,
title: &str,
all_curves: &[&(&BenchmarkId, Vec<f64>)],
path: &Path,
value_type: ValueType,
axis_scale: AxisScale,
) {
let (unit, series_data) = line_comparision_series_data(formatter, all_curves);
let x_range =
plotters::data::fitting_range(series_data.iter().map(|(_, xs, _)| xs.iter()).flatten());
let y_range =
plotters::data::fitting_range(series_data.iter().map(|(_, _, ys)| ys.iter()).flatten());
let root_area = SVGBackend::new(&path, SIZE)
.into_drawing_area()
.titled(&format!("{}: Comparision", title), (DEFAULT_FONT, 20))
.unwrap();
match axis_scale {
AxisScale::Linear => {
draw_line_comarision_figure(root_area, unit, x_range, y_range, value_type, series_data)
}
AxisScale::Logarithmic => draw_line_comarision_figure(
root_area,
unit,
LogRange(x_range),
LogRange(y_range),
value_type,
series_data,
),
}
}
fn draw_line_comarision_figure<XR: AsRangedCoord<Value = f64>, YR: AsRangedCoord<Value = f64>>(
root_area: DrawingArea<SVGBackend, Shift>,
y_unit: &str,
x_range: XR,
y_range: YR,
value_type: ValueType,
data: Vec<(Option<&String>, Vec<f64>, Vec<f64>)>,
) {
let input_suffix = match value_type {
ValueType::Bytes => " Size (Bytes)",
ValueType::Elements => " Size (Elements)",
ValueType::Value => "",
};
let mut chart = ChartBuilder::on(&root_area)
.margin((5).percent())
.set_label_area_size(LabelAreaPosition::Left, (5).percent_width().min(60))
.set_label_area_size(LabelAreaPosition::Bottom, (5).percent_height().min(40))
.build_ranged(x_range, y_range)
.unwrap();
chart
.configure_mesh()
.disable_mesh()
.x_desc(format!("Input{}", input_suffix))
.y_desc(format!("Average time ({})", y_unit))
.draw()
.unwrap();
for (id, (name, xs, ys)) in (0..).zip(data.into_iter()) {
let series = chart
.draw_series(
LineSeries::new(
xs.into_iter().zip(ys.into_iter()),
COMPARISON_COLORS[id % NUM_COLORS].filled(),
)
.point_size(POINT_SIZE),
)
.unwrap();
if let Some(name) = name {
let name: &str = &*name;
series.label(name).legend(move |(x, y)| {
Rectangle::new(
[(x, y - 5), (x + 20, y + 5)],
COMPARISON_COLORS[id % NUM_COLORS].filled(),
)
});
}
}
chart
.configure_series_labels()
.position(SeriesLabelPosition::UpperLeft)
.draw()
.unwrap();
}
#[allow(clippy::type_complexity)]
fn line_comparision_series_data<'a>(
formatter: &dyn ValueFormatter,
all_curves: &[&(&'a BenchmarkId, Vec<f64>)],
) -> (&'static str, Vec<(Option<&'a String>, Vec<f64>, Vec<f64>)>) {
let max = all_curves
.iter()
.map(|&&(_, ref data)| Sample::new(data).mean())
.fold(::std::f64::NAN, f64::max);
let mut dummy = [1.0];
let unit = formatter.scale_values(max, &mut dummy);
let mut series_data = vec![];
// This assumes the curves are sorted. It also assumes that the benchmark IDs all have numeric
// values or throughputs and that value is sensible (ie. not a mix of bytes and elements
// or whatnot)
for (key, group) in &all_curves.iter().group_by(|&&&(ref id, _)| &id.function_id) {
let mut tuples: Vec<_> = group
.map(|&&(ref id, ref sample)| {
// Unwrap is fine here because it will only fail if the assumptions above are not true
// ie. programmer error.
let x = id.as_number().unwrap();
let y = Sample::new(sample).mean();
(x, y)
})
.collect();
tuples.sort_by(|&(ax, _), &(bx, _)| (ax.partial_cmp(&bx).unwrap_or(Ordering::Less)));
let function_name = key.as_ref();
let (xs, mut ys): (Vec<_>, Vec<_>) = tuples.into_iter().unzip();
formatter.scale_values(max, &mut ys);
series_data.push((function_name, xs, ys));
}
(unit, series_data)
}
pub fn violin(
formatter: &dyn ValueFormatter,
title: &str,
all_curves: &[&(&BenchmarkId, Vec<f64>)],
path: &Path,
axis_scale: AxisScale,
) {
let all_curves_vec = all_curves.iter().rev().cloned().collect::<Vec<_>>();
let all_curves: &[&(&BenchmarkId, Vec<f64>)] = &*all_curves_vec;
let mut kdes = all_curves
.iter()
.map(|&&(ref id, ref sample)| {
let (x, mut y) = kde::sweep(Sample::new(sample), KDE_POINTS, None);
let y_max = Sample::new(&y).max();
for y in y.iter_mut() {
*y /= y_max;
}
(id.as_title(), x, y)
})
.collect::<Vec<_>>();
let mut xs = kdes
.iter()
.flat_map(|&(_, ref x, _)| x.iter())
.filter(|&&x| x > 0.);
let (mut min, mut max) = {
let &first = xs.next().unwrap();
(first, first)
};
for &e in xs {
if e < min {
min = e;
} else if e > max {
max = e;
}
}
let mut dummy = [1.0];
let unit = formatter.scale_values(max, &mut dummy);
kdes.iter_mut().for_each(|&mut (_, ref mut xs, _)| {
formatter.scale_values(max, xs);
});
let x_range = plotters::data::fitting_range(kdes.iter().map(|(_, xs, _)| xs.iter()).flatten());
let y_range = -0.5..all_curves.len() as f64 - 0.5;
let size = (960, 150 + (18 * all_curves.len() as u32));
let root_area = SVGBackend::new(&path, size)
.into_drawing_area()
.titled(&format!("{}: Violin plot", title), (DEFAULT_FONT, 20))
.unwrap();
match axis_scale {
AxisScale::Linear => draw_violin_figure(root_area, unit, x_range, y_range, kdes),
AxisScale::Logarithmic => {
draw_violin_figure(root_area, unit, LogRange(x_range), y_range, kdes)
}
}
}
#[allow(clippy::type_complexity)]
fn draw_violin_figure<XR: AsRangedCoord<Value = f64>, YR: AsRangedCoord<Value = f64>>(
root_area: DrawingArea<SVGBackend, Shift>,
unit: &'static str,
x_range: XR,
y_range: YR,
data: Vec<(&str, Box<[f64]>, Box<[f64]>)>,
) {
let mut chart = ChartBuilder::on(&root_area)
.margin((5).percent())
.set_label_area_size(LabelAreaPosition::Left, (10).percent_width().min(60))
.set_label_area_size(LabelAreaPosition::Bottom, (5).percent_width().min(40))
.build_ranged(x_range, y_range)
.unwrap();
chart
.configure_mesh()
.disable_mesh()
.y_desc("Input")
.x_desc(format!("Average time ({})", unit))
.y_label_style((DEFAULT_FONT, 10))
.y_label_formatter(&|v: &f64| data[v.round() as usize].0.to_string())
.y_labels(data.len())
.draw()
.unwrap();
for (i, (_, x, y)) in data.into_iter().enumerate() {
let base = i as f64;
chart
.draw_series(AreaSeries::new(
x.iter().zip(y.iter()).map(|(x, y)| (*x, base + *y / 2.0)),
base,
&DARK_BLUE.mix(0.25),
))
.unwrap();
chart
.draw_series(AreaSeries::new(
x.iter().zip(y.iter()).map(|(x, y)| (*x, base - *y / 2.0)),
base,
&DARK_BLUE.mix(0.25),
))
.unwrap();
}
}
| 31.723735 | 102 | 0.54434 |
e24c5429e0c916964912ba4aaa5e09ce4c2f2cf7
| 8,552 |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClusterProperties {
#[serde(rename = "nextLink", skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(rename = "clusterId", skip_serializing)]
pub cluster_id: Option<String>,
#[serde(rename = "provisioningState", skip_serializing)]
pub provisioning_state: Option<cluster_properties::ProvisioningState>,
#[serde(rename = "keyVaultProperties", skip_serializing_if = "Option::is_none")]
pub key_vault_properties: Option<KeyVaultProperties>,
}
pub mod cluster_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Creating,
Succeeded,
Failed,
Canceled,
Deleting,
ProvisioningAccount,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDetails>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetails {
#[serde(skip_serializing)]
pub code: Option<String>,
#[serde(skip_serializing)]
pub message: Option<String>,
#[serde(skip_serializing)]
pub target: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClusterPatchProperties {
#[serde(rename = "keyVaultProperties", skip_serializing_if = "Option::is_none")]
pub key_vault_properties: Option<KeyVaultProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClusterPatch {
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<ClusterPatchProperties>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Cluster {
#[serde(flatten)]
pub resource: Resource,
#[serde(skip_serializing_if = "Option::is_none")]
pub identity: Option<Identity>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<ClusterProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClusterListResult {
#[serde(rename = "nextLink", skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Cluster>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVaultProperties {
#[serde(rename = "keyVaultUri", skip_serializing_if = "Option::is_none")]
pub key_vault_uri: Option<String>,
#[serde(rename = "keyName", skip_serializing_if = "Option::is_none")]
pub key_name: Option<String>,
#[serde(rename = "keyVersion", skip_serializing_if = "Option::is_none")]
pub key_version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
#[serde(skip_serializing_if = "Option::is_none")]
pub capacity: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<sku::Name>,
}
pub mod sku {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
CapacityReservation,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Identity {
#[serde(rename = "principalId", skip_serializing)]
pub principal_id: Option<String>,
#[serde(rename = "tenantId", skip_serializing)]
pub tenant_id: Option<String>,
#[serde(rename = "type")]
pub type_: identity::Type,
}
pub mod identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
None,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(skip_serializing)]
pub id: Option<String>,
#[serde(skip_serializing)]
pub name: Option<String>,
#[serde(rename = "type", skip_serializing)]
pub type_: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkedServiceProperties {
#[serde(rename = "resourceId", skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "writeAccessResourceId", skip_serializing_if = "Option::is_none")]
pub write_access_resource_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkedService {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
pub properties: LinkedServiceProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkedServiceListResult {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<LinkedService>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyResource {
#[serde(skip_serializing)]
pub id: Option<String>,
#[serde(skip_serializing)]
pub name: Option<String>,
#[serde(rename = "type", skip_serializing)]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataExport {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<DataExportProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataExportListResult {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DataExport>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataExportProperties {
#[serde(rename = "dataExportId", skip_serializing_if = "Option::is_none")]
pub data_export_id: Option<String>,
#[serde(rename = "allTables", skip_serializing_if = "Option::is_none")]
pub all_tables: Option<bool>,
#[serde(rename = "tableNames", skip_serializing_if = "Vec::is_empty")]
pub table_names: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub destination: Option<Destination>,
#[serde(skip_serializing_if = "Option::is_none")]
pub enable: Option<bool>,
#[serde(rename = "createdDate", skip_serializing_if = "Option::is_none")]
pub created_date: Option<String>,
#[serde(rename = "lastModifiedDate", skip_serializing_if = "Option::is_none")]
pub last_modified_date: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Destination {
#[serde(rename = "resourceId")]
pub resource_id: String,
#[serde(rename = "type", skip_serializing)]
pub type_: Option<destination::Type>,
#[serde(rename = "metaData", skip_serializing_if = "Option::is_none")]
pub meta_data: Option<DestinationMetaData>,
}
pub mod destination {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
StorageAccount,
EventHub,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DestinationMetaData {
#[serde(rename = "eventHubName", skip_serializing_if = "Option::is_none")]
pub event_hub_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkedStorageAccountsProperties {
#[serde(rename = "dataSourceType", skip_serializing)]
pub data_source_type: Option<linked_storage_accounts_properties::DataSourceType>,
#[serde(rename = "storageAccountIds", skip_serializing_if = "Vec::is_empty")]
pub storage_account_ids: Vec<String>,
}
pub mod linked_storage_accounts_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum DataSourceType {
CustomLogs,
AzureWatson,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkedStorageAccounts {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
pub properties: LinkedStorageAccountsProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkedStorageAccountsListResult {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<LinkedStorageAccounts>,
}
| 37.021645 | 87 | 0.704514 |
ace9c488d5da2a3bd82a1b70a39c8af552d53db1
| 2,214 |
//! @ Since |line_break| is a rather lengthy procedure---sort of a small world unto
//! itself---we must build it up little by little, somewhat more cautiously
//! than we have done with the simpler procedures of \TeX. Here is the
//! general outline.
pub(crate) macro Get_ready_to_start_line_breaking($globals:expr) {{
crate::section_0816::Get_ready_to_start_line_breaking_0816!($globals);
crate::section_0827::Get_ready_to_start_line_breaking_0827!($globals);
crate::section_0834::Get_ready_to_start_line_breaking_0834!($globals);
crate::section_0848::Get_ready_to_start_line_breaking_0848!($globals);
}}
// @p@t\4@>@<Declare subprocedures for |line_break|@>
// procedure line_break(@!final_widow_penalty:integer);
#[cfg_attr(feature = "trace", tracing::instrument(level = "trace", skip(globals)))]
#[allow(unused_variables)]
pub(crate) fn line_break(globals: &mut TeXGlobals, final_widow_penalty: integer) -> TeXResult<()> {
// label done,done1,done2,done3,done4,done5,continue;
// var @<Local variables for line breaking@>@;
// begin pack_begin_line:=mode_line; {this is for over/underfull box messages}
/// this is for over/underfull box messages
const _: () = ();
globals.pack_begin_line = mode_line!(globals);
// @<Get ready to start line breaking@>;
Get_ready_to_start_line_breaking!(globals);
// @<Find optimal breakpoints@>;
crate::section_0863::Find_optimal_breakpoints!(globals);
// @<Break the paragraph at the chosen breakpoints, justify the resulting lines
// to the correct widths, and append them to the current vertical list@>;
crate::section_0876::Break_the_paragraph_at_the_chosen_breakpoints__justify_the_resulting_lines_to_the_correct_widths__and_append_them_to_the_current_vertical_list!(
globals,
final_widow_penalty
);
// @<Clean up the memory by removing the break nodes@>;
crate::section_0865::Clean_up_the_memory_by_removing_the_break_nodes!(globals);
// pack_begin_line:=0;
globals.pack_begin_line = 0;
// end;
crate::ok_nojump!()
}
use crate::pascal::integer;
use crate::section_0004::TeXGlobals;
use crate::section_0081::TeXResult;
use crate::section_0213::mode_line;
| 48.130435 | 169 | 0.743451 |
33438a39b2c27586a1d86f5d343b1dd70f5f7553
| 2,193 |
// @copyright
// Copyright (C) 2020 Assured Information Security, Inc.
//
// @copyright
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// @copyright
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// @copyright
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// NOTE:
// - The Rust manual states that a C style char type will "always" be a
// i8 or u8, which is absolutely not true.
// https://doc.rust-lang.org/std/os/raw/type.c_char.html
//
// - These types are not exposed to the core library either. The BSL requires
// that an unsigned char is a u8 (even though it doesn't have to be, and
// on some really weird systems, bytes are not 8 bits), but in our case,
// it is safe to assume that u8 will work for C compatibility as we will
// always be linking against LLVM style C and C++, which will set a char
// to u8 on the systems and operating systems we care about.
//
/// @brief Defines a C-style char type
pub type CharT = u8;
// -----------------------------------------------------------------------------
// Unit Tests
// -----------------------------------------------------------------------------
#[cfg(test)]
mod test_char_type {
use super::*;
#[test]
fn char_type_general() {
let _c = '*' as CharT;
}
}
| 40.611111 | 80 | 0.668035 |
db53733cecb8646288daa8584574b3e3a293e20a
| 4,954 |
//! TODO documentation
use std::ptr;
use wlroots_sys::{
wlr_output_cursor, wlr_output_cursor_create, wlr_output_cursor_destroy, wlr_output_cursor_move,
wlr_output_cursor_set_image, wlr_output_cursor_set_surface
};
use crate::{
output::{self, Output},
render,
surface::{self, Surface},
utils::{HandleErr, HandleResult, Handleable}
};
#[derive(Debug, Eq, PartialEq)]
pub struct Cursor {
cursor: *mut wlr_output_cursor,
output_handle: output::Handle
}
impl Cursor {
/// Creates a new `output::Cursor` that's bound to the given `Output`.
///
/// When the `Output` is destroyed each call will return an Error.
///
/// # Ergonomics
///
/// To make this easier for you, I would suggest putting the
/// `output::Cursor` in your `OutputHandler` implementor's state so that
/// when the `Output` is removed you just don't have to think about it
/// and it will clean itself up by itself.
pub fn new(output: &mut Output) -> Option<Cursor> {
unsafe {
let output_handle = output.weak_reference();
let cursor = wlr_output_cursor_create(output.as_ptr());
if cursor.is_null() {
None
} else {
Some(Cursor {
cursor,
output_handle
})
}
}
}
/// Return a copy of the output handle used by this cursor.
///
/// There are no guarantees that it is valid to use.
pub fn output(&self) -> output::Handle {
self.output_handle.clone()
}
/// Sets the hardware cursor's image.
pub fn set_image(&mut self, image: &render::Image) -> HandleResult<bool> {
unsafe {
let cursor = self.cursor;
if !self.output_handle.is_alive() {
return Err(HandleErr::AlreadyDropped);
}
Ok(wlr_output_cursor_set_image(
cursor,
image.pixels.as_ptr(),
image.stride,
image.width,
image.height,
image.hotspot_x,
image.hotspot_y
))
}
}
/// Sets the hardware cursor's surface.
pub fn set_surface<'a, T>(&mut self, surface: T, hotspot_x: i32, hotspot_y: i32) -> HandleResult<()>
where
T: Into<Option<&'a Surface>>
{
unsafe {
let surface_ptr = surface
.into()
.map(|surface| surface.as_ptr())
.unwrap_or_else(ptr::null_mut);
if !self.output_handle.is_alive() {
return Err(HandleErr::AlreadyDropped);
}
wlr_output_cursor_set_surface(self.cursor, surface_ptr, hotspot_x, hotspot_y);
Ok(())
}
}
/// Moves the hardware cursor to the desired location
pub fn move_relative(&mut self, x: f64, y: f64) -> HandleResult<bool> {
unsafe {
if !self.output_handle.is_alive() {
return Err(HandleErr::AlreadyDropped);
}
Ok(wlr_output_cursor_move(self.cursor, x, y))
}
}
/// Get the coordinates of the cursor.
///
/// Returned value is in (x, y) format.
pub fn coords(&self) -> (f64, f64) {
unsafe { ((*self.cursor).x, (*self.cursor).y) }
}
/// Determines if the hardware cursor is enabled or not.
pub fn enabled(&self) -> bool {
unsafe { (*self.cursor).enabled }
}
/// Determines if the hardware cursor is visible or not.
pub fn visible(&self) -> bool {
unsafe { (*self.cursor).visible }
}
/// Gets the width and height of the hardware cursor.
///
/// Returned value is in (width, height) format.
pub fn size(&self) -> (u32, u32) {
unsafe { ((*self.cursor).width, (*self.cursor).height) }
}
/// Gets the hotspot coordinates of the hardware cursor.
///
/// Returned value is in (x, y) coordinates.
pub fn hotspots(&self) -> (i32, i32) {
unsafe { ((*self.cursor).hotspot_x, (*self.cursor).hotspot_y) }
}
/// Gets the texture for the cursor, if a software cursor is used without a
/// surface.
pub fn texture(&self) -> Option<render::Texture> {
unsafe {
let texture = (*self.cursor).texture;
if texture.is_null() {
None
} else {
Some(render::Texture::from_ptr(texture))
}
}
}
/// Gets the surface for the cursor, if using a cursor surface.
pub fn surface(&self) -> Option<surface::Handle> {
unsafe {
let surface = (*self.cursor).surface;
if surface.is_null() {
None
} else {
Some(surface::Handle::from_ptr(surface))
}
}
}
}
impl Drop for Cursor {
fn drop(&mut self) {
unsafe { wlr_output_cursor_destroy(self.cursor) }
}
}
| 30.024242 | 104 | 0.551474 |
768d95effa2ea0cce2c25c1f13c5d34404c61ff0
| 36,584 |
//! The type system. We currently use this to infer types for completion, hover
//! information and various assists.
#[allow(unused)]
macro_rules! eprintln {
($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
}
mod autoderef;
pub mod primitive;
pub mod traits;
pub mod method_resolution;
mod op;
mod lower;
pub(crate) mod infer;
pub(crate) mod utils;
pub mod display;
pub mod db;
pub mod diagnostics;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod test_db;
use std::{iter, mem, ops::Deref, sync::Arc};
use base_db::{salsa, CrateId};
use hir_def::{
expr::ExprId,
type_ref::{Mutability, Rawness},
AdtId, AssocContainerId, DefWithBodyId, GenericDefId, HasModule, Lookup, TraitId, TypeAliasId,
TypeParamId,
};
use itertools::Itertools;
use crate::{
db::HirDatabase,
display::HirDisplay,
primitive::{FloatTy, IntTy},
utils::{generics, make_mut_slice, Generics},
};
pub use autoderef::autoderef;
pub use infer::{InferTy, InferenceResult};
pub use lower::CallableDefId;
pub use lower::{
associated_type_shorthand_candidates, callable_item_sig, ImplTraitLoweringMode, TyDefId,
TyLoweringContext, ValueTyDefId,
};
pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment};
pub use chalk_ir::{BoundVar, DebruijnIndex};
/// A type constructor or type name: this might be something like the primitive
/// type `bool`, a struct like `Vec`, or things like function pointers or
/// tuples.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum TypeCtor {
/// The primitive boolean type. Written as `bool`.
Bool,
/// The primitive character type; holds a Unicode scalar value
/// (a non-surrogate code point). Written as `char`.
Char,
/// A primitive integer type. For example, `i32`.
Int(IntTy),
/// A primitive floating-point type. For example, `f64`.
Float(FloatTy),
/// Structures, enumerations and unions.
Adt(AdtId),
/// The pointee of a string slice. Written as `str`.
Str,
/// The pointee of an array slice. Written as `[T]`.
Slice,
/// An array with the given length. Written as `[T; n]`.
Array,
/// A raw pointer. Written as `*mut T` or `*const T`
RawPtr(Mutability),
/// A reference; a pointer with an associated lifetime. Written as
/// `&'a mut T` or `&'a T`.
Ref(Mutability),
/// The anonymous type of a function declaration/definition. Each
/// function has a unique type, which is output (for a function
/// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
///
/// This includes tuple struct / enum variant constructors as well.
///
/// For example the type of `bar` here:
///
/// ```
/// fn foo() -> i32 { 1 }
/// let bar = foo; // bar: fn() -> i32 {foo}
/// ```
FnDef(CallableDefId),
/// A pointer to a function. Written as `fn() -> i32`.
///
/// For example the type of `bar` here:
///
/// ```
/// fn foo() -> i32 { 1 }
/// let bar: fn() -> i32 = foo;
/// ```
// FIXME make this a Ty variant like in Chalk
FnPtr { num_args: u16, is_varargs: bool },
/// The never type `!`.
Never,
/// A tuple type. For example, `(i32, bool)`.
Tuple { cardinality: u16 },
/// Represents an associated item like `Iterator::Item`. This is used
/// when we have tried to normalize a projection like `T::Item` but
/// couldn't find a better representation. In that case, we generate
/// an **application type** like `(Iterator::Item)<T>`.
AssociatedType(TypeAliasId),
/// This represents a placeholder for an opaque type in situations where we
/// don't know the hidden type (i.e. currently almost always). This is
/// analogous to the `AssociatedType` type constructor.
/// It is also used as the type of async block, with one type parameter
/// representing the Future::Output type.
OpaqueType(OpaqueTyId),
/// Represents a foreign type declared in external blocks.
ForeignType(TypeAliasId),
/// The type of a specific closure.
///
/// The closure signature is stored in a `FnPtr` type in the first type
/// parameter.
Closure { def: DefWithBodyId, expr: ExprId },
}
impl TypeCtor {
pub fn num_ty_params(self, db: &dyn HirDatabase) -> usize {
match self {
TypeCtor::Bool
| TypeCtor::Char
| TypeCtor::Int(_)
| TypeCtor::Float(_)
| TypeCtor::Str
| TypeCtor::Never => 0,
TypeCtor::Slice
| TypeCtor::Array
| TypeCtor::RawPtr(_)
| TypeCtor::Ref(_)
| TypeCtor::Closure { .. } // 1 param representing the signature of the closure
=> 1,
TypeCtor::Adt(adt) => {
let generic_params = generics(db.upcast(), adt.into());
generic_params.len()
}
TypeCtor::FnDef(callable) => {
let generic_params = generics(db.upcast(), callable.into());
generic_params.len()
}
TypeCtor::AssociatedType(type_alias) => {
let generic_params = generics(db.upcast(), type_alias.into());
generic_params.len()
}
TypeCtor::ForeignType(type_alias) => {
let generic_params = generics(db.upcast(), type_alias.into());
generic_params.len()
}
TypeCtor::OpaqueType(opaque_ty_id) => {
match opaque_ty_id {
OpaqueTyId::ReturnTypeImplTrait(func, _) => {
let generic_params = generics(db.upcast(), func.into());
generic_params.len()
}
// 1 param representing Future::Output type.
OpaqueTyId::AsyncBlockTypeImplTrait(..) => 1,
}
}
TypeCtor::FnPtr { num_args, is_varargs: _ } => num_args as usize + 1,
TypeCtor::Tuple { cardinality } => cardinality as usize,
}
}
pub fn krate(self, db: &dyn HirDatabase) -> Option<CrateId> {
match self {
TypeCtor::Bool
| TypeCtor::Char
| TypeCtor::Int(_)
| TypeCtor::Float(_)
| TypeCtor::Str
| TypeCtor::Never
| TypeCtor::Slice
| TypeCtor::Array
| TypeCtor::RawPtr(_)
| TypeCtor::Ref(_)
| TypeCtor::FnPtr { .. }
| TypeCtor::Tuple { .. } => None,
// Closure's krate is irrelevant for coherence I would think?
TypeCtor::Closure { .. } => None,
TypeCtor::Adt(adt) => Some(adt.module(db.upcast()).krate),
TypeCtor::FnDef(callable) => Some(callable.krate(db)),
TypeCtor::AssociatedType(type_alias) => {
Some(type_alias.lookup(db.upcast()).module(db.upcast()).krate)
}
TypeCtor::ForeignType(type_alias) => {
Some(type_alias.lookup(db.upcast()).module(db.upcast()).krate)
}
TypeCtor::OpaqueType(opaque_ty_id) => match opaque_ty_id {
OpaqueTyId::ReturnTypeImplTrait(func, _) => {
Some(func.lookup(db.upcast()).module(db.upcast()).krate)
}
OpaqueTyId::AsyncBlockTypeImplTrait(def, _) => Some(def.module(db.upcast()).krate),
},
}
}
pub fn as_generic_def(self) -> Option<GenericDefId> {
match self {
TypeCtor::Bool
| TypeCtor::Char
| TypeCtor::Int(_)
| TypeCtor::Float(_)
| TypeCtor::Str
| TypeCtor::Never
| TypeCtor::Slice
| TypeCtor::Array
| TypeCtor::RawPtr(_)
| TypeCtor::Ref(_)
| TypeCtor::FnPtr { .. }
| TypeCtor::Tuple { .. }
| TypeCtor::Closure { .. } => None,
TypeCtor::Adt(adt) => Some(adt.into()),
TypeCtor::FnDef(callable) => Some(callable.into()),
TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()),
TypeCtor::ForeignType(type_alias) => Some(type_alias.into()),
TypeCtor::OpaqueType(_impl_trait_id) => None,
}
}
}
/// A nominal type with (maybe 0) type parameters. This might be a primitive
/// type like `bool`, a struct, tuple, function pointer, reference or
/// several other things.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct ApplicationTy {
pub ctor: TypeCtor,
pub parameters: Substs,
}
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct OpaqueTy {
pub opaque_ty_id: OpaqueTyId,
pub parameters: Substs,
}
/// A "projection" type corresponds to an (unnormalized)
/// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the
/// trait and all its parameters are fully known.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct ProjectionTy {
pub associated_ty: TypeAliasId,
pub parameters: Substs,
}
impl ProjectionTy {
pub fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef {
TraitRef { trait_: self.trait_(db), substs: self.parameters.clone() }
}
fn trait_(&self, db: &dyn HirDatabase) -> TraitId {
match self.associated_ty.lookup(db.upcast()).container {
AssocContainerId::TraitId(it) => it,
_ => panic!("projection ty without parent trait"),
}
}
}
impl TypeWalk for ProjectionTy {
fn walk(&self, f: &mut impl FnMut(&Ty)) {
self.parameters.walk(f);
}
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
) {
self.parameters.walk_mut_binders(f, binders);
}
}
/// A type.
///
/// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents
/// the same thing (but in a different way).
///
/// This should be cheap to clone.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub enum Ty {
/// A nominal type with (maybe 0) type parameters. This might be a primitive
/// type like `bool`, a struct, tuple, function pointer, reference or
/// several other things.
Apply(ApplicationTy),
/// A "projection" type corresponds to an (unnormalized)
/// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the
/// trait and all its parameters are fully known.
Projection(ProjectionTy),
/// An opaque type (`impl Trait`).
///
/// This is currently only used for return type impl trait; each instance of
/// `impl Trait` in a return type gets its own ID.
Opaque(OpaqueTy),
/// A placeholder for a type parameter; for example, `T` in `fn f<T>(x: T)
/// {}` when we're type-checking the body of that function. In this
/// situation, we know this stands for *some* type, but don't know the exact
/// type.
Placeholder(TypeParamId),
/// A bound type variable. This is used in various places: when representing
/// some polymorphic type like the type of function `fn f<T>`, the type
/// parameters get turned into variables; during trait resolution, inference
/// variables get turned into bound variables and back; and in `Dyn` the
/// `Self` type is represented with a bound variable as well.
Bound(BoundVar),
/// A type variable used during type checking.
Infer(InferTy),
/// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust).
///
/// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)`
/// represents the `Self` type inside the bounds. This is currently
/// implicit; Chalk has the `Binders` struct to make it explicit, but it
/// didn't seem worth the overhead yet.
Dyn(Arc<[GenericPredicate]>),
/// A placeholder for a type which could not be computed; this is propagated
/// to avoid useless error messages. Doubles as a placeholder where type
/// variables are inserted before type checking, since we want to try to
/// infer a better type here anyway -- for the IDE use case, we want to try
/// to infer as much as possible even in the presence of type errors.
Unknown,
}
/// A list of substitutions for generic parameters.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct Substs(Arc<[Ty]>);
impl TypeWalk for Substs {
fn walk(&self, f: &mut impl FnMut(&Ty)) {
for t in self.0.iter() {
t.walk(f);
}
}
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
) {
for t in make_mut_slice(&mut self.0) {
t.walk_mut_binders(f, binders);
}
}
}
impl Substs {
pub fn empty() -> Substs {
Substs(Arc::new([]))
}
pub fn single(ty: Ty) -> Substs {
Substs(Arc::new([ty]))
}
pub fn prefix(&self, n: usize) -> Substs {
Substs(self.0[..std::cmp::min(self.0.len(), n)].into())
}
pub fn suffix(&self, n: usize) -> Substs {
Substs(self.0[self.0.len() - std::cmp::min(self.0.len(), n)..].into())
}
pub fn as_single(&self) -> &Ty {
if self.0.len() != 1 {
panic!("expected substs of len 1, got {:?}", self);
}
&self.0[0]
}
/// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
pub(crate) fn type_params_for_generics(generic_params: &Generics) -> Substs {
Substs(generic_params.iter().map(|(id, _)| Ty::Placeholder(id)).collect())
}
/// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
pub fn type_params(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substs {
let params = generics(db.upcast(), def.into());
Substs::type_params_for_generics(¶ms)
}
/// Return Substs that replace each parameter by a bound variable.
pub(crate) fn bound_vars(generic_params: &Generics, debruijn: DebruijnIndex) -> Substs {
Substs(
generic_params
.iter()
.enumerate()
.map(|(idx, _)| Ty::Bound(BoundVar::new(debruijn, idx)))
.collect(),
)
}
pub fn build_for_def(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder {
let def = def.into();
let params = generics(db.upcast(), def);
let param_count = params.len();
Substs::builder(param_count)
}
pub(crate) fn build_for_generics(generic_params: &Generics) -> SubstsBuilder {
Substs::builder(generic_params.len())
}
pub fn build_for_type_ctor(db: &dyn HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder {
Substs::builder(type_ctor.num_ty_params(db))
}
fn builder(param_count: usize) -> SubstsBuilder {
SubstsBuilder { vec: Vec::with_capacity(param_count), param_count }
}
}
/// Return an index of a parameter in the generic type parameter list by it's id.
pub fn param_idx(db: &dyn HirDatabase, id: TypeParamId) -> Option<usize> {
generics(db.upcast(), id.parent).param_idx(id)
}
#[derive(Debug, Clone)]
pub struct SubstsBuilder {
vec: Vec<Ty>,
param_count: usize,
}
impl SubstsBuilder {
pub fn build(self) -> Substs {
assert_eq!(self.vec.len(), self.param_count);
Substs(self.vec.into())
}
pub fn push(mut self, ty: Ty) -> Self {
self.vec.push(ty);
self
}
fn remaining(&self) -> usize {
self.param_count - self.vec.len()
}
pub fn fill_with_bound_vars(self, debruijn: DebruijnIndex, starting_from: usize) -> Self {
self.fill((starting_from..).map(|idx| Ty::Bound(BoundVar::new(debruijn, idx))))
}
pub fn fill_with_unknown(self) -> Self {
self.fill(iter::repeat(Ty::Unknown))
}
pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self {
self.vec.extend(filler.take(self.remaining()));
assert_eq!(self.remaining(), 0);
self
}
pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self {
assert!(self.vec.is_empty());
assert!(parent_substs.len() <= self.param_count);
self.vec.extend(parent_substs.iter().cloned());
self
}
}
impl Deref for Substs {
type Target = [Ty];
fn deref(&self) -> &[Ty] {
&self.0
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct Binders<T> {
pub num_binders: usize,
pub value: T,
}
impl<T> Binders<T> {
pub fn new(num_binders: usize, value: T) -> Self {
Self { num_binders, value }
}
pub fn as_ref(&self) -> Binders<&T> {
Binders { num_binders: self.num_binders, value: &self.value }
}
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Binders<U> {
Binders { num_binders: self.num_binders, value: f(self.value) }
}
pub fn filter_map<U>(self, f: impl FnOnce(T) -> Option<U>) -> Option<Binders<U>> {
Some(Binders { num_binders: self.num_binders, value: f(self.value)? })
}
}
impl<T: Clone> Binders<&T> {
pub fn cloned(&self) -> Binders<T> {
Binders { num_binders: self.num_binders, value: self.value.clone() }
}
}
impl<T: TypeWalk> Binders<T> {
/// Substitutes all variables.
pub fn subst(self, subst: &Substs) -> T {
assert_eq!(subst.len(), self.num_binders);
self.value.subst_bound_vars(subst)
}
/// Substitutes just a prefix of the variables (shifting the rest).
pub fn subst_prefix(self, subst: &Substs) -> Binders<T> {
assert!(subst.len() < self.num_binders);
Binders::new(self.num_binders - subst.len(), self.value.subst_bound_vars(subst))
}
}
impl<T: TypeWalk> TypeWalk for Binders<T> {
fn walk(&self, f: &mut impl FnMut(&Ty)) {
self.value.walk(f);
}
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
) {
self.value.walk_mut_binders(f, binders.shifted_in())
}
}
/// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait.
/// Name to be bikeshedded: TraitBound? TraitImplements?
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct TraitRef {
/// FIXME name?
pub trait_: TraitId,
pub substs: Substs,
}
impl TraitRef {
pub fn self_ty(&self) -> &Ty {
&self.substs[0]
}
}
impl TypeWalk for TraitRef {
fn walk(&self, f: &mut impl FnMut(&Ty)) {
self.substs.walk(f);
}
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
) {
self.substs.walk_mut_binders(f, binders);
}
}
/// Like `generics::WherePredicate`, but with resolved types: A condition on the
/// parameters of a generic item.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GenericPredicate {
/// The given trait needs to be implemented for its type parameters.
Implemented(TraitRef),
/// An associated type bindings like in `Iterator<Item = T>`.
Projection(ProjectionPredicate),
/// We couldn't resolve the trait reference. (If some type parameters can't
/// be resolved, they will just be Unknown).
Error,
}
impl GenericPredicate {
pub fn is_error(&self) -> bool {
matches!(self, GenericPredicate::Error)
}
pub fn is_implemented(&self) -> bool {
matches!(self, GenericPredicate::Implemented(_))
}
pub fn trait_ref(&self, db: &dyn HirDatabase) -> Option<TraitRef> {
match self {
GenericPredicate::Implemented(tr) => Some(tr.clone()),
GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)),
GenericPredicate::Error => None,
}
}
}
impl TypeWalk for GenericPredicate {
fn walk(&self, f: &mut impl FnMut(&Ty)) {
match self {
GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f),
GenericPredicate::Projection(projection_pred) => projection_pred.walk(f),
GenericPredicate::Error => {}
}
}
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
) {
match self {
GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders),
GenericPredicate::Projection(projection_pred) => {
projection_pred.walk_mut_binders(f, binders)
}
GenericPredicate::Error => {}
}
}
}
/// Basically a claim (currently not validated / checked) that the contained
/// type / trait ref contains no inference variables; any inference variables it
/// contained have been replaced by bound variables, and `kinds` tells us how
/// many there are and whether they were normal or float/int variables. This is
/// used to erase irrelevant differences between types before using them in
/// queries.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Canonical<T> {
pub value: T,
pub kinds: Arc<[TyKind]>,
}
impl<T> Canonical<T> {
pub fn new(value: T, kinds: impl IntoIterator<Item = TyKind>) -> Self {
Self { value, kinds: kinds.into_iter().collect() }
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum TyKind {
General,
Integer,
Float,
}
/// A function signature as seen by type inference: Several parameter types and
/// one return type.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FnSig {
params_and_return: Arc<[Ty]>,
is_varargs: bool,
}
/// A polymorphic function signature.
pub type PolyFnSig = Binders<FnSig>;
impl FnSig {
pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> FnSig {
params.push(ret);
FnSig { params_and_return: params.into(), is_varargs }
}
pub fn from_fn_ptr_substs(substs: &Substs, is_varargs: bool) -> FnSig {
FnSig { params_and_return: Arc::clone(&substs.0), is_varargs }
}
pub fn params(&self) -> &[Ty] {
&self.params_and_return[0..self.params_and_return.len() - 1]
}
pub fn ret(&self) -> &Ty {
&self.params_and_return[self.params_and_return.len() - 1]
}
}
impl TypeWalk for FnSig {
fn walk(&self, f: &mut impl FnMut(&Ty)) {
for t in self.params_and_return.iter() {
t.walk(f);
}
}
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
) {
for t in make_mut_slice(&mut self.params_and_return) {
t.walk_mut_binders(f, binders);
}
}
}
impl Ty {
pub fn simple(ctor: TypeCtor) -> Ty {
Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() })
}
pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty {
Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) })
}
pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty {
Ty::Apply(ApplicationTy { ctor, parameters })
}
pub fn unit() -> Self {
Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty())
}
pub fn fn_ptr(sig: FnSig) -> Self {
Ty::apply(
TypeCtor::FnPtr { num_args: sig.params().len() as u16, is_varargs: sig.is_varargs },
Substs(sig.params_and_return),
)
}
pub fn as_reference(&self) -> Option<(&Ty, Mutability)> {
match self {
Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => {
Some((parameters.as_single(), *mutability))
}
_ => None,
}
}
pub fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)> {
match self {
Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => {
Some((parameters.as_single(), Rawness::Ref, *mutability))
}
Ty::Apply(ApplicationTy { ctor: TypeCtor::RawPtr(mutability), parameters }) => {
Some((parameters.as_single(), Rawness::RawPtr, *mutability))
}
_ => None,
}
}
pub fn strip_references(&self) -> &Ty {
let mut t: &Ty = self;
while let Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(_mutability), parameters }) = t {
t = parameters.as_single();
}
t
}
pub fn as_adt(&self) -> Option<(AdtId, &Substs)> {
match self {
Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => {
Some((*adt_def, parameters))
}
_ => None,
}
}
pub fn as_tuple(&self) -> Option<&Substs> {
match self {
Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => {
Some(parameters)
}
_ => None,
}
}
pub fn is_never(&self) -> bool {
matches!(self, Ty::Apply(ApplicationTy { ctor: TypeCtor::Never, .. }))
}
/// If this is a `dyn Trait` type, this returns the `Trait` part.
pub fn dyn_trait_ref(&self) -> Option<&TraitRef> {
match self {
Ty::Dyn(bounds) => bounds.get(0).and_then(|b| match b {
GenericPredicate::Implemented(trait_ref) => Some(trait_ref),
_ => None,
}),
_ => None,
}
}
/// If this is a `dyn Trait`, returns that trait.
pub fn dyn_trait(&self) -> Option<TraitId> {
self.dyn_trait_ref().map(|it| it.trait_)
}
fn builtin_deref(&self) -> Option<Ty> {
match self {
Ty::Apply(a_ty) => match a_ty.ctor {
TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())),
TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())),
_ => None,
},
_ => None,
}
}
pub fn callable_sig(&self, db: &dyn HirDatabase) -> Option<FnSig> {
match self {
Ty::Apply(a_ty) => match a_ty.ctor {
TypeCtor::FnPtr { is_varargs, .. } => {
Some(FnSig::from_fn_ptr_substs(&a_ty.parameters, is_varargs))
}
TypeCtor::FnDef(def) => {
let sig = db.callable_item_signature(def);
Some(sig.subst(&a_ty.parameters))
}
TypeCtor::Closure { .. } => {
let sig_param = &a_ty.parameters[0];
sig_param.callable_sig(db)
}
_ => None,
},
_ => None,
}
}
/// If this is a type with type parameters (an ADT or function), replaces
/// the `Substs` for these type parameters with the given ones. (So e.g. if
/// `self` is `Option<_>` and the substs contain `u32`, we'll have
/// `Option<u32>` afterwards.)
pub fn apply_substs(self, substs: Substs) -> Ty {
match self {
Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => {
assert_eq!(previous_substs.len(), substs.len());
Ty::Apply(ApplicationTy { ctor, parameters: substs })
}
_ => self,
}
}
/// Returns the type parameters of this type if it has some (i.e. is an ADT
/// or function); so if `self` is `Option<u32>`, this returns the `u32`.
pub fn substs(&self) -> Option<Substs> {
match self {
Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()),
_ => None,
}
}
pub fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<GenericPredicate>> {
match self {
Ty::Apply(ApplicationTy { ctor: TypeCtor::OpaqueType(opaque_ty_id), .. }) => {
match opaque_ty_id {
OpaqueTyId::AsyncBlockTypeImplTrait(def, _expr) => {
let krate = def.module(db.upcast()).krate;
if let Some(future_trait) = db
.lang_item(krate, "future_trait".into())
.and_then(|item| item.as_trait())
{
// This is only used by type walking.
// Parameters will be walked outside, and projection predicate is not used.
// So just provide the Future trait.
let impl_bound = GenericPredicate::Implemented(TraitRef {
trait_: future_trait,
substs: Substs::empty(),
});
Some(vec![impl_bound])
} else {
None
}
}
OpaqueTyId::ReturnTypeImplTrait(..) => None,
}
}
Ty::Opaque(opaque_ty) => {
let predicates = match opaque_ty.opaque_ty_id {
OpaqueTyId::ReturnTypeImplTrait(func, idx) => {
db.return_type_impl_traits(func).map(|it| {
let data = (*it)
.as_ref()
.map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
data.subst(&opaque_ty.parameters)
})
}
// It always has an parameter for Future::Output type.
OpaqueTyId::AsyncBlockTypeImplTrait(..) => unreachable!(),
};
predicates.map(|it| it.value)
}
Ty::Placeholder(id) => {
let generic_params = db.generic_params(id.parent);
let param_data = &generic_params.types[id.local_id];
match param_data.provenance {
hir_def::generics::TypeParamProvenance::ArgumentImplTrait => {
let predicates = db
.generic_predicates_for_param(*id)
.into_iter()
.map(|pred| pred.value.clone())
.collect_vec();
Some(predicates)
}
_ => None,
}
}
_ => None,
}
}
pub fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId> {
match self {
Ty::Apply(ApplicationTy { ctor: TypeCtor::AssociatedType(type_alias_id), .. }) => {
match type_alias_id.lookup(db.upcast()).container {
AssocContainerId::TraitId(trait_id) => Some(trait_id),
_ => None,
}
}
Ty::Projection(projection_ty) => {
match projection_ty.associated_ty.lookup(db.upcast()).container {
AssocContainerId::TraitId(trait_id) => Some(trait_id),
_ => None,
}
}
_ => None,
}
}
}
/// This allows walking structures that contain types to do something with those
/// types, similar to Chalk's `Fold` trait.
pub trait TypeWalk {
fn walk(&self, f: &mut impl FnMut(&Ty));
fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) {
self.walk_mut_binders(&mut |ty, _binders| f(ty), DebruijnIndex::INNERMOST);
}
/// Walk the type, counting entered binders.
///
/// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers
/// to the innermost binder, 1 to the next, etc.. So when we want to
/// substitute a certain bound variable, we can't just walk the whole type
/// and blindly replace each instance of a certain index; when we 'enter'
/// things that introduce new bound variables, we have to keep track of
/// that. Currently, the only thing that introduces bound variables on our
/// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound
/// variable for the self type.
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
);
fn fold_binders(
mut self,
f: &mut impl FnMut(Ty, DebruijnIndex) -> Ty,
binders: DebruijnIndex,
) -> Self
where
Self: Sized,
{
self.walk_mut_binders(
&mut |ty_mut, binders| {
let ty = mem::replace(ty_mut, Ty::Unknown);
*ty_mut = f(ty, binders);
},
binders,
);
self
}
fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self
where
Self: Sized,
{
self.walk_mut(&mut |ty_mut| {
let ty = mem::replace(ty_mut, Ty::Unknown);
*ty_mut = f(ty);
});
self
}
/// Substitutes `Ty::Bound` vars with the given substitution.
fn subst_bound_vars(self, substs: &Substs) -> Self
where
Self: Sized,
{
self.subst_bound_vars_at_depth(substs, DebruijnIndex::INNERMOST)
}
/// Substitutes `Ty::Bound` vars with the given substitution.
fn subst_bound_vars_at_depth(mut self, substs: &Substs, depth: DebruijnIndex) -> Self
where
Self: Sized,
{
self.walk_mut_binders(
&mut |ty, binders| {
if let &mut Ty::Bound(bound) = ty {
if bound.debruijn >= binders {
*ty = substs.0[bound.index].clone().shift_bound_vars(binders);
}
}
},
depth,
);
self
}
/// Shifts up debruijn indices of `Ty::Bound` vars by `n`.
fn shift_bound_vars(self, n: DebruijnIndex) -> Self
where
Self: Sized,
{
self.fold_binders(
&mut |ty, binders| match ty {
Ty::Bound(bound) if bound.debruijn >= binders => {
Ty::Bound(bound.shifted_in_from(n))
}
ty => ty,
},
DebruijnIndex::INNERMOST,
)
}
}
impl TypeWalk for Ty {
fn walk(&self, f: &mut impl FnMut(&Ty)) {
match self {
Ty::Apply(a_ty) => {
for t in a_ty.parameters.iter() {
t.walk(f);
}
}
Ty::Projection(p_ty) => {
for t in p_ty.parameters.iter() {
t.walk(f);
}
}
Ty::Dyn(predicates) => {
for p in predicates.iter() {
p.walk(f);
}
}
Ty::Opaque(o_ty) => {
for t in o_ty.parameters.iter() {
t.walk(f);
}
}
Ty::Placeholder { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
}
f(self);
}
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
) {
match self {
Ty::Apply(a_ty) => {
a_ty.parameters.walk_mut_binders(f, binders);
}
Ty::Projection(p_ty) => {
p_ty.parameters.walk_mut_binders(f, binders);
}
Ty::Dyn(predicates) => {
for p in make_mut_slice(predicates) {
p.walk_mut_binders(f, binders.shifted_in());
}
}
Ty::Opaque(o_ty) => {
o_ty.parameters.walk_mut_binders(f, binders);
}
Ty::Placeholder { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
}
f(self, binders);
}
}
impl<T: TypeWalk> TypeWalk for Vec<T> {
fn walk(&self, f: &mut impl FnMut(&Ty)) {
for t in self {
t.walk(f);
}
}
fn walk_mut_binders(
&mut self,
f: &mut impl FnMut(&mut Ty, DebruijnIndex),
binders: DebruijnIndex,
) {
for t in self {
t.walk_mut_binders(f, binders);
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum OpaqueTyId {
ReturnTypeImplTrait(hir_def::FunctionId, u16),
AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
}
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct ReturnTypeImplTraits {
pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
}
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub(crate) struct ReturnTypeImplTrait {
pub bounds: Binders<Vec<GenericPredicate>>,
}
| 32.664286 | 118 | 0.559917 |
eb265e387c39ff116d58f4e28b044002ae1e89cb
| 2,007 |
pub mod expr;
pub mod ind;
use std::iter::Peekable;
use thiserror::Error;
use crate::{data::Expr, lexer::{Token, TokenInner}};
use self::expr::parse_expr;
#[derive(Error, Debug)]
pub enum ParseError<'a> {
#[error("Unexpected token: {token:?}")]
UnexpectedToken {
token: Token<'a>
},
#[error("Malformed constructor: {token:?}")]
MalformedCtr {
token: Token<'a>,
},
#[error("Malformed attribute: {token:?}")]
MalformedAttr {
token: Token<'a>,
},
#[error("Malformed attribute: {token:?}")]
MalformedUniverse {
token: Token<'a>,
},
#[error("Absolute import cannot have ..")]
AbsPathUp,
#[error("Unexpected EOF")]
EOF,
#[error("Unexpected EOF")]
SoftEOF,
}
pub type ParseResult<'a, T> = Result<T, ParseError<'a>>;
fn parse_single<'a, I: Iterator<Item = Token<'a>>>(tokens: &mut Peekable<I>, expected: TokenInner) -> ParseResult<'a, Token<'a>> {
let token = tokens.next().ok_or(ParseError::SoftEOF)?;
if token.inner != expected {
return Err(ParseError::UnexpectedToken{ token });
}
Ok(token)
}
fn parse_str<'a, I: Iterator<Item = Token<'a>>>(tokens: &mut Peekable<I>) -> ParseResult<'a, &'a str> {
let token = tokens.next().ok_or(ParseError::SoftEOF)?;
match token.inner {
TokenInner::Symb(s) | TokenInner::Word(s) => Ok(s),
_ => Err(ParseError::UnexpectedToken{ token }),
}
}
fn parse_level<'a, I: Iterator<Item = Token<'a>>>(tokens: &mut Peekable<I>) -> ParseResult<'a, Option<usize>> {
let token = tokens.next().ok_or(ParseError::SoftEOF)?;
match token.inner {
TokenInner::Symb("_") => Ok(None),
TokenInner::Word(s) => s.parse::<usize>().map_err(|_| ParseError::MalformedUniverse{ token }).map(Some),
_ => Err(ParseError::MalformedUniverse{ token }),
}
}
pub fn parse<'a, I: Iterator<Item = Token<'a>>>(tokens: &mut Peekable<I>) -> ParseResult<'a, Expr<'a, ()>> {
parse_expr(tokens, isize::MIN)
}
| 26.76 | 130 | 0.601893 |
e5aba787abc3fdeb309959b4ae8e58a3c7c6205a
| 4,682 |
// FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for Windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on Unix platforms because Ctrl-C
//! actually sends a signal to the *process group* rather than the parent
//! process, so everything will get torn down. On Windows, however, this does
//! not happen and Ctrl-C just kills cargo.
//!
//! To achieve the same semantics on Windows we use Job Objects to ensure that
//! all processes die at the same time. Job objects have a mode of operation
//! where when all handles to the object are closed it causes all child
//! processes associated with the object to be terminated immediately.
//! Conveniently whenever a process in the job object spawns a new process the
//! child will be associated with the job object as well. This means if we add
//! ourselves to the job object we create then everything will get torn down!
#![allow(clippy::missing_safety_doc)]
pub use self::imp::Setup;
pub fn setup() -> Option<Setup> {
unsafe { imp::setup() }
}
#[cfg(unix)]
mod imp {
pub type Setup = ();
pub unsafe fn setup() -> Option<()> {
Some(())
}
}
#[cfg(windows)]
mod imp {
use std::io;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::*;
use winapi::um::handleapi::*;
use winapi::um::jobapi2::*;
use winapi::um::processthreadsapi::*;
use winapi::um::winnt::HANDLE;
use winapi::um::winnt::*;
pub struct Setup {
job: Handle,
}
pub struct Handle {
inner: HANDLE,
}
fn last_err() -> io::Error {
io::Error::last_os_error()
}
pub unsafe fn setup() -> Option<Setup> {
// Creates a new job object for us to use and then adds ourselves to it.
// Note that all errors are basically ignored in this function,
// intentionally. Job objects are "relatively new" in Windows,
// particularly the ability to support nested job objects. Older
// Windows installs don't support this ability. We probably don't want
// to force Cargo to abort in this situation or force others to *not*
// use job objects, so we instead just ignore errors and assume that
// we're otherwise part of someone else's job object in this case.
let job = CreateJobObjectW(ptr::null_mut(), ptr::null());
if job.is_null() {
return None;
}
let job = Handle { inner: job };
// Indicate that when all handles to the job object are gone that all
// process in the object should be killed. Note that this includes our
// entire process tree by default because we've added ourselves and
// our children will reside in the job once we spawn a process.
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let r = SetInformationJobObject(
job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
return None;
}
// Assign our process to this job object, meaning that our children will
// now live or die based on our existence.
let me = GetCurrentProcess();
let r = AssignProcessToJobObject(job.inner, me);
if r == 0 {
return None;
}
Some(Setup { job })
}
impl Drop for Setup {
fn drop(&mut self) {
// On normal exits (not ctrl-c), we don't want to kill any child
// processes. The destructor here configures our job object to
// *not* kill everything on close, then closes the job object.
unsafe {
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
let r = SetInformationJobObject(
self.job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
info!("failed to configure job object to defaults: {}", last_err());
}
}
}
}
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.inner);
}
}
}
}
| 34.681481 | 88 | 0.604229 |
5d268658cc1556f109de3242859fd7e609565ce7
| 30,598 |
//! SPARC64-specific definitions for 64-bit linux-like values
use pthread_mutex_t;
pub type c_long = i64;
pub type c_ulong = u64;
pub type c_char = i8;
pub type wchar_t = i32;
pub type nlink_t = u32;
pub type blksize_t = i64;
pub type suseconds_t = i32;
pub type __u64 = ::c_ulonglong;
s! {
pub struct stat {
pub st_dev: ::dev_t,
__pad0: u64,
pub st_ino: ::ino_t,
pub st_mode: ::mode_t,
pub st_nlink: ::nlink_t,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
pub st_rdev: ::dev_t,
__pad1: u64,
pub st_size: ::off_t,
pub st_blksize: ::blksize_t,
pub st_blocks: ::blkcnt_t,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
pub st_ctime_nsec: ::c_long,
__unused: [::c_long; 2],
}
pub struct stat64 {
pub st_dev: ::dev_t,
__pad0: u64,
pub st_ino: ::ino64_t,
pub st_mode: ::mode_t,
pub st_nlink: ::nlink_t,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
pub st_rdev: ::dev_t,
__pad2: ::c_int,
pub st_size: ::off64_t,
pub st_blksize: ::blksize_t,
pub st_blocks: ::blkcnt64_t,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
pub st_ctime_nsec: ::c_long,
__reserved: [::c_long; 2],
}
pub struct statfs64 {
pub f_type: ::__fsword_t,
pub f_bsize: ::__fsword_t,
pub f_blocks: u64,
pub f_bfree: u64,
pub f_bavail: u64,
pub f_files: u64,
pub f_ffree: u64,
pub f_fsid: ::fsid_t,
pub f_namelen: ::__fsword_t,
pub f_frsize: ::__fsword_t,
pub f_flags: ::__fsword_t,
pub f_spare: [::__fsword_t; 4],
}
pub struct statvfs {
pub f_bsize: ::c_ulong,
pub f_frsize: ::c_ulong,
pub f_blocks: ::fsblkcnt_t,
pub f_bfree: ::fsblkcnt_t,
pub f_bavail: ::fsblkcnt_t,
pub f_files: ::fsfilcnt_t,
pub f_ffree: ::fsfilcnt_t,
pub f_favail: ::fsfilcnt_t,
pub f_fsid: ::c_ulong,
pub f_flag: ::c_ulong,
pub f_namemax: ::c_ulong,
__f_spare: [::c_int; 6],
}
pub struct statvfs64 {
pub f_bsize: ::c_ulong,
pub f_frsize: ::c_ulong,
pub f_blocks: u64,
pub f_bfree: u64,
pub f_bavail: u64,
pub f_files: u64,
pub f_ffree: u64,
pub f_favail: u64,
pub f_fsid: ::c_ulong,
pub f_flag: ::c_ulong,
pub f_namemax: ::c_ulong,
__f_spare: [::c_int; 6],
}
pub struct pthread_attr_t {
__size: [u64; 7]
}
pub struct ipc_perm {
pub __key: ::key_t,
pub uid: ::uid_t,
pub gid: ::gid_t,
pub cuid: ::uid_t,
pub cgid: ::gid_t,
pub mode: ::mode_t,
__pad0: u16,
pub __seq: ::c_ushort,
__unused1: ::c_ulonglong,
__unused2: ::c_ulonglong,
}
pub struct shmid_ds {
pub shm_perm: ::ipc_perm,
pub shm_atime: ::time_t,
pub shm_dtime: ::time_t,
pub shm_ctime: ::time_t,
pub shm_segsz: ::size_t,
pub shm_cpid: ::pid_t,
pub shm_lpid: ::pid_t,
pub shm_nattch: ::shmatt_t,
__reserved1: ::c_ulong,
__reserved2: ::c_ulong
}
pub struct termios2 {
pub c_iflag: ::tcflag_t,
pub c_oflag: ::tcflag_t,
pub c_cflag: ::tcflag_t,
pub c_lflag: ::tcflag_t,
pub c_line: ::cc_t,
pub c_cc: [::cc_t; 19],
pub c_ispeed: ::speed_t,
pub c_ospeed: ::speed_t,
}
}
pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56;
pub const TIOCGSOFTCAR: ::c_ulong = 0x40047464;
pub const TIOCSSOFTCAR: ::c_ulong = 0x80047465;
pub const RLIMIT_NOFILE: ::c_int = 6;
pub const RLIMIT_NPROC: ::c_int = 7;
pub const O_APPEND: ::c_int = 0x8;
pub const O_CREAT: ::c_int = 0x200;
pub const O_EXCL: ::c_int = 0x800;
pub const O_NOCTTY: ::c_int = 0x8000;
pub const O_NONBLOCK: ::c_int = 0x4000;
pub const O_SYNC: ::c_int = 0x802000;
pub const O_RSYNC: ::c_int = 0x802000;
pub const O_DSYNC: ::c_int = 0x2000;
pub const O_FSYNC: ::c_int = 0x802000;
pub const O_NOATIME: ::c_int = 0x200000;
pub const O_PATH: ::c_int = 0x1000000;
pub const O_TMPFILE: ::c_int = 0x2000000 | O_DIRECTORY;
pub const MAP_GROWSDOWN: ::c_int = 0x0200;
pub const EDEADLK: ::c_int = 78;
pub const ENAMETOOLONG: ::c_int = 63;
pub const ENOLCK: ::c_int = 79;
pub const ENOSYS: ::c_int = 90;
pub const ENOTEMPTY: ::c_int = 66;
pub const ELOOP: ::c_int = 62;
pub const ENOMSG: ::c_int = 75;
pub const EIDRM: ::c_int = 77;
pub const ECHRNG: ::c_int = 94;
pub const EL2NSYNC: ::c_int = 95;
pub const EL3HLT: ::c_int = 96;
pub const EL3RST: ::c_int = 97;
pub const ELNRNG: ::c_int = 98;
pub const EUNATCH: ::c_int = 99;
pub const ENOCSI: ::c_int = 100;
pub const EL2HLT: ::c_int = 101;
pub const EBADE: ::c_int = 102;
pub const EBADR: ::c_int = 103;
pub const EXFULL: ::c_int = 104;
pub const ENOANO: ::c_int = 105;
pub const EBADRQC: ::c_int = 106;
pub const EBADSLT: ::c_int = 107;
pub const EMULTIHOP: ::c_int = 87;
pub const EOVERFLOW: ::c_int = 92;
pub const ENOTUNIQ: ::c_int = 115;
pub const EBADFD: ::c_int = 93;
pub const EBADMSG: ::c_int = 76;
pub const EREMCHG: ::c_int = 89;
pub const ELIBACC: ::c_int = 114;
pub const ELIBBAD: ::c_int = 112;
pub const ELIBSCN: ::c_int = 124;
pub const ELIBMAX: ::c_int = 123;
pub const ELIBEXEC: ::c_int = 110;
pub const EILSEQ: ::c_int = 122;
pub const ERESTART: ::c_int = 116;
pub const ESTRPIPE: ::c_int = 91;
pub const EUSERS: ::c_int = 68;
pub const ENOTSOCK: ::c_int = 38;
pub const EDESTADDRREQ: ::c_int = 39;
pub const EMSGSIZE: ::c_int = 40;
pub const EPROTOTYPE: ::c_int = 41;
pub const ENOPROTOOPT: ::c_int = 42;
pub const EPROTONOSUPPORT: ::c_int = 43;
pub const ESOCKTNOSUPPORT: ::c_int = 44;
pub const EOPNOTSUPP: ::c_int = 45;
pub const EPFNOSUPPORT: ::c_int = 46;
pub const EAFNOSUPPORT: ::c_int = 47;
pub const EADDRINUSE: ::c_int = 48;
pub const EADDRNOTAVAIL: ::c_int = 49;
pub const ENETDOWN: ::c_int = 50;
pub const ENETUNREACH: ::c_int = 51;
pub const ENETRESET: ::c_int = 52;
pub const ECONNABORTED: ::c_int = 53;
pub const ECONNRESET: ::c_int = 54;
pub const ENOBUFS: ::c_int = 55;
pub const EISCONN: ::c_int = 56;
pub const ENOTCONN: ::c_int = 57;
pub const ESHUTDOWN: ::c_int = 58;
pub const ETOOMANYREFS: ::c_int = 59;
pub const ETIMEDOUT: ::c_int = 60;
pub const ECONNREFUSED: ::c_int = 61;
pub const EHOSTDOWN: ::c_int = 64;
pub const EHOSTUNREACH: ::c_int = 65;
pub const EALREADY: ::c_int = 37;
pub const EINPROGRESS: ::c_int = 36;
pub const ESTALE: ::c_int = 70;
pub const EDQUOT: ::c_int = 69;
pub const ENOMEDIUM: ::c_int = 125;
pub const EMEDIUMTYPE: ::c_int = 126;
pub const ECANCELED: ::c_int = 127;
pub const ENOKEY: ::c_int = 128;
pub const EKEYEXPIRED: ::c_int = 129;
pub const EKEYREVOKED: ::c_int = 130;
pub const EKEYREJECTED: ::c_int = 131;
pub const EOWNERDEAD: ::c_int = 132;
pub const ENOTRECOVERABLE: ::c_int = 133;
pub const EHWPOISON: ::c_int = 135;
pub const ERFKILL: ::c_int = 134;
pub const SOL_SOCKET: ::c_int = 0xffff;
pub const SO_PASSCRED: ::c_int = 2;
pub const SO_REUSEADDR: ::c_int = 4;
pub const SO_BINDTODEVICE: ::c_int = 0x000d;
pub const SO_TIMESTAMP: ::c_int = 0x001d;
pub const SO_MARK: ::c_int = 0x0022;
pub const SO_RXQ_OVFL: ::c_int = 0x0024;
pub const SO_PEEK_OFF: ::c_int = 0x0026;
pub const SO_BUSY_POLL: ::c_int = 0x0030;
pub const SO_TYPE: ::c_int = 0x1008;
pub const SO_ERROR: ::c_int = 0x1007;
pub const SO_DONTROUTE: ::c_int = 16;
pub const SO_BROADCAST: ::c_int = 32;
pub const SO_SNDBUF: ::c_int = 0x1001;
pub const SO_RCVBUF: ::c_int = 0x1002;
pub const SO_SNDBUFFORCE: ::c_int = 0x100a;
pub const SO_RCVBUFFORCE: ::c_int = 0x100b;
pub const SO_DOMAIN: ::c_int = 0x1029;
pub const SO_KEEPALIVE: ::c_int = 8;
pub const SO_OOBINLINE: ::c_int = 0x100;
pub const SO_LINGER: ::c_int = 128;
pub const SO_REUSEPORT: ::c_int = 0x200;
pub const SO_ACCEPTCONN: ::c_int = 0x8000;
pub const SA_ONSTACK: ::c_int = 1;
pub const SA_SIGINFO: ::c_int = 0x200;
pub const SA_NOCLDWAIT: ::c_int = 0x100;
pub const SIGCHLD: ::c_int = 20;
pub const SIGBUS: ::c_int = 10;
pub const SIGUSR1: ::c_int = 30;
pub const SIGUSR2: ::c_int = 31;
pub const SIGCONT: ::c_int = 19;
pub const SIGSTOP: ::c_int = 17;
pub const SIGTSTP: ::c_int = 18;
pub const SIGURG: ::c_int = 16;
pub const SIGIO: ::c_int = 23;
pub const SIGSYS: ::c_int = 12;
pub const SIGPOLL: ::c_int = 23;
pub const SIGPWR: ::c_int = 29;
pub const SIG_SETMASK: ::c_int = 4;
pub const SIG_BLOCK: ::c_int = 1;
pub const SIG_UNBLOCK: ::c_int = 2;
pub const POLLWRNORM: ::c_short = 4;
pub const POLLWRBAND: ::c_short = 0x100;
pub const O_ASYNC: ::c_int = 0x40;
pub const O_NDELAY: ::c_int = 0x4004;
pub const PTRACE_DETACH: ::c_uint = 11;
pub const EFD_NONBLOCK: ::c_int = 0x4000;
pub const F_GETLK: ::c_int = 7;
pub const F_GETOWN: ::c_int = 5;
pub const F_SETOWN: ::c_int = 6;
pub const F_SETLK: ::c_int = 8;
pub const F_SETLKW: ::c_int = 9;
pub const F_RDLCK: ::c_int = 1;
pub const F_WRLCK: ::c_int = 2;
pub const F_UNLCK: ::c_int = 3;
pub const SFD_NONBLOCK: ::c_int = 0x4000;
pub const TIOCEXCL: ::c_ulong = 0x2000740d;
pub const TIOCNXCL: ::c_ulong = 0x2000740e;
pub const TIOCSCTTY: ::c_ulong = 0x20007484;
pub const TIOCSTI: ::c_ulong = 0x80017472;
pub const TIOCMGET: ::c_ulong = 0x4004746a;
pub const TIOCMBIS: ::c_ulong = 0x8004746c;
pub const TIOCMBIC: ::c_ulong = 0x8004746b;
pub const TIOCMSET: ::c_ulong = 0x8004746d;
pub const TIOCCONS: ::c_ulong = 0x20007424;
pub const SFD_CLOEXEC: ::c_int = 0x400000;
pub const NCCS: usize = 17;
pub const O_TRUNC: ::c_int = 0x400;
pub const O_CLOEXEC: ::c_int = 0x400000;
pub const EBFONT: ::c_int = 109;
pub const ENOSTR: ::c_int = 72;
pub const ENODATA: ::c_int = 111;
pub const ETIME: ::c_int = 73;
pub const ENOSR: ::c_int = 74;
pub const ENONET: ::c_int = 80;
pub const ENOPKG: ::c_int = 113;
pub const EREMOTE: ::c_int = 71;
pub const ENOLINK: ::c_int = 82;
pub const EADV: ::c_int = 83;
pub const ESRMNT: ::c_int = 84;
pub const ECOMM: ::c_int = 85;
pub const EPROTO: ::c_int = 86;
pub const EDOTDOT: ::c_int = 88;
pub const SA_NODEFER: ::c_int = 0x20;
pub const SA_RESETHAND: ::c_int = 0x4;
pub const SA_RESTART: ::c_int = 0x2;
pub const SA_NOCLDSTOP: ::c_int = 0x00000008;
pub const EPOLL_CLOEXEC: ::c_int = 0x400000;
pub const EFD_CLOEXEC: ::c_int = 0x400000;
pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4;
pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40;
pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4;
align_const! {
pub const PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP: ::pthread_mutex_t =
pthread_mutex_t {
size: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
};
pub const PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP: ::pthread_mutex_t =
pthread_mutex_t {
size: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
};
pub const PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP: ::pthread_mutex_t =
pthread_mutex_t {
size: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
};
}
pub const O_DIRECTORY: ::c_int = 0o200000;
pub const O_NOFOLLOW: ::c_int = 0o400000;
pub const O_DIRECT: ::c_int = 0x100000;
pub const MAP_LOCKED: ::c_int = 0x0100;
pub const MAP_NORESERVE: ::c_int = 0x00040;
pub const EDEADLOCK: ::c_int = 108;
pub const SO_PEERCRED: ::c_int = 0x40;
pub const SO_RCVLOWAT: ::c_int = 0x800;
pub const SO_SNDLOWAT: ::c_int = 0x1000;
pub const SO_RCVTIMEO: ::c_int = 0x2000;
pub const SO_SNDTIMEO: ::c_int = 0x4000;
pub const FIOCLEX: ::c_ulong = 0x20006601;
pub const FIONBIO: ::c_ulong = 0x8004667e;
pub const MCL_CURRENT: ::c_int = 0x2000;
pub const MCL_FUTURE: ::c_int = 0x4000;
pub const SIGSTKSZ: ::size_t = 16384;
pub const MINSIGSTKSZ: ::size_t = 4096;
pub const CBAUD: ::tcflag_t = 0x0000100f;
pub const TAB1: ::c_int = 0x800;
pub const TAB2: ::c_int = 0x1000;
pub const TAB3: ::c_int = 0x1800;
pub const CR1: ::c_int = 0x200;
pub const CR2: ::c_int = 0x400;
pub const CR3: ::c_int = 0x600;
pub const FF1: ::c_int = 0x8000;
pub const BS1: ::c_int = 0x2000;
pub const VT1: ::c_int = 0x4000;
pub const VWERASE: usize = 0xe;
pub const VREPRINT: usize = 0xc;
pub const VSUSP: usize = 0xa;
pub const VSTART: usize = 0x8;
pub const VSTOP: usize = 0x9;
pub const VDISCARD: usize = 0xd;
pub const VTIME: usize = 0x5;
pub const IXON: ::tcflag_t = 0x400;
pub const IXOFF: ::tcflag_t = 0x1000;
pub const ONLCR: ::tcflag_t = 0x4;
pub const CSIZE: ::tcflag_t = 0x30;
pub const CS6: ::tcflag_t = 0x10;
pub const CS7: ::tcflag_t = 0x20;
pub const CS8: ::tcflag_t = 0x30;
pub const CSTOPB: ::tcflag_t = 0x40;
pub const CREAD: ::tcflag_t = 0x80;
pub const PARENB: ::tcflag_t = 0x100;
pub const PARODD: ::tcflag_t = 0x200;
pub const HUPCL: ::tcflag_t = 0x400;
pub const CLOCAL: ::tcflag_t = 0x800;
pub const ECHOKE: ::tcflag_t = 0x800;
pub const ECHOE: ::tcflag_t = 0x10;
pub const ECHOK: ::tcflag_t = 0x20;
pub const ECHONL: ::tcflag_t = 0x40;
pub const ECHOPRT: ::tcflag_t = 0x400;
pub const ECHOCTL: ::tcflag_t = 0x200;
pub const ISIG: ::tcflag_t = 0x1;
pub const ICANON: ::tcflag_t = 0x2;
pub const PENDIN: ::tcflag_t = 0x4000;
pub const NOFLSH: ::tcflag_t = 0x80;
pub const CIBAUD: ::tcflag_t = 0o02003600000;
pub const CBAUDEX: ::tcflag_t = 0x00001000;
pub const VSWTC: usize = 7;
pub const OLCUC: ::tcflag_t = 0o000002;
pub const NLDLY: ::tcflag_t = 0o000400;
pub const CRDLY: ::tcflag_t = 0o003000;
pub const TABDLY: ::tcflag_t = 0o014000;
pub const BSDLY: ::tcflag_t = 0o020000;
pub const FFDLY: ::tcflag_t = 0o100000;
pub const VTDLY: ::tcflag_t = 0o040000;
pub const XTABS: ::tcflag_t = 0o014000;
pub const B0: ::speed_t = 0o000000;
pub const B50: ::speed_t = 0o000001;
pub const B75: ::speed_t = 0o000002;
pub const B110: ::speed_t = 0o000003;
pub const B134: ::speed_t = 0o000004;
pub const B150: ::speed_t = 0o000005;
pub const B200: ::speed_t = 0o000006;
pub const B300: ::speed_t = 0o000007;
pub const B600: ::speed_t = 0o000010;
pub const B1200: ::speed_t = 0o000011;
pub const B1800: ::speed_t = 0o000012;
pub const B2400: ::speed_t = 0o000013;
pub const B4800: ::speed_t = 0o000014;
pub const B9600: ::speed_t = 0o000015;
pub const B19200: ::speed_t = 0o000016;
pub const B38400: ::speed_t = 0o000017;
pub const EXTA: ::speed_t = B19200;
pub const EXTB: ::speed_t = B38400;
pub const BOTHER: ::speed_t = 0x1000;
pub const B57600: ::speed_t = 0x1001;
pub const B115200: ::speed_t = 0x1002;
pub const B230400: ::speed_t = 0x1003;
pub const B460800: ::speed_t = 0x1004;
pub const B76800: ::speed_t = 0x1005;
pub const B153600: ::speed_t = 0x1006;
pub const B307200: ::speed_t = 0x1007;
pub const B614400: ::speed_t = 0x1008;
pub const B921600: ::speed_t = 0x1009;
pub const B500000: ::speed_t = 0x100a;
pub const B576000: ::speed_t = 0x100b;
pub const B1000000: ::speed_t = 0x100c;
pub const B1152000: ::speed_t = 0x100d;
pub const B1500000: ::speed_t = 0x100e;
pub const B2000000: ::speed_t = 0x100f;
pub const VEOL: usize = 5;
pub const VEOL2: usize = 6;
pub const VMIN: usize = 4;
pub const IEXTEN: ::tcflag_t = 0x8000;
pub const TOSTOP: ::tcflag_t = 0x100;
pub const FLUSHO: ::tcflag_t = 0x1000;
pub const EXTPROC: ::tcflag_t = 0x10000;
pub const TCGETS: ::c_ulong = 0x40245408;
pub const TCSETS: ::c_ulong = 0x80245409;
pub const TCSETSW: ::c_ulong = 0x8024540a;
pub const TCSETSF: ::c_ulong = 0x8024540b;
pub const TCGETA: ::c_ulong = 0x40125401;
pub const TCSETA: ::c_ulong = 0x80125402;
pub const TCSETAW: ::c_ulong = 0x80125403;
pub const TCSETAF: ::c_ulong = 0x80125404;
pub const TCSBRK: ::c_ulong = 0x20005405;
pub const TCXONC: ::c_ulong = 0x20005406;
pub const TCFLSH: ::c_ulong = 0x20005407;
pub const TIOCINQ: ::c_ulong = 0x4004667f;
pub const TIOCGPGRP: ::c_ulong = 0x40047483;
pub const TIOCSPGRP: ::c_ulong = 0x80047482;
pub const TIOCOUTQ: ::c_ulong = 0x40047473;
pub const TIOCGWINSZ: ::c_ulong = 0x40087468;
pub const TIOCSWINSZ: ::c_ulong = 0x80087467;
pub const FIONREAD: ::c_ulong = 0x4004667f;
pub const SYS_restart_syscall: ::c_long = 0;
pub const SYS_exit: ::c_long = 1;
pub const SYS_fork: ::c_long = 2;
pub const SYS_read: ::c_long = 3;
pub const SYS_write: ::c_long = 4;
pub const SYS_open: ::c_long = 5;
pub const SYS_close: ::c_long = 6;
pub const SYS_wait4: ::c_long = 7;
pub const SYS_creat: ::c_long = 8;
pub const SYS_link: ::c_long = 9;
pub const SYS_unlink: ::c_long = 10;
pub const SYS_execv: ::c_long = 11;
pub const SYS_chdir: ::c_long = 12;
pub const SYS_chown: ::c_long = 13;
pub const SYS_mknod: ::c_long = 14;
pub const SYS_chmod: ::c_long = 15;
pub const SYS_lchown: ::c_long = 16;
pub const SYS_brk: ::c_long = 17;
pub const SYS_perfctr: ::c_long = 18;
pub const SYS_lseek: ::c_long = 19;
pub const SYS_getpid: ::c_long = 20;
pub const SYS_capget: ::c_long = 21;
pub const SYS_capset: ::c_long = 22;
pub const SYS_setuid: ::c_long = 23;
pub const SYS_getuid: ::c_long = 24;
pub const SYS_vmsplice: ::c_long = 25;
pub const SYS_ptrace: ::c_long = 26;
pub const SYS_alarm: ::c_long = 27;
pub const SYS_sigaltstack: ::c_long = 28;
pub const SYS_pause: ::c_long = 29;
pub const SYS_utime: ::c_long = 30;
pub const SYS_access: ::c_long = 33;
pub const SYS_nice: ::c_long = 34;
pub const SYS_sync: ::c_long = 36;
pub const SYS_kill: ::c_long = 37;
pub const SYS_stat: ::c_long = 38;
pub const SYS_sendfile: ::c_long = 39;
pub const SYS_lstat: ::c_long = 40;
pub const SYS_dup: ::c_long = 41;
pub const SYS_pipe: ::c_long = 42;
pub const SYS_times: ::c_long = 43;
pub const SYS_umount2: ::c_long = 45;
pub const SYS_setgid: ::c_long = 46;
pub const SYS_getgid: ::c_long = 47;
pub const SYS_signal: ::c_long = 48;
pub const SYS_geteuid: ::c_long = 49;
pub const SYS_getegid: ::c_long = 50;
pub const SYS_acct: ::c_long = 51;
pub const SYS_memory_ordering: ::c_long = 52;
pub const SYS_ioctl: ::c_long = 54;
pub const SYS_reboot: ::c_long = 55;
pub const SYS_symlink: ::c_long = 57;
pub const SYS_readlink: ::c_long = 58;
pub const SYS_execve: ::c_long = 59;
pub const SYS_umask: ::c_long = 60;
pub const SYS_chroot: ::c_long = 61;
pub const SYS_fstat: ::c_long = 62;
pub const SYS_fstat64: ::c_long = 63;
pub const SYS_getpagesize: ::c_long = 64;
pub const SYS_msync: ::c_long = 65;
pub const SYS_vfork: ::c_long = 66;
pub const SYS_pread64: ::c_long = 67;
pub const SYS_pwrite64: ::c_long = 68;
pub const SYS_mmap: ::c_long = 71;
pub const SYS_munmap: ::c_long = 73;
pub const SYS_mprotect: ::c_long = 74;
pub const SYS_madvise: ::c_long = 75;
pub const SYS_vhangup: ::c_long = 76;
pub const SYS_mincore: ::c_long = 78;
pub const SYS_getgroups: ::c_long = 79;
pub const SYS_setgroups: ::c_long = 80;
pub const SYS_getpgrp: ::c_long = 81;
pub const SYS_setitimer: ::c_long = 83;
pub const SYS_swapon: ::c_long = 85;
pub const SYS_getitimer: ::c_long = 86;
pub const SYS_sethostname: ::c_long = 88;
pub const SYS_dup2: ::c_long = 90;
pub const SYS_fcntl: ::c_long = 92;
pub const SYS_select: ::c_long = 93;
pub const SYS_fsync: ::c_long = 95;
pub const SYS_setpriority: ::c_long = 96;
pub const SYS_socket: ::c_long = 97;
pub const SYS_connect: ::c_long = 98;
pub const SYS_accept: ::c_long = 99;
pub const SYS_getpriority: ::c_long = 100;
pub const SYS_rt_sigreturn: ::c_long = 101;
pub const SYS_rt_sigaction: ::c_long = 102;
pub const SYS_rt_sigprocmask: ::c_long = 103;
pub const SYS_rt_sigpending: ::c_long = 104;
pub const SYS_rt_sigtimedwait: ::c_long = 105;
pub const SYS_rt_sigqueueinfo: ::c_long = 106;
pub const SYS_rt_sigsuspend: ::c_long = 107;
pub const SYS_setresuid: ::c_long = 108;
pub const SYS_getresuid: ::c_long = 109;
pub const SYS_setresgid: ::c_long = 110;
pub const SYS_getresgid: ::c_long = 111;
pub const SYS_recvmsg: ::c_long = 113;
pub const SYS_sendmsg: ::c_long = 114;
pub const SYS_gettimeofday: ::c_long = 116;
pub const SYS_getrusage: ::c_long = 117;
pub const SYS_getsockopt: ::c_long = 118;
pub const SYS_getcwd: ::c_long = 119;
pub const SYS_readv: ::c_long = 120;
pub const SYS_writev: ::c_long = 121;
pub const SYS_settimeofday: ::c_long = 122;
pub const SYS_fchown: ::c_long = 123;
pub const SYS_fchmod: ::c_long = 124;
pub const SYS_recvfrom: ::c_long = 125;
pub const SYS_setreuid: ::c_long = 126;
pub const SYS_setregid: ::c_long = 127;
pub const SYS_rename: ::c_long = 128;
pub const SYS_truncate: ::c_long = 129;
pub const SYS_ftruncate: ::c_long = 130;
pub const SYS_flock: ::c_long = 131;
pub const SYS_lstat64: ::c_long = 132;
pub const SYS_sendto: ::c_long = 133;
pub const SYS_shutdown: ::c_long = 134;
pub const SYS_socketpair: ::c_long = 135;
pub const SYS_mkdir: ::c_long = 136;
pub const SYS_rmdir: ::c_long = 137;
pub const SYS_utimes: ::c_long = 138;
pub const SYS_stat64: ::c_long = 139;
pub const SYS_sendfile64: ::c_long = 140;
pub const SYS_getpeername: ::c_long = 141;
pub const SYS_futex: ::c_long = 142;
pub const SYS_gettid: ::c_long = 143;
pub const SYS_getrlimit: ::c_long = 144;
pub const SYS_setrlimit: ::c_long = 145;
pub const SYS_pivot_root: ::c_long = 146;
pub const SYS_prctl: ::c_long = 147;
pub const SYS_pciconfig_read: ::c_long = 148;
pub const SYS_pciconfig_write: ::c_long = 149;
pub const SYS_getsockname: ::c_long = 150;
pub const SYS_inotify_init: ::c_long = 151;
pub const SYS_inotify_add_watch: ::c_long = 152;
pub const SYS_poll: ::c_long = 153;
pub const SYS_getdents64: ::c_long = 154;
pub const SYS_inotify_rm_watch: ::c_long = 156;
pub const SYS_statfs: ::c_long = 157;
pub const SYS_fstatfs: ::c_long = 158;
pub const SYS_umount: ::c_long = 159;
pub const SYS_sched_set_affinity: ::c_long = 160;
pub const SYS_sched_get_affinity: ::c_long = 161;
pub const SYS_getdomainname: ::c_long = 162;
pub const SYS_setdomainname: ::c_long = 163;
pub const SYS_utrap_install: ::c_long = 164;
pub const SYS_quotactl: ::c_long = 165;
pub const SYS_set_tid_address: ::c_long = 166;
pub const SYS_mount: ::c_long = 167;
pub const SYS_ustat: ::c_long = 168;
pub const SYS_setxattr: ::c_long = 169;
pub const SYS_lsetxattr: ::c_long = 170;
pub const SYS_fsetxattr: ::c_long = 171;
pub const SYS_getxattr: ::c_long = 172;
pub const SYS_lgetxattr: ::c_long = 173;
pub const SYS_getdents: ::c_long = 174;
pub const SYS_setsid: ::c_long = 175;
pub const SYS_fchdir: ::c_long = 176;
pub const SYS_fgetxattr: ::c_long = 177;
pub const SYS_listxattr: ::c_long = 178;
pub const SYS_llistxattr: ::c_long = 179;
pub const SYS_flistxattr: ::c_long = 180;
pub const SYS_removexattr: ::c_long = 181;
pub const SYS_lremovexattr: ::c_long = 182;
pub const SYS_sigpending: ::c_long = 183;
pub const SYS_query_module: ::c_long = 184;
pub const SYS_setpgid: ::c_long = 185;
pub const SYS_fremovexattr: ::c_long = 186;
pub const SYS_tkill: ::c_long = 187;
pub const SYS_exit_group: ::c_long = 188;
pub const SYS_uname: ::c_long = 189;
pub const SYS_init_module: ::c_long = 190;
pub const SYS_personality: ::c_long = 191;
pub const SYS_remap_file_pages: ::c_long = 192;
pub const SYS_epoll_create: ::c_long = 193;
pub const SYS_epoll_ctl: ::c_long = 194;
pub const SYS_epoll_wait: ::c_long = 195;
pub const SYS_ioprio_set: ::c_long = 196;
pub const SYS_getppid: ::c_long = 197;
pub const SYS_sigaction: ::c_long = 198;
pub const SYS_sgetmask: ::c_long = 199;
pub const SYS_ssetmask: ::c_long = 200;
pub const SYS_sigsuspend: ::c_long = 201;
pub const SYS_oldlstat: ::c_long = 202;
pub const SYS_uselib: ::c_long = 203;
pub const SYS_readdir: ::c_long = 204;
pub const SYS_readahead: ::c_long = 205;
pub const SYS_socketcall: ::c_long = 206;
pub const SYS_syslog: ::c_long = 207;
pub const SYS_lookup_dcookie: ::c_long = 208;
pub const SYS_fadvise64: ::c_long = 209;
pub const SYS_fadvise64_64: ::c_long = 210;
pub const SYS_tgkill: ::c_long = 211;
pub const SYS_waitpid: ::c_long = 212;
pub const SYS_swapoff: ::c_long = 213;
pub const SYS_sysinfo: ::c_long = 214;
pub const SYS_ipc: ::c_long = 215;
pub const SYS_sigreturn: ::c_long = 216;
pub const SYS_clone: ::c_long = 217;
pub const SYS_ioprio_get: ::c_long = 218;
pub const SYS_adjtimex: ::c_long = 219;
pub const SYS_sigprocmask: ::c_long = 220;
pub const SYS_create_module: ::c_long = 221;
pub const SYS_delete_module: ::c_long = 222;
pub const SYS_get_kernel_syms: ::c_long = 223;
pub const SYS_getpgid: ::c_long = 224;
pub const SYS_bdflush: ::c_long = 225;
pub const SYS_sysfs: ::c_long = 226;
pub const SYS_afs_syscall: ::c_long = 227;
pub const SYS_setfsuid: ::c_long = 228;
pub const SYS_setfsgid: ::c_long = 229;
pub const SYS__newselect: ::c_long = 230;
pub const SYS_splice: ::c_long = 232;
pub const SYS_stime: ::c_long = 233;
pub const SYS_statfs64: ::c_long = 234;
pub const SYS_fstatfs64: ::c_long = 235;
pub const SYS__llseek: ::c_long = 236;
pub const SYS_mlock: ::c_long = 237;
pub const SYS_munlock: ::c_long = 238;
pub const SYS_mlockall: ::c_long = 239;
pub const SYS_munlockall: ::c_long = 240;
pub const SYS_sched_setparam: ::c_long = 241;
pub const SYS_sched_getparam: ::c_long = 242;
pub const SYS_sched_setscheduler: ::c_long =243;
pub const SYS_sched_getscheduler: ::c_long =244;
pub const SYS_sched_yield: ::c_long = 245;
pub const SYS_sched_get_priority_max: ::c_long =246;
pub const SYS_sched_get_priority_min: ::c_long =247;
pub const SYS_sched_rr_get_interval: ::c_long = 248;
pub const SYS_nanosleep: ::c_long = 249;
pub const SYS_mremap: ::c_long = 250;
pub const SYS__sysctl: ::c_long = 251;
pub const SYS_getsid: ::c_long = 252;
pub const SYS_fdatasync: ::c_long = 253;
pub const SYS_nfsservctl: ::c_long = 254;
pub const SYS_sync_file_range: ::c_long = 255;
pub const SYS_clock_settime: ::c_long = 256;
pub const SYS_clock_gettime: ::c_long = 257;
pub const SYS_clock_getres: ::c_long = 258;
pub const SYS_clock_nanosleep: ::c_long = 259;
pub const SYS_sched_getaffinity: ::c_long = 260;
pub const SYS_sched_setaffinity: ::c_long = 261;
pub const SYS_timer_settime: ::c_long = 262;
pub const SYS_timer_gettime: ::c_long = 263;
pub const SYS_timer_getoverrun: ::c_long = 264;
pub const SYS_timer_delete: ::c_long = 265;
pub const SYS_timer_create: ::c_long = 266;
pub const SYS_io_setup: ::c_long = 268;
pub const SYS_io_destroy: ::c_long = 269;
pub const SYS_io_submit: ::c_long = 270;
pub const SYS_io_cancel: ::c_long = 271;
pub const SYS_io_getevents: ::c_long = 272;
pub const SYS_mq_open: ::c_long = 273;
pub const SYS_mq_unlink: ::c_long = 274;
pub const SYS_mq_timedsend: ::c_long = 275;
pub const SYS_mq_timedreceive: ::c_long = 276;
pub const SYS_mq_notify: ::c_long = 277;
pub const SYS_mq_getsetattr: ::c_long = 278;
pub const SYS_waitid: ::c_long = 279;
pub const SYS_tee: ::c_long = 280;
pub const SYS_add_key: ::c_long = 281;
pub const SYS_request_key: ::c_long = 282;
pub const SYS_keyctl: ::c_long = 283;
pub const SYS_openat: ::c_long = 284;
pub const SYS_mkdirat: ::c_long = 285;
pub const SYS_mknodat: ::c_long = 286;
pub const SYS_fchownat: ::c_long = 287;
pub const SYS_futimesat: ::c_long = 288;
pub const SYS_fstatat64: ::c_long = 289;
pub const SYS_unlinkat: ::c_long = 290;
pub const SYS_renameat: ::c_long = 291;
pub const SYS_linkat: ::c_long = 292;
pub const SYS_symlinkat: ::c_long = 293;
pub const SYS_readlinkat: ::c_long = 294;
pub const SYS_fchmodat: ::c_long = 295;
pub const SYS_faccessat: ::c_long = 296;
pub const SYS_pselect6: ::c_long = 297;
pub const SYS_ppoll: ::c_long = 298;
pub const SYS_unshare: ::c_long = 299;
pub const SYS_set_robust_list: ::c_long = 300;
pub const SYS_get_robust_list: ::c_long = 301;
pub const SYS_migrate_pages: ::c_long =302;
pub const SYS_mbind: ::c_long = 303;
pub const SYS_get_mempolicy: ::c_long = 304;
pub const SYS_set_mempolicy: ::c_long = 305;
pub const SYS_kexec_load: ::c_long = 306;
pub const SYS_move_pages: ::c_long = 307;
pub const SYS_getcpu: ::c_long = 308;
pub const SYS_epoll_pwait: ::c_long = 309;
pub const SYS_utimensat: ::c_long = 310;
pub const SYS_signalfd: ::c_long = 311;
pub const SYS_timerfd_create: ::c_long = 312;
pub const SYS_eventfd: ::c_long = 313;
pub const SYS_fallocate: ::c_long = 314;
pub const SYS_timerfd_settime: ::c_long = 315;
pub const SYS_timerfd_gettime: ::c_long = 316;
pub const SYS_signalfd4: ::c_long = 317;
pub const SYS_eventfd2: ::c_long = 318;
pub const SYS_epoll_create1: ::c_long = 319;
pub const SYS_dup3: ::c_long = 320;
pub const SYS_pipe2: ::c_long = 321;
pub const SYS_inotify_init1: ::c_long = 322;
pub const SYS_accept4: ::c_long = 323;
pub const SYS_preadv: ::c_long = 324;
pub const SYS_pwritev: ::c_long = 325;
pub const SYS_rt_tgsigqueueinfo: ::c_long = 326;
pub const SYS_perf_event_open: ::c_long = 327;
pub const SYS_recvmmsg: ::c_long = 328;
pub const SYS_fanotify_init: ::c_long = 329;
pub const SYS_fanotify_mark: ::c_long = 330;
pub const SYS_prlimit64: ::c_long = 331;
pub const SYS_name_to_handle_at: ::c_long = 332;
pub const SYS_open_by_handle_at: ::c_long = 333;
pub const SYS_clock_adjtime: ::c_long = 334;
pub const SYS_syncfs: ::c_long = 335;
pub const SYS_sendmmsg: ::c_long = 336;
pub const SYS_setns: ::c_long = 337;
pub const SYS_process_vm_readv: ::c_long = 338;
pub const SYS_process_vm_writev: ::c_long = 339;
pub const SYS_kern_features: ::c_long = 340;
pub const SYS_kcmp: ::c_long = 341;
pub const SYS_finit_module: ::c_long = 342;
pub const SYS_sched_setattr: ::c_long = 343;
pub const SYS_sched_getattr: ::c_long = 344;
pub const SYS_renameat2: ::c_long = 345;
pub const SYS_seccomp: ::c_long = 346;
pub const SYS_getrandom: ::c_long = 347;
pub const SYS_memfd_create: ::c_long = 348;
pub const SYS_bpf: ::c_long = 349;
pub const SYS_execveat: ::c_long = 350;
pub const SYS_membarrier: ::c_long = 351;
pub const SYS_userfaultfd: ::c_long = 352;
pub const SYS_bind: ::c_long = 353;
pub const SYS_listen: ::c_long = 354;
pub const SYS_setsockopt: ::c_long = 355;
pub const SYS_mlock2: ::c_long = 356;
pub const SYS_copy_file_range: ::c_long = 357;
pub const SYS_preadv2: ::c_long = 358;
pub const SYS_pwritev2: ::c_long = 359;
#[link(name = "util")]
extern {
pub fn sysctl(name: *mut ::c_int,
namelen: ::c_int,
oldp: *mut ::c_void,
oldlenp: *mut ::size_t,
newp: *mut ::c_void,
newlen: ::size_t)
-> ::c_int;
}
| 35.210587 | 78 | 0.683541 |
ccc120c5421f536a1a85e5af638d7119ed08a7c8
| 382 |
// Regression test of #85581.
// Checks not to suggest to add `;` when the second mutable borrow
// is in the first's scope.
use std::collections::BinaryHeap;
fn foo(heap: &mut BinaryHeap<i32>) {
match heap.peek_mut() {
Some(_) => { heap.pop(); },
//~^ ERROR: cannot borrow `*heap` as mutable more than once at a time
None => (),
}
}
fn main() {}
| 23.875 | 77 | 0.596859 |
4ab8b076cd76f655b2912fab1c0c054fa8a79e7b
| 1,924 |
#[doc = "Register `LCDM7` reader"]
pub struct R(crate::R<LCDM7_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<LCDM7_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::convert::From<crate::R<LCDM7_SPEC>> for R {
fn from(reader: crate::R<LCDM7_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `LCDM7` writer"]
pub struct W(crate::W<LCDM7_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<LCDM7_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl core::convert::From<crate::W<LCDM7_SPEC>> for W {
fn from(writer: crate::W<LCDM7_SPEC>) -> Self {
W(writer)
}
}
impl W {
#[doc = "Writes raw bits to the register."]
pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "LCD Memory 7\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lcdm7](index.html) module"]
pub struct LCDM7_SPEC;
impl crate::RegisterSpec for LCDM7_SPEC {
type Ux = u8;
}
#[doc = "`read()` method returns [lcdm7::R](R) reader structure"]
impl crate::Readable for LCDM7_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [lcdm7::W](W) writer structure"]
impl crate::Writable for LCDM7_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets LCDM7 to value 0"]
impl crate::Resettable for LCDM7_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 31.032258 | 398 | 0.614345 |
e9ef3f5f8e5c2ba25f81c48dec83137ff60c1fdd
| 179 |
mod fetch;
mod model;
mod print;
pub use fetch::{fetch_yum_repository_path, fetch_yum_updates};
pub use model::{RepositoryMetadata, YumUpdate};
pub use print::print_yum_updates;
| 22.375 | 62 | 0.798883 |
674e7a1fecb8823ef8c39a99a3b1628f8235d0f2
| 2,346 |
#[cfg(test)]
mod test;
use super::Operation;
use crate::{
bson::Document,
client::SESSIONS_UNSUPPORTED_COMMANDS,
cmap::{Command, CommandResponse, StreamDescription},
error::{ErrorKind, Result},
options::WriteConcern,
selection_criteria::SelectionCriteria,
};
#[derive(Debug)]
pub(crate) struct RunCommand {
db: String,
command: Document,
selection_criteria: Option<SelectionCriteria>,
write_concern: Option<WriteConcern>,
}
impl RunCommand {
pub(crate) fn new(
db: String,
command: Document,
selection_criteria: Option<SelectionCriteria>,
) -> Result<Self> {
let write_concern = command
.get("writeConcern")
.map(|doc| bson::from_bson::<WriteConcern>(doc.clone()))
.transpose()?;
Ok(Self {
db,
command,
selection_criteria,
write_concern,
})
}
fn command_name(&self) -> Option<&str> {
self.command.keys().next().map(String::as_str)
}
}
impl Operation for RunCommand {
type O = Document;
// Since we can't actually specify a string statically here, we just put a descriptive string
// that should fail loudly if accidentally passed to the server.
const NAME: &'static str = "$genericRunCommand";
fn build(&self, description: &StreamDescription) -> Result<Command> {
let command_name = self
.command_name()
.ok_or_else(|| ErrorKind::ArgumentError {
message: "an empty document cannot be passed to a run_command operation".into(),
})?;
Ok(Command::new(
command_name.to_string(),
self.db.clone(),
self.command.clone(),
))
}
fn handle_response(&self, response: CommandResponse) -> Result<Self::O> {
Ok(response.raw_response)
}
fn selection_criteria(&self) -> Option<&SelectionCriteria> {
self.selection_criteria.as_ref()
}
fn write_concern(&self) -> Option<&WriteConcern> {
self.write_concern.as_ref()
}
fn supports_sessions(&self) -> bool {
self.command_name()
.map(|command_name| {
!SESSIONS_UNSUPPORTED_COMMANDS.contains(command_name.to_lowercase().as_str())
})
.unwrap_or(false)
}
}
| 26.965517 | 97 | 0.603154 |
d6c431ac5d49786329ec7be23e8a79bd7a72387d
| 6,122 |
use probe_rs::{
config::{CoreType, MemoryRegion},
Core, CoreRegisterAddress,
};
/// Extension trait for probe_rs::Core, which adds some GDB -> probe-rs internal translation functions.
///
/// Translates some GDB architecture dependant stuff
/// to probe-rs internals.
pub(crate) trait GdbArchitectureExt {
/// Translates a GDB register number to an internal register address.
fn translate_gdb_register_number(
&self,
gdb_reg_number: u32,
) -> Option<(CoreRegisterAddress, u32)>;
/// Returns the number of general registers.
fn num_general_registers(&self) -> usize;
}
impl<'probe> GdbArchitectureExt for Core<'probe> {
fn translate_gdb_register_number(
&self,
gdb_reg_number: u32,
) -> Option<(CoreRegisterAddress, u32)> {
let (probe_rs_number, bytesize): (u16, _) = match self.architecture() {
probe_rs::Architecture::Arm => {
match gdb_reg_number {
// Default ARM register (arm-m-profile.xml)
// Register 0 to 15
x @ 0..=15 => (x as u16, 4),
// CPSR register has number 16 in probe-rs
// See REGSEL bits, DCRSR register, ARM Reference Manual
25 => (16, 4),
// Floating Point registers (arm-m-profile-with-fpa.xml)
// f0 -f7 start at offset 0x40
// See REGSEL bits, DCRSR register, ARM Reference Manual
reg @ 16..=23 => ((reg as u16 - 16 + 0x40), 12),
// FPSCR has number 0x21 in probe-rs
// See REGSEL bits, DCRSR register, ARM Reference Manual
24 => (0x21, 4),
// Other registers are currently not supported,
// they are not listed in the xml files in GDB
other => {
log::warn!("Request for unsupported register with number {}", other);
return None;
}
}
}
probe_rs::Architecture::Riscv => match gdb_reg_number {
// general purpose registers 0 to 31
x @ 0..=31 => {
let addr: CoreRegisterAddress = self
.registers()
.get_platform_register(x as usize)
.expect("riscv register must exist")
.into();
(addr.0, 8)
}
// Program counter
32 => {
let addr: CoreRegisterAddress = self.registers().program_counter().into();
(addr.0, 8)
}
other => {
log::warn!("Request for unsupported register with number {}", other);
return None;
}
},
};
Some((CoreRegisterAddress(probe_rs_number as u16), bytesize))
}
fn num_general_registers(&self) -> usize {
match self.architecture() {
probe_rs::Architecture::Arm => 24,
probe_rs::Architecture::Riscv => 33,
}
}
}
/// Extension trait for probe_rs::Target, to get XML-based target description and
/// memory map.
pub trait GdbTargetExt {
/// Memory map in GDB XML format.
///
/// See https://sourceware.org/gdb/onlinedocs/gdb/Memory-Map-Format.html#Memory-Map-Format
fn gdb_memory_map(&self) -> String;
/// Target description in GDB XML Format.
///
/// See https://sourceware.org/gdb/onlinedocs/gdb/Target-Descriptions.html#Target-Descriptions
fn target_description(&self) -> String;
}
impl GdbTargetExt for probe_rs::Target {
fn gdb_memory_map(&self) -> String {
let mut xml_map = r#"<?xml version="1.0"?>
<!DOCTYPE memory-map PUBLIC "+//IDN gnu.org//DTD GDB Memory Map V1.0//EN" "http://sourceware.org/gdb/gdb-memory-map.dtd">
<memory-map>
"#.to_owned();
for region in &self.memory_map {
let region_entry = match region {
MemoryRegion::Ram(ram) => format!(
r#"<memory type="ram" start="{:#x}" length="{:#x}"/>\n"#,
ram.range.start,
ram.range.end - ram.range.start
),
MemoryRegion::Generic(region) => format!(
r#"<memory type="rom" start="{:#x}" length="{:#x}"/>\n"#,
region.range.start,
region.range.end - region.range.start
),
MemoryRegion::Nvm(region) => {
// TODO: Use flash with block size
format!(
r#"<memory type="rom" start="{:#x}" length="{:#x}"/>\n"#,
region.range.start,
region.range.end - region.range.start
)
}
};
xml_map.push_str(®ion_entry);
}
xml_map.push_str(r#"</memory-map>"#);
xml_map
}
fn target_description(&self) -> String {
// GDB-architectures
//
// - armv6-m -> Core-M0
// - armv7-m -> Core-M3
// - armv7e-m -> Core-M4, Core-M7
// - armv8-m.base -> Core-M23
// - armv8-m.main -> Core-M33
// - riscv:rv32 -> RISCV
let architecture = match self.core_type {
CoreType::M0 => "armv6-m",
CoreType::M3 => "armv7-m",
CoreType::M4 | CoreType::M7 => "armv7e-m",
CoreType::M33 => "armv8-m.main",
//CoreType::M23 => "armv8-m.base",
CoreType::Riscv => "riscv:rv32",
};
// Only target.xml is supported
let mut target_description = r#"<?xml version="1.0"?>
<!DOCTYPE target SYSTEM "gdb-target.dtd">
<target version="1.0">
"#
.to_owned();
target_description.push_str(&format!("<architecture>{}</architecture>", architecture));
target_description.push_str("</target>");
target_description
}
}
| 36.658683 | 121 | 0.507677 |
1a966b826bb48af8c8355260a39f1f754b72bfd9
| 1,536 |
// https://leetcode-cn.com/problems/reconstruct-itinerary/
// Runtime: 4 ms
// Memory Usage: 2.1 MB
use std::{
cmp::Reverse,
collections::{BinaryHeap, HashMap},
};
pub fn find_itinerary(tickets: Vec<Vec<String>>) -> Vec<String> {
let mut res = Vec::new();
let mut g: HashMap<String, BinaryHeap<Reverse<String>>> = HashMap::new();
for ticket in tickets {
g.entry(ticket[0].clone())
.or_default()
.push(Reverse(ticket[1].clone()));
}
let mut stack = vec!["JFK".to_string()];
while !stack.is_empty() {
while g.contains_key(stack.last().unwrap())
&& !g.get(stack.last().unwrap()).unwrap().is_empty()
{
let airports = g.get_mut(stack.last().unwrap()).unwrap();
let airport = airports.pop().unwrap().0;
stack.push(airport);
}
res.insert(0, stack.pop().unwrap());
}
res
}
// graph depth_first_search
#[test]
fn test1_332() {
use leetcode_prelude::{vec2_string, vec_string};
assert_eq!(
find_itinerary(vec2_string![
["MUC", "LHR"],
["JFK", "MUC"],
["SFO", "SJC"],
["LHR", "SFO"]
]),
vec_string!["JFK", "MUC", "LHR", "SFO", "SJC"]
);
assert_eq!(
find_itinerary(vec2_string![
["JFK", "SFO"],
["JFK", "ATL"],
["SFO", "ATL"],
["ATL", "JFK"],
["ATL", "SFO"]
]),
vec_string!["JFK", "ATL", "JFK", "SFO", "ATL", "SFO"]
);
}
| 28.981132 | 77 | 0.503255 |
1c9d8e1b67400abbcdab0777e0937200b679c2d0
| 15,657 |
use wide::*;
use bytemuck::*;
#[test]
fn size_align() {
assert_eq!(core::mem::size_of::<f64x4>(), 32);
assert_eq!(core::mem::align_of::<f64x4>(), 32);
}
#[test]
fn impl_debug_for_f64x4() {
let expected = "(1.0, 2.0, 3.0, 4.0)";
let actual = format!("{:?}", f64x4::from([1.0, 2.0, 3.0, 4.0]));
assert_eq!(expected, actual);
let expected = "(1.000, 2.000, 3.000, 4.000)";
let actual = format!("{:.3?}", f64x4::from([1.0, 2.0, 3.0, 4.0]));
assert_eq!(expected, actual);
}
#[test]
fn impl_add_for_f64x4() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([5.0, 6.0, 7.0, 8.0]);
let expected = f64x4::from([6.0, 8.0, 10.0, 12.0]);
let actual = a + b;
assert_eq!(expected, actual);
}
#[test]
fn impl_sub_for_f64x4() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([5.0, 7.0, 17.0, 1.0]);
let expected = f64x4::from([-4.0, -5.0, -14.0, 3.0]);
let actual = a - b;
assert_eq!(expected, actual);
}
#[test]
fn impl_mul_for_f64x4() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([5.0, 7.0, 17.0, 1.0]);
let expected = f64x4::from([5.0, 14.0, 51.0, 4.0]);
let actual = a * b;
assert_eq!(expected, actual);
}
#[test]
fn impl_div_for_f64x4() {
let a = f64x4::from([4.0, 9.0, 10.0, 12.0]);
let b = f64x4::from([2.0, 2.0, 5.0, -3.0]);
let expected = f64x4::from([2.0, 4.5, 2.0, -4.0]);
let actual = a / b;
assert_eq!(expected, actual);
}
#[test]
fn impl_bitand_for_f64x4() {
let a = f64x4::from([0.0, 0.0, 1.0, 1.0]);
let b = f64x4::from([0.0, 1.0, 0.0, 1.0]);
let expected = f64x4::from([0.0, 0.0, 0.0, 1.0]);
let actual = a & b;
assert_eq!(expected, actual);
}
#[test]
fn impl_bitor_for_f64x4() {
let a = f64x4::from([0.0, 0.0, 1.0, 1.0]);
let b = f64x4::from([0.0, 1.0, 0.0, 1.0]);
let expected = f64x4::from([0.0, 1.0, 1.0, 1.0]);
let actual = a | b;
assert_eq!(expected, actual);
}
#[test]
fn impl_bitxor_for_f64x4() {
let a = f64x4::from([0.0, 0.0, 1.0, 1.0]);
let b = f64x4::from([0.0, 1.0, 0.0, 1.0]);
let expected = f64x4::from([0.0, 1.0, 1.0, 0.0]);
let actual = a ^ b;
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_cmp_eq() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([2.0, 2.0, 2.0, 2.0]);
let expected: [i64; 4] = [0, -1, 0, 0];
let actual: [i64; 4] = cast(a.cmp_eq(b));
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_cmp_ne() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([2.0, 2.0, 2.0, 2.0]);
let expected: [i64; 4] = [-1, 0, -1, -1];
let actual: [i64; 4] = cast(a.cmp_ne(b));
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_cmp_ge() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([2.0, 2.0, 2.0, 2.0]);
let expected: [i64; 4] = [0, -1, -1, -1];
let actual: [i64; 4] = cast(a.cmp_ge(b));
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_cmp_gt() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([2.0, 2.0, 2.0, 2.0]);
let expected: [i64; 4] = [0, 0, -1, -1];
let actual: [i64; 4] = cast(a.cmp_gt(b));
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_cmp_le() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([2.0, 2.0, 2.0, 2.0]);
let expected: [i64; 4] = [-1, -1, 0, 0];
let actual: [i64; 4] = cast(a.cmp_le(b));
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_cmp_lt() {
let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let b = f64x4::from([2.0, 2.0, 2.0, 2.0]);
let expected: [i64; 4] = [-1, 0, 0, 0];
let actual: [i64; 4] = cast(a.cmp_lt(b));
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_blend() {
let use_t: f64 = f64::from_bits(u64::MAX);
let t = f64x4::from([1.0, 2.0, 3.0, 4.0]);
let f = f64x4::from([5.0, 6.0, 7.0, 8.0]);
let mask = f64x4::from([use_t, 0.0, use_t, 0.0]);
let expected = f64x4::from([1.0, 6.0, 3.0, 8.0]);
let actual = mask.blend(t, f);
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_abs() {
let a = f64x4::from([-1.0, 2.0, -3.5, f64::NEG_INFINITY]);
let expected = f64x4::from([1.0, 2.0, 3.5, f64::INFINITY]);
let actual = a.abs();
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_max() {
let a = f64x4::from([1.0, 5.0, 3.0, f64::NAN]);
let b = f64x4::from([2.0, f64::NEG_INFINITY, f64::INFINITY, 10.0]);
let expected = f64x4::from([2.0, 5.0, f64::INFINITY, 10.0]);
let actual = a.max(b);
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_min() {
let a = f64x4::from([1.0, 5.0, 3.0, f64::NAN]);
let b = f64x4::from([2.0, f64::NEG_INFINITY, f64::INFINITY, 10.0]);
let expected = f64x4::from([1.0, f64::NEG_INFINITY, 3.0, 10.0]);
let actual = a.min(b);
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_is_nan() {
let a = f64x4::from([0.0, f64::NAN, f64::NAN, 0.0]);
let expected = [0, u64::MAX, u64::MAX, 0];
let actual: [u64; 4] = cast(a.is_nan());
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_is_finite() {
let a = f64x4::from([f64::NAN, 1.0, f64::INFINITY, f64::NEG_INFINITY]);
let expected = [0, u64::MAX, 0, 0];
let actual: [u64; 4] = cast(a.is_finite());
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_round() {
let a = f64x4::from([1.1, 2.5, 3.7, 4.0]);
let expected = f64x4::from([1.0, 2.0, 4.0, 4.0]);
let actual = a.round();
assert_eq!(expected, actual);
//
let a = f64x4::from([-1.1, -2.5, -3.7, -4.0]);
let expected = f64x4::from([-1.0, -2.0, -4.0, -4.0]);
let actual = a.round();
assert_eq!(expected, actual);
//
let a = f64x4::from([f64::INFINITY, f64::NEG_INFINITY, 5.5, 5.0]);
let expected = f64x4::from([f64::INFINITY, f64::NEG_INFINITY, 6.0, 5.0]);
let actual = a.round();
assert_eq!(expected, actual);
//
let a = f64x4::from(f64::NAN);
let expected: [u64; 4] = [u64::MAX; 4];
let actual: [u64; 4] = cast(a.round().is_nan());
assert_eq!(expected, actual);
//
let a = f64x4::from(-0.0);
let expected = a;
let actual = a.round();
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_round_int() {
for (f, i) in [
(1.0, 1i64),
(1.1, 1),
(-2.1, -2),
(2.5, 2),
(0.0, 0),
(-0.0, 0),
(f64::NAN, i64::MIN),
(f64::INFINITY, i64::MIN),
(f64::NEG_INFINITY, i64::MIN),
]
.iter()
.copied()
{
let a = f64x4::from(f);
let expected = i64x4::from(i);
let actual = a.round_int();
assert_eq!(expected, actual);
}
}
#[test]
fn impl_f64x4_mul_add() {
let a = f64x4::from([2.0, 3.0, 4.0, 5.0]);
let b = f64x4::from([4.0, 5.0, 6.0, 7.0]);
let c = f64x4::from([1.0, 1.0, 1.0, 1.0]);
let expected = f64x4::from([9.0, 16.0, 25.0, 36.0]);
let actual = a.mul_add(b, c);
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_mul_neg_add() {
let a = f64x4::from([2.0, 3.0, 4.0, 5.0]);
let b = f64x4::from([4.0, 5.0, 6.0, 7.0]);
let c = f64x4::from([1.0, 1.0, 1.0, 1.0]);
let expected = f64x4::from([-7.0, -14.0, -23.0, -34.0]);
let actual = a.mul_neg_add(b, c);
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_flip_signs() {
let a = f64x4::from([1.0, 1.0, -1.0, -1.0]);
let b = f64x4::from([2.0, -3.0, 4.0, -5.0]);
let expected = f64x4::from([1.0, -1.0, -1.0, 1.0]);
let actual = a.flip_signs(b);
assert_eq!(expected, actual);
}
// FIXME: remove cfg requirement once masks as their own types are implemented
#[cfg(target_feature = "avx")]
#[test]
fn impl_f64x4_asin_acos() {
let inc = 1.0 / 2501.0 / 4.0;
for x in -2500..=2500 {
let base = (x * 4) as f64 * inc;
let origs = [base, base + inc, base + 2.0 * inc, base + 3.0 * inc];
let (actual_asins, actual_acoses) = f64x4::from(origs).asin_acos();
for i in 0..4 {
let orig = origs[i];
let check = |name: &str, vals: f64x4, expected: f64| {
let actual_arr: [f64; 4] = cast(vals);
let actual = actual_arr[i];
assert!(
(actual - expected).abs() < 0.0000006,
"Wanted {name}({orig}) to be {expected} but got {actual}",
name = name,
orig = orig,
expected = expected,
actual = actual
);
};
check("asin", actual_asins, orig.asin());
check("acos", actual_acoses, orig.acos());
}
}
}
// FIXME: remove cfg requirement once masks as their own types are implemented
#[cfg(target_feature = "avx")]
#[test]
fn impl_f64x4_asin() {
let inc = 1.0 / 2501.0 / 4.0;
for x in -2500..=2500 {
let base = (x * 4) as f64 * inc;
let origs = [base, base + inc, base + 2.0 * inc, base + 3.0 * inc];
let actual_asins = f64x4::from(origs).asin();
for i in 0..4 {
let orig = origs[i];
let check = |name: &str, vals: f64x4, expected: f64| {
let actual_arr: [f64; 4] = cast(vals);
let actual = actual_arr[i];
assert!(
(actual - expected).abs() < 0.0000006,
"Wanted {name}({orig}) to be {expected} but got {actual}",
name = name,
orig = orig,
expected = expected,
actual = actual
);
};
check("asin", actual_asins, orig.asin());
}
}
}
// FIXME: remove cfg requirement once masks as their own types are implemented
#[cfg(target_feature = "avx")]
#[test]
fn impl_f64x4_acos() {
let inc = 1.0 / 2501.0 / 4.0;
for x in -2500..=2500 {
let base = (x * 4) as f64 * inc;
let origs = [base, base + inc, base + 2.0 * inc, base + 3.0 * inc];
let actual_acoses = f64x4::from(origs).acos();
for i in 0..4 {
let orig = origs[i];
let check = |name: &str, vals: f64x4, expected: f64| {
let actual_arr: [f64; 4] = cast(vals);
let actual = actual_arr[i];
assert!(
(actual - expected).abs() < 0.0000006,
"Wanted {name}({orig}) to be {expected} but got {actual}",
name = name,
orig = orig,
expected = expected,
actual = actual
);
};
check("acos", actual_acoses, orig.acos());
}
}
}
#[test]
fn impl_f64x4_sin_cos() {
for x in -2500..=2500 {
let base = (x * 4) as f64;
let angles = [base, base + 1.0, base + 2.0, base + 3.0];
let (actual_sins, actual_coses) = f64x4::from(angles).sin_cos();
for i in 0..4 {
let angle = angles[i];
let check = |name: &str, vals: f64x4, expected: f64| {
let actual_arr: [f64; 4] = cast(vals);
let actual = actual_arr[i];
assert!(
(actual - expected).abs() < 0.00000006,
"Wanted {name}({angle}) to be {expected} but got {actual}",
name = name,
angle = angle,
expected = expected,
actual = actual
);
};
check("sin", actual_sins, angle.sin());
check("cos", actual_coses, angle.cos());
}
}
}
#[test]
fn impl_f64x4_to_degrees() {
let pi = core::f64::consts::PI;
let a = f64x4::from([0.0, pi / 2.0, pi, 2.0 * pi]);
let expected = f64x4::from([0.0, 90.0, 180.0, 360.0]);
let actual = a.to_degrees();
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_to_radians() {
let pi = core::f64::consts::PI;
let a = f64x4::from([0.0, 90.0, 180.0, 360.0]);
let expected = f64x4::from([0.0, pi / 2.0, pi, 2.0 * pi]);
let actual = a.to_radians();
assert_eq!(expected, actual);
}
#[test]
fn impl_f64x4_sqrt() {
for (f, e) in [
(f64::INFINITY, f64::INFINITY),
(0.0, 0.0),
(-0.0, -0.0),
(4.0, 2.0),
(9.0, 3.0),
(16.0, 4.0),
(25.0, 5.0),
(5000.0 * 5000.0, 5000.0),
]
.iter()
.copied()
{
let expected = f64x4::from(e);
let actual = f64x4::from(f).sqrt();
assert_eq!(expected, actual);
}
assert_eq!(
cast::<_, i64x4>(f64x4::from(f64::NAN).sqrt().is_nan()),
i64x4::from(-1)
);
assert_eq!(
cast::<_, i64x4>(f64x4::from(f64::NEG_INFINITY).sqrt().is_nan()),
i64x4::from(-1)
);
assert_eq!(
cast::<_, i64x4>(f64x4::from(-1.0).sqrt().is_nan()),
i64x4::from(-1)
);
}
#[test]
fn impl_f64x4_exp() {
for f in [(-2.0), (-1.0), (0.0), (1.0), (1.5), (2.0), (10.0)].iter().copied()
{
let expected = f64x4::from((f as f64).exp());
let actual = f64x4::from(f).exp();
let diff_from_std: [f64; 4] = cast((actual - expected).abs());
assert!(diff_from_std[0] < 0.000000000000001);
}
}
#[test]
fn test_f64x4_move_mask() {
let a = f64x4::from([-1.0, 0.0, -2.0, -3.0]);
let expected = 0b1101;
let actual = a.move_mask();
assert_eq!(expected, actual);
//
let a = f64x4::from([1.0, 0.0, 2.0, -3.0]);
let expected = 0b1000;
let actual = a.move_mask();
assert_eq!(expected, actual);
}
#[test]
fn test_f64x4_any() {
let a = f64x4::from([-1.0, 0.0, -2.0, -3.0]);
assert!(a.any());
//
let a = f64x4::from([1.0, 0.0, 2.0, 3.0]);
assert!(!a.any());
}
#[test]
fn test_f64x4_all() {
let a = f64x4::from([-1.0, -0.5, -2.0, -3.0]);
assert!(a.all());
//
let a = f64x4::from([1.0, -0.0, 2.0, 3.0]);
assert!(!a.all());
}
#[test]
fn test_f64x4_none() {
let a = f64x4::from([1.0, 0.0, 2.0, 3.0]);
assert!(a.none());
//
let a = f64x4::from([1.0, -0.0, 2.0, 3.0]);
assert!(!a.none());
}
#[test]
fn impl_f64x4_ln() {
if cfg!(target_feature = "sse") {
for f in [0.1, 0.5, 1.0, 2.718282, 10.0, 35.0, 1250.0].iter().copied() {
let expected = f64x4::from((f as f64).ln());
let actual = f64x4::from(f).ln();
let diff_from_std: [f64; 4] = cast((actual - expected).abs());
assert!(diff_from_std[0] < 0.00000000001);
}
}
}
#[test]
fn impl_f64x4_pow_single() {
for f in [0.1, 0.5, 1.0, 2.718282, 3.0, 4.0, 2.5, -1.0].iter().copied() {
let expected = f64x4::splat(2.0 as f64).powf(f);
let actual = f64x4::from(2.0_f64.powf(f));
let diff_from_std: [f64; 4] = cast((actual - expected).abs());
assert!(diff_from_std[0] < 0.000001);
}
}
#[cfg(target_feature = "sse")]
#[test]
// NOTE this fails due the signbit not working with the non-sse blend
// it only affects the case where there is a nan result
fn impl_f64x4_pow_nan() {
for f in [3.4].iter().copied() {
let expected: [f64; 4] = cast(f64x4::splat(-4.5_f64).powf(f));
let actual = (-4.5_f64).powf(f);
assert!(expected[0].is_nan());
assert!(actual.is_nan());
}
}
#[test]
fn impl_f64x4_pow_multiple() {
let p = f64x4::from([29.0, 0.1, 0.5, 1.0]);
let f = f64x4::from([1.2, 2.0, 3.0, 1.5]);
let res = f.pow_f64x4(p);
let p: [f64; 4] = cast(p);
let f: [f64; 4] = cast(f);
let res: [f64; 4] = cast(res);
for i in 0..p.len() {
let expected = f[i].powf(p[i]);
if expected.is_nan() && res[i].is_nan() {
assert!(true);
continue;
}
if !(expected.is_nan() && res[i].is_nan()) {
assert!((expected - res[i]).abs() < 0.0001);
}
}
let p = f64x4::from([2.718282, -0.2, -1.5, 3.4]);
let f = f64x4::from([9.2, 6.1, 2.5, 4.5]);
let res = f.pow_f64x4(p);
let p: [f64; 4] = cast(p);
let f: [f64; 4] = cast(f);
let res: [f64; 4] = cast(res);
for i in 0..p.len() {
let expected = f[i].powf(p[i]);
if !(expected.is_nan() && res[i].is_nan()) {
assert!((expected - res[i]).abs() < 0.0001);
}
}
}
#[test]
fn impl_f64x4_reduce_add() {
let p = f64x4::splat(0.001);
assert_eq!(p.reduce_add(), 0.004);
}
#[test]
fn impl_f64x4_sum() {
let mut p = Vec::with_capacity(250_000);
for _ in 0..250_000 {
p.push(f64x4::splat(0.001));
}
let now = std::time::Instant::now();
let sum: f64 = p.iter().map(|x| x.reduce_add()).sum();
let duration = now.elapsed().as_micros();
println!("Time take {} {}us", sum, duration);
let p = vec![0.001; 1_000_000];
let now = std::time::Instant::now();
let sum2: f64 = p.iter().sum();
let duration = now.elapsed().as_micros();
println!("Time take {} {}us", sum2, duration);
}
| 27.088235 | 79 | 0.551127 |
7a1dde1767e1f2e99e0aae7470858503f893d636
| 2,137 |
pub mod auth;
pub mod release;
pub mod user;
use actix_web::{web::Bytes, Error};
use color_eyre::Result;
use serde::{Deserialize, Serialize};
use std::pin::Pin;
use std::task::{Context, Poll};
#[derive(Deserialize)]
pub struct Info {
pub name: String,
pub age: u32,
}
#[derive(Deserialize)]
pub struct Query {
pub username: Option<String>,
}
#[derive(Serialize)]
pub struct Status {
pub status: &'static str,
pub message: String,
}
#[derive(Serialize, Debug)]
pub struct Task {
pub id: u32,
pub name: &'static str,
pub message: String,
}
pub struct TaskStream {
pub number: u32,
pub next: u32,
pub buf: Vec<u8>,
}
impl futures::Stream for TaskStream {
type Item = Result<Bytes, Error>;
// TODO: Ne fonctionne pas très bien si this.number = 0
fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.next == this.number {
// Stop stream
Poll::Ready(None)
} else {
// Array start
if this.next == 0 {
for v in b"[" {
this.buf.push(*v);
}
}
let res = serde_json::to_writer(
&mut this.buf,
&Task {
id: this.next,
name: "Coucou ceci est mon nom",
message: String::from("Mon message doit être un peu long pour augmenter la taille"),
},
);
if let Err(e) = res {
return Poll::Ready(Some(Err(e.into())));
}
this.next += 1;
if this.next < this.number {
// Comma between tasks
for v in b"," {
this.buf.push(*v);
}
} else {
// Array end
for v in b"]" {
this.buf.push(*v);
}
}
let poll = Poll::Ready(Some(Ok(Bytes::copy_from_slice(&this.buf))));
this.buf.clear();
poll
}
}
}
| 22.734043 | 104 | 0.479176 |
dbd4d946a86e499752a1dac40ba4a52ada72dfd0
| 5,083 |
use std::path::Path;
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
use futures::{
channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
future::FutureExt,
select,
sink::SinkExt,
stream::{Stream, StreamExt},
};
use log::debug;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_serial::{DataBits, FlowControl, Parity, Serial, SerialPortSettings, StopBits};
use tokio_util::codec::*;
use crate::error::*;
use crate::frame::*;
pub enum BrokerMessage {
AddListener {
listener: UnboundedSender<Frame>,
},
SendFrame {
frame: Frame,
responder: UnboundedSender<Result<Frame, Error>>,
},
}
pub struct Broker {
sender: UnboundedSender<BrokerMessage>,
}
async fn event_loop(
mut receiver: UnboundedReceiver<BrokerMessage>,
mut framed: Framed<impl AsyncReadExt + AsyncWriteExt + Unpin + Send + 'static, FrameCodec>,
) {
let mut listeners = Vec::<UnboundedSender<Frame>>::new();
loop {
select! {
maybe_frame = framed.next().fuse() => match(maybe_frame) {
Some(Ok(frame)) => {
debug!("Received Frame: {:02x?}", frame);
let mut new_listeners = Vec::with_capacity(listeners.len());
while let Some(mut listener) = listeners.pop() {
if listener.send(frame.clone()).await.is_ok() {
new_listeners.push(listener);
}
}
listeners = new_listeners;
},
_ => break,
},
msg = receiver.next() => {
match (msg) {
Some(BrokerMessage::AddListener{ listener }) => {
listeners.push(listener);
},
Some(BrokerMessage::SendFrame{ frame, mut responder }) => {
debug!("Sending Frame: {:02x?}", frame);
if let Err(e) = framed.send(frame).await {
let _ = responder.send(Err(e)).await;
continue;
}
match framed.next().await {
None => {
let _ = responder.send(Err(Error::Disconnected)).await;
break;
},
Some(response) => {
debug!("Received Response: {:02x?}", response);
let _ = responder.send(response).await;
}
}
},
None => break, // No more messages coming, exit
}
}
}
}
}
impl Broker {
pub fn from_path(path: impl AsRef<Path> + Send + 'static) -> Result<Broker, std::io::Error> {
let (sender, receiver) = unbounded();
let (init_sender, init_receiver) = channel();
thread::spawn(move || {
let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async move {
let settings = SerialPortSettings {
baud_rate: 19200,
data_bits: DataBits::Eight,
flow_control: FlowControl::None,
parity: Parity::None,
stop_bits: StopBits::One,
timeout: Duration::from_millis(100),
};
match Serial::from_path(path.as_ref(), &settings) {
Ok(port) => {
init_sender.send(Ok(())).unwrap();
event_loop(receiver, Framed::new(port, FrameCodec())).await
}
Err(e) => init_sender.send(Err(e)).unwrap(),
}
});
});
// Make sure we were able to create the port
init_receiver.recv().unwrap()?;
Ok(Broker { sender })
}
pub fn new(handle: impl AsyncReadExt + AsyncWriteExt + Unpin + Send + 'static) -> Broker {
let (sender, receiver) = unbounded();
thread::spawn(move || {
let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(
async move { event_loop(receiver, Framed::new(handle, FrameCodec())).await },
);
});
Broker { sender }
}
pub async fn send(&mut self, frame: Frame) -> Result<Frame, Error> {
let (sender, mut receiver) = unbounded();
self.sender
.send(BrokerMessage::SendFrame {
frame,
responder: sender,
})
.await?;
receiver.next().await.ok_or_else(|| Error::Disconnected)?
}
pub async fn listen(&mut self) -> Result<impl Stream<Item = Frame>, Error> {
let (sender, receiver) = unbounded();
self.sender
.send(BrokerMessage::AddListener { listener: sender })
.await?;
Ok(receiver)
}
}
| 32.793548 | 97 | 0.480425 |
03380067292eea6cfe6a4dd4b860e26da768f4a1
| 1,473 |
//! A very simple example processor which returns a new version of the
//! given AST with all comments changed to upper case.
use crate::generator::ast::*;
use crate::generator::processor::*;
pub struct UpcaseComments {}
impl UpcaseComments {
#[allow(dead_code)]
pub fn run(node: &Node) -> Result<Node> {
let mut p = UpcaseComments {};
Ok(node.process(&mut p)?.unwrap())
}
}
impl Processor for UpcaseComments {
fn on_node(&mut self, node: &Node) -> Result<Return> {
match &node.attrs {
Attrs::Comment(level, msg) => {
let new_node = node.replace_attrs(Attrs::Comment(*level, msg.to_uppercase()));
Ok(Return::Replace(new_node))
}
_ => Ok(Return::ProcessChildren),
}
}
}
#[cfg(test)]
mod tests {
use crate::generator::ast::*;
use crate::generator::processors::*;
#[test]
fn it_works() {
let mut ast = AST::new();
ast.push_and_open(node!(Test, "t1".to_string()));
ast.push(node!(Cycle, 1, false));
ast.push(node!(Comment, 1, "some comment".to_string()));
let mut expect = AST::new();
expect.push_and_open(node!(Test, "t1".to_string()));
expect.push(node!(Cycle, 1, false));
expect.push(node!(Comment, 1, "SOME COMMENT".to_string()));
assert_eq!(
UpcaseComments::run(&ast.to_node()).expect("Comments upcased"),
expect
);
}
}
| 28.326923 | 94 | 0.575017 |
e89b9d4387f3a71e2b6f55cdaf53e90b85245e55
| 2,927 |
use crate::common::util::*;
// tests for basic tee functionality.
// inspired by:
// https://github.com/coreutils/coreutils/tests/misc/tee.sh
#[test]
fn test_tee_processing_multiple_operands() {
// POSIX says: "Processing of at least 13 file operands shall be supported."
let content = "tee_sample_content";
for n in [1, 2, 12, 13] {
let files = (1..=n).map(|x| x.to_string()).collect::<Vec<_>>();
let (at, mut ucmd) = at_and_ucmd!();
ucmd.args(&files)
.pipe_in(content)
.succeeds()
.stdout_is(content);
for file in &files {
assert!(at.file_exists(file));
assert_eq!(at.read(file), content);
}
}
}
#[test]
fn test_tee_treat_minus_as_filename() {
// Ensure tee treats '-' as the name of a file, as mandated by POSIX.
let (at, mut ucmd) = at_and_ucmd!();
let content = "tee_sample_content";
let file = "-";
ucmd.arg("-").pipe_in(content).succeeds().stdout_is(content);
assert!(at.file_exists(file));
assert_eq!(at.read(file), content);
}
#[test]
fn test_tee_append() {
let (at, mut ucmd) = at_and_ucmd!();
let content = "tee_sample_content";
let file = "tee_out";
at.touch(file);
at.write(file, content);
assert_eq!(at.read(file), content);
ucmd.arg("-a")
.arg(file)
.pipe_in(content)
.succeeds()
.stdout_is(content);
assert!(at.file_exists(file));
assert_eq!(at.read(file), content.repeat(2));
}
#[test]
#[cfg(target_os = "linux")]
fn test_tee_no_more_writeable_1() {
// equals to 'tee /dev/full out2 <multi_read' call
let (at, mut ucmd) = at_and_ucmd!();
let content = (1..=10).map(|x| format!("{}\n", x)).collect::<String>();
let file_out = "tee_file_out";
ucmd.arg("/dev/full")
.arg(file_out)
.pipe_in(&content[..])
.fails()
.stdout_contains(&content)
.stderr_contains(&"No space left on device");
assert_eq!(at.read(file_out), content);
}
#[test]
#[cfg(target_os = "linux")]
fn test_tee_no_more_writeable_2() {
// should be equals to 'tee out1 out2 >/dev/full <multi_read' call
// but currently there is no way to redirect stdout to /dev/full
// so this test is disabled
let (_at, mut ucmd) = at_and_ucmd!();
let _content = (1..=10).map(|x| format!("{}\n", x)).collect::<String>();
let file_out_a = "tee_file_out_a";
let file_out_b = "tee_file_out_b";
let _result = ucmd
.arg(file_out_a)
.arg(file_out_b)
.pipe_in("/dev/full")
.succeeds(); // TODO: expected to succeed currently; change to fails() when required
// TODO: comment in after https://github.com/uutils/coreutils/issues/1805 is fixed
// assert_eq!(at.read(file_out_a), content);
// assert_eq!(at.read(file_out_b), content);
// assert!(result.stderr.contains("No space left on device"));
}
| 28.980198 | 92 | 0.608131 |
267043821c93acdfa51033712a2729303f04b4f5
| 927 |
use diesel::{self, prelude::*};
mod schema {
table! {
comments {
id -> Nullable<Integer>,
uid -> Text,
text -> Text,
}
}
}
use self::schema::comments;
use self::schema::comments::dsl::{comments as all_comments};
#[table_name="comments"]
#[derive(Serialize, Queryable, Insertable, Debug, Clone)]
pub struct Comment {
pub id: Option<i32>,
pub uid: String,
pub text: String,
}
#[derive(FromForm)]
pub struct NewComment {
pub uid: String,
pub text: String,
}
impl Comment {
pub fn all(conn: &PgConnection) -> Vec<Comment> {
all_comments.order(comments::id.desc()).load::<Comment>(conn).unwrap()
}
pub fn insert(comment: NewComment, conn: &PgConnection) -> bool {
let t = Comment { id: None, uid: comment.uid, text: comment.text };
diesel::insert_into(comments::table).values(&t).execute(conn).is_ok()
}
}
| 23.175 | 78 | 0.60302 |
87e1b9de3607c07758c9e1714e3771cd57332ed4
| 354 |
#![allow(improper_ctypes)]
use marine_rs_sdk::marine;
fn main() {}
#[marine]
struct StructWithPrivateFields {
a: i32,
b: usize,
}
#[marine]
fn export_func(_field: StructWithPrivateFields) { }
#[marine]
#[link(wasm_import_module = "record_module")]
extern "C" {
fn import_func(arg: &StructWithPrivateFields) -> StructWithPrivateFields;
}
| 16.857143 | 77 | 0.70904 |
bfd634ba54216776c4826784bfec8b5af6cd163f
| 244 |
asteracea::component! {
pub Sync()() -> Sync
[]
}
asteracea::component! {
pub UnSync()() -> !Sync
[]
}
asteracea::component! {
#[allow(dead_code)]
AutoSync()()
[]
}
asteracea::component! {
pub ExplicitAutoSync()() -> Sync?
[]
}
| 9.76 | 34 | 0.577869 |
e21e8fb2ddf39090cf0a88c701b83ac5a70559ee
| 43,986 |
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is 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.
// You may not use this file except in accordance with one or both of these
// licenses.
//! The logic to build claims and bump in-flight transactions until confirmations.
//!
//! OnchainTxHandler objetcs are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.
use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
use bitcoin::hash_types::Txid;
use bitcoin::secp256k1::{Secp256k1, Signature};
use bitcoin::secp256k1;
use ln::msgs::DecodeError;
use ln::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest};
use ln::channelmanager::PaymentPreimage;
use ln::chan_utils;
use ln::chan_utils::{TxCreationKeys, LocalCommitmentTransaction};
use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
use chain::keysinterface::ChannelKeys;
use util::logger::Logger;
use util::ser::{Readable, Writer, Writeable};
use util::byte_utils;
use std::collections::{HashMap, hash_map};
use std::cmp;
use std::ops::Deref;
const MAX_ALLOC_SIZE: usize = 64*1024;
/// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
/// once they mature to enough confirmations (ANTI_REORG_DELAY)
#[derive(Clone, PartialEq)]
enum OnchainEvent {
/// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
/// bump-txn candidate buffer.
Claim {
claim_request: Txid,
},
/// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a remote party tx.
/// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
/// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
ContentiousOutpoint {
outpoint: BitcoinOutPoint,
input_material: InputMaterial,
}
}
/// Higher-level cache structure needed to re-generate bumped claim txn if needed
#[derive(Clone, PartialEq)]
pub struct ClaimTxBumpMaterial {
// At every block tick, used to check if pending claiming tx is taking too
// much time for confirmation and we need to bump it.
height_timer: Option<u32>,
// Tracked in case of reorg to wipe out now-superflous bump material
feerate_previous: u32,
// Soonest timelocks among set of outpoints claimed, used to compute
// a priority of not feerate
soonest_timelock: u32,
// Cache of script, pubkey, sig or key to solve claimable outputs scriptpubkey.
per_input_material: HashMap<BitcoinOutPoint, InputMaterial>,
}
impl Writeable for ClaimTxBumpMaterial {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
self.height_timer.write(writer)?;
writer.write_all(&byte_utils::be32_to_array(self.feerate_previous))?;
writer.write_all(&byte_utils::be32_to_array(self.soonest_timelock))?;
writer.write_all(&byte_utils::be64_to_array(self.per_input_material.len() as u64))?;
for (outp, tx_material) in self.per_input_material.iter() {
outp.write(writer)?;
tx_material.write(writer)?;
}
Ok(())
}
}
impl Readable for ClaimTxBumpMaterial {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let height_timer = Readable::read(reader)?;
let feerate_previous = Readable::read(reader)?;
let soonest_timelock = Readable::read(reader)?;
let per_input_material_len: u64 = Readable::read(reader)?;
let mut per_input_material = HashMap::with_capacity(cmp::min(per_input_material_len as usize, MAX_ALLOC_SIZE / 128));
for _ in 0 ..per_input_material_len {
let outpoint = Readable::read(reader)?;
let input_material = Readable::read(reader)?;
per_input_material.insert(outpoint, input_material);
}
Ok(Self { height_timer, feerate_previous, soonest_timelock, per_input_material })
}
}
#[derive(PartialEq, Clone, Copy)]
pub(crate) enum InputDescriptors {
RevokedOfferedHTLC,
RevokedReceivedHTLC,
OfferedHTLC,
ReceivedHTLC,
RevokedOutput, // either a revoked to_local output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
}
impl Writeable for InputDescriptors {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
match self {
&InputDescriptors::RevokedOfferedHTLC => {
writer.write_all(&[0; 1])?;
},
&InputDescriptors::RevokedReceivedHTLC => {
writer.write_all(&[1; 1])?;
},
&InputDescriptors::OfferedHTLC => {
writer.write_all(&[2; 1])?;
},
&InputDescriptors::ReceivedHTLC => {
writer.write_all(&[3; 1])?;
}
&InputDescriptors::RevokedOutput => {
writer.write_all(&[4; 1])?;
}
}
Ok(())
}
}
impl Readable for InputDescriptors {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let input_descriptor = match <u8 as Readable>::read(reader)? {
0 => {
InputDescriptors::RevokedOfferedHTLC
},
1 => {
InputDescriptors::RevokedReceivedHTLC
},
2 => {
InputDescriptors::OfferedHTLC
},
3 => {
InputDescriptors::ReceivedHTLC
},
4 => {
InputDescriptors::RevokedOutput
}
_ => return Err(DecodeError::InvalidValue),
};
Ok(input_descriptor)
}
}
macro_rules! subtract_high_prio_fee {
($logger: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $used_feerate: expr) => {
{
$used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority).into();
let mut fee = $used_feerate as u64 * $predicted_weight / 1000;
if $value <= fee {
$used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal).into();
fee = $used_feerate as u64 * $predicted_weight / 1000;
if $value <= fee.into() {
$used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background).into();
fee = $used_feerate as u64 * $predicted_weight / 1000;
if $value <= fee {
log_error!($logger, "Failed to generate an on-chain punishment tx as even low priority fee ({} sat) was more than the entire claim balance ({} sat)",
fee, $value);
false
} else {
log_warn!($logger, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
$value);
$value -= fee;
true
}
} else {
log_warn!($logger, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
$value);
$value -= fee;
true
}
} else {
$value -= fee;
true
}
}
}
}
impl Readable for Option<Vec<Option<(usize, Signature)>>> {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
match Readable::read(reader)? {
0u8 => Ok(None),
1u8 => {
let vlen: u64 = Readable::read(reader)?;
let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<Option<(usize, Signature)>>()));
for _ in 0..vlen {
ret.push(match Readable::read(reader)? {
0u8 => None,
1u8 => Some((<u64 as Readable>::read(reader)? as usize, Readable::read(reader)?)),
_ => return Err(DecodeError::InvalidValue)
});
}
Ok(Some(ret))
},
_ => Err(DecodeError::InvalidValue),
}
}
}
impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
match self {
&Some(ref vec) => {
1u8.write(writer)?;
(vec.len() as u64).write(writer)?;
for opt in vec.iter() {
match opt {
&Some((ref idx, ref sig)) => {
1u8.write(writer)?;
(*idx as u64).write(writer)?;
sig.write(writer)?;
},
&None => 0u8.write(writer)?,
}
}
},
&None => 0u8.write(writer)?,
}
Ok(())
}
}
/// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
/// do RBF bumping if possible.
pub struct OnchainTxHandler<ChanSigner: ChannelKeys> {
destination_script: Script,
local_commitment: Option<LocalCommitmentTransaction>,
// local_htlc_sigs and prev_local_htlc_sigs are in the order as they appear in the commitment
// transaction outputs (hence the Option<>s inside the Vec). The first usize is the index in
// the set of HTLCs in the LocalCommitmentTransaction (including those which do not appear in
// the commitment transaction).
local_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
prev_local_commitment: Option<LocalCommitmentTransaction>,
prev_local_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
on_local_tx_csv: u16,
key_storage: ChanSigner,
// Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
// it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
// another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
// same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
// block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
// equality between spending transaction and claim request. If true, it means transaction was one our claiming one
// after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
// we need to regenerate new claim request with reduced set of still-claimable outpoints.
// Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
// us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
// Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
#[cfg(test)] // Used in functional_test to verify sanitization
pub pending_claim_requests: HashMap<Txid, ClaimTxBumpMaterial>,
#[cfg(not(test))]
pending_claim_requests: HashMap<Txid, ClaimTxBumpMaterial>,
// Used to link outpoints claimed in a connected block to a pending claim request.
// Key is outpoint than monitor parsing has detected we have keys/scripts to claim
// Value is (pending claim request identifier, confirmation_block), identifier
// is txid of the initial claiming transaction and is immutable until outpoint is
// post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
// block with output gets disconnected.
#[cfg(test)] // Used in functional_test to verify sanitization
pub claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
#[cfg(not(test))]
claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
secp_ctx: Secp256k1<secp256k1::All>,
}
impl<ChanSigner: ChannelKeys + Writeable> OnchainTxHandler<ChanSigner> {
pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
self.destination_script.write(writer)?;
self.local_commitment.write(writer)?;
self.local_htlc_sigs.write(writer)?;
self.prev_local_commitment.write(writer)?;
self.prev_local_htlc_sigs.write(writer)?;
self.on_local_tx_csv.write(writer)?;
self.key_storage.write(writer)?;
writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
ancestor_claim_txid.write(writer)?;
claim_tx_data.write(writer)?;
}
writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
outp.write(writer)?;
claim_and_height.0.write(writer)?;
claim_and_height.1.write(writer)?;
}
writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
writer.write_all(&byte_utils::be32_to_array(**target))?;
writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
for ev in events.iter() {
match *ev {
OnchainEvent::Claim { ref claim_request } => {
writer.write_all(&[0; 1])?;
claim_request.write(writer)?;
},
OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
writer.write_all(&[1; 1])?;
outpoint.write(writer)?;
input_material.write(writer)?;
}
}
}
}
Ok(())
}
}
impl<ChanSigner: ChannelKeys + Readable> Readable for OnchainTxHandler<ChanSigner> {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let destination_script = Readable::read(reader)?;
let local_commitment = Readable::read(reader)?;
let local_htlc_sigs = Readable::read(reader)?;
let prev_local_commitment = Readable::read(reader)?;
let prev_local_htlc_sigs = Readable::read(reader)?;
let on_local_tx_csv = Readable::read(reader)?;
let key_storage = Readable::read(reader)?;
let pending_claim_requests_len: u64 = Readable::read(reader)?;
let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
for _ in 0..pending_claim_requests_len {
pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
}
let claimable_outpoints_len: u64 = Readable::read(reader)?;
let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
for _ in 0..claimable_outpoints_len {
let outpoint = Readable::read(reader)?;
let ancestor_claim_txid = Readable::read(reader)?;
let height = Readable::read(reader)?;
claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
}
let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
for _ in 0..waiting_threshold_conf_len {
let height_target = Readable::read(reader)?;
let events_len: u64 = Readable::read(reader)?;
let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
for _ in 0..events_len {
let ev = match <u8 as Readable>::read(reader)? {
0 => {
let claim_request = Readable::read(reader)?;
OnchainEvent::Claim {
claim_request
}
},
1 => {
let outpoint = Readable::read(reader)?;
let input_material = Readable::read(reader)?;
OnchainEvent::ContentiousOutpoint {
outpoint,
input_material
}
}
_ => return Err(DecodeError::InvalidValue),
};
events.push(ev);
}
onchain_events_waiting_threshold_conf.insert(height_target, events);
}
Ok(OnchainTxHandler {
destination_script,
local_commitment,
local_htlc_sigs,
prev_local_commitment,
prev_local_htlc_sigs,
on_local_tx_csv,
key_storage,
claimable_outpoints,
pending_claim_requests,
onchain_events_waiting_threshold_conf,
secp_ctx: Secp256k1::new(),
})
}
}
impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
pub(super) fn new(destination_script: Script, keys: ChanSigner, on_local_tx_csv: u16) -> Self {
let key_storage = keys;
OnchainTxHandler {
destination_script,
local_commitment: None,
local_htlc_sigs: None,
prev_local_commitment: None,
prev_local_htlc_sigs: None,
on_local_tx_csv,
key_storage,
pending_claim_requests: HashMap::new(),
claimable_outpoints: HashMap::new(),
onchain_events_waiting_threshold_conf: HashMap::new(),
secp_ctx: Secp256k1::new(),
}
}
pub(super) fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
let mut tx_weight = 2; // count segwit flags
for inp in inputs {
// We use expected weight (and not actual) as signatures and time lock delays may vary
tx_weight += match inp {
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
&InputDescriptors::RevokedOfferedHTLC => {
1 + 1 + 73 + 1 + 33 + 1 + 133
},
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
&InputDescriptors::RevokedReceivedHTLC => {
1 + 1 + 73 + 1 + 33 + 1 + 139
},
// number_of_witness_elements + sig_length + remotehtlc_sig + preimage_length + preimage + witness_script_length + witness_script
&InputDescriptors::OfferedHTLC => {
1 + 1 + 73 + 1 + 32 + 1 + 133
},
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
&InputDescriptors::ReceivedHTLC => {
1 + 1 + 73 + 1 + 1 + 1 + 139
},
// number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
&InputDescriptors::RevokedOutput => {
1 + 1 + 73 + 1 + 1 + 1 + 77
},
};
}
tx_weight
}
/// In LN, output claimed are time-sensitive, which means we have to spend them before reaching some timelock expiration. At in-channel
/// output detection, we generate a first version of a claim tx and associate to it a height timer. A height timer is an absolute block
/// height than once reached we should generate a new bumped "version" of the claim tx to be sure than we safely claim outputs before
/// than our counterparty can do it too. If timelock expires soon, height timer is going to be scale down in consequence to increase
/// frequency of the bump and so increase our bets of success.
fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
if timelock_expiration <= current_height + 3 {
return current_height + 1
} else if timelock_expiration - current_height <= 15 {
return current_height + 3
}
current_height + 15
}
/// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration
/// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent.
fn generate_claim_tx<F: Deref, L: Deref>(&mut self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: F, logger: L) -> Option<(Option<u32>, u32, Transaction)>
where F::Target: FeeEstimator,
L::Target: Logger,
{
if cached_claim_datas.per_input_material.len() == 0 { return None } // But don't prune pending claiming request yet, we may have to resurrect HTLCs
let mut inputs = Vec::new();
for outp in cached_claim_datas.per_input_material.keys() {
log_trace!(logger, "Outpoint {}:{}", outp.txid, outp.vout);
inputs.push(TxIn {
previous_output: *outp,
script_sig: Script::new(),
sequence: 0xfffffffd,
witness: Vec::new(),
});
}
let mut bumped_tx = Transaction {
version: 2,
lock_time: 0,
input: inputs,
output: vec![TxOut {
script_pubkey: self.destination_script.clone(),
value: 0
}],
};
macro_rules! RBF_bump {
($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
{
let mut used_feerate: u32;
// If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) {
let mut value = $amount;
if subtract_high_prio_fee!(logger, $fee_estimator, value, $predicted_weight, used_feerate) {
// Overflow check is done in subtract_high_prio_fee
($amount - value)
} else {
log_trace!(logger, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount);
return None;
}
// ...else just increase the previous feerate by 25% (because that's a nice number)
} else {
let fee = $old_feerate as u64 * ($predicted_weight as u64) / 750;
if $amount <= fee {
log_trace!(logger, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
return None;
}
fee
};
let previous_fee = $old_feerate as u64 * ($predicted_weight as u64) / 1000;
let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * ($predicted_weight as u64) / 1000;
// BIP 125 Opt-in Full Replace-by-Fee Signaling
// * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
// * 4. The replacement transaction must also pay for its own bandwidth at or above the rate set by the node's minimum relay fee setting.
let new_fee = if new_fee < previous_fee + min_relay_fee {
new_fee + previous_fee + min_relay_fee - new_fee
} else {
new_fee
};
Some((new_fee, new_fee * 1000 / ($predicted_weight as u64)))
}
}
}
// Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
// didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
let new_timer = Some(Self::get_height_timer(height, cached_claim_datas.soonest_timelock));
let mut inputs_witnesses_weight = 0;
let mut amt = 0;
let mut dynamic_fee = true;
for per_outp_material in cached_claim_datas.per_input_material.values() {
match per_outp_material {
&InputMaterial::Revoked { ref input_descriptor, ref amount, .. } => {
inputs_witnesses_weight += Self::get_witnesses_weight(&[*input_descriptor]);
amt += *amount;
},
&InputMaterial::RemoteHTLC { ref preimage, ref htlc, .. } => {
inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC] });
amt += htlc.amount_msat / 1000;
},
&InputMaterial::LocalHTLC { .. } => {
dynamic_fee = false;
},
&InputMaterial::Funding { .. } => {
dynamic_fee = false;
}
}
}
if dynamic_fee {
let predicted_weight = (bumped_tx.get_weight() + inputs_witnesses_weight) as u64;
let mut new_feerate;
// If old feerate is 0, first iteration of this claim, use normal fee calculation
if cached_claim_datas.feerate_previous != 0 {
if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight) {
// If new computed fee is superior at the whole claimable amount burn all in fees
if new_fee as u64 > amt {
bumped_tx.output[0].value = 0;
} else {
bumped_tx.output[0].value = amt - new_fee as u64;
}
new_feerate = feerate;
} else { return None; }
} else {
if subtract_high_prio_fee!(logger, fee_estimator, amt, predicted_weight, new_feerate) {
bumped_tx.output[0].value = amt;
} else { return None; }
}
assert!(new_feerate != 0);
for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
match per_outp_material {
&InputMaterial::Revoked { ref per_commitment_point, ref remote_delayed_payment_base_key, ref remote_htlc_base_key, ref per_commitment_key, ref input_descriptor, ref amount, ref htlc, ref on_remote_tx_csv } => {
if let Ok(chan_keys) = TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, remote_delayed_payment_base_key, remote_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) {
let witness_script = if let Some(ref htlc) = *htlc {
chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &chan_keys.a_htlc_key, &chan_keys.b_htlc_key, &chan_keys.revocation_key)
} else {
chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, *on_remote_tx_csv, &chan_keys.a_delayed_payment_key)
};
if let Ok(sig) = self.key_storage.sign_justice_transaction(&bumped_tx, i, *amount, &per_commitment_key, htlc, &self.secp_ctx) {
bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
if htlc.is_some() {
bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
} else {
bumped_tx.input[i].witness.push(vec!(1));
}
bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
} else { return None; }
//TODO: panic ?
log_trace!(logger, "Going to broadcast Penalty Transaction {} claiming revoked {} output {} from {} with new feerate {}...", bumped_tx.txid(), if *input_descriptor == InputDescriptors::RevokedOutput { "to_local" } else if *input_descriptor == InputDescriptors::RevokedOfferedHTLC { "offered" } else if *input_descriptor == InputDescriptors::RevokedReceivedHTLC { "received" } else { "" }, outp.vout, outp.txid, new_feerate);
}
},
&InputMaterial::RemoteHTLC { ref per_commitment_point, ref remote_delayed_payment_base_key, ref remote_htlc_base_key, ref preimage, ref htlc } => {
if let Ok(chan_keys) = TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, remote_delayed_payment_base_key, remote_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) {
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &chan_keys.a_htlc_key, &chan_keys.b_htlc_key, &chan_keys.revocation_key);
if !preimage.is_some() { bumped_tx.lock_time = htlc.cltv_expiry }; // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = self.key_storage.sign_remote_htlc_transaction(&bumped_tx, i, &htlc.amount_msat / 1000, &per_commitment_point, htlc, &self.secp_ctx) {
bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
if let &Some(preimage) = preimage {
bumped_tx.input[i].witness.push(preimage.0.to_vec());
} else {
// Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
bumped_tx.input[i].witness.push(vec![]);
}
bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
}
log_trace!(logger, "Going to broadcast Claim Transaction {} claiming remote {} htlc output {} from {} with new feerate {}...", bumped_tx.txid(), if preimage.is_some() { "offered" } else { "received" }, outp.vout, outp.txid, new_feerate);
}
},
_ => unreachable!()
}
}
log_trace!(logger, "...with timer {}", new_timer.unwrap());
assert!(predicted_weight >= bumped_tx.get_weight() as u64);
return Some((new_timer, new_feerate as u32, bumped_tx))
} else {
for (_, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
match per_outp_material {
&InputMaterial::LocalHTLC { ref preimage, ref amount } => {
let htlc_tx = self.get_fully_signed_htlc_tx(outp, preimage);
if let Some(htlc_tx) = htlc_tx {
let feerate = (amount - htlc_tx.output[0].value) * 1000 / htlc_tx.get_weight() as u64;
// Timer set to $NEVER given we can't bump tx without anchor outputs
log_trace!(logger, "Going to broadcast Local HTLC-{} claiming HTLC output {} from {}...", if preimage.is_some() { "Success" } else { "Timeout" }, outp.vout, outp.txid);
return Some((None, feerate as u32, htlc_tx));
}
return None;
},
&InputMaterial::Funding { ref funding_redeemscript } => {
let signed_tx = self.get_fully_signed_local_tx(funding_redeemscript).unwrap();
// Timer set to $NEVER given we can't bump tx without anchor outputs
log_trace!(logger, "Going to broadcast Local Transaction {} claiming funding output {} from {}...", signed_tx.txid(), outp.vout, outp.txid);
return Some((None, self.local_commitment.as_ref().unwrap().feerate_per_kw, signed_tx));
}
_ => unreachable!()
}
}
}
None
}
pub(super) fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, txn_matched: &[&Transaction], claimable_outpoints: Vec<ClaimRequest>, height: u32, broadcaster: B, fee_estimator: F, logger: L)
where B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
log_trace!(logger, "Block at height {} connected with {} claim requests", height, claimable_outpoints.len());
let mut new_claims = Vec::new();
let mut aggregated_claim = HashMap::new();
let mut aggregated_soonest = ::std::u32::MAX;
// Try to aggregate outputs if their timelock expiration isn't imminent (absolute_timelock
// <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).
for req in claimable_outpoints {
// Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
if let Some(_) = self.claimable_outpoints.get(&req.outpoint) { log_trace!(logger, "Bouncing off outpoint {}:{}, already registered its claiming request", req.outpoint.txid, req.outpoint.vout); } else {
log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.absolute_timelock, height + CLTV_SHARED_CLAIM_BUFFER);
if req.absolute_timelock <= height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable { // Don't aggregate if outpoint absolute timelock is soon or marked as non-aggregable
let mut single_input = HashMap::new();
single_input.insert(req.outpoint, req.witness_data);
new_claims.push((req.absolute_timelock, single_input));
} else {
aggregated_claim.insert(req.outpoint, req.witness_data);
if req.absolute_timelock < aggregated_soonest {
aggregated_soonest = req.absolute_timelock;
}
}
}
}
new_claims.push((aggregated_soonest, aggregated_claim));
// Generate claim transactions and track them to bump if necessary at
// height timer expiration (i.e in how many blocks we're going to take action).
for (soonest_timelock, claim) in new_claims.drain(..) {
let mut claim_material = ClaimTxBumpMaterial { height_timer: None, feerate_previous: 0, soonest_timelock, per_input_material: claim };
if let Some((new_timer, new_feerate, tx)) = self.generate_claim_tx(height, &claim_material, &*fee_estimator, &*logger) {
claim_material.height_timer = new_timer;
claim_material.feerate_previous = new_feerate;
let txid = tx.txid();
for k in claim_material.per_input_material.keys() {
log_trace!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
self.claimable_outpoints.insert(k.clone(), (txid, height));
}
self.pending_claim_requests.insert(txid, claim_material);
log_trace!(logger, "Broadcast onchain {}", log_tx!(tx));
broadcaster.broadcast_transaction(&tx);
}
}
let mut bump_candidates = HashMap::new();
for tx in txn_matched {
// Scan all input to verify is one of the outpoint spent is of interest for us
let mut claimed_outputs_material = Vec::new();
for inp in &tx.input {
if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
// If outpoint has claim request pending on it...
if let Some(claim_material) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
//... we need to verify equality between transaction outpoints and claim request
// outpoints to know if transaction is the original claim or a bumped one issued
// by us.
let mut set_equality = true;
if claim_material.per_input_material.len() != tx.input.len() {
set_equality = false;
} else {
for (claim_inp, tx_inp) in claim_material.per_input_material.keys().zip(tx.input.iter()) {
if *claim_inp != tx_inp.previous_output {
set_equality = false;
}
}
}
macro_rules! clean_claim_request_after_safety_delay {
() => {
let new_event = OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() };
match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
hash_map::Entry::Occupied(mut entry) => {
if !entry.get().contains(&new_event) {
entry.get_mut().push(new_event);
}
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec![new_event]);
}
}
}
}
// If this is our transaction (or our counterparty spent all the outputs
// before we could anyway with same inputs order than us), wait for
// ANTI_REORG_DELAY and clean the RBF tracking map.
if set_equality {
clean_claim_request_after_safety_delay!();
} else { // If false, generate new claim request with update outpoint set
let mut at_least_one_drop = false;
for input in tx.input.iter() {
if let Some(input_material) = claim_material.per_input_material.remove(&input.previous_output) {
claimed_outputs_material.push((input.previous_output, input_material));
at_least_one_drop = true;
}
// If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
if claim_material.per_input_material.is_empty() {
clean_claim_request_after_safety_delay!();
}
}
//TODO: recompute soonest_timelock to avoid wasting a bit on fees
if at_least_one_drop {
bump_candidates.insert(first_claim_txid_height.0.clone(), claim_material.clone());
}
}
break; //No need to iterate further, either tx is our or their
} else {
panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
}
}
}
for (outpoint, input_material) in claimed_outputs_material.drain(..) {
let new_event = OnchainEvent::ContentiousOutpoint { outpoint, input_material };
match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
hash_map::Entry::Occupied(mut entry) => {
if !entry.get().contains(&new_event) {
entry.get_mut().push(new_event);
}
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec![new_event]);
}
}
}
}
// After security delay, either our claim tx got enough confs or outpoint is definetely out of reach
if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
for ev in events {
match ev {
OnchainEvent::Claim { claim_request } => {
// We may remove a whole set of claim outpoints here, as these one may have
// been aggregated in a single tx and claimed so atomically
if let Some(bump_material) = self.pending_claim_requests.remove(&claim_request) {
for outpoint in bump_material.per_input_material.keys() {
self.claimable_outpoints.remove(&outpoint);
}
}
},
OnchainEvent::ContentiousOutpoint { outpoint, .. } => {
self.claimable_outpoints.remove(&outpoint);
}
}
}
}
// Check if any pending claim request must be rescheduled
for (first_claim_txid, ref claim_data) in self.pending_claim_requests.iter() {
if let Some(h) = claim_data.height_timer {
if h == height {
bump_candidates.insert(*first_claim_txid, (*claim_data).clone());
}
}
}
// Build, bump and rebroadcast tx accordingly
log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
for (first_claim_txid, claim_material) in bump_candidates.iter() {
if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &claim_material, &*fee_estimator, &*logger) {
log_trace!(logger, "Broadcast onchain {}", log_tx!(bump_tx));
broadcaster.broadcast_transaction(&bump_tx);
if let Some(claim_material) = self.pending_claim_requests.get_mut(first_claim_txid) {
claim_material.height_timer = new_timer;
claim_material.feerate_previous = new_feerate;
}
}
}
}
pub(super) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: F, logger: L)
where B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
let mut bump_candidates = HashMap::new();
if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
//- our claim tx on a commitment tx output
//- resurect outpoint back in its claimable set and regenerate tx
for ev in events {
match ev {
OnchainEvent::ContentiousOutpoint { outpoint, input_material } => {
if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) {
if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
claim_material.per_input_material.insert(outpoint, input_material);
// Using a HashMap guarantee us than if we have multiple outpoints getting
// resurrected only one bump claim tx is going to be broadcast
bump_candidates.insert(ancestor_claimable_txid.clone(), claim_material.clone());
}
}
},
_ => {},
}
}
}
for (_, claim_material) in bump_candidates.iter_mut() {
if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &claim_material, &*fee_estimator, &*logger) {
claim_material.height_timer = new_timer;
claim_material.feerate_previous = new_feerate;
broadcaster.broadcast_transaction(&bump_tx);
}
}
for (ancestor_claim_txid, claim_material) in bump_candidates.drain() {
self.pending_claim_requests.insert(ancestor_claim_txid.0, claim_material);
}
//TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
// right now if one of the outpoint get disconnected, just erase whole pending claim request.
let mut remove_request = Vec::new();
self.claimable_outpoints.retain(|_, ref v|
if v.1 == height {
remove_request.push(v.0.clone());
false
} else { true });
for req in remove_request {
self.pending_claim_requests.remove(&req);
}
}
pub(super) fn provide_latest_local_tx(&mut self, tx: LocalCommitmentTransaction) -> Result<(), ()> {
// To prevent any unsafe state discrepancy between offchain and onchain, once local
// commitment transaction has been signed due to an event (either block height for
// HTLC-timeout or channel force-closure), don't allow any further update of local
// commitment transaction view to avoid delivery of revocation secret to counterparty
// for the aformentionned signed transaction.
if self.local_htlc_sigs.is_some() || self.prev_local_htlc_sigs.is_some() {
return Err(());
}
self.prev_local_commitment = self.local_commitment.take();
self.local_commitment = Some(tx);
Ok(())
}
fn sign_latest_local_htlcs(&mut self) {
if let Some(ref local_commitment) = self.local_commitment {
if let Ok(sigs) = self.key_storage.sign_local_commitment_htlc_transactions(local_commitment, &self.secp_ctx) {
self.local_htlc_sigs = Some(Vec::new());
let ret = self.local_htlc_sigs.as_mut().unwrap();
for (htlc_idx, (local_sig, &(ref htlc, _))) in sigs.iter().zip(local_commitment.per_htlc.iter()).enumerate() {
if let Some(tx_idx) = htlc.transaction_output_index {
if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
ret[tx_idx as usize] = Some((htlc_idx, local_sig.expect("Did not receive a signature for a non-dust HTLC")));
} else {
assert!(local_sig.is_none(), "Received a signature for a dust HTLC");
}
}
}
}
}
fn sign_prev_local_htlcs(&mut self) {
if let Some(ref local_commitment) = self.prev_local_commitment {
if let Ok(sigs) = self.key_storage.sign_local_commitment_htlc_transactions(local_commitment, &self.secp_ctx) {
self.prev_local_htlc_sigs = Some(Vec::new());
let ret = self.prev_local_htlc_sigs.as_mut().unwrap();
for (htlc_idx, (local_sig, &(ref htlc, _))) in sigs.iter().zip(local_commitment.per_htlc.iter()).enumerate() {
if let Some(tx_idx) = htlc.transaction_output_index {
if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
ret[tx_idx as usize] = Some((htlc_idx, local_sig.expect("Did not receive a signature for a non-dust HTLC")));
} else {
assert!(local_sig.is_none(), "Received a signature for a dust HTLC");
}
}
}
}
}
//TODO: getting lastest local transactions should be infaillible and result in us "force-closing the channel", but we may
// have empty local commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
// before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
// to monitor before.
pub(super) fn get_fully_signed_local_tx(&mut self, funding_redeemscript: &Script) -> Option<Transaction> {
if let Some(ref mut local_commitment) = self.local_commitment {
match self.key_storage.sign_local_commitment(local_commitment, &self.secp_ctx) {
Ok(sig) => Some(local_commitment.add_local_sig(funding_redeemscript, sig)),
Err(_) => return None,
}
} else {
None
}
}
#[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
pub(super) fn get_fully_signed_copy_local_tx(&mut self, funding_redeemscript: &Script) -> Option<Transaction> {
if let Some(ref mut local_commitment) = self.local_commitment {
let local_commitment = local_commitment.clone();
match self.key_storage.sign_local_commitment(&local_commitment, &self.secp_ctx) {
Ok(sig) => Some(local_commitment.add_local_sig(funding_redeemscript, sig)),
Err(_) => return None,
}
} else {
None
}
}
pub(super) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
let mut htlc_tx = None;
if self.local_commitment.is_some() {
let commitment_txid = self.local_commitment.as_ref().unwrap().txid();
if commitment_txid == outp.txid {
self.sign_latest_local_htlcs();
if let &Some(ref htlc_sigs) = &self.local_htlc_sigs {
let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
htlc_tx = Some(self.local_commitment.as_ref().unwrap()
.get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.on_local_tx_csv));
}
}
}
if self.prev_local_commitment.is_some() {
let commitment_txid = self.prev_local_commitment.as_ref().unwrap().txid();
if commitment_txid == outp.txid {
self.sign_prev_local_htlcs();
if let &Some(ref htlc_sigs) = &self.prev_local_htlc_sigs {
let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
htlc_tx = Some(self.prev_local_commitment.as_ref().unwrap()
.get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.on_local_tx_csv));
}
}
}
htlc_tx
}
#[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
pub(super) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
let latest_had_sigs = self.local_htlc_sigs.is_some();
let prev_had_sigs = self.prev_local_htlc_sigs.is_some();
let ret = self.get_fully_signed_htlc_tx(outp, preimage);
if !latest_had_sigs {
self.local_htlc_sigs = None;
}
if !prev_had_sigs {
self.prev_local_htlc_sigs = None;
}
ret
}
}
| 44.162651 | 431 | 0.705293 |
083f125746e0ffab79f746db123585b935b6ce64
| 2,991 |
use emerald::*;
const RES_WIDTH: usize = 320;
const RES_HEIGHT: usize = 160;
pub fn main() {
let mut settings = GameSettings::default();
let render_settings = RenderSettings {
resolution: (320 * 2, 160 * 2),
..Default::default()
};
settings.render_settings = render_settings;
emerald::start(
MyGame {
pos: Position::new(320.0, 160.0),
scale: 1.0,
render_texture: None,
},
settings,
)
}
pub struct MyGame {
pos: Position,
scale: f32,
render_texture: Option<TextureKey>,
}
impl Game for MyGame {
fn initialize(&mut self, mut emd: Emerald) {
emd.set_asset_folder_root(String::from("./examples/assets/"));
self.render_texture = Some(
emd.loader()
.render_texture(RES_WIDTH as usize, RES_HEIGHT as usize)
.unwrap(),
);
}
fn update(&mut self, mut emd: Emerald) {
let mut input = emd.input();
let delta = emd.delta();
let speed = 150.0;
if input.is_key_pressed(KeyCode::Left) {
self.pos.x -= speed * delta;
}
if input.is_key_pressed(KeyCode::Right) {
self.pos.x += speed * delta;
}
if input.is_key_pressed(KeyCode::Up) {
self.pos.y += speed * delta;
}
if input.is_key_pressed(KeyCode::Down) {
self.pos.y -= speed * delta;
}
if input.is_key_just_pressed(KeyCode::A) {
self.scale *= 0.5;
}
if input.is_key_just_pressed(KeyCode::S) {
self.scale *= 2.0;
}
println!("pos {:?}", self.pos);
}
fn draw(&mut self, mut emd: Emerald) {
let now = std::time::Instant::now();
emd.graphics()
.begin_texture(self.render_texture.as_ref().unwrap().clone())
.unwrap();
let rabbit = emd.loader().sprite("bunny.png").unwrap();
emd.graphics().draw_color_rect(
&ColorRect::new(WHITE, 500 * 500, 500 * 500),
&Position::new((RES_WIDTH / 2) as f32, (RES_HEIGHT / 2) as f32),
);
emd.graphics().draw_sprite(
&rabbit,
&Position::new((RES_WIDTH / 2) as f32, (RES_HEIGHT / 2) as f32),
);
let texture_key = emd.graphics().render_texture().unwrap();
let e = std::time::Instant::now();
println!("texture render: {:?}", e - now);
// println!("{:?}", screen_sprite);
let now = std::time::Instant::now();
let e = std::time::Instant::now();
let mut screen_sprite = Sprite::from_texture(texture_key);
screen_sprite.centered = false;
screen_sprite.scale.x = self.scale;
screen_sprite.scale.y = self.scale;
emd.graphics().begin().unwrap();
emd.graphics().draw_sprite(&screen_sprite, &self.pos);
emd.graphics().render().unwrap();
println!("screen draw: {:?}", e - now);
}
}
| 27.190909 | 76 | 0.537947 |
5dbe0d792470e89806eaaf622990e53e5e6b4522
| 6,829 |
use std::borrow::Cow;
use std::convert::TryFrom;
use std::ffi::{OsStr, OsString};
use std::slice;
use crate::convert::UnboxRubyError;
use crate::core::{ConvertMut, TryConvertMut, Value as _};
use crate::error::Error;
use crate::ffi;
use crate::sys;
use crate::types::{Ruby, Rust};
use crate::value::Value;
use crate::Artichoke;
impl ConvertMut<Vec<u8>, Value> for Artichoke {
fn convert_mut(&mut self, value: Vec<u8>) -> Value {
self.convert_mut(value.as_slice())
}
}
impl ConvertMut<&[u8], Value> for Artichoke {
fn convert_mut(&mut self, value: &[u8]) -> Value {
// Ruby strings contain raw bytes, so we can convert from a &[u8] to a
// `char *` and `size_t`.
let raw = value.as_ptr() as *const i8;
let len = value.len();
// `mrb_str_new` copies the `char *` to the mruby heap so we do not have
// to worry about the lifetime of the slice passed into this converter.
let string = unsafe { self.with_ffi_boundary(|mrb| sys::mrb_str_new(mrb, raw, len)) };
Value::from(string.unwrap())
}
}
impl<'a> ConvertMut<Cow<'a, [u8]>, Value> for Artichoke {
fn convert_mut(&mut self, value: Cow<'a, [u8]>) -> Value {
match value {
Cow::Borrowed(bytes) => self.convert_mut(bytes),
Cow::Owned(bytes) => self.convert_mut(bytes),
}
}
}
impl TryConvertMut<OsString, Value> for Artichoke {
type Error = Error;
fn try_convert_mut(&mut self, value: OsString) -> Result<Value, Self::Error> {
let bytes = ffi::os_str_to_bytes(&*value)?;
Ok(self.convert_mut(bytes))
}
}
impl TryConvertMut<&OsStr, Value> for Artichoke {
type Error = Error;
fn try_convert_mut(&mut self, value: &OsStr) -> Result<Value, Self::Error> {
let bytes = ffi::os_str_to_bytes(value)?;
Ok(self.convert_mut(bytes))
}
}
impl<'a> TryConvertMut<Cow<'a, OsStr>, Value> for Artichoke {
type Error = Error;
fn try_convert_mut(&mut self, value: Cow<'a, OsStr>) -> Result<Value, Self::Error> {
match value {
Cow::Borrowed(value) => {
let bytes = ffi::os_str_to_bytes(value)?;
Ok(self.convert_mut(bytes))
}
Cow::Owned(value) => {
let bytes = ffi::os_string_to_bytes(value)?;
Ok(self.convert_mut(bytes))
}
}
}
}
impl TryConvertMut<Value, Vec<u8>> for Artichoke {
type Error = Error;
fn try_convert_mut(&mut self, value: Value) -> Result<Vec<u8>, Self::Error> {
TryConvertMut::<_, &[u8]>::try_convert_mut(self, value).map(<[_]>::to_vec)
}
}
impl<'a> TryConvertMut<Value, &'a [u8]> for Artichoke {
type Error = Error;
fn try_convert_mut(&mut self, value: Value) -> Result<&'a [u8], Self::Error> {
if let Ruby::String = value.ruby_type() {
let bytes = value.inner();
unsafe {
self.with_ffi_boundary(|mrb| {
let raw = sys::mrb_string_value_ptr(mrb, bytes) as *const u8;
let len = sys::mrb_string_value_len(mrb, bytes);
if let Ok(len) = usize::try_from(len) {
// We can return a borrowed slice because the memory is
// stored on the mruby heap. As long as `value` is
// reachable, this slice points to valid memory.
Ok(slice::from_raw_parts(raw, len))
} else {
Err(UnboxRubyError::new(&value, Rust::Bytes).into())
}
})?
}
} else {
Err(UnboxRubyError::new(&value, Rust::Bytes).into())
}
}
}
#[cfg(test)]
mod tests {
use quickcheck_macros::quickcheck;
use crate::test::prelude::*;
#[test]
fn fail_convert() {
let mut interp = interpreter().unwrap();
// get a Ruby value that can't be converted to a primitive type.
let value = interp.eval(b"Object.new").unwrap();
let result = value.try_into_mut::<Vec<u8>>(&mut interp);
assert!(result.is_err());
}
#[quickcheck]
fn convert_to_vec(bytes: Vec<u8>) -> bool {
let mut interp = interpreter().unwrap();
let value = interp.convert_mut(bytes);
value.ruby_type() == Ruby::String
}
#[quickcheck]
fn bytestring(bytes: Vec<u8>) -> bool {
let mut interp = interpreter().unwrap();
// Borrowed converter
let value = interp.convert_mut(bytes.as_slice());
let len = value.funcall(&mut interp, "length", &[], None).unwrap();
let len = len.try_into::<usize>(&interp).unwrap();
if len != bytes.len() {
return false;
}
let empty = value.funcall(&mut interp, "empty?", &[], None).unwrap();
let empty = empty.try_into::<bool>(&interp).unwrap();
if empty != bytes.is_empty() {
return false;
}
let zero = interp.convert(0);
let first = value.funcall(&mut interp, "[]", &[zero], None).unwrap();
let first = first.try_into_mut::<Option<&[u8]>>(&mut interp).unwrap();
if first != bytes.get(0..1) {
return false;
}
let recovered: Vec<u8> = interp.try_convert_mut(value).unwrap();
if recovered != bytes {
return false;
}
// Owned converter
let value = interp.convert_mut(bytes.to_vec());
let len = value.funcall(&mut interp, "length", &[], None).unwrap();
let len = len.try_into::<usize>(&interp).unwrap();
if len != bytes.len() {
return false;
}
let empty = value.funcall(&mut interp, "empty?", &[], None).unwrap();
let empty = empty.try_into::<bool>(&interp).unwrap();
if empty != bytes.is_empty() {
return false;
}
let zero = interp.convert(0);
let first = value.funcall(&mut interp, "[]", &[zero], None).unwrap();
let first = first.try_into_mut::<Option<&[u8]>>(&mut interp).unwrap();
if first != bytes.get(0..1) {
return false;
}
let recovered: Vec<u8> = interp.try_convert_mut(value).unwrap();
if recovered != bytes {
return false;
}
true
}
#[quickcheck]
fn roundtrip(bytes: Vec<u8>) -> bool {
let mut interp = interpreter().unwrap();
let value = interp.convert_mut(bytes.as_slice());
let value = value.try_into_mut::<Vec<u8>>(&mut interp).unwrap();
value == bytes
}
#[quickcheck]
fn roundtrip_err(b: bool) -> bool {
let mut interp = interpreter().unwrap();
let value = interp.convert(b);
let value = value.try_into_mut::<Vec<u8>>(&mut interp);
value.is_err()
}
}
| 34.145 | 94 | 0.557475 |
22ba55b6baa01df473b2d94af7bbd7b173cc0443
| 12,667 |
#[doc = "Register `uart_int_en` reader"]
pub struct R(crate::R<UART_INT_EN_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<UART_INT_EN_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::convert::From<crate::R<UART_INT_EN_SPEC>> for R {
fn from(reader: crate::R<UART_INT_EN_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `uart_int_en` writer"]
pub struct W(crate::W<UART_INT_EN_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<UART_INT_EN_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl core::convert::From<crate::W<UART_INT_EN_SPEC>> for W {
fn from(writer: crate::W<UART_INT_EN_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `cr_urx_fer_en` reader - "]
pub struct CR_URX_FER_EN_R(crate::FieldReader<bool, bool>);
impl CR_URX_FER_EN_R {
pub(crate) fn new(bits: bool) -> Self {
CR_URX_FER_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_URX_FER_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_urx_fer_en` writer - "]
pub struct CR_URX_FER_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_URX_FER_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Field `cr_utx_fer_en` reader - "]
pub struct CR_UTX_FER_EN_R(crate::FieldReader<bool, bool>);
impl CR_UTX_FER_EN_R {
pub(crate) fn new(bits: bool) -> Self {
CR_UTX_FER_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_UTX_FER_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_utx_fer_en` writer - "]
pub struct CR_UTX_FER_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_UTX_FER_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Field `cr_urx_pce_en` reader - "]
pub struct CR_URX_PCE_EN_R(crate::FieldReader<bool, bool>);
impl CR_URX_PCE_EN_R {
pub(crate) fn new(bits: bool) -> Self {
CR_URX_PCE_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_URX_PCE_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_urx_pce_en` writer - "]
pub struct CR_URX_PCE_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_URX_PCE_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Field `cr_urx_rto_en` reader - "]
pub struct CR_URX_RTO_EN_R(crate::FieldReader<bool, bool>);
impl CR_URX_RTO_EN_R {
pub(crate) fn new(bits: bool) -> Self {
CR_URX_RTO_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_URX_RTO_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_urx_rto_en` writer - "]
pub struct CR_URX_RTO_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_URX_RTO_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Field `cr_urx_fifo_en` reader - "]
pub struct CR_URX_FIFO_EN_R(crate::FieldReader<bool, bool>);
impl CR_URX_FIFO_EN_R {
pub(crate) fn new(bits: bool) -> Self {
CR_URX_FIFO_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_URX_FIFO_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_urx_fifo_en` writer - "]
pub struct CR_URX_FIFO_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_URX_FIFO_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Field `cr_utx_fifo_en` reader - "]
pub struct CR_UTX_FIFO_EN_R(crate::FieldReader<bool, bool>);
impl CR_UTX_FIFO_EN_R {
pub(crate) fn new(bits: bool) -> Self {
CR_UTX_FIFO_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_UTX_FIFO_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_utx_fifo_en` writer - "]
pub struct CR_UTX_FIFO_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_UTX_FIFO_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Field `cr_urx_end_en` reader - "]
pub struct CR_URX_END_EN_R(crate::FieldReader<bool, bool>);
impl CR_URX_END_EN_R {
pub(crate) fn new(bits: bool) -> Self {
CR_URX_END_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_URX_END_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_urx_end_en` writer - "]
pub struct CR_URX_END_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_URX_END_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Field `cr_utx_end_en` reader - "]
pub struct CR_UTX_END_EN_R(crate::FieldReader<bool, bool>);
impl CR_UTX_END_EN_R {
pub(crate) fn new(bits: bool) -> Self {
CR_UTX_END_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_UTX_END_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_utx_end_en` writer - "]
pub struct CR_UTX_END_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_UTX_END_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 7"]
#[inline(always)]
pub fn cr_urx_fer_en(&self) -> CR_URX_FER_EN_R {
CR_URX_FER_EN_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6"]
#[inline(always)]
pub fn cr_utx_fer_en(&self) -> CR_UTX_FER_EN_R {
CR_UTX_FER_EN_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5"]
#[inline(always)]
pub fn cr_urx_pce_en(&self) -> CR_URX_PCE_EN_R {
CR_URX_PCE_EN_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn cr_urx_rto_en(&self) -> CR_URX_RTO_EN_R {
CR_URX_RTO_EN_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3"]
#[inline(always)]
pub fn cr_urx_fifo_en(&self) -> CR_URX_FIFO_EN_R {
CR_URX_FIFO_EN_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2"]
#[inline(always)]
pub fn cr_utx_fifo_en(&self) -> CR_UTX_FIFO_EN_R {
CR_UTX_FIFO_EN_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn cr_urx_end_en(&self) -> CR_URX_END_EN_R {
CR_URX_END_EN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn cr_utx_end_en(&self) -> CR_UTX_END_EN_R {
CR_UTX_END_EN_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 7"]
#[inline(always)]
pub fn cr_urx_fer_en(&mut self) -> CR_URX_FER_EN_W {
CR_URX_FER_EN_W { w: self }
}
#[doc = "Bit 6"]
#[inline(always)]
pub fn cr_utx_fer_en(&mut self) -> CR_UTX_FER_EN_W {
CR_UTX_FER_EN_W { w: self }
}
#[doc = "Bit 5"]
#[inline(always)]
pub fn cr_urx_pce_en(&mut self) -> CR_URX_PCE_EN_W {
CR_URX_PCE_EN_W { w: self }
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn cr_urx_rto_en(&mut self) -> CR_URX_RTO_EN_W {
CR_URX_RTO_EN_W { w: self }
}
#[doc = "Bit 3"]
#[inline(always)]
pub fn cr_urx_fifo_en(&mut self) -> CR_URX_FIFO_EN_W {
CR_URX_FIFO_EN_W { w: self }
}
#[doc = "Bit 2"]
#[inline(always)]
pub fn cr_utx_fifo_en(&mut self) -> CR_UTX_FIFO_EN_W {
CR_UTX_FIFO_EN_W { w: self }
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn cr_urx_end_en(&mut self) -> CR_URX_END_EN_W {
CR_URX_END_EN_W { w: self }
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn cr_utx_end_en(&mut self) -> CR_UTX_END_EN_W {
CR_UTX_END_EN_W { w: self }
}
#[doc = "Writes raw bits to the register."]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "UART interrupt enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_int_en](index.html) module"]
pub struct UART_INT_EN_SPEC;
impl crate::RegisterSpec for UART_INT_EN_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [uart_int_en::R](R) reader structure"]
impl crate::Readable for UART_INT_EN_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [uart_int_en::W](W) writer structure"]
impl crate::Writable for UART_INT_EN_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets uart_int_en to value 0"]
impl crate::Resettable for UART_INT_EN_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 29.321759 | 413 | 0.577958 |
d79d169c06ebde10951f2c54040f07a64cbdecf2
| 16,318 |
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use quickcheck::{Arbitrary, Gen, Testable, QuickCheck, StdGen};
use {Expr, ExprBuilder, CharClass, ClassRange, ByteClass, ByteRange, Repeater, dec_char};
fn qc<T: Testable>(t: T) {
QuickCheck::new()
.tests(10_000)
.max_tests(20_000)
.quickcheck(t);
}
fn class(ranges: &[(char, char)]) -> CharClass {
let ranges = ranges.iter()
.cloned()
.map(|(c1, c2)| ClassRange::new(c1, c2))
.collect();
CharClass::new(ranges)
}
// Test invariants for canonicalizing character classes.
#[test]
fn negate() {
fn prop(ranges: Vec<(char, char)>) -> bool {
let expected = class(&ranges).canonicalize();
let got = class(&ranges).negate().negate();
expected == got
}
qc(prop as fn(Vec<(char, char)>) -> bool);
}
#[test]
fn classes_are_sorted_and_nonoverlapping() {
fn prop(ranges: Vec<(char, char)>) -> bool {
class(&ranges)
.canonicalize()
.windows(2)
.all(|w| w[0].end < dec_char(w[1].start))
}
qc(prop as fn(Vec<(char, char)>) -> bool);
}
#[test]
fn valid_class_ranges() {
fn prop(ranges: Vec<(char, char)>) -> bool {
class(&ranges).canonicalize().into_iter().all(|r| r.start <= r.end)
}
qc(prop as fn(Vec<(char, char)>) -> bool);
}
/// A wrapper type for generating "regex-like" Unicode strings.
///
/// In particular, this type's `Arbitrary` impl specifically biases toward
/// special regex characters to make test cases more interesting.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct RegexLikeString(String);
impl Arbitrary for RegexLikeString {
fn arbitrary<G: Gen>(g: &mut G) -> RegexLikeString {
const SPECIAL: &'static [char] = &['\\', '.', '+', '*', '?', '(', ')', '|', '[', ']', '{',
'}', '^', '$'];
// Generating random Unicode strings results in mostly uninteresting
// regexes. Namely, they'll mostly just be literals.
// To make properties using regex strings more interesting, we bias
// toward selecting characters of significance to a regex.
let size = {
let s = g.size();
g.gen_range(0, s)
};
RegexLikeString((0..size)
.map(|_| {
if g.gen_weighted_bool(3) {
*g.choose(SPECIAL).unwrap()
} else {
g.gen()
}
})
.collect())
}
fn shrink(&self) -> Box<Iterator<Item = RegexLikeString>> {
// The regular `String` shrinker is good enough.
Box::new(self.0.shrink().map(RegexLikeString))
}
}
/// A special type for generating small non-zero sized ASCII strings.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct SmallAscii(String);
impl Arbitrary for SmallAscii {
fn arbitrary<G: Gen>(g: &mut G) -> SmallAscii {
use libtww::std::char::from_u32;
let size = g.gen_range(1, 5);
SmallAscii((0..size)
.map(|_| from_u32(g.gen_range(97, 123)).unwrap())
.collect())
}
fn shrink(&self) -> Box<Iterator<Item = SmallAscii>> {
Box::new(self.0.shrink().map(SmallAscii))
}
}
#[test]
fn parser_never_panics() {
fn prop(s: RegexLikeString) -> bool {
let _ = Expr::parse(&s.0);
true
}
qc(prop as fn(RegexLikeString) -> bool);
}
// Testing entire expressions.
//
// We only have one test at the moment, but the machinery could be useful
// for other things.
//
// In particular, Russ Cox writes about testing regexes by comparing the
// strings they match with other regex implementations. A fuzzer/shrinker
// (which is what's implemented below) would be a great way to drive that
// process. ---AG
impl Arbitrary for Expr {
fn arbitrary<G: Gen>(g: &mut G) -> Expr {
let e = fix_capture_indices(gen_expr(g, 0, ExprType::Anything));
e.simplify(200).unwrap()
}
fn shrink(&self) -> Box<Iterator<Item = Expr>> {
use Expr::*;
let nada = || Box::new(None.into_iter());
let es: Box<Iterator<Item = Expr>> = match *self {
Empty | AnyChar | AnyCharNoNL | AnyByte | AnyByteNoNL | StartLine | EndLine |
StartText | EndText | WordBoundary | NotWordBoundary | WordBoundaryAscii |
NotWordBoundaryAscii => nada(),
Literal { ref chars, .. } if chars.len() == 1 => nada(),
Literal { ref chars, casei } => {
Box::new((chars.clone(), casei)
.shrink()
.filter(|&(ref chars, _)| chars.len() > 0)
.map(|(chars, casei)| {
Literal {
chars: chars,
casei: casei,
}
}))
}
LiteralBytes { ref bytes, .. } if bytes.len() == 1 => nada(),
LiteralBytes { ref bytes, casei } => {
Box::new((bytes.clone(), casei)
.shrink()
.filter(|&(ref bytes, _)| bytes.len() > 0)
.map(|(bytes, casei)| {
LiteralBytes {
bytes: bytes,
casei: casei,
}
}))
}
Class(ref cls) => Box::new(cls.shrink().map(Class)),
ClassBytes(ref cls) => Box::new(cls.shrink().map(ClassBytes)),
Group { ref e, ref i, ref name } => {
let (i, name) = (i.clone(), name.clone());
Box::new(e.clone()
.shrink()
.chain(e.clone()
.shrink()
.map(move |e| {
Group {
e: Box::new(e),
i: i.clone(),
name: name.clone(),
}
})))
}
Repeat { ref e, ref r, greedy } => {
Box::new((*e.clone(), r.clone())
.shrink()
.filter(|&(ref e, _)| e.can_repeat())
.map(move |(e, r)| {
Repeat {
e: Box::new(e),
r: r,
greedy: greedy,
}
}))
}
// Concat(ref es) if es.len() <= 2 => nada(),
Concat(ref es) => {
Box::new(es.clone()
.shrink()
.filter(|es| es.len() > 0)
.map(|mut es| if es.len() == 1 {
es.pop().unwrap()
} else {
Concat(es)
}))
}
// Alternate(ref es) if es.len() <= 2 => nada(),
Alternate(ref es) => {
Box::new(es.clone()
.shrink()
.filter(|es| es.len() > 0)
.map(|mut es| if es.len() == 1 {
es.pop().unwrap()
} else {
Alternate(es)
}))
}
};
Box::new(es.map(|e| fix_capture_indices(e).simplify(200).unwrap()))
}
}
enum ExprType {
NoSequences, // disallow concat/alternate
Anything,
}
fn gen_expr<G: Gen>(g: &mut G, depth: u32, ty: ExprType) -> Expr {
use Expr::*;
let ub = match (depth as usize >= g.size(), ty) {
(true, _) => 16,
(false, ExprType::NoSequences) => 18,
(false, ExprType::Anything) => 20,
};
match g.gen_range(1, ub) {
0 => Empty,
1 => {
Literal {
chars: SmallAscii::arbitrary(g).0.chars().collect(),
casei: g.gen(),
}
}
2 => {
LiteralBytes {
bytes: SmallAscii::arbitrary(g).0.as_bytes().to_owned(),
casei: g.gen(),
}
}
3 => AnyChar,
4 => AnyCharNoNL,
5 => AnyByte,
6 => AnyByteNoNL,
7 => Class(CharClass::arbitrary(g)),
8 => StartLine,
9 => EndLine,
10 => StartText,
11 => EndText,
12 => WordBoundary,
13 => NotWordBoundary,
14 => WordBoundaryAscii,
15 => NotWordBoundaryAscii,
16 => gen_group_expr(g, depth + 1),
17 => {
Repeat {
e: Box::new(gen_repeatable_expr(g, depth + 1)),
r: Repeater::arbitrary(g),
greedy: bool::arbitrary(g),
}
}
18 => {
let size = {
let s = g.size();
g.gen_range(2, s)
};
Concat((0..size)
.map(|_| gen_expr(g, depth + 1, ExprType::NoSequences))
.collect())
}
19 => {
let size = {
let s = g.size();
g.gen_range(2, s)
};
Alternate((0..size)
.map(|_| gen_expr(g, depth + 1, ExprType::NoSequences))
.collect())
}
_ => unreachable!(),
}
}
fn gen_repeatable_expr<G: Gen>(g: &mut G, depth: u32) -> Expr {
use Expr::*;
match g.gen_range(1, 10) {
0 => Empty,
1 => {
Literal {
chars: vec![Arbitrary::arbitrary(g)],
casei: g.gen(),
}
}
2 => {
LiteralBytes {
bytes: vec![Arbitrary::arbitrary(g)],
casei: g.gen(),
}
}
3 => AnyChar,
4 => AnyCharNoNL,
5 => AnyByte,
6 => AnyByteNoNL,
7 => Class(CharClass::arbitrary(g)),
8 => ClassBytes(ByteClass::arbitrary(g)),
9 => gen_group_expr(g, depth + 1),
_ => unreachable!(),
}
}
fn gen_group_expr<G: Gen>(g: &mut G, depth: u32) -> Expr {
let (i, name) = if g.gen() {
(None, None)
} else {
(Some(0),
if g.gen() {
Some(SmallAscii::arbitrary(g).0)
} else {
None
})
};
Expr::Group {
e: Box::new(gen_expr(g, depth + 1, ExprType::Anything)),
i: i,
name: name,
}
}
fn fix_capture_indices(e: Expr) -> Expr {
fn bx(e: Expr) -> Box<Expr> {
Box::new(e)
}
fn fix(e: Expr, capi: &mut usize, names: &mut Vec<String>) -> Expr {
use Expr::*;
match e {
Group { e, i: Some(_), mut name } => {
*capi += 1;
let i = *capi;
let mut dupe_name = false;
if let Some(ref n1) = name {
if names.iter().any(|n2| n1 == n2) {
dupe_name = true;
} else {
names.push(n1.clone());
}
}
if dupe_name {
name = None;
}
Group {
e: bx(fix(*e, capi, names)),
i: Some(i),
name: name,
}
}
Group { e, i, name } => {
Group {
e: bx(fix(*e, capi, names)),
i: i,
name: name,
}
}
Repeat { e, r, greedy } => {
Repeat {
e: bx(fix(*e, capi, names)),
r: r,
greedy: greedy,
}
}
Concat(es) => Concat(es.into_iter().map(|e| fix(e, capi, names)).collect()),
Alternate(es) => Alternate(es.into_iter().map(|e| fix(e, capi, names)).collect()),
e => e,
}
}
fix(e, &mut 0, &mut vec![])
}
impl Arbitrary for Repeater {
fn arbitrary<G: Gen>(g: &mut G) -> Repeater {
use Repeater::*;
match g.gen_range(0, 4) {
0 => ZeroOrOne,
1 => ZeroOrMore,
2 => OneOrMore,
3 => {
use libtww::std::cmp::{max, min};
let n1 = Arbitrary::arbitrary(g);
let n2 = Arbitrary::arbitrary(g);
Range {
min: min(n1, n2),
max: if g.gen() {
None
} else {
Some(max(n1, n2))
},
}
}
_ => unreachable!(),
}
}
fn shrink(&self) -> Box<Iterator<Item = Repeater>> {
use Repeater::*;
match *self {
ZeroOrOne | ZeroOrMore | OneOrMore => Box::new(None.into_iter()),
Range { min, max } => {
Box::new((min, max)
.shrink()
.map(|(min, max)| {
Range {
min: min,
max: max,
}
}))
}
}
}
}
impl Arbitrary for CharClass {
fn arbitrary<G: Gen>(g: &mut G) -> CharClass {
let mut ranges: Vec<ClassRange> = Arbitrary::arbitrary(g);
if ranges.is_empty() {
ranges.push(Arbitrary::arbitrary(g));
}
let cls = CharClass { ranges: ranges }.canonicalize();
if g.gen() {
cls.case_fold()
} else {
cls
}
}
fn shrink(&self) -> Box<Iterator<Item = CharClass>> {
Box::new(self.ranges
.clone()
.shrink()
.filter(|ranges| ranges.len() > 0)
.map(|ranges| CharClass { ranges: ranges }.canonicalize()))
}
}
impl Arbitrary for ClassRange {
fn arbitrary<G: Gen>(g: &mut G) -> ClassRange {
use libtww::std::char::from_u32;
ClassRange::new(from_u32(g.gen_range(97, 123)).unwrap(),
from_u32(g.gen_range(97, 123)).unwrap())
}
fn shrink(&self) -> Box<Iterator<Item = ClassRange>> {
Box::new((self.start, self.end)
.shrink()
.map(|(s, e)| ClassRange::new(s, e)))
}
}
impl Arbitrary for ByteClass {
fn arbitrary<G: Gen>(g: &mut G) -> ByteClass {
let mut ranges: Vec<ByteRange> = Arbitrary::arbitrary(g);
if ranges.is_empty() {
ranges.push(Arbitrary::arbitrary(g));
}
let cls = ByteClass { ranges: ranges }.canonicalize();
if g.gen() {
cls.case_fold()
} else {
cls
}
}
fn shrink(&self) -> Box<Iterator<Item = ByteClass>> {
Box::new(self.ranges
.clone()
.shrink()
.filter(|ranges| ranges.len() > 0)
.map(|ranges| ByteClass { ranges: ranges }.canonicalize()))
}
}
impl Arbitrary for ByteRange {
fn arbitrary<G: Gen>(g: &mut G) -> ByteRange {
ByteRange::new(g.gen_range(97, 123), g.gen_range(97, 123))
}
fn shrink(&self) -> Box<Iterator<Item = ByteRange>> {
Box::new((self.start, self.end)
.shrink()
.map(|(s, e)| ByteRange::new(s, e)))
}
}
#[test]
fn display_regex_roundtrips() {
// Given an AST, if we print it as a regex and then re-parse it, do we
// get back the same AST?
// A lot of this relies crucially on regex simplification. So this is
// testing `Expr::simplify` as much as it is testing the `Display` impl.
fn prop(e: Expr) -> bool {
let parser = ExprBuilder::new().allow_bytes(true);
e == parser.parse(&e.to_string()).unwrap()
}
QuickCheck::new()
.tests(10_000)
.max_tests(20_000)
.gen(StdGen::new(::rand::thread_rng(), 50))
.quickcheck(prop as fn(Expr) -> bool);
}
| 31.380769 | 98 | 0.451097 |
f5a236ed9a0faac1c71921c21a6160a38ba59930
| 10,389 |
use ckb_chain_spec::consensus::ConsensusBuilder;
use ckb_chain_spec::consensus::TWO_IN_TWO_OUT_BYTES;
use ckb_crypto::secp::{Generator, Privkey, Pubkey, Signature};
use ckb_db::RocksDB;
use ckb_db_schema::COLUMNS;
use ckb_hash::{blake2b_256, new_blake2b};
use ckb_store::{data_loader_wrapper::DataLoaderWrapper, ChainDB};
use ckb_test_chain_utils::{
ckb_testnet_consensus, secp256k1_blake160_sighash_cell, secp256k1_data_cell,
type_lock_script_code_hash,
};
use ckb_types::{
core::{
capacity_bytes, cell::CellMetaBuilder, hardfork::HardForkSwitch, Capacity, Cycle, DepType,
EpochNumber, EpochNumberWithFraction, HeaderView, ScriptHashType, TransactionBuilder,
TransactionInfo,
},
h256,
packed::{
Byte32, CellDep, CellInput, OutPoint, Script, TransactionInfoBuilder,
TransactionKeyBuilder, WitnessArgs,
},
H256,
};
use faster_hex::hex_encode;
use std::{fs::File, path::Path};
use tempfile::TempDir;
use crate::verify::*;
pub(crate) const ALWAYS_SUCCESS_SCRIPT_CYCLE: u64 = 537;
pub(crate) const CYCLE_BOUND: Cycle = 200_000;
fn sha3_256<T: AsRef<[u8]>>(s: T) -> [u8; 32] {
use tiny_keccak::{Hasher, Sha3};
let mut output = [0; 32];
let mut sha3 = Sha3::v256();
sha3.update(s.as_ref());
sha3.finalize(&mut output);
output
}
pub(crate) fn open_cell_always_success() -> File {
File::open(Path::new(env!("CARGO_MANIFEST_DIR")).join("testdata/always_success")).unwrap()
}
pub(crate) fn open_cell_always_failure() -> File {
File::open(Path::new(env!("CARGO_MANIFEST_DIR")).join("testdata/always_failure")).unwrap()
}
pub(crate) fn random_keypair() -> (Privkey, Pubkey) {
Generator::random_keypair()
}
pub(crate) fn to_hex_pubkey(pubkey: &Pubkey) -> Vec<u8> {
let pubkey = pubkey.serialize();
let mut hex_pubkey = vec![0; pubkey.len() * 2];
hex_encode(&pubkey, &mut hex_pubkey).expect("hex pubkey");
hex_pubkey
}
pub(crate) fn to_hex_signature(signature: &Signature) -> Vec<u8> {
let signature_der = signature.serialize_der();
let mut hex_signature = vec![0; signature_der.len() * 2];
hex_encode(&signature_der, &mut hex_signature).expect("hex signature");
hex_signature
}
pub(crate) fn sign_args(args: &[u8], privkey: &Privkey) -> Signature {
let hash = sha3_256(sha3_256(args));
privkey.sign_recoverable(&hash.into()).unwrap()
}
pub(crate) fn default_transaction_info() -> TransactionInfo {
TransactionInfoBuilder::default()
.block_number(1u64.pack())
.block_epoch(0u64.pack())
.key(
TransactionKeyBuilder::default()
.block_hash(Byte32::zero())
.index(1u32.pack())
.build(),
)
.build()
.unpack()
}
pub(crate) struct TransactionScriptsVerifierWithEnv {
// The fields of a struct are dropped in declaration order.
// So, put `ChainDB` (`RocksDB`) before `TempDir`.
//
// Ref: https://doc.rust-lang.org/reference/destructors.html
store: ChainDB,
version_1_enabled_at: EpochNumber,
consensus: Consensus,
_tmp_dir: TempDir,
}
impl TransactionScriptsVerifierWithEnv {
pub(crate) fn new() -> Self {
let tmp_dir = TempDir::new().unwrap();
let db = RocksDB::open_in(&tmp_dir, COLUMNS);
let store = ChainDB::new(db, Default::default());
let version_1_enabled_at = 10;
let hardfork_switch = HardForkSwitch::new_without_any_enabled()
.as_builder()
.rfc_0032(version_1_enabled_at)
.build()
.unwrap();
let consensus = ConsensusBuilder::default()
.hardfork_switch(hardfork_switch)
.build();
Self {
store,
version_1_enabled_at,
consensus,
_tmp_dir: tmp_dir,
}
}
pub(crate) fn verify_without_limit(
&self,
version: ScriptVersion,
rtx: &ResolvedTransaction,
) -> Result<Cycle, Error> {
self.verify(version, rtx, u64::MAX)
}
// If the max cycles is meaningless, please use `verify_without_limit`,
// so reviewers or developers can understand the intentions easier.
pub(crate) fn verify(
&self,
version: ScriptVersion,
rtx: &ResolvedTransaction,
max_cycles: Cycle,
) -> Result<Cycle, Error> {
self.verify_map(version, rtx, |verifier| verifier.verify(max_cycles))
}
pub(crate) fn verify_map<R, F>(
&self,
version: ScriptVersion,
rtx: &ResolvedTransaction,
mut verify_func: F,
) -> R
where
F: FnMut(TransactionScriptsVerifier<'_, DataLoaderWrapper<'_, ChainDB>>) -> R,
{
let data_loader = DataLoaderWrapper::new(&self.store);
let epoch = match version {
ScriptVersion::V0 => EpochNumberWithFraction::new(0, 0, 1),
ScriptVersion::V1 => EpochNumberWithFraction::new(self.version_1_enabled_at, 0, 1),
};
let header = HeaderView::new_advanced_builder()
.epoch(epoch.pack())
.build();
let tx_env = TxVerifyEnv::new_commit(&header);
let verifier = TransactionScriptsVerifier::new(rtx, &self.consensus, &data_loader, &tx_env);
verify_func(verifier)
}
}
pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction {
let consensus = ckb_testnet_consensus();
let dep_group_tx_hash = consensus.genesis_block().transactions()[1].hash();
let secp_out_point = OutPoint::new(dep_group_tx_hash, 0);
let cell_dep = CellDep::new_builder()
.out_point(secp_out_point)
.dep_type(DepType::DepGroup.into())
.build();
let input1 = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 0), 0);
let input2 = CellInput::new(OutPoint::new(h256!("0x1111").pack(), 0), 0);
let mut generator = Generator::non_crypto_safe_prng(42);
let privkey = generator.gen_privkey();
let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize();
let lock_arg = Bytes::from((&blake2b_256(&pubkey_data)[0..20]).to_owned());
let privkey2 = generator.gen_privkey();
let pubkey_data2 = privkey2.pubkey().expect("Get pubkey failed").serialize();
let lock_arg2 = Bytes::from((&blake2b_256(&pubkey_data2)[0..20]).to_owned());
let lock = Script::new_builder()
.args(lock_arg.pack())
.code_hash(type_lock_script_code_hash().pack())
.hash_type(ScriptHashType::Type.into())
.build();
let lock2 = Script::new_builder()
.args(lock_arg2.pack())
.code_hash(type_lock_script_code_hash().pack())
.hash_type(ScriptHashType::Type.into())
.build();
let output1 = CellOutput::new_builder()
.capacity(capacity_bytes!(100).pack())
.lock(lock.clone())
.build();
let output2 = CellOutput::new_builder()
.capacity(capacity_bytes!(100).pack())
.lock(lock2.clone())
.build();
let tx = TransactionBuilder::default()
.cell_dep(cell_dep)
.input(input1.clone())
.input(input2.clone())
.output(output1)
.output(output2)
.output_data(Default::default())
.output_data(Default::default())
.build();
let tx_hash: H256 = tx.hash().unpack();
// sign input1
let witness = {
WitnessArgs::new_builder()
.lock(Some(Bytes::from(vec![0u8; 65])).pack())
.build()
};
let witness_len: u64 = witness.as_bytes().len() as u64;
let mut hasher = new_blake2b();
hasher.update(tx_hash.as_bytes());
hasher.update(&witness_len.to_le_bytes());
hasher.update(&witness.as_bytes());
let message = {
let mut buf = [0u8; 32];
hasher.finalize(&mut buf);
H256::from(buf)
};
let sig = privkey.sign_recoverable(&message).expect("sign");
let witness = WitnessArgs::new_builder()
.lock(Some(Bytes::from(sig.serialize())).pack())
.build();
// sign input2
let witness2 = WitnessArgs::new_builder()
.lock(Some(Bytes::from(vec![0u8; 65])).pack())
.build();
let witness2_len: u64 = witness2.as_bytes().len() as u64;
let mut hasher = new_blake2b();
hasher.update(tx_hash.as_bytes());
hasher.update(&witness2_len.to_le_bytes());
hasher.update(&witness2.as_bytes());
let message2 = {
let mut buf = [0u8; 32];
hasher.finalize(&mut buf);
H256::from(buf)
};
let sig2 = privkey2.sign_recoverable(&message2).expect("sign");
let witness2 = WitnessArgs::new_builder()
.lock(Some(Bytes::from(sig2.serialize())).pack())
.build();
let tx = tx
.as_advanced_builder()
.witness(witness.as_bytes().pack())
.witness(witness2.as_bytes().pack())
.build();
let serialized_size = tx.data().as_slice().len() as u64;
assert_eq!(
serialized_size, TWO_IN_TWO_OUT_BYTES,
"2 in 2 out tx serialized size changed, PLEASE UPDATE consensus"
);
let (secp256k1_blake160_cell, secp256k1_blake160_cell_data) =
secp256k1_blake160_sighash_cell(consensus.clone());
let (secp256k1_data_cell, secp256k1_data_cell_data) = secp256k1_data_cell(consensus);
let input_cell1 = CellOutput::new_builder()
.capacity(capacity_bytes!(100).pack())
.lock(lock)
.build();
let resolved_input_cell1 = CellMetaBuilder::from_cell_output(input_cell1, Default::default())
.out_point(input1.previous_output())
.build();
let input_cell2 = CellOutput::new_builder()
.capacity(capacity_bytes!(100).pack())
.lock(lock2)
.build();
let resolved_input_cell2 = CellMetaBuilder::from_cell_output(input_cell2, Default::default())
.out_point(input2.previous_output())
.build();
let resolved_secp256k1_blake160_cell =
CellMetaBuilder::from_cell_output(secp256k1_blake160_cell, secp256k1_blake160_cell_data)
.build();
let resolved_secp_data_cell =
CellMetaBuilder::from_cell_output(secp256k1_data_cell, secp256k1_data_cell_data).build();
ResolvedTransaction {
transaction: tx,
resolved_cell_deps: vec![resolved_secp256k1_blake160_cell, resolved_secp_data_cell],
resolved_inputs: vec![resolved_input_cell1, resolved_input_cell2],
resolved_dep_groups: vec![],
}
}
| 34.062295 | 100 | 0.642892 |
9c900f0726df67a03f5a07e41ef0b8eeac52918c
| 865 |
use std::{
fs::File,
io::{prelude::*, BufReader},
path::Path,
};
fn lines_from_file(filename: impl AsRef<Path>) -> Vec<i64> {
let file = File::open(filename).expect("no such file");
let buf = BufReader::new(file);
buf.lines()
.map(|line| line.unwrap().parse::<i64>().unwrap())
.collect()
}
pub fn run() {
println!("Day 01:");
let lines = lines_from_file("./src/day01/input");
// Part A
let mut res = 0;
let mut prev = -1;
for line in lines.iter() {
if *line > prev && prev != -1 {
res += 1;
}
prev = *line;
}
println!("{}", res);
// Part B
res = 0;
for i in 0..lines.len() - 3 {
if lines[i + 1] + lines[i + 2] + lines[i + 3] > lines[i] + lines[i + 1] + lines[i + 2] {
res += 1;
}
}
println!("{}", res);
}
| 22.179487 | 96 | 0.471676 |
1a3b2087822639d0876c43f0c81ed0381773c3df
| 290 |
// https://codeforces.com/problemset/problem/472/A
// simple math
use std::io;
fn main() {
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.unwrap();
let n: i64 = n.trim().parse().unwrap();
println!("{} {}", n%2+8, n-(n%2+8));
}
| 18.125 | 51 | 0.489655 |
deb74b5ee857dafae5d7750a91ebc5acc89c32e7
| 1,851 |
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use anyhow::{anyhow, Result};
use antidns::{Config, Server};
use trust_dns_resolver::{
config::{NameServerConfig, ResolverConfig},
proto::rr::{RData, Record},
TokioAsyncResolver,
};
async fn get_server() -> Result<(Server, TokioAsyncResolver)> {
let socket_port =
portpicker::pick_unused_port().ok_or_else(|| anyhow!("failed to pick port"))?;
let cfg = Config {
host_name: "dns.menmos.org".into(),
root_domain: "menmos.org".into(),
public_ip: IpAddr::from([127, 0, 0, 1]),
listen: SocketAddr::new(IpAddr::from([0, 0, 0, 0]), socket_port),
nb_of_concurrent_requests: 8,
};
let mut resolver_cfg = ResolverConfig::new();
resolver_cfg.add_name_server(NameServerConfig {
socket_addr: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), socket_port),
protocol: trust_dns_resolver::config::Protocol::Udp,
tls_dns_name: None,
trust_nx_responses: true,
});
let resolver = TokioAsyncResolver::tokio(resolver_cfg, Default::default())?;
Ok((Server::start(cfg), resolver))
}
#[tokio::test]
async fn dns_server_lifecycle() -> Result<()> {
let (server, _resolver) = get_server().await?;
server.stop().await?;
Ok(())
}
#[tokio::test]
async fn dns_resolution_of_magic_domain_names() -> Result<()> {
let (server, resolver) = get_server().await?;
let result: Vec<Record> = resolver
.lookup_ip("192-168-2-100.menmos.org")
.await?
.as_lookup()
.record_iter()
.cloned()
.collect();
assert_eq!(result.len(), 1);
if let RData::A(ip) = result[0].rdata() {
assert_eq!(ip, &Ipv4Addr::from([192, 168, 2, 100]));
} else {
return Err(anyhow!("missing A record"));
}
server.stop().await?;
Ok(())
}
| 28.045455 | 86 | 0.615343 |
fb50f94316e7a8710c891c64d713488e9e15b210
| 1,615 |
use log::{error, info};
use crate::dddk::aliases::Events;
use crate::dddk::command::command::Command;
use crate::dddk::command::command_bus::CommandBus;
pub struct CommandLoggingMiddleware {
command_bus: Box<dyn CommandBus>,
}
impl CommandLoggingMiddleware {
pub fn new(command_bus: Box<dyn CommandBus>) -> CommandLoggingMiddleware {
CommandLoggingMiddleware {
command_bus
}
}
}
impl CommandBus for CommandLoggingMiddleware {
fn dispatch<'b>(&self, command: &'b dyn Command) -> Events {
info!("Dispatching a command [{}] [{:?}].",
command.get_command_name(),
command);
let events = self.command_bus.dispatch(command);
if events.is_err() {
let error = events.err().unwrap();
let error_message = error.to_string();
error!(
"An error has occurred when dispatching command [{}] [{:?}]: {}",
command.get_command_name(),
command,
error_message
);
return Err(error);
}
let events = events.unwrap();
let mut event_names = String::new();
events.iter()
.for_each(|event| {
event_names.push_str(event.get_event_name().as_str());
event_names.push_str(" ");
});
info!(
"Command[{}] [{:?}] has been handled and has produced [{}] events [{}].",
command.get_command_name(),
command,
events.len(),
event_names
);
return Ok(events);
}
}
| 30.471698 | 85 | 0.543653 |
d6cef7aa53428caf5b8011d62506aa044a4c9574
| 1,107 |
//! Platform abstraction layer for Trusted Execution Environments
use std::fmt::Debug;
use std::path::Path;
pub trait ErrorType: Debug + Into<anyhow::Error> {}
impl<T: Debug + Into<anyhow::Error>> ErrorType for T {}
pub trait Sealing {
type SealError: ErrorType;
type UnsealError: ErrorType;
fn seal_data(&self, path: impl AsRef<Path>, data: &[u8]) -> Result<(), Self::SealError>;
fn unseal_data(&self, path: impl AsRef<Path>) -> Result<Option<Vec<u8>>, Self::UnsealError>;
}
pub trait RA {
type Error: ErrorType;
fn create_attestation_report(&self, data: &[u8]) -> Result<(String, String, String), Self::Error>;
}
pub struct MemoryUsage {
pub total_peak_used: usize,
pub rust_used: usize,
pub rust_peak_used: usize,
}
pub trait MemoryStats {
fn memory_usage(&self) -> MemoryUsage;
}
pub trait Machine {
fn machine_id(&self) -> Vec<u8>;
fn cpu_core_num(&self) -> u32;
fn cpu_feature_level(&self) -> u32;
}
pub trait Platform: Sealing + RA + Machine + MemoryStats + Clone {}
impl<T: Sealing + RA + Machine + MemoryStats + Clone> Platform for T {}
| 27.675 | 102 | 0.677507 |
f92798c889e57182e87e2dd9003425a2e0bd24a3
| 3,031 |
use std::sync::Arc;
use anyhow::Result;
use fixtures::RaftRouter;
use maplit::btreeset;
use openraft::raft::InstallSnapshotRequest;
use openraft::Config;
use openraft::LogId;
use openraft::SnapshotMeta;
use openraft::State;
#[macro_use]
mod fixtures;
/// API test: install_snapshot with various condition.
///
/// What does this test do?
///
/// - build a stable single node cluster.
/// - send install_snapshot request with matched/mismatched id and offset
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn snapshot_ge_half_threshold() -> Result<()> {
let (_log_guard, ut_span) = init_ut!();
let _ent = ut_span.enter();
let config = Arc::new(Config::default().validate()?);
let router = Arc::new(RaftRouter::new(config.clone()));
let mut n_logs = 0;
tracing::info!("--- initializing cluster");
{
router.new_raft_node(0).await;
router.wait_for_log(&btreeset![0], n_logs, None, "empty").await?;
router.wait_for_state(&btreeset![0], State::Learner, None, "empty").await?;
router.initialize_from_single_node(0).await?;
n_logs += 1;
router.wait_for_log(&btreeset![0], n_logs, None, "init leader").await?;
router.assert_stable_cluster(Some(1), Some(n_logs)).await;
}
let n = router.remove_node(0).await.ok_or_else(|| anyhow::anyhow!("node not found"))?;
let req0 = InstallSnapshotRequest {
term: 1,
leader_id: 0,
meta: SnapshotMeta {
snapshot_id: "ss1".into(),
last_log_id: LogId { term: 1, index: 0 },
},
offset: 0,
data: vec![1, 2, 3],
done: false,
};
tracing::info!("--- only allow to begin a new session when offset is 0");
{
let mut req = req0.clone();
req.offset = 2;
let res = n.0.install_snapshot(req).await;
assert_eq!("expect: ss1+0, got: ss1+2", res.unwrap_err().to_string());
}
tracing::info!("--- install and write ss1:[0,3)");
{
let req = req0.clone();
n.0.install_snapshot(req).await?;
}
tracing::info!("-- continue write with different id");
{
let mut req = req0.clone();
req.offset = 3;
req.meta.snapshot_id = "ss2".into();
let res = n.0.install_snapshot(req).await;
assert_eq!("expect: ss1+3, got: ss2+3", res.unwrap_err().to_string());
}
tracing::info!("-- write from offset=0 with different id, create a new session");
{
let mut req = req0.clone();
req.offset = 0;
req.meta.snapshot_id = "ss2".into();
n.0.install_snapshot(req).await?;
let mut req = req0.clone();
req.offset = 3;
req.meta.snapshot_id = "ss2".into();
n.0.install_snapshot(req).await?;
}
tracing::info!("-- continue write with mismatched offset is allowed");
{
let mut req = req0.clone();
req.offset = 8;
req.meta.snapshot_id = "ss2".into();
n.0.install_snapshot(req).await?;
}
Ok(())
}
| 29.427184 | 90 | 0.596173 |
032393b4f12534e3727808531de87e5bfd9a8999
| 55,563 |
// 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.
//! A Folder represents an AST->AST fold; it accepts an AST piece,
//! and returns a piece of the same type. So, for instance, macro
//! expansion is a Folder that walks over an AST and produces another
//! AST.
//!
//! Note: using a Folder (other than the MacroExpander Folder) on
//! an AST before macro expansion is probably a bad idea. For instance,
//! a folder renaming item names in a module will miss all of those
//! that are created by the expansion of a macro.
use ast::*;
use ast;
use syntax_pos::Span;
use source_map::{Spanned, respan};
use parse::token::{self, Token};
use ptr::P;
use OneVector;
use symbol::keywords;
use ThinVec;
use tokenstream::*;
use util::move_map::MoveMap;
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::small_vec::ExpectOne;
pub trait Folder : Sized {
// Any additions to this trait should happen in form
// of a call to a public `noop_*` function that only calls
// out to the folder again, not other `noop_*` functions.
//
// This is a necessary API workaround to the problem of not
// being able to call out to the super default method
// in an overridden default method.
fn fold_crate(&mut self, c: Crate) -> Crate {
noop_fold_crate(c, self)
}
fn fold_meta_items(&mut self, meta_items: Vec<MetaItem>) -> Vec<MetaItem> {
noop_fold_meta_items(meta_items, self)
}
fn fold_meta_list_item(&mut self, list_item: NestedMetaItem) -> NestedMetaItem {
noop_fold_meta_list_item(list_item, self)
}
fn fold_meta_item(&mut self, meta_item: MetaItem) -> MetaItem {
noop_fold_meta_item(meta_item, self)
}
fn fold_use_tree(&mut self, use_tree: UseTree) -> UseTree {
noop_fold_use_tree(use_tree, self)
}
fn fold_foreign_item(&mut self, ni: ForeignItem) -> OneVector<ForeignItem> {
noop_fold_foreign_item(ni, self)
}
fn fold_foreign_item_simple(&mut self, ni: ForeignItem) -> ForeignItem {
noop_fold_foreign_item_simple(ni, self)
}
fn fold_item(&mut self, i: P<Item>) -> OneVector<P<Item>> {
noop_fold_item(i, self)
}
fn fold_item_simple(&mut self, i: Item) -> Item {
noop_fold_item_simple(i, self)
}
fn fold_fn_header(&mut self, header: FnHeader) -> FnHeader {
noop_fold_fn_header(header, self)
}
fn fold_struct_field(&mut self, sf: StructField) -> StructField {
noop_fold_struct_field(sf, self)
}
fn fold_item_kind(&mut self, i: ItemKind) -> ItemKind {
noop_fold_item_kind(i, self)
}
fn fold_trait_item(&mut self, i: TraitItem) -> OneVector<TraitItem> {
noop_fold_trait_item(i, self)
}
fn fold_impl_item(&mut self, i: ImplItem) -> OneVector<ImplItem> {
noop_fold_impl_item(i, self)
}
fn fold_fn_decl(&mut self, d: P<FnDecl>) -> P<FnDecl> {
noop_fold_fn_decl(d, self)
}
fn fold_asyncness(&mut self, a: IsAsync) -> IsAsync {
noop_fold_asyncness(a, self)
}
fn fold_block(&mut self, b: P<Block>) -> P<Block> {
noop_fold_block(b, self)
}
fn fold_stmt(&mut self, s: Stmt) -> OneVector<Stmt> {
noop_fold_stmt(s, self)
}
fn fold_arm(&mut self, a: Arm) -> Arm {
noop_fold_arm(a, self)
}
fn fold_guard(&mut self, g: Guard) -> Guard {
noop_fold_guard(g, self)
}
fn fold_pat(&mut self, p: P<Pat>) -> P<Pat> {
noop_fold_pat(p, self)
}
fn fold_anon_const(&mut self, c: AnonConst) -> AnonConst {
noop_fold_anon_const(c, self)
}
fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
e.map(|e| noop_fold_expr(e, self))
}
fn fold_range_end(&mut self, re: RangeEnd) -> RangeEnd {
noop_fold_range_end(re, self)
}
fn fold_opt_expr(&mut self, e: P<Expr>) -> Option<P<Expr>> {
noop_fold_opt_expr(e, self)
}
fn fold_exprs(&mut self, es: Vec<P<Expr>>) -> Vec<P<Expr>> {
noop_fold_exprs(es, self)
}
fn fold_generic_arg(&mut self, arg: GenericArg) -> GenericArg {
match arg {
GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.fold_lifetime(lt)),
GenericArg::Type(ty) => GenericArg::Type(self.fold_ty(ty)),
}
}
fn fold_ty(&mut self, t: P<Ty>) -> P<Ty> {
noop_fold_ty(t, self)
}
fn fold_lifetime(&mut self, l: Lifetime) -> Lifetime {
noop_fold_lifetime(l, self)
}
fn fold_ty_binding(&mut self, t: TypeBinding) -> TypeBinding {
noop_fold_ty_binding(t, self)
}
fn fold_mod(&mut self, m: Mod) -> Mod {
noop_fold_mod(m, self)
}
fn fold_foreign_mod(&mut self, nm: ForeignMod) -> ForeignMod {
noop_fold_foreign_mod(nm, self)
}
fn fold_global_asm(&mut self, ga: P<GlobalAsm>) -> P<GlobalAsm> {
noop_fold_global_asm(ga, self)
}
fn fold_variant(&mut self, v: Variant) -> Variant {
noop_fold_variant(v, self)
}
fn fold_ident(&mut self, i: Ident) -> Ident {
noop_fold_ident(i, self)
}
fn fold_usize(&mut self, i: usize) -> usize {
noop_fold_usize(i, self)
}
fn fold_path(&mut self, p: Path) -> Path {
noop_fold_path(p, self)
}
fn fold_qpath(&mut self, qs: Option<QSelf>, p: Path) -> (Option<QSelf>, Path) {
noop_fold_qpath(qs, p, self)
}
fn fold_generic_args(&mut self, p: GenericArgs) -> GenericArgs {
noop_fold_generic_args(p, self)
}
fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedArgs)
-> AngleBracketedArgs
{
noop_fold_angle_bracketed_parameter_data(p, self)
}
fn fold_parenthesized_parameter_data(&mut self, p: ParenthesisedArgs)
-> ParenthesisedArgs
{
noop_fold_parenthesized_parameter_data(p, self)
}
fn fold_local(&mut self, l: P<Local>) -> P<Local> {
noop_fold_local(l, self)
}
fn fold_mac(&mut self, _mac: Mac) -> Mac {
panic!("fold_mac disabled by default");
// NB: see note about macros above.
// if you really want a folder that
// works on macros, use this
// definition in your trait impl:
// fold::noop_fold_mac(_mac, self)
}
fn fold_macro_def(&mut self, def: MacroDef) -> MacroDef {
noop_fold_macro_def(def, self)
}
fn fold_label(&mut self, label: Label) -> Label {
noop_fold_label(label, self)
}
fn fold_attribute(&mut self, at: Attribute) -> Option<Attribute> {
noop_fold_attribute(at, self)
}
fn fold_arg(&mut self, a: Arg) -> Arg {
noop_fold_arg(a, self)
}
fn fold_generics(&mut self, generics: Generics) -> Generics {
noop_fold_generics(generics, self)
}
fn fold_trait_ref(&mut self, p: TraitRef) -> TraitRef {
noop_fold_trait_ref(p, self)
}
fn fold_poly_trait_ref(&mut self, p: PolyTraitRef) -> PolyTraitRef {
noop_fold_poly_trait_ref(p, self)
}
fn fold_variant_data(&mut self, vdata: VariantData) -> VariantData {
noop_fold_variant_data(vdata, self)
}
fn fold_generic_param(&mut self, param: GenericParam) -> GenericParam {
noop_fold_generic_param(param, self)
}
fn fold_generic_params(&mut self, params: Vec<GenericParam>) -> Vec<GenericParam> {
noop_fold_generic_params(params, self)
}
fn fold_tt(&mut self, tt: TokenTree) -> TokenTree {
noop_fold_tt(tt, self)
}
fn fold_tts(&mut self, tts: TokenStream) -> TokenStream {
noop_fold_tts(tts, self)
}
fn fold_token(&mut self, t: token::Token) -> token::Token {
noop_fold_token(t, self)
}
fn fold_interpolated(&mut self, nt: token::Nonterminal) -> token::Nonterminal {
noop_fold_interpolated(nt, self)
}
fn fold_opt_bounds(&mut self, b: Option<GenericBounds>) -> Option<GenericBounds> {
noop_fold_opt_bounds(b, self)
}
fn fold_bounds(&mut self, b: GenericBounds) -> GenericBounds {
noop_fold_bounds(b, self)
}
fn fold_param_bound(&mut self, tpb: GenericBound) -> GenericBound {
noop_fold_param_bound(tpb, self)
}
fn fold_mt(&mut self, mt: MutTy) -> MutTy {
noop_fold_mt(mt, self)
}
fn fold_field(&mut self, field: Field) -> Field {
noop_fold_field(field, self)
}
fn fold_where_clause(&mut self, where_clause: WhereClause)
-> WhereClause {
noop_fold_where_clause(where_clause, self)
}
fn fold_where_predicate(&mut self, where_predicate: WherePredicate)
-> WherePredicate {
noop_fold_where_predicate(where_predicate, self)
}
fn fold_vis(&mut self, vis: Visibility) -> Visibility {
noop_fold_vis(vis, self)
}
fn new_id(&mut self, i: NodeId) -> NodeId {
i
}
fn new_span(&mut self, sp: Span) -> Span {
sp
}
}
pub fn noop_fold_meta_items<T: Folder>(meta_items: Vec<MetaItem>, fld: &mut T) -> Vec<MetaItem> {
meta_items.move_map(|x| fld.fold_meta_item(x))
}
pub fn noop_fold_use_tree<T: Folder>(use_tree: UseTree, fld: &mut T) -> UseTree {
UseTree {
span: fld.new_span(use_tree.span),
prefix: fld.fold_path(use_tree.prefix),
kind: match use_tree.kind {
UseTreeKind::Simple(rename, id1, id2) =>
UseTreeKind::Simple(rename.map(|ident| fld.fold_ident(ident)),
fld.new_id(id1), fld.new_id(id2)),
UseTreeKind::Glob => UseTreeKind::Glob,
UseTreeKind::Nested(items) => UseTreeKind::Nested(items.move_map(|(tree, id)| {
(fld.fold_use_tree(tree), fld.new_id(id))
})),
},
}
}
pub fn fold_attrs<T: Folder>(attrs: Vec<Attribute>, fld: &mut T) -> Vec<Attribute> {
attrs.move_flat_map(|x| fld.fold_attribute(x))
}
pub fn fold_thin_attrs<T: Folder>(attrs: ThinVec<Attribute>, fld: &mut T) -> ThinVec<Attribute> {
fold_attrs(attrs.into(), fld).into()
}
pub fn noop_fold_arm<T: Folder>(Arm {attrs, pats, guard, body}: Arm,
fld: &mut T) -> Arm {
Arm {
attrs: fold_attrs(attrs, fld),
pats: pats.move_map(|x| fld.fold_pat(x)),
guard: guard.map(|x| fld.fold_guard(x)),
body: fld.fold_expr(body),
}
}
pub fn noop_fold_guard<T: Folder>(g: Guard, fld: &mut T) -> Guard {
match g {
Guard::If(e) => Guard::If(fld.fold_expr(e)),
}
}
pub fn noop_fold_ty_binding<T: Folder>(b: TypeBinding, fld: &mut T) -> TypeBinding {
TypeBinding {
id: fld.new_id(b.id),
ident: fld.fold_ident(b.ident),
ty: fld.fold_ty(b.ty),
span: fld.new_span(b.span),
}
}
pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> {
t.map(|Ty {id, node, span}| Ty {
id: fld.new_id(id),
node: match node {
TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err => node,
TyKind::Slice(ty) => TyKind::Slice(fld.fold_ty(ty)),
TyKind::Ptr(mt) => TyKind::Ptr(fld.fold_mt(mt)),
TyKind::Rptr(region, mt) => {
TyKind::Rptr(region.map(|lt| noop_fold_lifetime(lt, fld)), fld.fold_mt(mt))
}
TyKind::BareFn(f) => {
TyKind::BareFn(f.map(|BareFnTy {generic_params, unsafety, abi, decl}| BareFnTy {
generic_params: fld.fold_generic_params(generic_params),
unsafety,
abi,
decl: fld.fold_fn_decl(decl)
}))
}
TyKind::Never => node,
TyKind::Tup(tys) => TyKind::Tup(tys.move_map(|ty| fld.fold_ty(ty))),
TyKind::Paren(ty) => TyKind::Paren(fld.fold_ty(ty)),
TyKind::Path(qself, path) => {
let (qself, path) = fld.fold_qpath(qself, path);
TyKind::Path(qself, path)
}
TyKind::Array(ty, length) => {
TyKind::Array(fld.fold_ty(ty), fld.fold_anon_const(length))
}
TyKind::Typeof(expr) => {
TyKind::Typeof(fld.fold_anon_const(expr))
}
TyKind::TraitObject(bounds, syntax) => {
TyKind::TraitObject(bounds.move_map(|b| fld.fold_param_bound(b)), syntax)
}
TyKind::ImplTrait(id, bounds) => {
TyKind::ImplTrait(fld.new_id(id), bounds.move_map(|b| fld.fold_param_bound(b)))
}
TyKind::Mac(mac) => {
TyKind::Mac(fld.fold_mac(mac))
}
},
span: fld.new_span(span)
})
}
pub fn noop_fold_foreign_mod<T: Folder>(ForeignMod {abi, items}: ForeignMod,
fld: &mut T) -> ForeignMod {
ForeignMod {
abi,
items: items.move_flat_map(|x| fld.fold_foreign_item(x)),
}
}
pub fn noop_fold_global_asm<T: Folder>(ga: P<GlobalAsm>,
_: &mut T) -> P<GlobalAsm> {
ga
}
pub fn noop_fold_variant<T: Folder>(v: Variant, fld: &mut T) -> Variant {
Spanned {
node: Variant_ {
ident: fld.fold_ident(v.node.ident),
attrs: fold_attrs(v.node.attrs, fld),
data: fld.fold_variant_data(v.node.data),
disr_expr: v.node.disr_expr.map(|e| fld.fold_anon_const(e)),
},
span: fld.new_span(v.span),
}
}
pub fn noop_fold_ident<T: Folder>(ident: Ident, fld: &mut T) -> Ident {
Ident::new(ident.name, fld.new_span(ident.span))
}
pub fn noop_fold_usize<T: Folder>(i: usize, _: &mut T) -> usize {
i
}
pub fn noop_fold_path<T: Folder>(Path { segments, span }: Path, fld: &mut T) -> Path {
Path {
segments: segments.move_map(|PathSegment { ident, args }| PathSegment {
ident: fld.fold_ident(ident),
args: args.map(|args| args.map(|args| fld.fold_generic_args(args))),
}),
span: fld.new_span(span)
}
}
pub fn noop_fold_qpath<T: Folder>(qself: Option<QSelf>,
path: Path,
fld: &mut T) -> (Option<QSelf>, Path) {
let qself = qself.map(|QSelf { ty, path_span, position }| {
QSelf {
ty: fld.fold_ty(ty),
path_span: fld.new_span(path_span),
position,
}
});
(qself, fld.fold_path(path))
}
pub fn noop_fold_generic_args<T: Folder>(generic_args: GenericArgs, fld: &mut T) -> GenericArgs
{
match generic_args {
GenericArgs::AngleBracketed(data) => {
GenericArgs::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data))
}
GenericArgs::Parenthesized(data) => {
GenericArgs::Parenthesized(fld.fold_parenthesized_parameter_data(data))
}
}
}
pub fn noop_fold_angle_bracketed_parameter_data<T: Folder>(data: AngleBracketedArgs,
fld: &mut T)
-> AngleBracketedArgs
{
let AngleBracketedArgs { args, bindings, span } = data;
AngleBracketedArgs {
args: args.move_map(|arg| fld.fold_generic_arg(arg)),
bindings: bindings.move_map(|b| fld.fold_ty_binding(b)),
span: fld.new_span(span)
}
}
pub fn noop_fold_parenthesized_parameter_data<T: Folder>(data: ParenthesisedArgs,
fld: &mut T)
-> ParenthesisedArgs
{
let ParenthesisedArgs { inputs, output, span } = data;
ParenthesisedArgs {
inputs: inputs.move_map(|ty| fld.fold_ty(ty)),
output: output.map(|ty| fld.fold_ty(ty)),
span: fld.new_span(span)
}
}
pub fn noop_fold_local<T: Folder>(l: P<Local>, fld: &mut T) -> P<Local> {
l.map(|Local {id, pat, ty, init, span, attrs}| Local {
id: fld.new_id(id),
pat: fld.fold_pat(pat),
ty: ty.map(|t| fld.fold_ty(t)),
init: init.map(|e| fld.fold_expr(e)),
span: fld.new_span(span),
attrs: fold_attrs(attrs.into(), fld).into(),
})
}
pub fn noop_fold_attribute<T: Folder>(attr: Attribute, fld: &mut T) -> Option<Attribute> {
Some(Attribute {
id: attr.id,
style: attr.style,
path: fld.fold_path(attr.path),
tokens: fld.fold_tts(attr.tokens),
is_sugared_doc: attr.is_sugared_doc,
span: fld.new_span(attr.span),
})
}
pub fn noop_fold_mac<T: Folder>(Spanned {node, span}: Mac, fld: &mut T) -> Mac {
Spanned {
node: Mac_ {
tts: fld.fold_tts(node.stream()).into(),
path: fld.fold_path(node.path),
delim: node.delim,
},
span: fld.new_span(span)
}
}
pub fn noop_fold_macro_def<T: Folder>(def: MacroDef, fld: &mut T) -> MacroDef {
MacroDef {
tokens: fld.fold_tts(def.tokens.into()).into(),
legacy: def.legacy,
}
}
pub fn noop_fold_meta_list_item<T: Folder>(li: NestedMetaItem, fld: &mut T)
-> NestedMetaItem {
Spanned {
node: match li.node {
NestedMetaItemKind::MetaItem(mi) => {
NestedMetaItemKind::MetaItem(fld.fold_meta_item(mi))
},
NestedMetaItemKind::Literal(lit) => NestedMetaItemKind::Literal(lit)
},
span: fld.new_span(li.span)
}
}
pub fn noop_fold_meta_item<T: Folder>(mi: MetaItem, fld: &mut T) -> MetaItem {
MetaItem {
ident: mi.ident,
node: match mi.node {
MetaItemKind::Word => MetaItemKind::Word,
MetaItemKind::List(mis) => {
MetaItemKind::List(mis.move_map(|e| fld.fold_meta_list_item(e)))
},
MetaItemKind::NameValue(s) => MetaItemKind::NameValue(s),
},
span: fld.new_span(mi.span)
}
}
pub fn noop_fold_arg<T: Folder>(Arg {id, pat, ty}: Arg, fld: &mut T) -> Arg {
Arg {
id: fld.new_id(id),
pat: fld.fold_pat(pat),
ty: fld.fold_ty(ty)
}
}
pub fn noop_fold_tt<T: Folder>(tt: TokenTree, fld: &mut T) -> TokenTree {
match tt {
TokenTree::Token(span, tok) =>
TokenTree::Token(fld.new_span(span), fld.fold_token(tok)),
TokenTree::Delimited(span, delimed) => TokenTree::Delimited(
DelimSpan::from_pair(fld.new_span(span.open), fld.new_span(span.close)),
Delimited {
tts: fld.fold_tts(delimed.stream()).into(),
delim: delimed.delim,
}
),
}
}
pub fn noop_fold_tts<T: Folder>(tts: TokenStream, fld: &mut T) -> TokenStream {
tts.map(|tt| fld.fold_tt(tt))
}
// apply ident folder if it's an ident, apply other folds to interpolated nodes
pub fn noop_fold_token<T: Folder>(t: token::Token, fld: &mut T) -> token::Token {
match t {
token::Ident(id, is_raw) => token::Ident(fld.fold_ident(id), is_raw),
token::Lifetime(id) => token::Lifetime(fld.fold_ident(id)),
token::Interpolated(nt) => {
let nt = match Lrc::try_unwrap(nt) {
Ok(nt) => nt,
Err(nt) => (*nt).clone(),
};
Token::interpolated(fld.fold_interpolated(nt.0))
}
_ => t
}
}
/// apply folder to elements of interpolated nodes
//
// NB: this can occur only when applying a fold to partially expanded code, where
// parsed pieces have gotten implanted ito *other* macro invocations. This is relevant
// for macro hygiene, but possibly not elsewhere.
//
// One problem here occurs because the types for fold_item, fold_stmt, etc. allow the
// folder to return *multiple* items; this is a problem for the nodes here, because
// they insist on having exactly one piece. One solution would be to mangle the fold
// trait to include one-to-many and one-to-one versions of these entry points, but that
// would probably confuse a lot of people and help very few. Instead, I'm just going
// to put in dynamic checks. I think the performance impact of this will be pretty much
// nonexistent. The danger is that someone will apply a fold to a partially expanded
// node, and will be confused by the fact that their "fold_item" or "fold_stmt" isn't
// getting called on NtItem or NtStmt nodes. Hopefully they'll wind up reading this
// comment, and doing something appropriate.
//
// BTW, design choice: I considered just changing the type of, e.g., NtItem to contain
// multiple items, but decided against it when I looked at parse_item_or_view_item and
// tried to figure out what I would do with multiple items there....
pub fn noop_fold_interpolated<T: Folder>(nt: token::Nonterminal, fld: &mut T)
-> token::Nonterminal {
match nt {
token::NtItem(item) =>
token::NtItem(fld.fold_item(item)
// this is probably okay, because the only folds likely
// to peek inside interpolated nodes will be renamings/markings,
// which map single items to single items
.expect_one("expected fold to produce exactly one item")),
token::NtBlock(block) => token::NtBlock(fld.fold_block(block)),
token::NtStmt(stmt) =>
token::NtStmt(fld.fold_stmt(stmt)
// this is probably okay, because the only folds likely
// to peek inside interpolated nodes will be renamings/markings,
// which map single items to single items
.expect_one("expected fold to produce exactly one statement")),
token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)),
token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)),
token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)),
token::NtIdent(ident, is_raw) => token::NtIdent(fld.fold_ident(ident), is_raw),
token::NtLifetime(ident) => token::NtLifetime(fld.fold_ident(ident)),
token::NtLiteral(expr) => token::NtLiteral(fld.fold_expr(expr)),
token::NtMeta(meta) => token::NtMeta(fld.fold_meta_item(meta)),
token::NtPath(path) => token::NtPath(fld.fold_path(path)),
token::NtTT(tt) => token::NtTT(fld.fold_tt(tt)),
token::NtArm(arm) => token::NtArm(fld.fold_arm(arm)),
token::NtImplItem(item) =>
token::NtImplItem(fld.fold_impl_item(item)
.expect_one("expected fold to produce exactly one item")),
token::NtTraitItem(item) =>
token::NtTraitItem(fld.fold_trait_item(item)
.expect_one("expected fold to produce exactly one item")),
token::NtGenerics(generics) => token::NtGenerics(fld.fold_generics(generics)),
token::NtWhereClause(where_clause) =>
token::NtWhereClause(fld.fold_where_clause(where_clause)),
token::NtArg(arg) => token::NtArg(fld.fold_arg(arg)),
token::NtVis(vis) => token::NtVis(fld.fold_vis(vis)),
token::NtForeignItem(ni) =>
token::NtForeignItem(fld.fold_foreign_item(ni)
// see reasoning above
.expect_one("expected fold to produce exactly one item")),
}
}
pub fn noop_fold_asyncness<T: Folder>(asyncness: IsAsync, fld: &mut T) -> IsAsync {
match asyncness {
IsAsync::Async { closure_id, return_impl_trait_id } => IsAsync::Async {
closure_id: fld.new_id(closure_id),
return_impl_trait_id: fld.new_id(return_impl_trait_id),
},
IsAsync::NotAsync => IsAsync::NotAsync,
}
}
pub fn noop_fold_fn_decl<T: Folder>(decl: P<FnDecl>, fld: &mut T) -> P<FnDecl> {
decl.map(|FnDecl {inputs, output, variadic}| FnDecl {
inputs: inputs.move_map(|x| fld.fold_arg(x)),
output: match output {
FunctionRetTy::Ty(ty) => FunctionRetTy::Ty(fld.fold_ty(ty)),
FunctionRetTy::Default(span) => FunctionRetTy::Default(fld.new_span(span)),
},
variadic,
})
}
pub fn noop_fold_param_bound<T>(pb: GenericBound, fld: &mut T) -> GenericBound where T: Folder {
match pb {
GenericBound::Trait(ty, modifier) => {
GenericBound::Trait(fld.fold_poly_trait_ref(ty), modifier)
}
GenericBound::Outlives(lifetime) => {
GenericBound::Outlives(noop_fold_lifetime(lifetime, fld))
}
}
}
pub fn noop_fold_generic_param<T: Folder>(param: GenericParam, fld: &mut T) -> GenericParam {
let attrs: Vec<_> = param.attrs.into();
GenericParam {
ident: fld.fold_ident(param.ident),
id: fld.new_id(param.id),
attrs: attrs.into_iter()
.flat_map(|x| fld.fold_attribute(x).into_iter())
.collect::<Vec<_>>()
.into(),
bounds: param.bounds.move_map(|l| noop_fold_param_bound(l, fld)),
kind: match param.kind {
GenericParamKind::Lifetime => GenericParamKind::Lifetime,
GenericParamKind::Type { default } => GenericParamKind::Type {
default: default.map(|ty| fld.fold_ty(ty))
}
}
}
}
pub fn noop_fold_generic_params<T: Folder>(
params: Vec<GenericParam>,
fld: &mut T
) -> Vec<GenericParam> {
params.move_map(|p| fld.fold_generic_param(p))
}
pub fn noop_fold_label<T: Folder>(label: Label, fld: &mut T) -> Label {
Label {
ident: fld.fold_ident(label.ident),
}
}
fn noop_fold_lifetime<T: Folder>(l: Lifetime, fld: &mut T) -> Lifetime {
Lifetime {
id: fld.new_id(l.id),
ident: fld.fold_ident(l.ident),
}
}
pub fn noop_fold_generics<T: Folder>(Generics { params, where_clause, span }: Generics,
fld: &mut T) -> Generics {
Generics {
params: fld.fold_generic_params(params),
where_clause: fld.fold_where_clause(where_clause),
span: fld.new_span(span),
}
}
pub fn noop_fold_where_clause<T: Folder>(
WhereClause {id, predicates, span}: WhereClause,
fld: &mut T)
-> WhereClause {
WhereClause {
id: fld.new_id(id),
predicates: predicates.move_map(|predicate| {
fld.fold_where_predicate(predicate)
}),
span,
}
}
pub fn noop_fold_where_predicate<T: Folder>(
pred: WherePredicate,
fld: &mut T)
-> WherePredicate {
match pred {
ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{bound_generic_params,
bounded_ty,
bounds,
span}) => {
ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
bound_generic_params: fld.fold_generic_params(bound_generic_params),
bounded_ty: fld.fold_ty(bounded_ty),
bounds: bounds.move_map(|x| fld.fold_param_bound(x)),
span: fld.new_span(span)
})
}
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{lifetime,
bounds,
span}) => {
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
span: fld.new_span(span),
lifetime: noop_fold_lifetime(lifetime, fld),
bounds: bounds.move_map(|bound| noop_fold_param_bound(bound, fld))
})
}
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{id,
lhs_ty,
rhs_ty,
span}) => {
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{
id: fld.new_id(id),
lhs_ty: fld.fold_ty(lhs_ty),
rhs_ty: fld.fold_ty(rhs_ty),
span: fld.new_span(span)
})
}
}
}
pub fn noop_fold_variant_data<T: Folder>(vdata: VariantData, fld: &mut T) -> VariantData {
match vdata {
ast::VariantData::Struct(fields, id) => {
ast::VariantData::Struct(fields.move_map(|f| fld.fold_struct_field(f)),
fld.new_id(id))
}
ast::VariantData::Tuple(fields, id) => {
ast::VariantData::Tuple(fields.move_map(|f| fld.fold_struct_field(f)),
fld.new_id(id))
}
ast::VariantData::Unit(id) => ast::VariantData::Unit(fld.new_id(id))
}
}
pub fn noop_fold_trait_ref<T: Folder>(p: TraitRef, fld: &mut T) -> TraitRef {
let id = fld.new_id(p.ref_id);
let TraitRef {
path,
ref_id: _,
} = p;
ast::TraitRef {
path: fld.fold_path(path),
ref_id: id,
}
}
pub fn noop_fold_poly_trait_ref<T: Folder>(p: PolyTraitRef, fld: &mut T) -> PolyTraitRef {
ast::PolyTraitRef {
bound_generic_params: fld.fold_generic_params(p.bound_generic_params),
trait_ref: fld.fold_trait_ref(p.trait_ref),
span: fld.new_span(p.span),
}
}
pub fn noop_fold_struct_field<T: Folder>(f: StructField, fld: &mut T) -> StructField {
StructField {
span: fld.new_span(f.span),
id: fld.new_id(f.id),
ident: f.ident.map(|ident| fld.fold_ident(ident)),
vis: fld.fold_vis(f.vis),
ty: fld.fold_ty(f.ty),
attrs: fold_attrs(f.attrs, fld),
}
}
pub fn noop_fold_field<T: Folder>(f: Field, folder: &mut T) -> Field {
Field {
ident: folder.fold_ident(f.ident),
expr: folder.fold_expr(f.expr),
span: folder.new_span(f.span),
is_shorthand: f.is_shorthand,
attrs: fold_thin_attrs(f.attrs, folder),
}
}
pub fn noop_fold_mt<T: Folder>(MutTy {ty, mutbl}: MutTy, folder: &mut T) -> MutTy {
MutTy {
ty: folder.fold_ty(ty),
mutbl,
}
}
pub fn noop_fold_opt_bounds<T: Folder>(b: Option<GenericBounds>, folder: &mut T)
-> Option<GenericBounds> {
b.map(|bounds| folder.fold_bounds(bounds))
}
fn noop_fold_bounds<T: Folder>(bounds: GenericBounds, folder: &mut T)
-> GenericBounds {
bounds.move_map(|bound| folder.fold_param_bound(bound))
}
pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> {
b.map(|Block {id, stmts, rules, span, recovered}| Block {
id: folder.new_id(id),
stmts: stmts.move_flat_map(|s| folder.fold_stmt(s).into_iter()),
rules,
span: folder.new_span(span),
recovered,
})
}
pub fn noop_fold_item_kind<T: Folder>(i: ItemKind, folder: &mut T) -> ItemKind {
match i {
ItemKind::ExternCrate(orig_name) => ItemKind::ExternCrate(orig_name),
ItemKind::Use(use_tree) => {
ItemKind::Use(use_tree.map(|tree| folder.fold_use_tree(tree)))
}
ItemKind::Static(t, m, e) => {
ItemKind::Static(folder.fold_ty(t), m, folder.fold_expr(e))
}
ItemKind::Const(t, e) => {
ItemKind::Const(folder.fold_ty(t), folder.fold_expr(e))
}
ItemKind::Fn(decl, header, generics, body) => {
let generics = folder.fold_generics(generics);
let header = folder.fold_fn_header(header);
let decl = folder.fold_fn_decl(decl);
let body = folder.fold_block(body);
ItemKind::Fn(decl, header, generics, body)
}
ItemKind::Mod(m) => ItemKind::Mod(folder.fold_mod(m)),
ItemKind::ForeignMod(nm) => ItemKind::ForeignMod(folder.fold_foreign_mod(nm)),
ItemKind::GlobalAsm(ga) => ItemKind::GlobalAsm(folder.fold_global_asm(ga)),
ItemKind::Ty(t, generics) => {
ItemKind::Ty(folder.fold_ty(t), folder.fold_generics(generics))
}
ItemKind::Existential(bounds, generics) => ItemKind::Existential(
folder.fold_bounds(bounds),
folder.fold_generics(generics),
),
ItemKind::Enum(enum_definition, generics) => {
let generics = folder.fold_generics(generics);
let variants = enum_definition.variants.move_map(|x| folder.fold_variant(x));
ItemKind::Enum(ast::EnumDef { variants: variants }, generics)
}
ItemKind::Struct(struct_def, generics) => {
let generics = folder.fold_generics(generics);
ItemKind::Struct(folder.fold_variant_data(struct_def), generics)
}
ItemKind::Union(struct_def, generics) => {
let generics = folder.fold_generics(generics);
ItemKind::Union(folder.fold_variant_data(struct_def), generics)
}
ItemKind::Impl(unsafety,
polarity,
defaultness,
generics,
ifce,
ty,
impl_items) => ItemKind::Impl(
unsafety,
polarity,
defaultness,
folder.fold_generics(generics),
ifce.map(|trait_ref| folder.fold_trait_ref(trait_ref.clone())),
folder.fold_ty(ty),
impl_items.move_flat_map(|item| folder.fold_impl_item(item)),
),
ItemKind::Trait(is_auto, unsafety, generics, bounds, items) => ItemKind::Trait(
is_auto,
unsafety,
folder.fold_generics(generics),
folder.fold_bounds(bounds),
items.move_flat_map(|item| folder.fold_trait_item(item)),
),
ItemKind::TraitAlias(generics, bounds) => ItemKind::TraitAlias(
folder.fold_generics(generics),
folder.fold_bounds(bounds)),
ItemKind::Mac(m) => ItemKind::Mac(folder.fold_mac(m)),
ItemKind::MacroDef(def) => ItemKind::MacroDef(folder.fold_macro_def(def)),
}
}
pub fn noop_fold_trait_item<T: Folder>(i: TraitItem, folder: &mut T)
-> OneVector<TraitItem> {
smallvec![TraitItem {
id: folder.new_id(i.id),
ident: folder.fold_ident(i.ident),
attrs: fold_attrs(i.attrs, folder),
generics: folder.fold_generics(i.generics),
node: match i.node {
TraitItemKind::Const(ty, default) => {
TraitItemKind::Const(folder.fold_ty(ty),
default.map(|x| folder.fold_expr(x)))
}
TraitItemKind::Method(sig, body) => {
TraitItemKind::Method(noop_fold_method_sig(sig, folder),
body.map(|x| folder.fold_block(x)))
}
TraitItemKind::Type(bounds, default) => {
TraitItemKind::Type(folder.fold_bounds(bounds),
default.map(|x| folder.fold_ty(x)))
}
ast::TraitItemKind::Macro(mac) => {
TraitItemKind::Macro(folder.fold_mac(mac))
}
},
span: folder.new_span(i.span),
tokens: i.tokens,
}]
}
pub fn noop_fold_impl_item<T: Folder>(i: ImplItem, folder: &mut T)
-> OneVector<ImplItem> {
smallvec![ImplItem {
id: folder.new_id(i.id),
vis: folder.fold_vis(i.vis),
ident: folder.fold_ident(i.ident),
attrs: fold_attrs(i.attrs, folder),
generics: folder.fold_generics(i.generics),
defaultness: i.defaultness,
node: match i.node {
ast::ImplItemKind::Const(ty, expr) => {
ast::ImplItemKind::Const(folder.fold_ty(ty), folder.fold_expr(expr))
}
ast::ImplItemKind::Method(sig, body) => {
ast::ImplItemKind::Method(noop_fold_method_sig(sig, folder),
folder.fold_block(body))
}
ast::ImplItemKind::Type(ty) => ast::ImplItemKind::Type(folder.fold_ty(ty)),
ast::ImplItemKind::Existential(bounds) => {
ast::ImplItemKind::Existential(folder.fold_bounds(bounds))
},
ast::ImplItemKind::Macro(mac) => ast::ImplItemKind::Macro(folder.fold_mac(mac))
},
span: folder.new_span(i.span),
tokens: i.tokens,
}]
}
pub fn noop_fold_fn_header<T: Folder>(mut header: FnHeader, folder: &mut T) -> FnHeader {
header.asyncness = folder.fold_asyncness(header.asyncness);
header
}
pub fn noop_fold_mod<T: Folder>(Mod {inner, items}: Mod, folder: &mut T) -> Mod {
Mod {
inner: folder.new_span(inner),
items: items.move_flat_map(|x| folder.fold_item(x)),
}
}
pub fn noop_fold_crate<T: Folder>(Crate {module, attrs, span}: Crate,
folder: &mut T) -> Crate {
let mut items = folder.fold_item(P(ast::Item {
ident: keywords::Invalid.ident(),
attrs,
id: ast::DUMMY_NODE_ID,
vis: respan(span.shrink_to_lo(), ast::VisibilityKind::Public),
span,
node: ast::ItemKind::Mod(module),
tokens: None,
})).into_iter();
let (module, attrs, span) = match items.next() {
Some(item) => {
assert!(items.next().is_none(),
"a crate cannot expand to more than one item");
item.and_then(|ast::Item { attrs, span, node, .. }| {
match node {
ast::ItemKind::Mod(m) => (m, attrs, span),
_ => panic!("fold converted a module to not a module"),
}
})
}
None => (ast::Mod {
inner: span,
items: vec![],
}, vec![], span)
};
Crate {
module,
attrs,
span,
}
}
// fold one item into possibly many items
pub fn noop_fold_item<T: Folder>(i: P<Item>, folder: &mut T) -> OneVector<P<Item>> {
smallvec![i.map(|i| folder.fold_item_simple(i))]
}
// fold one item into exactly one item
pub fn noop_fold_item_simple<T: Folder>(Item {id, ident, attrs, node, vis, span, tokens}: Item,
folder: &mut T) -> Item {
Item {
id: folder.new_id(id),
vis: folder.fold_vis(vis),
ident: folder.fold_ident(ident),
attrs: fold_attrs(attrs, folder),
node: folder.fold_item_kind(node),
span: folder.new_span(span),
// FIXME: if this is replaced with a call to `folder.fold_tts` it causes
// an ICE during resolve... odd!
tokens,
}
}
pub fn noop_fold_foreign_item<T: Folder>(ni: ForeignItem, folder: &mut T)
-> OneVector<ForeignItem> {
smallvec![folder.fold_foreign_item_simple(ni)]
}
pub fn noop_fold_foreign_item_simple<T: Folder>(ni: ForeignItem, folder: &mut T) -> ForeignItem {
ForeignItem {
id: folder.new_id(ni.id),
vis: folder.fold_vis(ni.vis),
ident: folder.fold_ident(ni.ident),
attrs: fold_attrs(ni.attrs, folder),
node: match ni.node {
ForeignItemKind::Fn(fdec, generics) => {
ForeignItemKind::Fn(folder.fold_fn_decl(fdec), folder.fold_generics(generics))
}
ForeignItemKind::Static(t, m) => {
ForeignItemKind::Static(folder.fold_ty(t), m)
}
ForeignItemKind::Ty => ForeignItemKind::Ty,
ForeignItemKind::Macro(mac) => ForeignItemKind::Macro(folder.fold_mac(mac)),
},
span: folder.new_span(ni.span)
}
}
pub fn noop_fold_method_sig<T: Folder>(sig: MethodSig, folder: &mut T) -> MethodSig {
MethodSig {
header: folder.fold_fn_header(sig.header),
decl: folder.fold_fn_decl(sig.decl)
}
}
pub fn noop_fold_pat<T: Folder>(p: P<Pat>, folder: &mut T) -> P<Pat> {
p.map(|Pat {id, node, span}| Pat {
id: folder.new_id(id),
node: match node {
PatKind::Wild => PatKind::Wild,
PatKind::Ident(binding_mode, ident, sub) => {
PatKind::Ident(binding_mode,
folder.fold_ident(ident),
sub.map(|x| folder.fold_pat(x)))
}
PatKind::Lit(e) => PatKind::Lit(folder.fold_expr(e)),
PatKind::TupleStruct(pth, pats, ddpos) => {
PatKind::TupleStruct(folder.fold_path(pth),
pats.move_map(|x| folder.fold_pat(x)), ddpos)
}
PatKind::Path(qself, pth) => {
let (qself, pth) = folder.fold_qpath(qself, pth);
PatKind::Path(qself, pth)
}
PatKind::Struct(pth, fields, etc) => {
let pth = folder.fold_path(pth);
let fs = fields.move_map(|f| {
Spanned { span: folder.new_span(f.span),
node: ast::FieldPat {
ident: folder.fold_ident(f.node.ident),
pat: folder.fold_pat(f.node.pat),
is_shorthand: f.node.is_shorthand,
attrs: fold_attrs(f.node.attrs.into(), folder).into()
}}
});
PatKind::Struct(pth, fs, etc)
}
PatKind::Tuple(elts, ddpos) => {
PatKind::Tuple(elts.move_map(|x| folder.fold_pat(x)), ddpos)
}
PatKind::Box(inner) => PatKind::Box(folder.fold_pat(inner)),
PatKind::Ref(inner, mutbl) => PatKind::Ref(folder.fold_pat(inner), mutbl),
PatKind::Range(e1, e2, Spanned { span, node: end }) => {
PatKind::Range(folder.fold_expr(e1),
folder.fold_expr(e2),
Spanned { span, node: folder.fold_range_end(end) })
},
PatKind::Slice(before, slice, after) => {
PatKind::Slice(before.move_map(|x| folder.fold_pat(x)),
slice.map(|x| folder.fold_pat(x)),
after.move_map(|x| folder.fold_pat(x)))
}
PatKind::Paren(inner) => PatKind::Paren(folder.fold_pat(inner)),
PatKind::Mac(mac) => PatKind::Mac(folder.fold_mac(mac))
},
span: folder.new_span(span)
})
}
pub fn noop_fold_range_end<T: Folder>(end: RangeEnd, _folder: &mut T) -> RangeEnd {
end
}
pub fn noop_fold_anon_const<T: Folder>(constant: AnonConst, folder: &mut T) -> AnonConst {
let AnonConst {id, value} = constant;
AnonConst {
id: folder.new_id(id),
value: folder.fold_expr(value),
}
}
pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mut T) -> Expr {
Expr {
node: match node {
ExprKind::Box(e) => {
ExprKind::Box(folder.fold_expr(e))
}
ExprKind::ObsoleteInPlace(a, b) => {
ExprKind::ObsoleteInPlace(folder.fold_expr(a), folder.fold_expr(b))
}
ExprKind::Array(exprs) => {
ExprKind::Array(folder.fold_exprs(exprs))
}
ExprKind::Repeat(expr, count) => {
ExprKind::Repeat(folder.fold_expr(expr), folder.fold_anon_const(count))
}
ExprKind::Tup(exprs) => ExprKind::Tup(folder.fold_exprs(exprs)),
ExprKind::Call(f, args) => {
ExprKind::Call(folder.fold_expr(f),
folder.fold_exprs(args))
}
ExprKind::MethodCall(seg, args) => {
ExprKind::MethodCall(
PathSegment {
ident: folder.fold_ident(seg.ident),
args: seg.args.map(|args| {
args.map(|args| folder.fold_generic_args(args))
}),
},
folder.fold_exprs(args))
}
ExprKind::Binary(binop, lhs, rhs) => {
ExprKind::Binary(binop,
folder.fold_expr(lhs),
folder.fold_expr(rhs))
}
ExprKind::Unary(binop, ohs) => {
ExprKind::Unary(binop, folder.fold_expr(ohs))
}
ExprKind::Lit(l) => ExprKind::Lit(l),
ExprKind::Cast(expr, ty) => {
ExprKind::Cast(folder.fold_expr(expr), folder.fold_ty(ty))
}
ExprKind::Type(expr, ty) => {
ExprKind::Type(folder.fold_expr(expr), folder.fold_ty(ty))
}
ExprKind::AddrOf(m, ohs) => ExprKind::AddrOf(m, folder.fold_expr(ohs)),
ExprKind::If(cond, tr, fl) => {
ExprKind::If(folder.fold_expr(cond),
folder.fold_block(tr),
fl.map(|x| folder.fold_expr(x)))
}
ExprKind::IfLet(pats, expr, tr, fl) => {
ExprKind::IfLet(pats.move_map(|pat| folder.fold_pat(pat)),
folder.fold_expr(expr),
folder.fold_block(tr),
fl.map(|x| folder.fold_expr(x)))
}
ExprKind::While(cond, body, opt_label) => {
ExprKind::While(folder.fold_expr(cond),
folder.fold_block(body),
opt_label.map(|label| folder.fold_label(label)))
}
ExprKind::WhileLet(pats, expr, body, opt_label) => {
ExprKind::WhileLet(pats.move_map(|pat| folder.fold_pat(pat)),
folder.fold_expr(expr),
folder.fold_block(body),
opt_label.map(|label| folder.fold_label(label)))
}
ExprKind::ForLoop(pat, iter, body, opt_label) => {
ExprKind::ForLoop(folder.fold_pat(pat),
folder.fold_expr(iter),
folder.fold_block(body),
opt_label.map(|label| folder.fold_label(label)))
}
ExprKind::Loop(body, opt_label) => {
ExprKind::Loop(folder.fold_block(body),
opt_label.map(|label| folder.fold_label(label)))
}
ExprKind::Match(expr, arms) => {
ExprKind::Match(folder.fold_expr(expr),
arms.move_map(|x| folder.fold_arm(x)))
}
ExprKind::Closure(capture_clause, asyncness, movability, decl, body, span) => {
ExprKind::Closure(capture_clause,
folder.fold_asyncness(asyncness),
movability,
folder.fold_fn_decl(decl),
folder.fold_expr(body),
folder.new_span(span))
}
ExprKind::Block(blk, opt_label) => {
ExprKind::Block(folder.fold_block(blk),
opt_label.map(|label| folder.fold_label(label)))
}
ExprKind::Async(capture_clause, node_id, body) => {
ExprKind::Async(
capture_clause,
folder.new_id(node_id),
folder.fold_block(body),
)
}
ExprKind::Assign(el, er) => {
ExprKind::Assign(folder.fold_expr(el), folder.fold_expr(er))
}
ExprKind::AssignOp(op, el, er) => {
ExprKind::AssignOp(op,
folder.fold_expr(el),
folder.fold_expr(er))
}
ExprKind::Field(el, ident) => {
ExprKind::Field(folder.fold_expr(el), folder.fold_ident(ident))
}
ExprKind::Index(el, er) => {
ExprKind::Index(folder.fold_expr(el), folder.fold_expr(er))
}
ExprKind::Range(e1, e2, lim) => {
ExprKind::Range(e1.map(|x| folder.fold_expr(x)),
e2.map(|x| folder.fold_expr(x)),
lim)
}
ExprKind::Path(qself, path) => {
let (qself, path) = folder.fold_qpath(qself, path);
ExprKind::Path(qself, path)
}
ExprKind::Break(opt_label, opt_expr) => {
ExprKind::Break(opt_label.map(|label| folder.fold_label(label)),
opt_expr.map(|e| folder.fold_expr(e)))
}
ExprKind::Continue(opt_label) => {
ExprKind::Continue(opt_label.map(|label| folder.fold_label(label)))
}
ExprKind::Ret(e) => ExprKind::Ret(e.map(|x| folder.fold_expr(x))),
ExprKind::InlineAsm(asm) => ExprKind::InlineAsm(asm.map(|asm| {
InlineAsm {
inputs: asm.inputs.move_map(|(c, input)| {
(c, folder.fold_expr(input))
}),
outputs: asm.outputs.move_map(|out| {
InlineAsmOutput {
constraint: out.constraint,
expr: folder.fold_expr(out.expr),
is_rw: out.is_rw,
is_indirect: out.is_indirect,
}
}),
..asm
}
})),
ExprKind::Mac(mac) => ExprKind::Mac(folder.fold_mac(mac)),
ExprKind::Struct(path, fields, maybe_expr) => {
ExprKind::Struct(folder.fold_path(path),
fields.move_map(|x| folder.fold_field(x)),
maybe_expr.map(|x| folder.fold_expr(x)))
},
ExprKind::Paren(ex) => {
let sub_expr = folder.fold_expr(ex);
return Expr {
// Nodes that are equal modulo `Paren` sugar no-ops should have the same ids.
id: sub_expr.id,
node: ExprKind::Paren(sub_expr),
span: folder.new_span(span),
attrs: fold_attrs(attrs.into(), folder).into(),
};
}
ExprKind::Yield(ex) => ExprKind::Yield(ex.map(|x| folder.fold_expr(x))),
ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)),
ExprKind::TryBlock(body) => ExprKind::TryBlock(folder.fold_block(body)),
},
id: folder.new_id(id),
span: folder.new_span(span),
attrs: fold_attrs(attrs.into(), folder).into(),
}
}
pub fn noop_fold_opt_expr<T: Folder>(e: P<Expr>, folder: &mut T) -> Option<P<Expr>> {
Some(folder.fold_expr(e))
}
pub fn noop_fold_exprs<T: Folder>(es: Vec<P<Expr>>, folder: &mut T) -> Vec<P<Expr>> {
es.move_flat_map(|e| folder.fold_opt_expr(e))
}
pub fn noop_fold_stmt<T: Folder>(Stmt {node, span, id}: Stmt, folder: &mut T) -> OneVector<Stmt> {
let id = folder.new_id(id);
let span = folder.new_span(span);
noop_fold_stmt_kind(node, folder).into_iter().map(|node| {
Stmt { id: id, node: node, span: span }
}).collect()
}
pub fn noop_fold_stmt_kind<T: Folder>(node: StmtKind, folder: &mut T) -> OneVector<StmtKind> {
match node {
StmtKind::Local(local) => smallvec![StmtKind::Local(folder.fold_local(local))],
StmtKind::Item(item) => folder.fold_item(item).into_iter().map(StmtKind::Item).collect(),
StmtKind::Expr(expr) => {
folder.fold_opt_expr(expr).into_iter().map(StmtKind::Expr).collect()
}
StmtKind::Semi(expr) => {
folder.fold_opt_expr(expr).into_iter().map(StmtKind::Semi).collect()
}
StmtKind::Mac(mac) => smallvec![StmtKind::Mac(mac.map(|(mac, semi, attrs)| {
(folder.fold_mac(mac), semi, fold_attrs(attrs.into(), folder).into())
}))],
}
}
pub fn noop_fold_vis<T: Folder>(vis: Visibility, folder: &mut T) -> Visibility {
match vis.node {
VisibilityKind::Restricted { path, id } => {
respan(vis.span, VisibilityKind::Restricted {
path: path.map(|path| folder.fold_path(path)),
id: folder.new_id(id),
})
}
_ => vis,
}
}
#[cfg(test)]
mod tests {
use std::io;
use ast::{self, Ident};
use util::parser_testing::{string_to_crate, matches_codepattern};
use print::pprust;
use fold;
use with_globals;
use super::*;
// this version doesn't care about getting comments or docstrings in.
fn fake_print_crate(s: &mut pprust::State,
krate: &ast::Crate) -> io::Result<()> {
s.print_mod(&krate.module, &krate.attrs)
}
// change every identifier to "zz"
struct ToZzIdentFolder;
impl Folder for ToZzIdentFolder {
fn fold_ident(&mut self, _: ast::Ident) -> ast::Ident {
Ident::from_str("zz")
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
fold::noop_fold_mac(mac, self)
}
}
// maybe add to expand.rs...
macro_rules! assert_pred {
($pred:expr, $predname:expr, $a:expr , $b:expr) => (
{
let pred_val = $pred;
let a_val = $a;
let b_val = $b;
if !(pred_val(&a_val, &b_val)) {
panic!("expected args satisfying {}, got {} and {}",
$predname, a_val, b_val);
}
}
)
}
// make sure idents get transformed everywhere
#[test] fn ident_transformation () {
with_globals(|| {
let mut zz_fold = ToZzIdentFolder;
let ast = string_to_crate(
"#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
let folded_crate = zz_fold.fold_crate(ast);
assert_pred!(
matches_codepattern,
"matches_codepattern",
pprust::to_string(|s| fake_print_crate(s, &folded_crate)),
"#[zz]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string());
})
}
// even inside macro defs....
#[test] fn ident_transformation_in_defs () {
with_globals(|| {
let mut zz_fold = ToZzIdentFolder;
let ast = string_to_crate(
"macro_rules! a {(b $c:expr $(d $e:token)f+ => \
(g $(d $d $e)+))} ".to_string());
let folded_crate = zz_fold.fold_crate(ast);
assert_pred!(
matches_codepattern,
"matches_codepattern",
pprust::to_string(|s| fake_print_crate(s, &folded_crate)),
"macro_rules! zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)));".to_string());
})
}
}
| 37.190763 | 98 | 0.552202 |
6707b23fec0a3bb37876b121983abdc14df4e07c
| 4,777 |
//! Generating sequences of Wasmtime API calls.
//!
//! We only generate *valid* sequences of API calls. To do this, we keep track
//! of what objects we've already created in earlier API calls via the `Scope`
//! struct.
//!
//! To generate even-more-pathological sequences of API calls, we use [swarm
//! testing]:
//!
//! > In swarm testing, the usual practice of potentially including all features
//! > in every test case is abandoned. Rather, a large “swarm” of randomly
//! > generated configurations, each of which omits some features, is used, with
//! > configurations receiving equal resources.
//!
//! [swarm testing]: https://www.cs.utah.edu/~regehr/papers/swarm12.pdf
use crate::generators::Config;
use arbitrary::{Arbitrary, Unstructured};
use std::collections::BTreeSet;
#[derive(Arbitrary, Debug)]
struct Swarm {
module_new: bool,
module_drop: bool,
instance_new: bool,
instance_drop: bool,
call_exported_func: bool,
}
/// A call to one of Wasmtime's public APIs.
#[derive(Arbitrary, Debug)]
#[allow(missing_docs)]
pub enum ApiCall {
StoreNew(Config),
ModuleNew { id: usize, wasm: Vec<u8> },
ModuleDrop { id: usize },
InstanceNew { id: usize, module: usize },
InstanceDrop { id: usize },
CallExportedFunc { instance: usize, nth: usize },
}
use ApiCall::*;
struct Scope {
id_counter: usize,
modules: BTreeSet<usize>,
instances: BTreeSet<usize>,
config: Config,
}
impl Scope {
fn next_id(&mut self) -> usize {
let id = self.id_counter;
self.id_counter = id + 1;
id
}
}
/// A sequence of API calls.
#[derive(Debug)]
pub struct ApiCalls {
/// The API calls.
pub calls: Vec<ApiCall>,
}
impl<'a> Arbitrary<'a> for ApiCalls {
fn arbitrary(input: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
crate::init_fuzzing();
let swarm = Swarm::arbitrary(input)?;
let mut calls = vec![];
let config = Config::arbitrary(input)?;
calls.push(StoreNew(config.clone()));
let mut scope = Scope {
id_counter: 0,
modules: BTreeSet::default(),
instances: BTreeSet::default(),
config,
};
// Total limit on number of API calls we'll generate. This exists to
// avoid libFuzzer timeouts.
let max_calls = 100;
for _ in 0..input.arbitrary_len::<ApiCall>()? {
if calls.len() > max_calls {
break;
}
let mut choices: Vec<fn(_, &mut Scope) -> arbitrary::Result<ApiCall>> = vec![];
if swarm.module_new {
choices.push(|input, scope| {
let id = scope.next_id();
let wasm = scope.config.generate(input, Some(1000))?;
scope.modules.insert(id);
Ok(ModuleNew {
id,
wasm: wasm.to_bytes(),
})
});
}
if swarm.module_drop && !scope.modules.is_empty() {
choices.push(|input, scope| {
let modules: Vec<_> = scope.modules.iter().collect();
let id = **input.choose(&modules)?;
scope.modules.remove(&id);
Ok(ModuleDrop { id })
});
}
if swarm.instance_new && !scope.modules.is_empty() {
choices.push(|input, scope| {
let modules: Vec<_> = scope.modules.iter().collect();
let module = **input.choose(&modules)?;
let id = scope.next_id();
scope.instances.insert(id);
Ok(InstanceNew { id, module })
});
}
if swarm.instance_drop && !scope.instances.is_empty() {
choices.push(|input, scope| {
let instances: Vec<_> = scope.instances.iter().collect();
let id = **input.choose(&instances)?;
scope.instances.remove(&id);
Ok(InstanceDrop { id })
});
}
if swarm.call_exported_func && !scope.instances.is_empty() {
choices.push(|input, scope| {
let instances: Vec<_> = scope.instances.iter().collect();
let instance = **input.choose(&instances)?;
let nth = usize::arbitrary(input)?;
Ok(CallExportedFunc { instance, nth })
});
}
if choices.is_empty() {
break;
}
let c = input.choose(&choices)?;
calls.push(c(input, &mut scope)?);
}
Ok(ApiCalls { calls })
}
}
| 32.277027 | 91 | 0.530668 |
224f1b19f20cbe8f9c78bb1a44a87a767c583fcf
| 958 |
use std::time::Duration;
use tests::test_component::TestRunner;
use windows::foundation::{IPropertyValue, PropertyValue, TimeSpan};
use windows::Interface;
#[test]
fn conversion() -> windows::Result<()> {
let a: TimeSpan = Duration::from_millis(1234).into();
let b = TestRunner::create_time_span(1234)?;
assert_eq!(a, b);
let c: Duration = b.into();
assert_eq!(c.as_millis(), 1234);
Ok(())
}
#[test]
fn duration_param() -> windows::Result<()> {
let object = PropertyValue::create_time_span(Duration::from_millis(1234))?;
let pv: IPropertyValue = object.cast()?;
assert!(pv.get_time_span()? == Duration::from_millis(1234).into());
Ok(())
}
#[test]
fn time_span_param() -> windows::Result<()> {
let object = PropertyValue::create_time_span(TestRunner::create_time_span(1234)?)?;
let pv: IPropertyValue = object.cast()?;
assert!(pv.get_time_span()? == Duration::from_millis(1234).into());
Ok(())
}
| 27.371429 | 87 | 0.660752 |
bb0018bddb863c1b29ad71cffd66c003ee45602c
| 21,882 |
use std::fmt;
use std::fmt::Debug;
use std::fmt::Display;
use std::io::Error;
use std::io::ErrorKind;
use std::str::Utf8Error;
use content_inspector::{inspect, ContentType};
use tracing::{trace, warn};
use once_cell::sync::Lazy;
use bytes::Buf;
use bytes::BufMut;
use crate::core::{Encoder, Decoder};
use crate::core::DecoderVarInt;
use crate::core::EncoderVarInt;
use crate::core::Version;
use crate::batch::Batch;
use crate::Offset;
/// maximum text to display
static MAX_STRING_DISPLAY: Lazy<usize> = Lazy::new(|| {
let var_value = std::env::var("FLV_MAX_STRING_DISPLAY").unwrap_or_default();
var_value.parse().unwrap_or(16384)
});
/// A key for determining which partition a record should be sent to.
///
/// This type is used to support conversions from any other type that
/// may be converted to a `Vec<u8>`, while still allowing the ability
/// to explicitly state that a record may have no key (`RecordKey::NULL`).
///
/// # Examples
///
/// ```
/// # use fluvio_dataplane_protocol::record::RecordKey;
/// let key = RecordKey::NULL;
/// let key: RecordKey = "Hello, world!".into();
/// let key: RecordKey = String::from("Hello, world!").into();
/// let key: RecordKey = vec![1, 2, 3, 4].into();
/// ```
pub struct RecordKey(RecordKeyInner);
impl RecordKey {
pub const NULL: Self = Self(RecordKeyInner::Null);
fn into_option(self) -> Option<RecordData> {
match self.0 {
RecordKeyInner::Key(key) => Some(key),
RecordKeyInner::Null => None,
}
}
#[doc(hidden)]
pub fn from_option(key: Option<RecordData>) -> Self {
let inner = match key {
Some(key) => RecordKeyInner::Key(key),
None => RecordKeyInner::Null,
};
Self(inner)
}
}
enum RecordKeyInner {
Null,
Key(RecordData),
}
impl<K: Into<Vec<u8>>> From<K> for RecordKey {
fn from(k: K) -> Self {
Self(RecordKeyInner::Key(RecordData::from(k)))
}
}
/// A type containing the data contents of a Record.
///
/// The `RecordData` type provides useful conversions for
/// constructing it from any type that may convert into a `Vec<u8>`.
/// This is the basis for flexible APIs that allow users to supply
/// various different argument types as record contents. See
/// [the Producer API] as an example.
///
/// [the Producer API]: https://docs.rs/fluvio/producer/TopicProducer::send
#[derive(Clone, Default, PartialEq)]
pub struct RecordData(Bytes);
impl RecordData {
pub fn len(&self) -> usize {
self.0.len()
}
/// Check if value is binary content
pub fn is_binary(&self) -> bool {
matches!(inspect(&self.0), ContentType::BINARY)
}
/// Describe value - return text, binary, or 0 bytes
pub fn describe(&self) -> String {
if self.is_binary() {
format!("binary: ({} bytes)", self.len())
} else {
format!("text: '{}'", self)
}
}
// as string slice
pub fn as_str(&self) -> Result<&str, Utf8Error> {
std::str::from_utf8(self.as_ref())
}
}
impl<V: Into<Vec<u8>>> From<V> for RecordData {
fn from(value: V) -> Self {
Self(Bytes::from(value.into()))
}
}
impl AsRef<[u8]> for RecordData {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl Debug for RecordData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let value = &self.0;
if matches!(inspect(value), ContentType::BINARY) {
write!(f, "values binary: ({} bytes)", self.len())
} else if value.len() < *MAX_STRING_DISPLAY {
write!(f, "{}", String::from_utf8_lossy(value))
} else {
write!(
f,
"{}...",
String::from_utf8_lossy(&value[0..*MAX_STRING_DISPLAY])
)
}
}
}
impl Display for RecordData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let value = &self.0;
if matches!(inspect(value), ContentType::BINARY) {
write!(f, "binary: ({} bytes)", self.len())
} else if value.len() < *MAX_STRING_DISPLAY {
write!(f, "{}", String::from_utf8_lossy(value))
} else {
write!(
f,
"{}...",
String::from_utf8_lossy(&value[0..*MAX_STRING_DISPLAY])
)
}
}
}
impl Encoder for RecordData {
fn write_size(&self, version: Version) -> usize {
let len = self.0.len() as i64;
self.0.iter().fold(len.var_write_size(), |sum, val| {
sum + val.write_size(version)
})
}
fn encode<T>(&self, dest: &mut T, version: Version) -> Result<(), Error>
where
T: BufMut,
{
let len: i64 = self.0.len() as i64;
len.encode_varint(dest)?;
for v in self.0.iter() {
v.encode(dest, version)?;
}
Ok(())
}
}
impl Decoder for RecordData {
fn decode<T>(&mut self, src: &mut T, _: Version) -> Result<(), Error>
where
T: Buf,
{
trace!("decoding default asyncbuffer");
let mut len: i64 = 0;
len.decode_varint(src)?;
let len = len as usize;
// Take `len` bytes from `src` and put them into a new BytesMut buffer
let slice = src.take(len);
let mut bytes = BytesMut::with_capacity(len);
bytes.put(slice);
// Replace the inner Bytes buffer of this RecordData
self.0 = bytes.freeze();
Ok(())
}
}
/// Represents sets of batches in storage
// It is written consequently with len as prefix
#[derive(Default, Debug)]
pub struct RecordSet {
pub batches: Vec<Batch>,
}
impl fmt::Display for RecordSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} batches", self.batches.len())
}
}
impl RecordSet {
pub fn add(mut self, batch: Batch) -> Self {
self.batches.push(batch);
self
}
/// this is next offset to be fetched
pub fn last_offset(&self) -> Option<Offset> {
self.batches
.last()
.map(|batch| batch.computed_last_offset())
}
/// total records
pub fn total_records(&self) -> usize {
self.batches
.iter()
.map(|batches| batches.records().len())
.sum()
}
/// return base offset
pub fn base_offset(&self) -> Offset {
self.batches
.first()
.map(|batches| batches.base_offset)
.unwrap_or_else(|| -1)
}
}
impl Decoder for RecordSet {
fn decode<T>(&mut self, src: &mut T, version: Version) -> Result<(), Error>
where
T: Buf,
{
trace!(len = src.remaining(), "raw buffer size");
let mut len: i32 = 0;
len.decode(src, version)?;
trace!(len, "Record sets decoded content");
if src.remaining() < len as usize {
return Err(Error::new(
ErrorKind::UnexpectedEof,
format!(
"expected message len: {} but founded {}",
len,
src.remaining()
),
));
}
let mut buf = src.take(len as usize);
let mut count = 0;
while buf.remaining() > 0 {
trace!(count, remaining = buf.remaining(), "decoding batches");
let mut batch = Batch::default();
match batch.decode(&mut buf, version) {
Ok(_) => self.batches.push(batch),
Err(err) => match err.kind() {
ErrorKind::UnexpectedEof => {
warn!(
len,
remaining = buf.remaining(),
version,
count,
"not enough bytes for decoding batch from recordset"
);
return Ok(());
}
_ => {
warn!("problem decoding batch: {}", err);
return Ok(());
}
},
}
count += 1;
}
Ok(())
}
}
impl Encoder for RecordSet {
fn write_size(&self, version: Version) -> usize {
self.batches
.iter()
.fold(4, |sum, val| sum + val.write_size(version))
}
fn encode<T>(&self, dest: &mut T, version: Version) -> Result<(), Error>
where
T: BufMut,
{
trace!("Record set encoding");
let mut out: Vec<u8> = Vec::new();
for batch in &self.batches {
trace!("encoding batch..");
batch.encode(&mut out, version)?;
}
let length: i32 = out.len() as i32;
trace!("Record Set encode len: {}", length);
length.encode(dest, version)?;
dest.put_slice(&out);
Ok(())
}
}
#[derive(Decoder, Encoder, Default, Debug, Clone)]
pub struct RecordHeader {
attributes: i8,
#[varint]
timestamp_delta: i64,
#[varint]
offset_delta: Offset,
}
impl RecordHeader {
pub fn set_offset_delta(&mut self, delta: Offset) {
self.offset_delta = delta;
}
pub fn offset_delta(&self) -> Offset {
self.offset_delta
}
}
#[derive(Default, Clone)]
pub struct Record<B = RecordData> {
pub preamble: RecordHeader,
pub key: Option<B>,
pub value: B,
pub headers: i64,
}
impl<B: Default> Record<B> {
pub fn get_offset_delta(&self) -> Offset {
self.preamble.offset_delta
}
/// add offset delta with new relative base offset
pub fn add_base_offset(&mut self, relative_base_offset: Offset) {
self.preamble.offset_delta += relative_base_offset;
}
/// Returns a reference to the inner value
pub fn value(&self) -> &B {
&self.value
}
/// Returns a reference to the inner key if it exists
pub fn key(&self) -> Option<&B> {
self.key.as_ref()
}
/// Consumes this record, returning the inner value
pub fn into_value(self) -> B {
self.value
}
/// Consumes this record, returning the inner key if it esists
pub fn into_key(self) -> Option<B> {
self.key
}
}
impl Record {
pub fn new<V>(value: V) -> Self
where
V: Into<RecordData>,
{
Record {
value: value.into(),
..Default::default()
}
}
pub fn new_key_value<K, V>(key: K, value: V) -> Self
where
K: Into<RecordKey>,
V: Into<RecordData>,
{
let key = key.into().into_option();
Record {
key,
value: value.into(),
..Default::default()
}
}
}
impl<K, V> From<(K, V)> for Record
where
K: Into<RecordKey>,
V: Into<RecordData>,
{
fn from((key, value): (K, V)) -> Self {
Self::new_key_value(key, value)
}
}
impl<B: Debug> Debug for Record<B> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Record")
.field("preamble", &self.preamble)
.field("key", &self.key)
.field("value", &self.value)
.field("headers", &self.headers)
.finish()
}
}
impl<B> Encoder for Record<B>
where
B: Encoder + Default,
{
fn write_size(&self, version: Version) -> usize {
let inner_size = self.preamble.write_size(version)
+ self.key.write_size(version)
+ self.value.write_size(version)
+ self.headers.var_write_size();
let len: i64 = inner_size as i64;
len.var_write_size() + inner_size
}
fn encode<T>(&self, dest: &mut T, version: Version) -> Result<(), Error>
where
T: BufMut,
{
let mut out: Vec<u8> = Vec::new();
self.preamble.encode(&mut out, version)?;
self.key.encode(&mut out, version)?;
self.value.encode(&mut out, version)?;
self.headers.encode_varint(&mut out)?;
let len: i64 = out.len() as i64;
trace!("record encode as {} bytes", len);
len.encode_varint(dest)?;
dest.put_slice(&out);
Ok(())
}
}
impl<B> Decoder for Record<B>
where
B: Decoder,
{
fn decode<T>(&mut self, src: &mut T, version: Version) -> Result<(), Error>
where
T: Buf,
{
trace!("decoding record");
let mut len: i64 = 0;
len.decode_varint(src)?;
trace!("record contains: {} bytes", len);
if (src.remaining() as i64) < len {
return Err(Error::new(
ErrorKind::UnexpectedEof,
"not enought for record",
));
}
self.preamble.decode(src, version)?;
trace!("offset delta: {}", self.preamble.offset_delta);
self.key.decode(src, version)?;
self.value.decode(src, version)?;
self.headers.decode_varint(src)?;
Ok(())
}
}
use Record as DefaultRecord;
/// Record that can be used by Consumer which needs access to metadata
pub struct ConsumerRecord<B = DefaultRecord> {
/// The offset of this Record into its partition
pub offset: i64,
/// The partition where this Record is stored
pub partition: i32,
/// The Record contents
pub record: B,
}
impl<B> ConsumerRecord<B> {
/// The offset from the initial offset for a given stream.
pub fn offset(&self) -> i64 {
self.offset
}
/// The partition where this Record is stored.
pub fn partition(&self) -> i32 {
self.partition
}
/// Returns the inner representation of the Record
pub fn into_inner(self) -> B {
self.record
}
/// Returns a ref to the inner representation of the Record
pub fn inner(&self) -> &B {
&self.record
}
}
impl ConsumerRecord<DefaultRecord> {
/// Returns the contents of this Record's key, if it exists
pub fn key(&self) -> Option<&[u8]> {
self.record.key().map(|it| it.as_ref())
}
/// Returns the contents of this Record's value
pub fn value(&self) -> &[u8] {
self.record.value().as_ref()
}
}
impl AsRef<[u8]> for ConsumerRecord<DefaultRecord> {
fn as_ref(&self) -> &[u8] {
self.value()
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::Cursor;
use std::io::Error as IoError;
use crate::core::Decoder;
use crate::core::Encoder;
use crate::record::Record;
#[test]
fn test_decode_encode_record() -> Result<(), IoError> {
/* Below is how you generate the vec<u8> for the `data` varible below.
let mut record = Record::from(String::from("dog"));
record.preamble.set_offset_delta(1);
let mut out = vec![];
record.encode(&mut out, 0)?;
println!("ENCODED: {:#x?}", out);
*/
let data = [0x12, 0x0, 0x0, 0x2, 0x0, 0x6, 0x64, 0x6f, 0x67, 0x0];
let record = Record::<RecordData>::decode_from(&mut Cursor::new(&data), 0)?;
assert_eq!(record.as_bytes(0)?.len(), data.len());
assert_eq!(record.write_size(0), data.len());
println!("offset_delta: {:?}", record.get_offset_delta());
assert_eq!(record.get_offset_delta(), 1);
let value = record.value.as_ref();
assert_eq!(value.len(), 3);
assert_eq!(value[0], 0x64);
Ok(())
}
/// test decoding of records when one of the batch was truncated
#[test]
fn test_decode_batch_truncation() {
use super::RecordSet;
use crate::batch::Batch;
use crate::record::Record;
fn create_batch() -> Batch {
let value = vec![0x74, 0x65, 0x73, 0x74];
let record = Record::new(value);
let mut batch = Batch::default();
batch.add_record(record);
batch
}
// add 3 batches
let batches = RecordSet::default()
.add(create_batch())
.add(create_batch())
.add(create_batch());
const TRUNCATED: usize = 10;
let mut bytes = batches.as_bytes(0).expect("bytes");
let original_len = bytes.len();
let _ = bytes.split_off(original_len - TRUNCATED); // truncate record sets
let body = bytes.split_off(4); // split off body so we can manipulate len
let new_len = (original_len - TRUNCATED - 4) as i32;
let mut out = vec![];
new_len.encode(&mut out, 0).expect("encoding");
out.extend_from_slice(&body);
assert_eq!(out.len(), original_len - TRUNCATED);
println!("decoding...");
let decoded_batches = RecordSet::decode_from(&mut Cursor::new(out), 0).expect("decoding");
assert_eq!(decoded_batches.batches.len(), 2);
}
#[test]
fn test_key_value_encoding() {
let key = "KKKKKKKKKK".to_string();
let value = "VVVVVVVVVV".to_string();
let record = Record::new_key_value(key, value);
let mut encoded = Vec::new();
record.encode(&mut encoded, 0).unwrap();
let decoded = Record::<RecordData>::decode_from(&mut Cursor::new(encoded), 0).unwrap();
let record_key = record.key.unwrap();
let decoded_key = decoded.key.unwrap();
assert_eq!(record_key.as_ref(), decoded_key.as_ref());
assert_eq!(record.value.as_ref(), decoded.value.as_ref());
}
// Test Specification:
//
// A record was encoded and written to a file, using the following code:
//
// ```rust
// use fluvio_dataplane_protocol::record::{Record, DefaultAsyncBuffer};
// use fluvio_protocol::Encoder;
// let value = "VVVVVVVVVV".to_string();
// let record = Record {
// key: DefaultAsyncBuffer::default(),
// value: DefaultAsyncBuffer::new(value.into_bytes()),
// ..Default::default()
// };
// let mut encoded = Vec::new();
// record.encode(&mut encoded, 0);
// ```
//
// This was back when records defined keys as `key: B` rather than `key: Option<B>`.
//
// It just so happens that our public API never allowed any records to be sent with
// any contents in the `key` field, so what was sent over the wire was a buffer whose
// length was zero, encoded as a single zero `0x00` (for "length-zero buffer").
//
// In the new `key: Option<B>` encoding, a key is encoded with a tag for
// Some or None, with 0x00 representing None and 0x01 representing Some.
// So, when reading old records, the 0x00 "length encoding" will be re-interpreted
// as the 0x00 "None encoding". Since all old keys were empty, this should work for
// all old records _in practice_. This will not work if any record is decoded which
// artificially was given contents in the key field.
#[test]
fn test_decode_old_record_empty_key() {
let old_encoded = std::fs::read("./tests/test_old_record_empty_key.bin").unwrap();
let decoded = Record::<RecordData>::decode_from(&mut Cursor::new(old_encoded), 0).unwrap();
assert_eq!(
std::str::from_utf8(decoded.value.0.as_ref()).unwrap(),
"VVVVVVVVVV"
);
assert!(decoded.key.is_none());
}
}
#[cfg(feature = "file")]
pub use file::*;
use crate::bytes::{Bytes, BytesMut};
#[cfg(feature = "file")]
mod file {
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind;
use tracing::trace;
use bytes::BufMut;
use bytes::BytesMut;
use fluvio_future::file_slice::AsyncFileSlice;
use crate::core::bytes::Buf;
use crate::core::Decoder;
use crate::core::Encoder;
use crate::core::Version;
use crate::store::FileWrite;
use crate::store::StoreValue;
#[derive(Default, Debug)]
pub struct FileRecordSet(AsyncFileSlice);
impl fmt::Display for FileRecordSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "pos: {} len: {}", self.position(), self.len())
}
}
impl FileRecordSet {
pub fn position(&self) -> u64 {
self.0.position()
}
pub fn len(&self) -> usize {
self.0.len() as usize
}
pub fn raw_slice(&self) -> AsyncFileSlice {
self.0.clone()
}
}
impl From<AsyncFileSlice> for FileRecordSet {
fn from(slice: AsyncFileSlice) -> Self {
Self(slice)
}
}
impl Encoder for FileRecordSet {
fn write_size(&self, _version: Version) -> usize {
self.len() + 4 // include header
}
fn encode<T>(&self, src: &mut T, version: Version) -> Result<(), IoError>
where
T: BufMut,
{
// can only encode zero length
if self.len() == 0 {
let len: u32 = 0;
len.encode(src, version)
} else {
Err(IoError::new(
ErrorKind::InvalidInput,
format!("len {} is not zeo", self.len()),
))
}
}
}
impl Decoder for FileRecordSet {
fn decode<T>(&mut self, _src: &mut T, _version: Version) -> Result<(), IoError>
where
T: Buf,
{
unimplemented!("file slice cannot be decoded in the ButMut")
}
}
impl FileWrite for FileRecordSet {
fn file_encode(
&self,
dest: &mut BytesMut,
data: &mut Vec<StoreValue>,
version: Version,
) -> Result<(), IoError> {
// write total len
let len: i32 = self.len() as i32;
trace!("KfFileRecordSet encoding file slice len: {}", len);
len.encode(dest, version)?;
let bytes = dest.split_to(dest.len()).freeze();
data.push(StoreValue::Bytes(bytes));
data.push(StoreValue::FileSlice(self.raw_slice()));
Ok(())
}
}
}
| 28.125964 | 99 | 0.552143 |
eded754eee2282a4970e985bd93ec971a6af8d2e
| 428 |
use std::sync::Mutex;
use lazy_static::lazy_static;
use rand::thread_rng;
use xsalsa20poly1305::generate_nonce;
lazy_static! {
pub static ref KEYGREP: Mutex<Option<String>> = Mutex::new(None);
pub static ref ID: Mutex<Option<String>> = Mutex::new(None);
pub static ref ID_KEY: Mutex<String> = Mutex::new(generate_idkey());
}
fn generate_idkey() -> String {
base64::encode(generate_nonce(&mut thread_rng()))
}
| 26.75 | 72 | 0.71028 |
0879ebd86b01cf6b1f2cbe5059a7a13b9568c563
| 14,760 |
use std::fs::File;
use std::io::BufReader;
use std::option::Option::Some;
use rev_lines::RevLines;
use sysinfo::{ComponentExt, DiskExt, NetworkExt, NetworksExt, ProcessorExt, System, SystemExt};
use tui::{
backend::Backend,
layout::{Constraint, Direction, Layout, Rect},
style::{Color, Style},
text::Span,
widgets::{Block, Borders, Cell, Row, Table},
Frame,
};
use crate::torrentLib::response::{SessionStats, Stats};
use crate::u2client::types::{Status, UserInfo};
pub struct TabsState {
pub index: usize,
}
const TITLE: &[&str] = &["Status", "BT", "LOG"];
impl TabsState {
pub fn new() -> TabsState {
TabsState { index: 0 }
}
pub fn next(&mut self) {
self.index = (self.index + 1) % 3;
}
pub fn previous(&mut self) {
if self.index > 0 {
self.index -= 1;
} else {
self.index = 2;
}
}
}
impl Default for TabsState {
fn default() -> Self {
Self::new()
}
}
pub fn draw<B: Backend>(f: &mut Frame<B>, x: Status, mask: u8, idx: usize) {
let chunks = Layout::default()
.constraints([Constraint::Percentage(10), Constraint::Percentage(90)].as_ref())
.direction(Direction::Vertical)
.split(f.size());
let items: Vec<Vec<Cell>> = vec![TITLE
.iter()
.map(|x| {
if x == TITLE.get(idx).unwrap() {
Cell::from(Span::styled(
x.to_owned(),
Style::default().fg(Color::Yellow),
))
} else {
Cell::from(Span::raw(x.to_owned()))
}
})
.collect()];
let items: Vec<Row> = items.into_iter().map(Row::new).collect();
let table = Table::new(items)
.block(Block::default().title("Tab").borders(Borders::ALL))
.widths(&[
Constraint::Percentage(8),
Constraint::Percentage(8),
Constraint::Percentage(8),
]);
f.render_widget(table, chunks[0]);
let area = chunks[1];
match idx {
0 => {
let chunks = Layout::default()
.constraints([Constraint::Percentage(20), Constraint::Percentage(40)].as_ref())
.direction(Direction::Vertical)
.split(area);
drawRemoteInfo(f, chunks[0], &x.remote, (mask >> 1) & 1);
drawHardwareInfo(f, chunks[1], &x.hardware);
}
1 => {
drawLocalInfo(f, area, &x.local, mask & 1);
}
2 => {
drawLog(f, area, &x.logDir);
}
_ => {}
}
}
fn drawLog<B: Backend>(f: &mut Frame<B>, area: Rect, log: &Option<String>) {
let F = |x: &Option<String>| -> crate::Result<Vec<Row>> {
let x = x.as_ref().ok_or("")?;
let file = File::open(x)?;
let rev_lines = RevLines::new(BufReader::new(file))?;
Ok(rev_lines
.take(25)
.map(|x| Row::new(vec![Cell::from(Span::raw(x))]))
.collect::<Vec<Row>>())
};
let items =
F(log).unwrap_or_else(|_| vec![Row::new(vec![Cell::from(Span::raw("failed to get log"))])]);
let table = Table::new(items)
.block(Block::default().title("Logs").borders(Borders::ALL))
.widths(&[Constraint::Percentage(100)]);
f.render_widget(table, area);
}
fn splitTime(mut time: u64) -> (u64, u64, u64, u64) {
let days = time / 86400;
time -= days * 86400;
let hours = time / 3600;
time -= hours * 3600;
let minutes = time / 60;
let secs = time - minutes * 60;
(days, hours, minutes, secs)
}
fn getUpdatedInfoCell(mask: u8) -> Cell<'static> {
if mask != 0 {
Cell::from(Span::styled(
"Updated".to_string(),
Style::default().fg(Color::Green),
))
} else {
Cell::from(Span::styled(
"Outdated".to_string(),
Style::default().fg(Color::Red),
))
}
}
fn drawRemoteInfo<B: Backend>(f: &mut Frame<B>, area: Rect, x: &Option<UserInfo>, mask: u8) {
let items: Vec<Vec<Cell>> = match x {
Some(x) => {
vec![
vec![
Cell::from(Span::raw(format!("Welcome {}", x.username))),
Cell::from(Span::styled(
format!("coin {}", x.coin),
Style::default().fg(Color::Yellow),
)),
getUpdatedInfoCell(mask),
],
vec![
Cell::from(Span::raw(format!("Download {}", x.download))),
Cell::from(Span::raw(format!("Upload {}", x.upload))),
Cell::from(Span::styled(
format!("shareRate {}", x.shareRate),
Style::default().fg(Color::Yellow),
)),
],
vec![
Cell::from(Span::raw(format!("Actual Download {}", x.actualDownload))),
Cell::from(Span::raw(format!("Actual Upload {}", x.actualUpload))),
],
vec![
Cell::from(Span::raw(format!("Upload Time {}", x.uploadTime))),
Cell::from(Span::raw(format!("Download Time {}", x.downloadTime))),
Cell::from(Span::styled(
format!("timeRate {}", x.timeRate),
Style::default().fg(Color::Yellow),
)),
],
]
}
None => {
vec![vec![Cell::from(Span::raw("loading".to_string()))]]
}
};
let items: Vec<Row> = items.into_iter().map(Row::new).collect();
let table = Table::new(items)
.block(Block::default().title("User").borders(Borders::ALL))
.widths(&[
Constraint::Percentage(30),
Constraint::Percentage(30),
Constraint::Percentage(30),
]);
f.render_widget(table, area);
}
fn drawHardwareInfo<B: Backend>(f: &mut Frame<B>, area: Rect, sys: &Option<System>) {
let items: Vec<Vec<Cell>> = match sys {
Some(sys) => {
let firstCore = sys.get_processors().get(0);
let brand = if let Some(firstCore) = firstCore {
firstCore.get_brand()
} else {
"Unknown CPU"
};
let (days, hours, minutes, secs) = splitTime(sys.get_uptime());
let mut items = vec![
vec![
Cell::from(Span::raw(brand.to_string())),
Cell::from(Span::raw(format!(
"{} days {} hours {} mins {}",
days, hours, minutes, secs
))),
],
vec![
Cell::from(Span::raw(format!(
"Memory {:.3}GB/{:.3}GB",
sys.get_used_memory() as f32 / 1e6,
sys.get_total_memory() as f32 / 1e6
))),
Cell::from(Span::raw(format!(
"Swap {:.3}GB/{:.3}GB",
sys.get_used_swap() as f32 / 1e6,
sys.get_total_swap() as f32 / 1e6
))),
],
vec![
Cell::from(Span::raw(format!(
"{} {}",
sys.get_name().unwrap_or_else(|| "<unknown>".to_owned()),
sys.get_kernel_version()
.unwrap_or_else(|| "<unknown>".to_owned())
))),
Cell::from(Span::raw(format!(
"Version {}",
sys.get_os_version()
.unwrap_or_else(|| "<unknown>".to_owned())
))),
Cell::from(Span::raw(
sys.get_host_name()
.unwrap_or_else(|| "<unknown>".to_string()),
)),
],
];
let mut s = sys
.get_disks()
.iter()
.map(|i| {
(
i.get_mount_point().to_str().unwrap().to_string(),
vec![
Cell::from(Span::raw(format!(
"{:?} {}",
i.get_type(),
i.get_mount_point().to_str().unwrap()
))),
Cell::from(Span::styled(
format!("Free {:.3}GB", i.get_available_space() as f32 / 1e9),
Style::default().fg(Color::Yellow),
)),
Cell::from(Span::raw(format!(
"Total {:.3}GB",
i.get_total_space() as f32 / 1e9
))),
],
)
})
.collect::<Vec<(String, Vec<Cell>)>>();
macro_rules! gao {
($arg:tt) => {
($arg).sort_by_key(|x| x.0.to_owned());
let s: Vec<Vec<Cell>> = ($arg).into_iter().map(|x| x.1).collect();
items.push(vec![]);
for i in s.into_iter() {
items.push(i);
}
};
}
gao!(s);
let mut s = sys
.get_networks()
.iter()
.map(|(a, b)| {
let mut a = a.clone();
a.truncate(20);
(
a.to_owned(),
vec![
Cell::from(Span::raw(a)),
Cell::from(Span::raw(format!(
"Download {:.3}GB",
b.get_total_received() as f32 / 1e9
))),
Cell::from(Span::raw(format!(
"Upload {:.3}GB",
b.get_total_transmitted() as f32 / 1e9
))),
],
)
})
.collect::<Vec<(String, Vec<Cell>)>>();
gao!(s);
let mut s = sys
.get_components()
.iter()
.map(|x| {
(
x.get_label().to_string(),
vec![
Cell::from(Span::raw(x.get_label().to_string())),
Cell::from(Span::raw(format!("Temp {:.3}", x.get_temperature()))),
Cell::from(Span::raw(format!("Max {:.3}", x.get_max()))),
],
)
})
.collect::<Vec<(String, Vec<Cell>)>>();
gao!(s);
items
}
None => {
vec![vec![Cell::from(Span::raw("loading".to_string()))]]
}
};
let items: Vec<Row> = items.into_iter().map(Row::new).collect();
let table = Table::new(items)
.block(Block::default().title("Hardware").borders(Borders::ALL))
.widths(&[
Constraint::Percentage(40),
Constraint::Percentage(30),
Constraint::Percentage(30),
]);
f.render_widget(table, area);
}
fn drawLocalInfo<B: Backend>(f: &mut Frame<B>, area: Rect, x: &Option<SessionStats>, mask: u8) {
let chunks = Layout::default()
.constraints(
[
Constraint::Percentage(33),
Constraint::Percentage(33),
Constraint::Percentage(33),
]
.as_ref(),
)
.direction(Direction::Vertical)
.split(area);
let items: Vec<Vec<Cell>> = match x {
Some(x) => {
vec![
vec![
Cell::from(Span::raw(format!(
"Active Torrents {}",
x.activeTorrentCount
))),
Cell::from(Span::raw(format!(
"Paused Torrents {}",
x.pausedTorrentCount
))),
Cell::from(Span::raw(format!("Torrents {}", x.torrentCount))),
],
vec![
Cell::from(Span::raw(format!(
"uploadSpeed {:.3} MB/s",
x.uploadSpeed as f32 / 1e6
))),
Cell::from(Span::raw(format!(
"downloadSpeed {:.3} MB/s",
x.downloadSpeed as f32 / 1e6
))),
getUpdatedInfoCell(mask),
],
]
}
None => {
vec![vec![Cell::from(Span::raw("loading".to_string()))]]
}
};
let items: Vec<Row> = items.into_iter().map(Row::new).collect();
let table = Table::new(items)
.block(Block::default().title("BT").borders(Borders::ALL))
.widths(&[
Constraint::Percentage(30),
Constraint::Percentage(30),
Constraint::Percentage(30),
]);
f.render_widget(table, chunks[0]);
if let Some(x) = x {
drawStats(f, chunks[1], &x.current_stats, "current");
drawStats(f, chunks[2], &x.cumulative_stats, "cumulative");
}
}
fn drawStats<B: Backend>(f: &mut Frame<B>, area: Rect, x: &Stats, head: &str) {
let (days, hours, minutes, secs) = splitTime(x.secondsActive);
let items: Vec<Vec<Cell>> = vec![
vec![
Cell::from(Span::raw(format!(
"Uploaded {:.3}GB",
x.uploadedBytes as f32 / 1e9
))),
Cell::from(Span::raw(format!(
"Downloaded {:.3}GB",
x.downloadedBytes as f32 / 1e9
))),
],
vec![
Cell::from(Span::raw(format!("Files Added {}", x.filesAdded))),
Cell::from(Span::raw(format!("Sessions {}", x.sessionCount))),
Cell::from(Span::raw(format!(
"Active {} days {} hours {} mins {}",
days, hours, minutes, secs
))),
],
];
let items: Vec<Row> = items.into_iter().map(Row::new).collect();
let table = Table::new(items)
.block(Block::default().title(head).borders(Borders::ALL))
.widths(&[
Constraint::Percentage(30),
Constraint::Percentage(30),
Constraint::Percentage(30),
]);
f.render_widget(table, area);
}
| 34.566745 | 100 | 0.419986 |
e8808027416c93624a065b45df7b35f3678bac11
| 894 |
//! Small tool to get public IP address.
#![forbid(missing_debug_implementations, missing_docs, unsafe_code)]
use std::collections::HashMap;
use reqwest::Client;
/// Make a request to the specified `url` and returns a `HashMap` containing the JSON response.
async fn json_resp(client: &Client, url: &str) -> Result<HashMap<String, String>, Box<dyn std::error::Error>> {
let resp = client.get(url)
.send()
.await?
.json::<HashMap<String, String>>()
.await?;
Ok(resp)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let ipv4 = json_resp(&client, "https://api.ipify.org?format=json").await?;
let ipv6 = json_resp(&client, "https://api64.ipify.org?format=json").await?;
println!("IPv4: {}", ipv4.get("ip").unwrap());
println!("IPv6: {}", ipv6.get("ip").unwrap());
Ok(())
}
| 33.111111 | 111 | 0.630872 |
875daea5c6c6bd043dda4ec0275630158db95d8d
| 4,456 |
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use crate::Rect;
use crate::Vec3;
use glib::translate::*;
glib::glib_wrapper! {
#[derive(Debug, PartialOrd, Ord, Hash)]
pub struct Point3D(Boxed<ffi::graphene_point3d_t>);
match fn {
copy => |ptr| glib::gobject_ffi::g_boxed_copy(ffi::graphene_point3d_get_type(), ptr as *mut _) as *mut ffi::graphene_point3d_t,
free => |ptr| glib::gobject_ffi::g_boxed_free(ffi::graphene_point3d_get_type(), ptr as *mut _),
init => |_ptr| (),
clear => |_ptr| (),
get_type => || ffi::graphene_point3d_get_type(),
}
}
impl Point3D {
pub fn cross(&self, b: &Point3D) -> Point3D {
unsafe {
let mut res = Point3D::uninitialized();
ffi::graphene_point3d_cross(
self.to_glib_none().0,
b.to_glib_none().0,
res.to_glib_none_mut().0,
);
res
}
}
pub fn distance(&self, b: &Point3D) -> (f32, Vec3) {
unsafe {
let mut delta = Vec3::uninitialized();
let ret = ffi::graphene_point3d_distance(
self.to_glib_none().0,
b.to_glib_none().0,
delta.to_glib_none_mut().0,
);
(ret, delta)
}
}
pub fn dot(&self, b: &Point3D) -> f32 {
unsafe { ffi::graphene_point3d_dot(self.to_glib_none().0, b.to_glib_none().0) }
}
fn equal(&self, b: &Point3D) -> bool {
unsafe {
from_glib(ffi::graphene_point3d_equal(
self.to_glib_none().0,
b.to_glib_none().0,
))
}
}
pub fn init(&mut self, x: f32, y: f32, z: f32) {
unsafe {
ffi::graphene_point3d_init(self.to_glib_none_mut().0, x, y, z);
}
}
pub fn init_from_point(&mut self, src: &Point3D) {
unsafe {
ffi::graphene_point3d_init_from_point(self.to_glib_none_mut().0, src.to_glib_none().0);
}
}
pub fn init_from_vec3(&mut self, v: &Vec3) {
unsafe {
ffi::graphene_point3d_init_from_vec3(self.to_glib_none_mut().0, v.to_glib_none().0);
}
}
pub fn interpolate(&self, b: &Point3D, factor: f64) -> Point3D {
unsafe {
let mut res = Point3D::uninitialized();
ffi::graphene_point3d_interpolate(
self.to_glib_none().0,
b.to_glib_none().0,
factor,
res.to_glib_none_mut().0,
);
res
}
}
pub fn length(&self) -> f32 {
unsafe { ffi::graphene_point3d_length(self.to_glib_none().0) }
}
pub fn near(&self, b: &Point3D, epsilon: f32) -> bool {
unsafe {
from_glib(ffi::graphene_point3d_near(
self.to_glib_none().0,
b.to_glib_none().0,
epsilon,
))
}
}
pub fn normalize(&self) -> Point3D {
unsafe {
let mut res = Point3D::uninitialized();
ffi::graphene_point3d_normalize(self.to_glib_none().0, res.to_glib_none_mut().0);
res
}
}
pub fn normalize_viewport(&self, viewport: &Rect, z_near: f32, z_far: f32) -> Point3D {
unsafe {
let mut res = Point3D::uninitialized();
ffi::graphene_point3d_normalize_viewport(
self.to_glib_none().0,
viewport.to_glib_none().0,
z_near,
z_far,
res.to_glib_none_mut().0,
);
res
}
}
pub fn scale(&self, factor: f32) -> Point3D {
unsafe {
let mut res = Point3D::uninitialized();
ffi::graphene_point3d_scale(self.to_glib_none().0, factor, res.to_glib_none_mut().0);
res
}
}
pub fn to_vec3(&self) -> Vec3 {
unsafe {
let mut v = Vec3::uninitialized();
ffi::graphene_point3d_to_vec3(self.to_glib_none().0, v.to_glib_none_mut().0);
v
}
}
pub fn zero() -> Point3D {
assert_initialized_main_thread!();
unsafe { from_glib_none(ffi::graphene_point3d_zero()) }
}
}
impl PartialEq for Point3D {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.equal(other)
}
}
impl Eq for Point3D {}
| 28.382166 | 135 | 0.527154 |
393f52c81911645e3ebb79290f050ec69f1e4171
| 72 |
const INPUT: &str = include_str!("../input.txt");
util::bench!(day_12);
| 24 | 49 | 0.652778 |
75f435e1b75f8a89d20b7664747c6d4e9e58d51d
| 1,384 |
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate kitsu;
extern crate tokio_core;
use futures::Future;
use futures::stream::Stream;
use hyper::Client;
use hyper_tls::HttpsConnector;
use kitsu::KitsuHyperRequester;
use std::io::{self, Write};
use tokio_core::reactor::Core;
fn main() {
// Read an anime name to search for from the users input.
let mut input = String::new();
print!("Enter an anime name to search for:\n>");
let _ = io::stdout().flush();
io::stdin().read_line(&mut input).expect("Error reading input");
let input_trimmed = input.trim();
// Create the core and client which will be uesd to search.
let mut core = Core::new().expect("Error creating reactor core");
let connector = HttpsConnector::new(1, &core.handle())
.expect("Error creating connector");
let client = Client::configure()
.connector(connector)
.build(&core.handle());
// Search for the anime and return the response.
let runner = client.search_anime(|f| f.filter("text", input_trimmed))
.expect("Error making request")
.and_then(|res| {
res.body().for_each(|chunk| {
io::stdout().write_all(&chunk).map_err(From::from)
})
}).map(|_| {
println!("\n\nDone")
});
core.run(runner).expect("Error running core");
}
| 30.755556 | 73 | 0.634393 |
110ff38c4fcf1ec6446d56f508bcfde679540c79
| 8,795 |
use std::io;
use std::fmt;
use std::collections::HashMap;
use super::{
Allocation,
BacktraceId,
CodePointer,
Data,
Frame,
StringId,
Timestamp,
Operation
};
use crate::io_adapter::IoAdapter;
#[derive(PartialEq, Eq, Hash)]
struct AllocInfo {
size: u64,
backtrace: usize
}
struct Child {
ip_index: usize,
trace_node_index: usize
}
struct TraceNode {
children: Vec< Child >
}
pub struct HeaptrackExporter< 'a, T: fmt::Write > {
alloc_info_to_index: HashMap< AllocInfo, usize >,
backtrace_to_index: HashMap< BacktraceId, usize >,
ip_to_index: HashMap< CodePointer, usize >,
string_map: HashMap< StringId, usize >,
trace_tree: Vec< TraceNode >,
tx: T,
data: &'a Data,
last_elapsed: Timestamp
}
/*
Format of the heaptrack data file:
Header:
v <heaptrack_version> <file_format_version>
X <cmdline>
I <page_size> <total_memory_in_pages>
Allocation:
+ <alloc_info_index>
Deallocation:
- <alloc_info_index>
Alloc info:
a <size> <trace_index>
Trace:
t <ip_index> <parent_trace_index>
IP:
i <address> <module_name_index> [<function_name_index>] [<file_name_index> <line>] [for each inlined frame: <function_name_index> <file_name_index> <line>]...
String:
s <string>
*/
impl< 'a, T: fmt::Write > HeaptrackExporter< 'a, T > {
fn new( data: &'a Data, mut tx: T ) -> Result< Self, fmt::Error > {
writeln!( tx, "v 10100 2" )?;
writeln!( tx, "X {}", data.executable() )?;
let exporter = HeaptrackExporter {
alloc_info_to_index: HashMap::new(),
backtrace_to_index: HashMap::new(),
ip_to_index: HashMap::new(),
string_map: HashMap::new(),
trace_tree: vec![ TraceNode {
children: Vec::new()
}],
tx,
data,
last_elapsed: Timestamp::min()
};
Ok( exporter )
}
fn emit_timestamp( &mut self, timestamp: Timestamp ) -> Result< (), fmt::Error > {
let elapsed = timestamp - self.data.initial_timestamp();
if self.last_elapsed != elapsed {
writeln!( self.tx, "c {:x}", elapsed.as_msecs() )?;
self.last_elapsed = elapsed;
}
Ok(())
}
fn get_size( &self, allocation: &Allocation ) -> u64 {
allocation.size + allocation.extra_usable_space as u64
}
pub fn handle_alloc( &mut self, allocation: &Allocation ) -> Result< (), fmt::Error > {
let alloc_info = AllocInfo {
size: self.get_size( allocation ),
backtrace: self.resolve_backtrace( allocation.backtrace )?
};
self.emit_timestamp( allocation.timestamp )?;
let alloc_info_index = self.resolve_alloc_info( alloc_info )?;
writeln!( self.tx, "+ {:x}", alloc_info_index )
}
pub fn handle_dealloc( &mut self, allocation: &Allocation ) -> Result< (), fmt::Error > {
let alloc_info = AllocInfo {
size: self.get_size( allocation ),
backtrace: self.resolve_backtrace( allocation.backtrace )?
};
self.emit_timestamp( allocation.timestamp )?;
let alloc_info_index = self.alloc_info_to_index.get( &alloc_info ).unwrap();
writeln!( self.tx, "- {:x}", alloc_info_index )
}
fn resolve_backtrace( &mut self, backtrace_id: BacktraceId ) -> Result< usize, fmt::Error > {
if let Some( &index ) = self.backtrace_to_index.get( &backtrace_id ) {
return Ok( index );
}
let mut parent_trace_index = 0;
let frame_ids = self.data.get_frame_ids( backtrace_id );
if frame_ids.is_empty() {
warn!( "Empty backtrace with ID = {:?}", backtrace_id );
return Ok( 0 );
}
let mut i = frame_ids.len() - 1;
while i > 0 {
let frame = self.data.get_frame( frame_ids[ i ] );
if frame.is_inline() {
i -= 1;
continue;
}
i -= 1;
let ip_index = self.resolve_ip( frame )?;
if let Some( child ) = self.trace_tree[ parent_trace_index ].children.iter().find( |child| child.ip_index == ip_index ) {
parent_trace_index = child.trace_node_index;
continue;
}
let trace_node_index = self.trace_tree.len();
self.trace_tree.push( TraceNode {
children: Vec::new()
});
self.trace_tree[ parent_trace_index ].children.push( Child {
ip_index,
trace_node_index
});
writeln!( self.tx, "t {:x} {:x}", ip_index, parent_trace_index )?;
parent_trace_index = trace_node_index;
}
self.backtrace_to_index.insert( backtrace_id, parent_trace_index );
Ok( parent_trace_index )
}
fn resolve_ip( &mut self, frame: &Frame ) -> Result< usize, fmt::Error > {
let address = frame.address();
if let Some( &index ) = self.ip_to_index.get( &address ) {
return Ok( index );
}
let module_name_index;
if let Some( library_id ) = frame.library() {
module_name_index = self.resolve_string( library_id )?;
} else {
module_name_index = 0;
}
let function_name_index;
let source;
if let Some( id ) = frame.function().or( frame.raw_function() ) {
function_name_index = Some( self.resolve_string( id )? );
} else {
function_name_index = None;
};
match (frame.source(), frame.line()) {
(Some( id ), Some( line )) => {
let index = self.resolve_string( id )?;
source = Some( (index, line) );
},
_ => {
source = None;
}
}
write!( self.tx, "i {:x} {:x}", frame.address().raw(), module_name_index )?;
if let Some( index ) = function_name_index {
write!( self.tx, " {:x}", index )?;
if let Some( (index, line) ) = source {
write!( self.tx, " {:x} {:x}", index, line )?;
}
}
writeln!( self.tx, "" )?;
let index = self.ip_to_index.len() + 1;
self.ip_to_index.insert( address, index );
Ok( index )
}
fn resolve_string( &mut self, string_id: StringId ) -> Result< usize, fmt::Error > {
if let Some( &index ) = self.string_map.get( &string_id ) {
return Ok( index );
}
writeln!( self.tx, "s {}", self.data.interner().resolve( string_id ).unwrap() )?;
let index = self.string_map.len() + 1;
self.string_map.insert( string_id, index );
Ok( index )
}
fn resolve_alloc_info( &mut self, alloc_info: AllocInfo ) -> Result< usize, fmt::Error > {
let alloc_info_index = self.alloc_info_to_index.get( &alloc_info ).cloned();
let alloc_info_index = match alloc_info_index {
Some( value ) => value,
None => {
writeln!( self.tx, "a {:x} {:x}", alloc_info.size, alloc_info.backtrace )?;
let index = self.alloc_info_to_index.len();
self.alloc_info_to_index.insert( alloc_info, index );
index
}
};
Ok( alloc_info_index )
}
}
fn io_err< T: fmt::Display >( err: T ) -> io::Error {
io::Error::new( io::ErrorKind::Other, format!( "serialization failed: {}", err ) )
}
pub fn export_as_heaptrack< T: io::Write, F: Fn( &Allocation ) -> bool >( data: &Data, data_out: T, filter: F ) -> io::Result< () > {
let mut exporter = HeaptrackExporter::new( data, IoAdapter::new( data_out ) ).map_err( io_err )?;
for op in data.operations() {
match op {
Operation::Allocation { allocation, .. } => {
if !filter( allocation ) {
continue;
}
exporter.handle_alloc( allocation ).map_err( io_err )?;
},
Operation::Deallocation { allocation, .. } => {
if !filter( allocation ) {
continue;
}
exporter.handle_dealloc( allocation ).map_err( io_err )?;
},
Operation::Reallocation { old_allocation, new_allocation, .. } => {
if filter( old_allocation ) {
exporter.handle_dealloc( old_allocation ).map_err( io_err )?;
}
if filter( new_allocation ) {
exporter.handle_alloc( new_allocation ).map_err( io_err )?;
}
}
}
}
Ok(())
}
| 30.96831 | 166 | 0.54008 |
8a079f9857cf5029cf2bb39699af80069fb3eb32
| 3,519 |
use super::decoder::Decoder;
use super::encoder::Encoder;
use super::{threading, Compliance, Debug, Flags, Id, Parameters};
use crate::ffi::*;
use crate::media;
use crate::{Codec, Error};
use libc::c_int;
use std::ptr;
use std::rc::Rc;
pub struct Context {
ptr: *mut AVCodecContext,
owner: Option<Rc<dyn Drop>>,
}
unsafe impl Send for Context {}
impl Context {
pub unsafe fn wrap(ptr: *mut AVCodecContext, owner: Option<Rc<dyn Drop>>) -> Self {
Context { ptr, owner }
}
pub unsafe fn as_ptr(&self) -> *const AVCodecContext {
self.ptr as *const _
}
pub unsafe fn as_mut_ptr(&mut self) -> *mut AVCodecContext {
self.ptr
}
}
impl Context {
pub fn new() -> Self {
unsafe {
Context {
ptr: avcodec_alloc_context3(ptr::null()),
owner: None,
}
}
}
pub fn decoder(self) -> Decoder {
Decoder(self)
}
pub fn encoder(self) -> Encoder {
Encoder(self)
}
pub fn codec(&self) -> Option<Codec> {
unsafe {
if (*self.as_ptr()).codec.is_null() {
None
} else {
Some(Codec::wrap((*self.as_ptr()).codec as *mut _))
}
}
}
pub fn medium(&self) -> media::Type {
unsafe { media::Type::from((*self.as_ptr()).codec_type) }
}
pub fn set_flags(&mut self, value: Flags) {
unsafe {
(*self.as_mut_ptr()).flags = value.bits() as c_int;
}
}
pub fn id(&self) -> Id {
unsafe { Id::from((*self.as_ptr()).codec_id) }
}
pub fn compliance(&mut self, value: Compliance) {
unsafe {
(*self.as_mut_ptr()).strict_std_compliance = value.into();
}
}
pub fn debug(&mut self, value: Debug) {
unsafe {
(*self.as_mut_ptr()).debug = value.bits();
}
}
pub fn set_threading(&mut self, config: threading::Config) {
unsafe {
(*self.as_mut_ptr()).thread_type = config.kind.into();
(*self.as_mut_ptr()).thread_count = config.count as c_int;
(*self.as_mut_ptr()).thread_safe_callbacks = if config.safe { 1 } else { 0 };
}
}
pub fn threading(&self) -> threading::Config {
unsafe {
threading::Config {
kind: threading::Type::from((*self.as_ptr()).active_thread_type),
count: (*self.as_ptr()).thread_count as usize,
safe: (*self.as_ptr()).thread_safe_callbacks != 0,
}
}
}
pub fn set_parameters<P: Into<Parameters>>(&mut self, parameters: P) -> Result<(), Error> {
let parameters = parameters.into();
unsafe {
match avcodec_parameters_to_context(self.as_mut_ptr(), parameters.as_ptr()) {
e if e < 0 => Err(Error::from(e)),
_ => Ok(()),
}
}
}
}
impl Default for Context {
fn default() -> Self {
Self::new()
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
if self.owner.is_none() {
avcodec_free_context(&mut self.as_mut_ptr());
}
}
}
}
impl Clone for Context {
fn clone(&self) -> Self {
let mut ctx = Context::new();
ctx.clone_from(self);
ctx
}
fn clone_from(&mut self, source: &Self) {
unsafe {
avcodec_copy_context(self.as_mut_ptr(), source.as_ptr());
}
}
}
| 24.10274 | 95 | 0.521455 |
d616c757a55498402e2e9324450458a61c31aa59
| 587 |
struct Solution;
use std::collections::HashMap;
impl Solution {
fn find_lhs(nums: Vec<i32>) -> i32 {
let mut hs: HashMap<i32, i32> = HashMap::new();
let mut max = 0;
for &x in &nums {
let e = hs.entry(x).or_default();
*e += 1;
}
for (x, u) in &hs {
if let Some(v) = hs.get(&(x - 1)) {
max = i32::max(u + v, max);
}
}
max
}
}
#[test]
fn test() {
let nums = vec![1, 3, 2, 2, 5, 2, 3, 7];
let res = 5;
assert_eq!(Solution::find_lhs(nums), res);
}
| 20.964286 | 55 | 0.439523 |
d79eff57443d0b50d114b95b7cba873fcbf54467
| 1,528 |
pub struct IconPayment {
props: crate::Props,
}
impl yew::Component for IconPayment {
type Properties = crate::Props;
type Message = ();
fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self
{
Self { props }
}
fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender
{
true
}
fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender
{
false
}
fn view(&self) -> yew::prelude::Html
{
yew::prelude::html! {
<svg
class=self.props.class.unwrap_or("")
width=self.props.size.unwrap_or(24).to_string()
height=self.props.size.unwrap_or(24).to_string()
viewBox="0 0 24 24"
fill=self.props.fill.unwrap_or("none")
stroke=self.props.color.unwrap_or("currentColor")
stroke-width=self.props.stroke_width.unwrap_or(2).to_string()
stroke-linecap=self.props.stroke_linecap.unwrap_or("round")
stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round")
>
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm-1 14H5c-.55 0-1-.45-1-1v-5h16v5c0 .55-.45 1-1 1zm1-10H4V7c0-.55.45-1 1-1h14c.55 0 1 .45 1 1v1z"/></svg>
</svg>
}
}
}
| 33.217391 | 339 | 0.574607 |
1d1bd38bda4c7ddff061292e29e335dca0148edf
| 848 |
use select::document::Document;
use reqwest::Url;
use reqwest;
use std::io::Read;
use social::WEBSITE;
pub(crate) fn remove_clutter(toshorten: String) -> String {
let toshorten = toshorten.replace("\t", "");
let toshorten = toshorten.replace("\n", "");
let toshorten = toshorten.replace("\"", "");
let toshorten = toshorten.trim();
return toshorten.to_string();
}
pub(crate) fn getcontent(url: &str) -> Result<Document, String> {
let url = Url::parse(&url).map_err(|e| e.to_string())?;
let mut resp = reqwest::get(url).map_err(|e| e.to_string() + "Could not connect to over.gg")?;
let mut content = String::new();
let _ = resp.read_to_string(&mut content);
Ok(Document::from(content.as_ref()))
}
pub(crate) fn fix_link(link: &str) -> String {
let link = WEBSITE.to_string() + link;
return link.to_string();
}
| 19.272727 | 95 | 0.659198 |
64a78a4708b417b6d90ac886c4d4f1d8e6241751
| 44,806 |
use std::collections::HashMap;
use dprint_core::configuration::*;
use super::resolve_config::resolve_config;
use super::types::*;
/// TypeScript formatting configuration builder.
///
/// # Example
///
/// ```
/// use dprint_plugin_typescript::configuration::*;
///
/// let config = ConfigurationBuilder::new()
/// .line_width(80)
/// .prefer_hanging(true)
/// .prefer_single_line(false)
/// .quote_style(QuoteStyle::PreferSingle)
/// .next_control_flow_position(NextControlFlowPosition::SameLine)
/// .build();
/// ```
pub struct ConfigurationBuilder {
pub(super) config: ConfigKeyMap,
global_config: Option<GlobalConfiguration>,
}
impl ConfigurationBuilder {
/// Constructs a new configuration builder.
pub fn new() -> ConfigurationBuilder {
ConfigurationBuilder {
config: HashMap::new(),
global_config: None,
}
}
/// Gets the final configuration that can be used to format a file.
pub fn build(&self) -> Configuration {
if let Some(global_config) = &self.global_config {
resolve_config(self.config.clone(), global_config).config
} else {
let global_config = resolve_global_config(HashMap::new()).config;
resolve_config(self.config.clone(), &global_config).config
}
}
/// Set the global configuration.
pub fn global_config(&mut self, global_config: GlobalConfiguration) -> &mut Self {
self.global_config = Some(global_config);
self
}
/// Helper method to set the configuration to what's used for Deno.
pub fn deno(&mut self) -> &mut Self {
self.line_width(80)
.indent_width(2)
.next_control_flow_position(NextControlFlowPosition::SameLine)
.binary_expression_operator_position(OperatorPosition::SameLine)
.brace_position(BracePosition::SameLine)
.comment_line_force_space_after_slashes(false)
.construct_signature_space_after_new_keyword(true)
.constructor_type_space_after_new_keyword(true)
.arrow_function_use_parentheses(UseParentheses::Force)
.new_line_kind(NewLineKind::LineFeed)
.function_expression_space_after_function_keyword(true)
.tagged_template_space_before_literal(false)
.conditional_expression_prefer_single_line(true)
.quote_style(QuoteStyle::PreferDouble)
.ignore_node_comment_text("deno-fmt-ignore")
.ignore_file_comment_text("deno-fmt-ignore-file")
.module_sort_import_declarations(SortOrder::Maintain)
.module_sort_export_declarations(SortOrder::Maintain)
}
/// The width of a line the printer will try to stay under. Note that the printer may exceed this width in certain cases.
///
/// Default: `120`
pub fn line_width(&mut self, value: u32) -> &mut Self {
self.insert("lineWidth", (value as i32).into())
}
/// Whether to use tabs (true) or spaces (false).
///
/// Default: `false`
pub fn use_tabs(&mut self, value: bool) -> &mut Self {
self.insert("useTabs", value.into())
}
/// The number of columns for an indent.
///
/// Default: `4`
pub fn indent_width(&mut self, value: u8) -> &mut Self {
self.insert("indentWidth", (value as i32).into())
}
/// The kind of newline to use.
///
/// Default: `NewLineKind::LineFeed`
pub fn new_line_kind(&mut self, value: NewLineKind) -> &mut Self {
self.insert("newLineKind", value.to_string().into())
}
/// The quote style to use.
///
/// Default: `QuoteStyle::AlwaysDouble`
pub fn quote_style(&mut self, value: QuoteStyle) -> &mut Self {
self.insert("quoteStyle", value.to_string().into())
}
/// Whether statements should end in a semi-colon.
///
/// Default: `SemiColons::Prefer`
pub fn semi_colons(&mut self, value: SemiColons) -> &mut Self {
self.insert("semiColons", value.to_string().into())
}
/// Set to prefer hanging indentation when exceeding the line width.
///
/// Default: `false`
pub fn prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("preferHanging", value.into())
}
/// Where to place the opening brace.
///
/// Default: `BracePosition::SameLineUnlessHanging`
pub fn brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("bracePosition", value.to_string().into())
}
/// Where to place the next control flow within a control flow statement.
///
/// Default: `NextControlFlowPosition::NextLine`
pub fn next_control_flow_position(&mut self, value: NextControlFlowPosition) -> &mut Self {
self.insert("nextControlFlowPosition", value.to_string().into())
}
/// Where to place the operator for expressions that span multiple lines.
///
/// Default: `OperatorPosition::NextLine`
pub fn operator_position(&mut self, value: OperatorPosition) -> &mut Self {
self.insert("operatorPosition", value.to_string().into())
}
/// Where to place the expression of a statement that could possibly be on one line (ex. `if (true) console.log(5);`).
///
/// Default: SingleBodyPosition::Maintain
pub fn single_body_position(&mut self, value: SingleBodyPosition) -> &mut Self {
self.insert("singleBodyPosition", value.to_string().into())
}
/// If trailing commas should be used.
///
/// Default: `TrailingCommas::OnlyMultiLine`
pub fn trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("trailingCommas", value.to_string().into())
}
/// If braces should be used or not.
///
/// Default: `UseBraces::WhenNotSingleLine`
pub fn use_braces(&mut self, value: UseBraces) -> &mut Self {
self.insert("useBraces", value.to_string().into())
}
/// If code should revert back from being on multiple lines to
/// being on a single line when able.
///
/// Default: `false`
pub fn prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("preferSingleLine", value.into())
}
/* space settings */
/// Whether to surround bitwise and arithmetic operators in a binary expression with spaces.
///
/// * `true` (default) - Ex. `1 + 2`
/// * `false` - Ex. `1+2`
pub fn binary_expression_space_surrounding_bitwise_and_arithmetic_operator(&mut self, value: bool) -> &mut Self {
self.insert("binaryExpression.spaceSurroundingBitwiseAndArithmeticOperator", value.into())
}
/// Forces a space after the double slash in a comment line.
///
/// `true` (default) - Ex. `//test` -> `// test`
/// `false` - Ex. `//test` -> `//test`
pub fn comment_line_force_space_after_slashes(&mut self, value: bool) -> &mut Self {
self.insert("commentLine.forceSpaceAfterSlashes", value.into())
}
/// Whether to add a space after the `new` keyword in a construct signature.
///
/// `true` - Ex. `new (): MyClass;`
/// `false` (default) - Ex. `new(): MyClass;`
pub fn construct_signature_space_after_new_keyword(&mut self, value: bool) -> &mut Self {
self.insert("constructSignature.spaceAfterNewKeyword", value.into())
}
/// Whether to add a space before the parentheses of a constructor.
///
/// `true` - Ex. `constructor ()`
/// `false` (false) - Ex. `constructor()`
pub fn constructor_space_before_parentheses(&mut self, value: bool) -> &mut Self {
self.insert("constructor.spaceBeforeParentheses", value.into())
}
/// Whether to add a space after the `new` keyword in a constructor type.
///
/// `true` - Ex. `type MyClassCtor = new () => MyClass;`
/// `false` (default) - Ex. `type MyClassCtor = new() => MyClass;`
pub fn constructor_type_space_after_new_keyword(&mut self, value: bool) -> &mut Self {
self.insert("constructorType.spaceAfterNewKeyword", value.into())
}
/// Whether to add a space after the `while` keyword in a do while statement.
///
/// `true` (true) - Ex. `do {\n} while (condition);`
/// `false` - Ex. `do {\n} while(condition);`
pub fn do_while_statement_space_after_while_keyword(&mut self, value: bool) -> &mut Self {
self.insert("doWhileStatement.spaceAfterWhileKeyword", value.into())
}
/// Whether to add spaces around named exports in an export declaration.
///
/// * `true` (default) - Ex. `export { SomeExport, OtherExport };`
/// * `false` - Ex. `export {SomeExport, OtherExport};`
pub fn export_declaration_space_surrounding_named_exports(&mut self, value: bool) -> &mut Self {
self.insert("exportDeclaration.spaceSurroundingNamedExports", value.into())
}
/// Whether to add a space after the `for` keyword in a "for" statement.
///
/// * `true` (default) - Ex. `for (let i = 0; i < 5; i++)`
/// * `false` - Ex. `for(let i = 0; i < 5; i++)`
pub fn for_statement_space_after_for_keyword(&mut self, value: bool) -> &mut Self {
self.insert("forStatement.spaceAfterForKeyword", value.into())
}
/// Whether to add a space after the semi-colons in a "for" statement.
///
/// * `true` (default) - Ex. `for (let i = 0; i < 5; i++)`
/// * `false` - Ex. `for (let i = 0;i < 5;i++)`
pub fn for_statement_space_after_semi_colons(&mut self, value: bool) -> &mut Self {
self.insert("forStatement.spaceAfterSemiColons", value.into())
}
/// Whether to add a space after the `for` keyword in a "for in" statement.
///
/// * `true` (default) - Ex. `for (const prop in obj)`
/// * `false` - Ex. `for(const prop in obj)`
pub fn for_in_statement_space_after_for_keyword(&mut self, value: bool) -> &mut Self {
self.insert("forInStatement.spaceAfterForKeyword", value.into())
}
/// Whether to add a space after the `for` keyword in a "for of" statement.
///
/// * `true` (default) - Ex. `for (const value of myArray)`
/// * `false` - Ex. `for(const value of myArray)`
pub fn for_of_statement_space_after_for_keyword(&mut self, value: bool) -> &mut Self {
self.insert("forOfStatement.spaceAfterForKeyword", value.into())
}
/// Whether to add a space before the parentheses of a function declaration.
///
/// * `true` - Ex. `function myFunction ()`
/// * `false` (default) - Ex. `function myFunction()`
pub fn function_declaration_space_before_parentheses(&mut self, value: bool) -> &mut Self {
self.insert("functionDeclaration.spaceBeforeParentheses", value.into())
}
/// Whether to add a space before the parentheses of a function expression.
///
/// `true` - Ex. `function<T> ()`
/// `false` (default) - Ex. `function<T> ()`
pub fn function_expression_space_before_parentheses(&mut self, value: bool) -> &mut Self {
self.insert("functionExpression.spaceBeforeParentheses", value.into())
}
/// Whether to add a space after the function keyword of a function expression.
///
/// `true` - Ex. `function <T>()`.
/// `false` (default) - Ex. `function<T>()`
pub fn function_expression_space_after_function_keyword(&mut self, value: bool) -> &mut Self {
self.insert("functionExpression.spaceAfterFunctionKeyword", value.into())
}
/// Whether to add a space before the parentheses of a get accessor.
///
/// `true` - Ex. `get myProp ()`
/// `false` (false) - Ex. `get myProp()`
pub fn get_accessor_space_before_parentheses(&mut self, value: bool) -> &mut Self {
self.insert("getAccessor.spaceBeforeParentheses", value.into())
}
/// Whether to add a space after the `if` keyword in an "if" statement.
///
/// `true` (default) - Ex. `if (true)`
/// `false` - Ex. `if(true)`
pub fn if_statement_space_after_if_keyword(&mut self, value: bool) -> &mut Self {
self.insert("ifStatement.spaceAfterIfKeyword", value.into())
}
/// Whether to add spaces around named imports in an import declaration.
///
/// * `true` (default) - Ex. `import { SomeExport, OtherExport } from "my-module";`
/// * `false` - Ex. `import {SomeExport, OtherExport} from "my-module";`
pub fn import_declaration_space_surrounding_named_imports(&mut self, value: bool) -> &mut Self {
self.insert("importDeclaration.spaceSurroundingNamedImports", value.into())
}
/// Whether to add a space surrounding the expression of a JSX container.
///
/// * `true` - Ex. `{ myValue }`
/// * `false` (default) - Ex. `{myValue}`
pub fn jsx_expression_container_space_surrounding_expression(&mut self, value: bool) -> &mut Self {
self.insert("jsxExpressionContainer.spaceSurroundingExpression", value.into())
}
/// Whether to add a space before the parentheses of a method.
///
/// `true` - Ex. `myMethod ()`
/// `false` - Ex. `myMethod()`
pub fn method_space_before_parentheses(&mut self, value: bool) -> &mut Self {
self.insert("method.spaceBeforeParentheses", value.into())
}
/// Whether to add a space before the parentheses of a set accessor.
///
/// `true` - Ex. `set myProp (value: string)`
/// `false` (default) - Ex. `set myProp(value: string)`
pub fn set_accessor_space_before_parentheses(&mut self, value: bool) -> &mut Self {
self.insert("setAccessor.spaceBeforeParentheses", value.into())
}
/// Whether to add a space before the literal in a tagged template.
///
/// * `true` (default) - Ex. `html \`<element />\``
/// * `false` - Ex. `html\`<element />\``
pub fn tagged_template_space_before_literal(&mut self, value: bool) -> &mut Self {
self.insert("taggedTemplate.spaceBeforeLiteral", value.into())
}
/// Whether to add a space before the colon of a type annotation.
///
/// * `true` - Ex. `function myFunction() : string`
/// * `false` (default) - Ex. `function myFunction(): string`
pub fn type_annotation_space_before_colon(&mut self, value: bool) -> &mut Self {
self.insert("typeAnnotation.spaceBeforeColon", value.into())
}
/// Whether to add a space before the expression in a type assertion.
///
/// * `true` (default) - Ex. `<string> myValue`
/// * `false` - Ex. `<string>myValue`
pub fn type_assertion_space_before_expression(&mut self, value: bool) -> &mut Self {
self.insert("typeAssertion.spaceBeforeExpression", value.into())
}
/// Whether to add a space after the `while` keyword in a while statement.
///
/// * `true` (default) - Ex. `while (true)`
/// * `false` - Ex. `while(true)`
pub fn while_statement_space_after_while_keyword(&mut self, value: bool) -> &mut Self {
self.insert("whileStatement.spaceAfterWhileKeyword", value.into())
}
/* situational */
/// Whether to use parentheses for arrow functions.
///
/// Default: `UseParentheses::Maintain`
pub fn arrow_function_use_parentheses(&mut self, value: UseParentheses) -> &mut Self {
self.insert("arrowFunction.useParentheses", value.to_string().into())
}
/// Whether to force a line per expression when spanning multiple lines.
///
/// * `true` - Formats with each part on a new line.
/// * `false` (default) - Maintains the line breaks as written by the programmer.
pub fn binary_expression_line_per_expression(&mut self, value: bool) -> &mut Self {
self.insert("binaryExpression.linePerExpression", value.into())
}
/// Whether to force a line per expression when spanning multiple lines.
///
/// * `true` - Formats with each part on a new line.
/// * `false` (default) - Maintains the line breaks as written by the programmer.
pub fn member_expression_line_per_expression(&mut self, value: bool) -> &mut Self {
self.insert("memberExpression.linePerExpression", value.into())
}
/// The kind of separator to use in type literals.
pub fn type_literal_separator_kind(&mut self, value: SemiColonOrComma) -> &mut Self {
self.insert("typeLiteral.separatorKind", value.to_string().into())
}
/// The kind of separator to use in type literals when single line.
pub fn type_literal_separator_kind_single_line(&mut self, value: SemiColonOrComma) -> &mut Self {
self.insert("typeLiteral.separatorKind.singleLine", value.to_string().into())
}
/// The kind of separator to use in type literals when multi-line.
pub fn type_literal_separator_kind_multi_line(&mut self, value: SemiColonOrComma) -> &mut Self {
self.insert("typeLiteral.separatorKind.multiLine", value.to_string().into())
}
/* sorting */
/// Alphabetically sorts the import declarations based on their module specifiers.
///
/// Default: Case insensitive
pub fn module_sort_import_declarations(&mut self, value: SortOrder) -> &mut Self {
self.insert("module.sortImportDeclarations", value.to_string().into())
}
/// Alphabetically sorts the export declarations based on their module specifiers.
///
/// Default: Case insensitive
pub fn module_sort_export_declarations(&mut self, value: SortOrder) -> &mut Self {
self.insert("module.sortExportDeclarations", value.to_string().into())
}
/// Alphabetically sorts the import declaration's named imports.
///
/// Default: Case insensitive
pub fn import_declaration_sort_named_imports(&mut self, value: SortOrder) -> &mut Self {
self.insert("importDeclaration.sortNamedImports", value.to_string().into())
}
/// Alphabetically sorts the export declaration's named exports.
///
/// Default: Case insensitive
pub fn export_declaration_sort_named_exports(&mut self, value: SortOrder) -> &mut Self {
self.insert("exportDeclaration.sortNamedExports", value.to_string().into())
}
/* ignore comments */
/// The text to use for an ignore comment (ex. `// dprint-ignore`).
///
/// Default: `"dprint-ignore"`
pub fn ignore_node_comment_text(&mut self, value: &str) -> &mut Self {
self.insert("ignoreNodeCommentText", value.into())
}
/// The text to use for a file ignore comment (ex. `// dprint-ignore-file`).
///
/// Default: `"dprint-ignore-file"`
pub fn ignore_file_comment_text(&mut self, value: &str) -> &mut Self {
self.insert("ignoreFileCommentText", value.into())
}
/* brace position */
pub fn arrow_function_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("arrowFunction.bracePosition", value.to_string().into())
}
pub fn class_declaration_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("classDeclaration.bracePosition", value.to_string().into())
}
pub fn class_expression_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("classExpression.bracePosition", value.to_string().into())
}
pub fn constructor_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("constructor.bracePosition", value.to_string().into())
}
pub fn do_while_statement_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("doWhileStatement.bracePosition", value.to_string().into())
}
pub fn enum_declaration_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("enumDeclaration.bracePosition", value.to_string().into())
}
pub fn for_statement_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("forStatement.bracePosition", value.to_string().into())
}
pub fn for_in_statement_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("forInStatement.bracePosition", value.to_string().into())
}
pub fn for_of_statement_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("forOfStatement.bracePosition", value.to_string().into())
}
pub fn get_accessor_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("getAccessor.bracePosition", value.to_string().into())
}
pub fn if_statement_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("ifStatement.bracePosition", value.to_string().into())
}
pub fn interface_declaration_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("interfaceDeclaration.bracePosition", value.to_string().into())
}
pub fn function_declaration_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("functionDeclaration.bracePosition", value.to_string().into())
}
pub fn function_expression_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("functionExpression.bracePosition", value.to_string().into())
}
pub fn method_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("method.bracePosition", value.to_string().into())
}
pub fn module_declaration_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("moduleDeclaration.bracePosition", value.to_string().into())
}
pub fn set_accessor_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("setAccessor.bracePosition", value.to_string().into())
}
pub fn switch_case_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("switchCase.bracePosition", value.to_string().into())
}
pub fn switch_statement_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("switchStatement.bracePosition", value.to_string().into())
}
pub fn try_statement_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("tryStatement.bracePosition", value.to_string().into())
}
pub fn while_statement_brace_position(&mut self, value: BracePosition) -> &mut Self {
self.insert("whileStatement.bracePosition", value.to_string().into())
}
/* prefer hanging */
pub fn arguments_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("arguments.preferHanging", value.into())
}
pub fn array_expression_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("arrayExpression.preferHanging", value.into())
}
pub fn array_pattern_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("arrayPattern.preferHanging", value.into())
}
pub fn do_while_statement_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("doWhileStatement.preferHanging", value.into())
}
pub fn export_declaration_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("exportDeclaration.preferHanging", value.into())
}
pub fn extends_clause_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("extendsClause.preferHanging", value.into())
}
pub fn for_in_statement_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("forInStatement.preferHanging", value.into())
}
pub fn for_of_statement_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("forOfStatement.preferHanging", value.into())
}
pub fn for_statement_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("forStatement.preferHanging", value.into())
}
pub fn if_statement_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("ifStatement.preferHanging", value.into())
}
pub fn implements_clause_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("implementsClause.preferHanging", value.into())
}
pub fn import_declaration_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("importDeclaration.preferHanging", value.into())
}
pub fn jsx_attributes_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("jsxAttributes.preferHanging", value.into())
}
pub fn object_expression_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("objectExpression.preferHanging", value.into())
}
pub fn object_pattern_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("objectPattern.preferHanging", value.into())
}
pub fn parameters_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("parameters.preferHanging", value.into())
}
pub fn sequence_expression_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("sequenceExpression.preferHanging", value.into())
}
pub fn switch_statement_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("switchStatement.preferHanging", value.into())
}
pub fn tuple_type_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("tupleType.preferHanging", value.into())
}
pub fn type_literal_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("typeLiteral.preferHanging", value.into())
}
pub fn type_parameters_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("typeParameters.preferHanging", value.into())
}
pub fn union_and_intersection_type_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("unionAndIntersectionType.preferHanging", value.into())
}
pub fn variable_statement_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("variableStatement.preferHanging", value.into())
}
pub fn while_statement_prefer_hanging(&mut self, value: bool) -> &mut Self {
self.insert("whileStatement.preferHanging", value.into())
}
/* member spacing */
pub fn enum_declaration_member_spacing(&mut self, value: MemberSpacing) -> &mut Self {
self.insert("enumDeclaration.memberSpacing", value.to_string().into())
}
/* next control flow position */
pub fn if_statement_next_control_flow_position(&mut self, value: NextControlFlowPosition) -> &mut Self {
self.insert("ifStatement.nextControlFlowPosition", value.to_string().into())
}
pub fn try_statement_next_control_flow_position(&mut self, value: NextControlFlowPosition) -> &mut Self {
self.insert("tryStatement.nextControlFlowPosition", value.to_string().into())
}
/* operator position */
pub fn binary_expression_operator_position(&mut self, value: OperatorPosition) -> &mut Self {
self.insert("binaryExpression.operatorPosition", value.to_string().into())
}
pub fn conditional_expression_operator_position(&mut self, value: OperatorPosition) -> &mut Self {
self.insert("conditionalExpression.operatorPosition", value.to_string().into())
}
/* single body position */
pub fn if_statement_single_body_position(&mut self, value: SingleBodyPosition) -> &mut Self {
self.insert("ifStatement.singleBodyPosition", value.to_string().into())
}
pub fn for_statement_single_body_position(&mut self, value: SingleBodyPosition) -> &mut Self {
self.insert("forStatement.singleBodyPosition", value.to_string().into())
}
pub fn for_in_statement_single_body_position(&mut self, value: SingleBodyPosition) -> &mut Self {
self.insert("forInStatement.singleBodyPosition", value.to_string().into())
}
pub fn for_of_statement_single_body_position(&mut self, value: SingleBodyPosition) -> &mut Self {
self.insert("forOfStatement.singleBodyPosition", value.to_string().into())
}
pub fn while_statement_single_body_position(&mut self, value: SingleBodyPosition) -> &mut Self {
self.insert("whileStatement.singleBodyPosition", value.to_string().into())
}
/* trailing commas */
pub fn arguments_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("arguments.trailingCommas", value.to_string().into())
}
pub fn parameters_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("parameters.trailingCommas", value.to_string().into())
}
pub fn array_expression_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("arrayExpression.trailingCommas", value.to_string().into())
}
pub fn array_pattern_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("arrayPattern.trailingCommas", value.to_string().into())
}
pub fn enum_declaration_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("enumDeclaration.trailingCommas", value.to_string().into())
}
pub fn export_declaration_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("exportDeclaration.trailingCommas", value.to_string().into())
}
pub fn import_declaration_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("importDeclaration.trailingCommas", value.to_string().into())
}
pub fn object_expression_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("objectExpression.trailingCommas", value.to_string().into())
}
pub fn object_pattern_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("objectPattern.trailingCommas", value.to_string().into())
}
pub fn tuple_type_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("tupleType.trailingCommas", value.to_string().into())
}
/// Only applies when using commas on type literals.
pub fn type_literal_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("typeLiteral.trailingCommas", value.to_string().into())
}
pub fn type_parameters_trailing_commas(&mut self, value: TrailingCommas) -> &mut Self {
self.insert("typeParameters.trailingCommas", value.to_string().into())
}
/* use braces */
pub fn if_statement_use_braces(&mut self, value: UseBraces) -> &mut Self {
self.insert("ifStatement.useBraces", value.to_string().into())
}
pub fn for_statement_use_braces(&mut self, value: UseBraces) -> &mut Self {
self.insert("forStatement.useBraces", value.to_string().into())
}
pub fn for_in_statement_use_braces(&mut self, value: UseBraces) -> &mut Self {
self.insert("forInStatement.useBraces", value.to_string().into())
}
pub fn for_of_statement_use_braces(&mut self, value: UseBraces) -> &mut Self {
self.insert("forOfStatement.useBraces", value.to_string().into())
}
pub fn while_statement_use_braces(&mut self, value: UseBraces) -> &mut Self {
self.insert("whileStatement.useBraces", value.to_string().into())
}
/* prefer single line */
pub fn array_expression_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("arrayExpression.preferSingleLine", value.into())
}
pub fn array_pattern_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("arrayPattern.preferSingleLine", value.into())
}
pub fn arguments_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("arguments.preferSingleLine", value.into())
}
pub fn binary_expression_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("binaryExpression.preferSingleLine", value.into())
}
pub fn computed_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("computed.preferSingleLine", value.into())
}
pub fn conditional_expression_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("conditionalExpression.preferSingleLine", value.into())
}
pub fn conditional_type_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("conditionalType.preferSingleLine", value.into())
}
pub fn decorators_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("decorators.preferSingleLine", value.into())
}
pub fn export_declaration_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("exportDeclaration.preferSingleLine", value.into())
}
pub fn for_statement_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("forStatement.preferSingleLine", value.into())
}
pub fn import_declaration_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("importDeclaration.preferSingleLine", value.into())
}
pub fn jsx_attributes_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("jsxAttributes.preferSingleLine", value.into())
}
pub fn jsx_element_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("jsxElement.preferSingleLine", value.into())
}
pub fn mapped_type_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("mappedType.preferSingleLine", value.into())
}
pub fn member_expression_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("memberExpression.preferSingleLine", value.into())
}
pub fn object_expression_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("objectExpression.preferSingleLine", value.into())
}
pub fn object_pattern_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("objectPattern.preferSingleLine", value.into())
}
pub fn parameters_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("parameters.preferSingleLine", value.into())
}
pub fn parentheses_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("parentheses.preferSingleLine", value.into())
}
pub fn tuple_type_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("tupleType.preferSingleLine", value.into())
}
pub fn type_literal_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("typeLiteral.preferSingleLine", value.into())
}
pub fn type_parameters_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("typeParameters.preferSingleLine", value.into())
}
pub fn union_and_intersection_type_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("unionAndIntersectionType.preferSingleLine", value.into())
}
pub fn variable_statement_prefer_single_line(&mut self, value: bool) -> &mut Self {
self.insert("variableStatement.preferSingleLine", value.into())
}
#[cfg(test)]
pub(super) fn get_inner_config(&self) -> ConfigKeyMap {
self.config.clone()
}
fn insert(&mut self, name: &str, value: ConfigKeyValue) -> &mut Self {
self.config.insert(String::from(name), value);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_all_values_set() {
let mut config = ConfigurationBuilder::new();
config.new_line_kind(NewLineKind::Auto)
.line_width(80)
.use_tabs(false)
.indent_width(4)
/* common */
.quote_style(QuoteStyle::AlwaysDouble)
.semi_colons(SemiColons::Prefer)
.brace_position(BracePosition::NextLine)
.next_control_flow_position(NextControlFlowPosition::SameLine)
.operator_position(OperatorPosition::SameLine)
.single_body_position(SingleBodyPosition::SameLine)
.trailing_commas(TrailingCommas::Never)
.use_braces(UseBraces::WhenNotSingleLine)
.prefer_hanging(false)
/* situational */
.arrow_function_use_parentheses(UseParentheses::Maintain)
.binary_expression_line_per_expression(false)
.member_expression_line_per_expression(false)
.type_literal_separator_kind(SemiColonOrComma::Comma)
.type_literal_separator_kind_single_line(SemiColonOrComma::Comma)
.type_literal_separator_kind_multi_line(SemiColonOrComma::Comma)
/* sorting */
.module_sort_import_declarations(SortOrder::Maintain)
.module_sort_export_declarations(SortOrder::Maintain)
.import_declaration_sort_named_imports(SortOrder::Maintain)
.export_declaration_sort_named_exports(SortOrder::Maintain)
/* ignore comments */
.ignore_node_comment_text("ignore")
.ignore_file_comment_text("ignore-file")
/* brace position*/
.arrow_function_brace_position(BracePosition::NextLine)
.class_declaration_brace_position(BracePosition::NextLine)
.class_expression_brace_position(BracePosition::NextLine)
.constructor_brace_position(BracePosition::NextLine)
.do_while_statement_brace_position(BracePosition::NextLine)
.enum_declaration_brace_position(BracePosition::NextLine)
.for_statement_brace_position(BracePosition::NextLine)
.for_in_statement_brace_position(BracePosition::NextLine)
.for_of_statement_brace_position(BracePosition::NextLine)
.get_accessor_brace_position(BracePosition::NextLine)
.if_statement_brace_position(BracePosition::NextLine)
.interface_declaration_brace_position(BracePosition::NextLine)
.function_declaration_brace_position(BracePosition::NextLine)
.function_expression_brace_position(BracePosition::NextLine)
.method_brace_position(BracePosition::NextLine)
.module_declaration_brace_position(BracePosition::NextLine)
.set_accessor_brace_position(BracePosition::NextLine)
.switch_case_brace_position(BracePosition::NextLine)
.switch_statement_brace_position(BracePosition::NextLine)
.try_statement_brace_position(BracePosition::NextLine)
.while_statement_brace_position(BracePosition::NextLine)
/* prefer hanging */
.arguments_prefer_hanging(true)
.array_expression_prefer_hanging(true)
.array_pattern_prefer_hanging(true)
.do_while_statement_prefer_hanging(true)
.export_declaration_prefer_hanging(true)
.extends_clause_prefer_hanging(true)
.for_in_statement_prefer_hanging(true)
.for_of_statement_prefer_hanging(true)
.for_statement_prefer_hanging(true)
.if_statement_prefer_hanging(true)
.implements_clause_prefer_hanging(true)
.import_declaration_prefer_hanging(true)
.jsx_attributes_prefer_hanging(true)
.object_expression_prefer_hanging(true)
.object_pattern_prefer_hanging(true)
.parameters_prefer_hanging(true)
.sequence_expression_prefer_hanging(true)
.switch_statement_prefer_hanging(true)
.tuple_type_prefer_hanging(true)
.type_literal_prefer_hanging(true)
.type_parameters_prefer_hanging(true)
.union_and_intersection_type_prefer_hanging(true)
.variable_statement_prefer_hanging(true)
.while_statement_prefer_hanging(true)
/* member spacing */
.enum_declaration_member_spacing(MemberSpacing::Maintain)
/* next control flow position */
.if_statement_next_control_flow_position(NextControlFlowPosition::SameLine)
.try_statement_next_control_flow_position(NextControlFlowPosition::SameLine)
/* operator position */
.binary_expression_operator_position(OperatorPosition::SameLine)
.conditional_expression_operator_position(OperatorPosition::SameLine)
/* single body position */
.if_statement_single_body_position(SingleBodyPosition::SameLine)
.for_statement_single_body_position(SingleBodyPosition::SameLine)
.for_in_statement_single_body_position(SingleBodyPosition::SameLine)
.for_of_statement_single_body_position(SingleBodyPosition::SameLine)
.while_statement_single_body_position(SingleBodyPosition::SameLine)
/* trailing commas */
.arguments_trailing_commas(TrailingCommas::Never)
.parameters_trailing_commas(TrailingCommas::Never)
.array_expression_trailing_commas(TrailingCommas::Never)
.array_pattern_trailing_commas(TrailingCommas::Never)
.enum_declaration_trailing_commas(TrailingCommas::Never)
.import_declaration_trailing_commas(TrailingCommas::Never)
.export_declaration_trailing_commas(TrailingCommas::Never)
.object_expression_trailing_commas(TrailingCommas::Never)
.object_pattern_trailing_commas(TrailingCommas::Never)
.type_parameters_trailing_commas(TrailingCommas::Never)
.tuple_type_trailing_commas(TrailingCommas::Never)
.type_literal_trailing_commas(TrailingCommas::Never)
/* use braces */
.if_statement_use_braces(UseBraces::Always)
.for_statement_use_braces(UseBraces::Always)
.for_in_statement_use_braces(UseBraces::Always)
.for_of_statement_use_braces(UseBraces::Always)
.while_statement_use_braces(UseBraces::Always)
/* prefer single line */
.array_expression_prefer_single_line(false)
.array_pattern_prefer_single_line(false)
.arguments_prefer_single_line(false)
.binary_expression_prefer_single_line(false)
.computed_prefer_single_line(false)
.conditional_expression_prefer_single_line(false)
.conditional_type_prefer_single_line(false)
.decorators_prefer_single_line(false)
.export_declaration_prefer_single_line(false)
.for_statement_prefer_single_line(false)
.import_declaration_prefer_single_line(false)
.jsx_attributes_prefer_single_line(false)
.jsx_element_prefer_single_line(false)
.mapped_type_prefer_single_line(false)
.member_expression_prefer_single_line(false)
.object_expression_prefer_single_line(false)
.object_pattern_prefer_single_line(false)
.parameters_prefer_single_line(false)
.parentheses_prefer_single_line(false)
.tuple_type_prefer_single_line(false)
.type_literal_prefer_single_line(false)
.type_parameters_prefer_single_line(false)
.union_and_intersection_type_prefer_single_line(false)
.variable_statement_prefer_single_line(false)
/* space settings */
.binary_expression_space_surrounding_bitwise_and_arithmetic_operator(true)
.comment_line_force_space_after_slashes(false)
.construct_signature_space_after_new_keyword(true)
.constructor_space_before_parentheses(true)
.constructor_type_space_after_new_keyword(true)
.do_while_statement_space_after_while_keyword(true)
.export_declaration_space_surrounding_named_exports(true)
.for_statement_space_after_for_keyword(true)
.for_statement_space_after_semi_colons(true)
.for_in_statement_space_after_for_keyword(true)
.for_of_statement_space_after_for_keyword(true)
.function_declaration_space_before_parentheses(true)
.function_expression_space_before_parentheses(true)
.function_expression_space_after_function_keyword(true)
.get_accessor_space_before_parentheses(true)
.if_statement_space_after_if_keyword(true)
.import_declaration_space_surrounding_named_imports(true)
.jsx_expression_container_space_surrounding_expression(true)
.method_space_before_parentheses(true)
.set_accessor_space_before_parentheses(true)
.tagged_template_space_before_literal(false)
.type_annotation_space_before_colon(true)
.type_assertion_space_before_expression(true)
.while_statement_space_after_while_keyword(true);
let inner_config = config.get_inner_config();
assert_eq!(inner_config.len(), 145);
let diagnostics = resolve_config(inner_config, &resolve_global_config(HashMap::new()).config).diagnostics;
assert_eq!(diagnostics.len(), 0);
}
}
| 43.124158 | 125 | 0.672008 |
ed9db23a4ae9b7e9b0666bd4ae13ce45194603e0
| 11,214 |
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vfmsubadd213ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM3)), operand3: Some(Direct(XMM5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 97, 167, 245], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_2() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM4)), operand3: Some(IndirectScaledDisplaced(ECX, Four, 2138699849, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 89, 167, 36, 141, 73, 248, 121, 127], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_3() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM6)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 121, 167, 246], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_4() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM3)), operand3: Some(Indirect(RDX, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 97, 167, 34], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_5() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM1)), operand2: Some(Direct(YMM5)), operand3: Some(Direct(YMM0)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 85, 167, 200], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_6() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM6)), operand2: Some(Direct(YMM4)), operand3: Some(IndirectScaledIndexedDisplaced(EBX, ECX, Four, 1250965578, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 93, 167, 180, 139, 74, 56, 144, 74], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_7() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM2)), operand2: Some(Direct(YMM5)), operand3: Some(Direct(YMM4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 85, 167, 212], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_8() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM7)), operand3: Some(Indirect(RCX, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 69, 167, 25], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_9() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM3)), operand3: Some(Direct(XMM5)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 242, 101, 137, 167, 245], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_10() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectDisplaced(EDI, 1935469381, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 242, 101, 137, 167, 143, 69, 235, 92, 115], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_11() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM6)), operand3: Some(IndirectDisplaced(ESI, 1366847221, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: Some(BroadcastMode::Broadcast1To4) }, &[98, 242, 77, 156, 167, 174, 245, 110, 120, 81], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_12() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM29)), operand2: Some(Direct(XMM17)), operand3: Some(Direct(XMM31)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 2, 117, 131, 167, 239], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_13() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: Some(IndirectDisplaced(RDX, 930367438, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 242, 109, 139, 167, 146, 206, 71, 116, 55], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_14() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM27)), operand3: Some(IndirectScaledDisplaced(RCX, Eight, 1581566786, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: Some(BroadcastMode::Broadcast1To4) }, &[98, 242, 37, 149, 167, 4, 205, 66, 203, 68, 94], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_15() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM2)), operand2: Some(Direct(YMM4)), operand3: Some(Direct(YMM0)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 242, 93, 174, 167, 208], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_16() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM2)), operand2: Some(Direct(YMM3)), operand3: Some(Indirect(ECX, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 242, 101, 172, 167, 17], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_17() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM2)), operand2: Some(Direct(YMM3)), operand3: Some(IndirectScaledDisplaced(EBX, Two, 1260262369, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: Some(BroadcastMode::Broadcast1To8) }, &[98, 242, 101, 190, 167, 20, 93, 225, 19, 30, 75], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_18() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM21)), operand2: Some(Direct(YMM29)), operand3: Some(Direct(YMM10)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 194, 21, 166, 167, 234], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_19() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM8)), operand2: Some(Direct(YMM17)), operand3: Some(IndirectDisplaced(RCX, 159677962, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 114, 117, 162, 167, 129, 10, 126, 132, 9], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_20() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(YMM20)), operand2: Some(Direct(YMM5)), operand3: Some(IndirectDisplaced(RDX, 377227726, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: Some(BroadcastMode::Broadcast1To8) }, &[98, 226, 85, 188, 167, 162, 206, 9, 124, 22], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_21() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(ZMM4)), operand2: Some(Direct(ZMM1)), operand3: Some(Direct(ZMM1)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 242, 117, 153, 167, 225], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_22() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(ZMM0)), operand2: Some(Direct(ZMM7)), operand3: Some(Indirect(ESI, Some(OperandSize::Zmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 242, 69, 205, 167, 6], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_23() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(ZMM0)), operand2: Some(Direct(ZMM7)), operand3: Some(IndirectScaledIndexedDisplaced(EDX, EAX, Four, 1281546851, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: Some(BroadcastMode::Broadcast1To16) }, &[98, 242, 69, 219, 167, 132, 130, 99, 218, 98, 76], OperandSize::Dword)
}
#[test]
fn vfmsubadd213ps_24() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(ZMM8)), operand2: Some(Direct(ZMM4)), operand3: Some(Direct(ZMM27)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 18, 93, 153, 167, 195], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_25() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(ZMM10)), operand2: Some(Direct(ZMM29)), operand3: Some(IndirectScaledIndexed(RBX, RBX, Eight, Some(OperandSize::Zmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 114, 21, 199, 167, 20, 219], OperandSize::Qword)
}
#[test]
fn vfmsubadd213ps_26() {
run_test(&Instruction { mnemonic: Mnemonic::VFMSUBADD213PS, operand1: Some(Direct(ZMM11)), operand2: Some(Direct(ZMM17)), operand3: Some(IndirectDisplaced(RSI, 1022118514, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: Some(BroadcastMode::Broadcast1To16) }, &[98, 114, 117, 209, 167, 158, 114, 74, 236, 60], OperandSize::Qword)
}
| 80.676259 | 476 | 0.721509 |
f8a57bc6a6b707f22eb204b657396f3cd934aa03
| 10,151 |
//! Zero-copy allocator based on TCP.
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{VecDeque, HashMap};
// use std::sync::mpsc::{channel, Sender, Receiver};
use bytes::arc::Bytes;
use networking::MessageHeader;
use {Allocate, Message, Data, Push, Pull};
use allocator::AllocateBuilder;
use allocator::{Event, Process};
use allocator::process::ProcessBuilder;
use allocator::canary::Canary;
use super::bytes_exchange::{BytesPull, SendEndpoint, MergeQueue, Signal};
use super::push_pull::{Pusher, PullerInner};
/// Builds an instance of a TcpAllocator.
///
/// Builders are required because some of the state in a `TcpAllocator` cannot be sent between
/// threads (specifically, the `Rc<RefCell<_>>` local channels). So, we must package up the state
/// shared between threads here, and then provide a method that will instantiate the non-movable
/// members once in the destination thread.
pub struct TcpBuilder<A: AllocateBuilder> {
inner: A,
index: usize, // number out of peers
peers: usize, // number of peer allocators.
sends: Vec<MergeQueue>, // for pushing bytes at remote processes.
recvs: Vec<MergeQueue>, // for pulling bytes from remote processes.
signal: Signal,
}
/// Creates a vector of builders, sharing appropriate state.
///
/// `threads` is the number of workers in a single process, `processes` is the
/// total number of processes.
/// The returned tuple contains
/// ```
/// (
/// AllocateBuilder for local threads,
/// info to spawn egress comm threads,
/// info to spawn ingress comm thresds,
/// )
/// ```
pub fn new_vector(
my_process: usize,
threads: usize,
processes: usize)
-> (Vec<TcpBuilder<ProcessBuilder>>,
Vec<(Vec<MergeQueue>, Signal)>,
Vec<Vec<MergeQueue>>) {
// The results are a vector of builders, as well as the necessary shared state to build each
// of the send and receive communication threads, respectively.
// One signal per local destination worker thread
let worker_signals: Vec<Signal> = (0 .. threads).map(|_| Signal::new()).collect();
// One signal per destination egress communication thread
let network_signals: Vec<Signal> = (0 .. processes-1).map(|_| Signal::new()).collect();
let worker_to_network: Vec<Vec<_>> = (0 .. threads).map(|_| (0 .. processes-1).map(|p| MergeQueue::new(network_signals[p].clone())).collect()).collect();
let network_to_worker: Vec<Vec<_>> = (0 .. processes-1).map(|_| (0 .. threads).map(|t| MergeQueue::new(worker_signals[t].clone())).collect()).collect();
let worker_from_network: Vec<Vec<_>> = (0 .. threads).map(|t| (0 .. processes-1).map(|p| network_to_worker[p][t].clone()).collect()).collect();
let network_from_worker: Vec<Vec<_>> = (0 .. processes-1).map(|p| (0 .. threads).map(|t| worker_to_network[t][p].clone()).collect()).collect();
let builders =
Process::new_vector(threads) // Vec<Process> (Process is Allocate)
.into_iter()
.zip(worker_signals)
.zip(worker_to_network)
.zip(worker_from_network)
.enumerate()
.map(|(index, (((inner, signal), sends), recvs))| {
// sends are handles to MergeQueues to remote processes
// (one per remote process)
// recvs are handles to MergeQueues from remote processes
// (one per remote process)
TcpBuilder {
inner,
index: my_process * threads + index,
peers: threads * processes,
sends,
recvs,
signal,
}})
.collect();
// for each egress communicaton thread, construct the tuple (MergeQueues from local
// threads, corresponding signal)
let sends = network_from_worker.into_iter().zip(network_signals).collect();
(/* AllocateBuilder for local threads */ builders,
/* info to spawn egress comm threads */ sends,
/* info to spawn ingress comm thresds */ network_to_worker)
}
impl<A: AllocateBuilder> TcpBuilder<A> {
/// Builds a `TcpAllocator`, instantiating `Rc<RefCell<_>>` elements.
pub fn build(self) -> TcpAllocator<A::Allocator> {
let sends: Vec<_> = self.sends.into_iter().map(
|send| Rc::new(RefCell::new(SendEndpoint::new(send)))).collect();
TcpAllocator {
inner: self.inner.build(),
index: self.index,
peers: self.peers,
_signal: self.signal,
canaries: Rc::new(RefCell::new(Vec::new())),
staged: Vec::new(),
sends,
recvs: self.recvs,
to_local: HashMap::new(),
}
}
}
/// A TCP-based allocator for inter-process communication.
pub struct TcpAllocator<A: Allocate> {
inner: A, // A non-serialized inner allocator for process-local peers.
index: usize, // number out of peers
peers: usize, // number of peer allocators (for typed channel allocation).
_signal: Signal,
staged: Vec<Bytes>, // staging area for incoming Bytes
canaries: Rc<RefCell<Vec<usize>>>,
// sending, receiving, and responding to binary buffers.
sends: Vec<Rc<RefCell<SendEndpoint<MergeQueue>>>>, // sends[x] -> goes to process x.
recvs: Vec<MergeQueue>, // recvs[x] <- from process x.
to_local: HashMap<usize, Rc<RefCell<VecDeque<Bytes>>>>, // to worker-local typed pullers.
}
impl<A: Allocate> Allocate for TcpAllocator<A> {
fn index(&self) -> usize { self.index }
fn peers(&self) -> usize { self.peers }
fn allocate<T: Data>(&mut self, identifier: usize) -> (Vec<Box<Push<Message<T>>>>, Box<Pull<Message<T>>>) {
// Result list of boxed pushers.
let mut pushes = Vec::<Box<Push<Message<T>>>>::new();
// Inner exchange allocations.
let inner_peers = self.inner.peers();
let (mut inner_sends, inner_recv) = self.inner.allocate(identifier);
for target_index in 0 .. self.peers() {
// TODO: crappy place to hardcode this rule.
let mut process_id = target_index / inner_peers;
if process_id == self.index / inner_peers {
pushes.push(inner_sends.remove(0));
}
else {
// message header template.
let header = MessageHeader {
channel: identifier,
source: self.index,
target: target_index,
length: 0,
seqno: 0,
};
// create, box, and stash new process_binary pusher.
if process_id > self.index / inner_peers { process_id -= 1; }
pushes.push(Box::new(Pusher::new(header, self.sends[process_id].clone())));
}
}
let channel =
self.to_local
.entry(identifier)
.or_insert_with(|| Rc::new(RefCell::new(VecDeque::new())))
.clone();
use allocator::counters::Puller as CountPuller;
let canary = Canary::new(identifier, self.canaries.clone());
let puller = Box::new(CountPuller::new(PullerInner::new(inner_recv, channel, canary), identifier, self.events().clone()));
(pushes, puller, )
}
// Perform preparatory work, most likely reading binary buffers from self.recv.
#[inline(never)]
fn receive(&mut self) {
// Check for channels whose `Puller` has been dropped.
let mut canaries = self.canaries.borrow_mut();
for dropped_channel in canaries.drain(..) {
let dropped =
self.to_local
.remove(&dropped_channel)
.expect("non-existent channel dropped");
assert!(dropped.borrow().is_empty());
}
::std::mem::drop(canaries);
self.inner.receive();
for recv in self.recvs.iter_mut() {
recv.drain_into(&mut self.staged);
}
let mut events = self.inner.events().borrow_mut();
for mut bytes in self.staged.drain(..) {
// We expect that `bytes` contains an integral number of messages.
// No splitting occurs across allocations.
while bytes.len() > 0 {
if let Some(header) = MessageHeader::try_read(&mut bytes[..]) {
// Get the header and payload, ditch the header.
let mut peel = bytes.extract_to(header.required_bytes());
let _ = peel.extract_to(40);
// Increment message count for channel.
events.push_back((header.channel, Event::Pushed(1)));
// Ensure that a queue exists.
// We may receive data before allocating, and shouldn't block.
self.to_local
.entry(header.channel)
.or_insert_with(|| Rc::new(RefCell::new(VecDeque::new())))
.borrow_mut()
.push_back(peel);
}
else {
println!("failed to read full header!");
}
}
}
}
// Perform postparatory work, most likely sending un-full binary buffers.
fn release(&mut self) {
// Publish outgoing byte ledgers.
for send in self.sends.iter_mut() {
send.borrow_mut().publish();
}
// OPTIONAL: Tattle on channels sitting on borrowed data.
// OPTIONAL: Perhaps copy borrowed data into owned allocation.
// for (index, list) in self.to_local.iter() {
// let len = list.borrow_mut().len();
// if len > 0 {
// eprintln!("Warning: worker {}, undrained channel[{}].len() = {}", self.index, index, len);
// }
// }
}
fn events(&self) -> &Rc<RefCell<VecDeque<(usize, Event)>>> {
self.inner.events()
}
}
| 38.596958 | 157 | 0.575411 |
6974274463f5569105d355bba479ffefa9c01174
| 8,814 |
use std::io::{self, Read};
type Error = Box<dyn std::error::Error + Send + Sync>;
type Result<T, E = Error> = std::result::Result<T, E>;
const TRACE: bool = false;
macro_rules! trace {
($($arg:tt)+) => {
if TRACE {
println!($($arg)+);
}
}
}
fn main() -> Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let ram = parse(&input)?;
let mut p1 = std::isize::MIN;
let mut phases = [0,1,2,3,4];
while permute(&mut phases) {
p1 = p1.max(evaluate(&phases, &ram));
}
let mut p2 = std::isize::MIN;
let mut phases = [5,6,7,8,9];
while permute(&mut phases) {
p2 = p2.max(evaluate(&phases, &ram));
}
println!("p1: {}", p1);
println!("p2: {}", p2);
Ok(())
}
fn parse(input: &str) -> Result<Box<[isize]>> {
let ram: Vec<isize> = input
.trim()
.split(',')
.map(|s| s.parse::<isize>())
.collect::<Result<Vec<_>, _>>()?;
Ok(ram.into_boxed_slice())
}
fn permute(data: &mut [u8]) -> bool {
// Finding the longest non-increasing suffix.
let mut i = data.len() - 1;
while i > 0 && data[i - 1] >= data[i] {
i -= 1;
}
if i <= 0 {
return false;
}
// data[i - 1] is the pivot, so finding the rightmost
// element, which exceeds it.
let mut j = data.len() - 1;
while data[j] <= data[i - 1] {
j -= 1;
}
// data[j] will be the new pivot.
debug_assert!(j >= i, "wrong pivot");
data.swap(i - 1, j);
// Reversing the suffix.
j = data.len() - 1;
while i < j {
data.swap(i, j);
i += 1;
j -= 1;
}
true
}
fn evaluate(phases: &[u8], code: &[isize]) -> isize {
let mut machines: Vec<Machine> = phases.iter().map(|_| Machine::from(&code)).collect();
for (phase, machine) in phases.iter().zip(machines.iter_mut()) {
machine.feed(*phase as isize);
}
let mut output = Vec::new();
let mut signal = 0;
loop {
let mut n = 0;
for m in machines.iter_mut() {
if m.is_halted() {
continue;
}
n += 1;
m.feed(signal);
output.clear();
let _ = m.run(&mut output);
if let Some(s) = output.last() {
signal = *s;
}
}
if n == 0 {
break;
}
}
signal
}
struct Machine {
ram: Box<[isize]>,
pc: usize,
state: State,
input: Vec<isize>,
consumed: usize,
}
impl Machine {
fn from(rom: &[isize]) -> Machine {
let ram = rom.to_vec().into_boxed_slice();
Machine {
ram: ram,
pc: 0,
state: State::Ready,
input: Vec::new(),
consumed: 0,
}
}
fn feed(&mut self, x: isize) {
self.input.push(x);
}
fn is_halted(&self) -> bool {
self.state == State::Halted
}
fn run(&mut self, output: &mut Vec<isize>) -> State {
if self.state == State::Halted {
return self.state;
}
loop {
let (op, len) = decode(&self.ram[self.pc..]);
trace!("{:?}", op);
match op {
Op::Add(a, b, Param::Pos(c)) => {
let a = load_value(&self.ram, a);
let b = load_value(&self.ram, b);
self.ram[c] = a + b
},
Op::Mul(a, b, Param::Pos(c)) => {
let a = load_value(&self.ram, a);
let b = load_value(&self.ram, b);
self.ram[c] = a * b
},
Op::In(Param::Pos(d)) => {
if self.consumed < self.input.len() {
let x = self.input[self.consumed];
self.ram[d] = x;
self.consumed += 1;
trace!(";; read {}", x);
} else {
trace!(";; suspend due to input waiting");
self.state = State::NeedsInput;
break;
}
},
Op::Out(a) => {
let a = load_value(&self.ram, a);
output.push(a);
trace!(";; wrote {}", a);
},
Op::JmpTrue(a, b) => {
let a = load_value(&self.ram, a);
let b = load_value(&self.ram, b);
if a != 0 {
self.pc = b as usize;
trace!(";; jumped to {}", self.pc);
continue;
}
},
Op::JmpFalse(a, b) => {
let a = load_value(&self.ram, a);
let b = load_value(&self.ram, b);
if a == 0 {
self.pc = b as usize;
trace!(";; jumped to {}", self.pc);
continue;
}
},
Op::CmpLess(a, b, Param::Pos(c)) => {
let a = load_value(&self.ram, a);
let b = load_value(&self.ram, b);
self.ram[c] = if a < b { 1 } else { 0 };
trace!(";; wrote {}", self.ram[c]);
},
Op::CmpEq(a, b, Param::Pos(c)) => {
let a = load_value(&self.ram, a);
let b = load_value(&self.ram, b);
self.ram[c] = if a == b { 1 } else { 0 };
trace!(";; wrote {}", self.ram[c]);
},
Op::Halt => {
self.state = State::Halted;
break;
},
_ => panic!("unknown opcode"),
}
self.pc += len;
}
self.state
}
}
#[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Debug)]
enum State {
Ready = 0,
NeedsInput,
Halted,
}
fn load_value(ram: &[isize], p: Param) -> isize {
match p {
Param::Pos(i) => ram[i],
Param::Imm(x) => x,
}
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
enum Param {
Pos(usize),
Imm(isize),
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
enum Op {
Add(Param, Param, Param),
Mul(Param, Param, Param),
In(Param),
Out(Param),
JmpTrue(Param, Param),
JmpFalse(Param, Param),
CmpLess(Param, Param, Param),
CmpEq(Param, Param, Param),
Halt,
}
fn decode(ram: &[isize]) -> (Op, usize) {
let opcode = ram[0];
let op = opcode % 100;
match op {
1 => {
let (am, bm, cm) = decode_triple_modes(opcode);
let (av, bv, cv) = (ram[1], ram[2], ram[3]);
let a = decode_param(am, av);
let b = decode_param(bm, bv);
let c = decode_param(cm, cv);
(Op::Add(a, b, c), 4)
},
2 => {
let (am, bm, cm) = decode_triple_modes(opcode);
let (av, bv, cv) = (ram[1], ram[2], ram[3]);
let a = decode_param(am, av);
let b = decode_param(bm, bv);
let c = decode_param(cm, cv);
(Op::Mul(a, b, c), 4)
},
3 => {
let i = ram[1] as usize;
(Op::In(Param::Pos(i)), 2)
},
4 => {
let (am, _, _) = decode_triple_modes(opcode);
let av = ram[1];
let a = decode_param(am, av);
(Op::Out(a), 2)
},
5 => {
let (am, bm, _) = decode_triple_modes(opcode);
let (av, bv) = (ram[1], ram[2]);
let a = decode_param(am, av);
let b = decode_param(bm, bv);
(Op::JmpTrue(a, b), 3)
},
6 => {
let (am, bm, _) = decode_triple_modes(opcode);
let (av, bv) = (ram[1], ram[2]);
let a = decode_param(am, av);
let b = decode_param(bm, bv);
(Op::JmpFalse(a, b), 3)
},
7 => {
let (am, bm, cm) = decode_triple_modes(opcode);
let (av, bv, cv) = (ram[1], ram[2], ram[3]);
let a = decode_param(am, av);
let b = decode_param(bm, bv);
let c = decode_param(cm, cv);
(Op::CmpLess(a, b, c), 4)
},
8 => {
let (am, bm, cm) = decode_triple_modes(opcode);
let (av, bv, cv) = (ram[1], ram[2], ram[3]);
let a = decode_param(am, av);
let b = decode_param(bm, bv);
let c = decode_param(cm, cv);
(Op::CmpEq(a, b, c), 4)
},
99 => (Op::Halt, 1),
_ => panic!("unknown instruction"),
}
}
// cbaop
fn decode_triple_modes(mut opcode: isize) -> (u8, u8, u8) {
opcode /= 100;
let a = (opcode % 10) as u8;
opcode /= 10;
let b = (opcode % 10) as u8;
opcode /= 10;
let c = (opcode % 10) as u8;
(a, b, c)
}
fn decode_param(mode: u8, value: isize) -> Param {
match mode {
0 => Param::Pos(value as usize),
1 => Param::Imm(value),
_ => panic!("unknown parameter mode"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn permutations() {
let mut data = [0, 1, 2];
assert_eq!(permute(&mut data), true);
assert_eq!(data, [0, 2, 1]);
assert_eq!(permute(&mut data), true);
assert_eq!(data, [1, 0, 2]);
assert_eq!(permute(&mut data), true);
assert_eq!(data, [1, 2, 0]);
assert_eq!(permute(&mut data), true);
assert_eq!(data, [2, 0, 1]);
assert_eq!(permute(&mut data), true);
assert_eq!(data, [2, 1, 0]);
assert_eq!(permute(&mut data), false);
assert_eq!(data, [2, 1, 0]);
}
#[test]
fn examples1() {
assert_eq!(run(&[4,3,2,1,0], "3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0"), 43210);
}
#[test]
fn examples2() {
assert_eq!(run(&[0,1,2,3,4], "3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0"), 54321);
}
#[test]
fn examples3() {
assert_eq!(run(&[1,0,4,3,2], "3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0"), 65210);
}
fn run(phases: &[u8], code: &str) -> isize {
let rom = parse(code).unwrap();
evaluate(phases, &rom)
}
#[test]
fn examples4() {
assert_eq!(run(&[9,8,7,6,5], "3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5"), 139629729);
}
#[test]
fn examples5() {
assert_eq!(run(&[9,7,8,5,6], "3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10"), 18216);
}
fn run(phases: &[u8], code: &str) -> isize {
let rom = parse(code).unwrap();
evaluate(phases, &rom)
}
}
| 21.70936 | 216 | 0.543227 |
895c3b3aac41d8714e44ab0c5a9b613ff400d541
| 22,162 |
#![no_std]
#![forbid(missing_docs)]
#![deny(clippy::missing_safety_doc)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![allow(clippy::transmute_ptr_to_ptr)]
// FIXME - the docs in this crate a *very* minimal, and need to be expanded upon
//! A set of very efficient, and very customizable arenas that
//! can elide bounds checks wherever possible.
//!
//! This crate is heavily inspired by crates like [`slotmap`](https://crates.io/crate/slotmap)
//! and [`slab`](https://crates.io/crate/slab).
//!
//! `pui-arena` provides a set of collections that allow you to insert and delete
//! items in at least amortized `O(1)`, access elements in `O(1)`. It also provides
//! the tools required to avoid the [`ABA` problem](https://en.wikipedia.org/wiki/ABA_problem).
//!
//! You can think of the collections in `pui-arena` as a `HashMap`/`BTreeMap` where
//! the arena manages the keys, and provides a very efficient way to access elements.
//!
//! # Why use `pui-arena` over alternatives
//!
//! `pui-arena` allows you to minimize overhead wherever possible, and fully customize
//! the arenas. This allows you to use an api like `slab` or `slotmap` based on how
//! you use the api. (There are also newtypes featured-gated by the features `slab`
//! and `slotmap` that implement a similar interface to those two crates).
//!
//! If you use the `pui`/`scoped` feature, then you can also eliminate bounds checks
//! entirely, which can be a huge performance save in performance sensitive regions.
//!
//! `pui-arena` also provides a more features than competitors, such as a vacant entry
//! api for versioned arenas, and `drain_filter` for all arenas.
//!
//! # Choosing [`sparse`](base::sparse), [`hop`](base::hop), or [`dense`](base::dense)
//!
//! * If you want fast insertion/deletion/acccess and don't care about iteration speed,
//! use [`sparse`](base::sparse).
//!
//! * If you want fast iteration speed above all else, use [`dense`](base::dense)
//!
//! * If you want reasonable iteration speed and also fast access/delete, or if [`dense`](base::dense)
//! is to memory heavy, use [`hop`](base::hop)
//!
//! You can read about the details of how each works in the corrosponding module docs
//!
//! # Performance characteristics
//!
//! ## Speed
//!
//! all of the collections in `pui-arena` allow you to
//! * insert elements in amortized `O(1)`
//! * delete/access elements in `O(1)`
//! * guarantee that keys *never* get invalidated unless `remove` is called
//!
//! ## Memory
//!
//! For each `Arena<T, _, V>` where `V: Version`, the memory overhead is as follows:
//! * [`sparse`](base::sparse) [`Arena`](base::sparse::Arena) -
//! `size_of(V) + max(size_of(T), size_of(usize))` per slot
//! * [`hop`](base::hop) [`Arena`](base::hop::Arena) -
//! `size_of(V) + max(size_of(T), 3 * size_of(usize))` per slot
//! * [`dense`](base::dense) [`Arena`](base::dense::Arena) -
//! `size_of(V) + size_of(usize)` per slot,
//! and `size_of(usize) + size_of(T)` per value
//!
//! ## Implementation Details
//!
//! The core of this crate is the the [`Version`](version::Version) trait,
//! the [`ArenaKey`](ArenaKey) trait, and the [`BuildArenaKey`](BuildArenaKey) trait.
//!
//! `Version` specifies the behavior of the arenas.
//! `pui-arena` provides three implementations,
//! see [`Version`](version::Version) for more details:
//!
//! * [`DefaultVersion`](version::DefaultVersion)
//! * Ensures that all keys produced by `insert` are unique
//! * backed by a `u32`, so it may waste space for small values
//! * technically if items are inserted/removed many times,
//! slots will be "leaked", and iteraton performance may degrade
//! but, this is unlikely, unless the same slot is reused over
//! 2 billion times
//! * [`TinyVersion`](version::TinyVersion) -
//! * Ensures that all keys produced by `insert` are unique
//! * backed by a `u8`, if items are inserted/removed many times,
//! slots will be "leaked", and iteraton performance may degrade
//! * [`Unversioned`](version::Unversioned) -
//! * Keys produced by `insert` are not guartneed to be unique
//! * slots will never be "leaked"
//!
//! [`ArenaKey`] specifies the behavior of keys into arenas.
//! `pui-arena` provides a number of implementations. See [`ArenaKey`]
//! for details.
//!
//! * [`usize`] - allows accessing a given slot directly, with no regard for it's version
//! * Note: when I say "with no regard for it's version", it still checks the version
//! to see if the slot is occupied, but it has no means of checking if a slot
//! a value was re-inserted into the same slot
//! * [`Key<K, _>`](Key) - allows accessing a slot specified by `K`, and checks the generation
//! of the slot before providing a value.
//! * `K` can be one of the other keys listed here (except for `ScopedKey`)
//! * [`TrustedIndex`] - allows accessing a given slot directly, with no regard for it's version
//! * elides bounds checks, but is unsafe to construct
//! * This one should be used with care, if at all. It is better to use the `pui` feature
//! and use `pui_vec::Id` instead. It is safe, and also guartnees bound check elision
//! * [`ScopedKey<'_, _>`](scoped::ScopedKey) - only allows access into scoped arenas
//! (otherwise identical to `Key`)
//!
//! enabled with the `pui` feature
//!
//! * [`pui_vec::Id`] - allows accessing a given slot directly, with no regard for it's version
//! * elides bounds checks
//!
//! [`BuildArenaKey`] specifies how arenas should create keys, all implementors of [`ArenaKey`]
//! provided by this crate also implement [`BuildArenaKey`] except for [`TrustedIndex`].
//!
//! # Custom arenas
//!
//! You can newtype arenas with the [`newtype`] macro, or the features: `slab`, `slotmap`, or `scoped`.
//!
//! * [`slab`] - provides a similar api to the [`slab` crate](https://crates.io/crate/slab)
//! * uses `usize` keys, and [`Unversioned`](version::Unversioned) slots
//! * [`slotmap`] - provides a similar api to the [`slab` crate](https://crates.io/crate/slotmap)
//! * uses [`Key<usize>`](Key) keys, and [`DefaultVersion`](version::DefaultVersion) slots
//! * [`scoped`] - provides newtyped arenas that use `pui_core::scoped` to elide bounds checks
//! * uses [`scoped::ScopedKey<'_, _>`](scoped::ScopedKey) keys,
//! and is generic over the version
//! * [`newtype`] - creates a set of newtyped arenas with the module structure of `base`
//! * These arenas elide bounds checks, in favor of id checks, which are cheaper,
//! and depending on your backing id, can be no check at all!
//! (see [`pui_core::scalar_allocator`] details)
//!
//! ```
//! // Because the backing id type is `()`, there are no bounds checks when using
//! // this arena!
//! # use inner::*; mod inner {
//! pui_arena::newtype! {
//! pub struct MyCustomArena;
//! }
//! # }
//!
//! let my_sparse_arena = sparse::Arena::<()>::new();
//! // You can also use `dense` or `hop`
//! // let my_dense_arena = dense::Arena::<()>::new();
//! // let my_hop_arena = hop::Arena::<()>::new();
//! ```
//!
//! Becomes something like
//!
//! ```ignore
//! pui_core::scalar_allocator! {
//! struct MyCustomArena;
//! }
//!
//! mod sparse {
//! pub(super) Arena(pub(super) pui_arena::base::sparse::Arena<...>);
//!
//! /// more type aliases here
//! }
//!
//! mod dense {
//! pub(super) Arena(pub(super) pui_arena::base::dense::Arena<...>);
//!
//! /// more type aliases here
//! }
//!
//! mod hop {
//! pub(super) Arena(pub(super) pui_arena::base::hop::Arena<...>);
//!
//! /// more type aliases here
//! }
//!
//! let my_sparse_arena = sparse::Arena::<()>::new();
//! // You can also use `dense` or `hop`
//! // let my_dense_arena = dense::Arena::<()>::new();
//! // let my_hop_arena = hop::Arena::<()>::new();
//! ```
//!
//! Where each `Arena` newtype has a simplified api, and better error messages.
#[doc(hidden)]
pub extern crate alloc as std;
pub mod version;
mod arena_access;
pub use arena_access::{ArenaKey, BuildArenaKey, CompleteValidator, Key, Validator};
/// the core implementations of different types of arenas
pub mod base {
pub mod dense;
pub mod hop;
pub mod sparse;
}
#[cfg(feature = "scoped")]
#[cfg_attr(docsrs, doc(cfg(feature = "scoped")))]
pub mod scoped;
/// a reimplementation of [`slab`](https://docs.rs/slab/) in terms
/// of the generic arenas in [`base`]
#[cfg(feature = "slab")]
#[cfg_attr(docsrs, doc(cfg(feature = "slab")))]
pub mod slab;
#[cfg(feature = "slotmap")]
#[cfg_attr(docsrs, doc(cfg(feature = "slotmap")))]
pub mod slotmap;
#[doc(hidden)]
#[cfg(feature = "pui")]
pub use {core, pui_core, pui_vec};
/// An index that's guaranteed to be in bounds of the arena it's used on
#[derive(Clone, Copy)]
pub struct TrustedIndex(usize);
impl TrustedIndex {
/// Create a new `TrustedIndex`
///
/// # Safety
///
/// This `index` must be in bounds on all arenas this `Self` is used on
#[inline]
pub unsafe fn new(index: usize) -> Self { Self(index) }
}
struct SetOnDrop<'a>(&'a mut bool);
impl Drop for SetOnDrop<'_> {
fn drop(&mut self) { *self.0 = true; }
}
impl SetOnDrop<'_> {
fn defuse(self) { core::mem::forget(self) }
}
/// Create newtype of all the arenas in [`base`]
///
/// The module structure here is identical to [`crate::base`], and
/// you can look there for detailed documentation about the types.
/// Each implementation of `SlotMap` will have all the methods from the
/// corrosponding `Arena`, and those that take or produce generic keys
/// will instead take/produce a `Key`.
///
/// In each module, you'll find an `Arena` newtype (with one public field),
/// a `VacantEntry` newtype (again with one public field). These are thin
/// wrappers around their generic counterparts. Their only serve the purpose
/// of making error messages easier to parse, and use a default `Key`.
/// You will also find a vareity of type aliases for various iterators, and
/// for the default `Key` type for ease of use.
///
/// If you want to access the raw backing `Arena`/`VacantEntry`, you still can,
/// it is the only public field of each scoped arena/vacant entry.
#[macro_export]
#[cfg(feature = "pui")]
#[cfg_attr(docsrs, doc(cfg(feature = "pui")))]
macro_rules! newtype {
(
$(#[$meta:meta])*
$( pub $(( $($vis:tt)* ))? )? struct $name:ident;
$(type Version = $version:ty;)?
) => {
$crate::pui_core::scalar_allocator! {
$(#[$meta])*
$( pub $(( $($vis)* ))? )? struct $name;
}
$crate::__newtype! { @resolve_vis $( pub $(( $($vis)* ))? )? $name, $($version,)? $crate::version::DefaultVersion }
};
(
$(#[$meta:meta])*
$( pub $(( $($vis:tt)* ))? )? struct $name:ident($inner:ty);
$(type Version = $version:ty;)?
) => {
$crate::pui_core::scalar_allocator! {
$(#[$meta])*
$( pub $(( $($vis)* ))? )? struct $name($inner);
}
$crate::__newtype! { @resolve_vis $( pub $(( $($vis)* ))? )? $name, $($version,)? $crate::version::DefaultVersion }
};
}
#[doc(hidden)]
#[macro_export]
#[cfg(feature = "pui")]
macro_rules! __newtype {
(@resolve_vis $name:ident, $default_version:ty $(, $extra:ty)?) => {
$crate::__newtype! { @build_module (pub(self)) (pub(super)) $name, $default_version }
};
(@resolve_vis pub $name:ident, $default_version:ty $(, $extra:ty)?) => {
$crate::__newtype! { @build_module (pub) (pub) $name, $default_version }
};
(@resolve_vis pub(self) $name:ident, $default_version:ty $(, $extra:ty)?) => {
$crate::__newtype! { @build_module (pub(self)) (pub(super)) $name, $default_version }
};
(@resolve_vis pub(crate) $name:ident, $default_version:ty $(, $extra:ty)?) => {
$crate::__newtype! { @build_module (pub(crate)) (pub(crate)) $name, $default_version }
};
(@resolve_vis pub(in $($path:tt)*) $name:ident, $default_version:ty $(, $extra:ty)?) => {
$crate::__newtype! { @build_module (pub(in $($path)*)) (pub(in super::$($path)*)) $name, $default_version }
};
(
@forward
($item_vis:vis) $name:ident
slots: $slots:ident
$($keys:ident)?
) => {
/// The backing identifier for [`Arena`]
$item_vis type Identifier = $crate::pui_core::dynamic::Dynamic<super::$name>;
/// The key for [`Arena`]
$item_vis type Key = $crate::Key<$crate::pui_vec::Id<$crate::pui_core::dynamic::DynamicToken<super::$name>>, <Version as $crate::version::Version>::Save>;
/// The backing arena for [`Arena`]
$item_vis type BaseArena<T> = imp::Arena<T, Identifier, Version>;
/// The backing vacant entry for [`VacantEntry`]
$item_vis type BaseVacantEntry<'a, T> = imp::VacantEntry<'a, T, Identifier, Version>;
/// A newtyped arena
$item_vis struct Arena<T>($item_vis imp::Arena<T, Identifier, Version>);
/// A newtyped vacant entry
$item_vis struct VacantEntry<'a, T>($item_vis imp::VacantEntry<'a, T, Identifier, Version>);
/// Returned from [`Arena::entries`]
$item_vis type Entries<'a, T> = imp::Entries<'a, T, Identifier, Version, Key>;
/// Returned from [`Arena::entries_mut`]
$item_vis type EntriesMut<'a, T> = imp::EntriesMut<'a, T, Identifier, Version, Key>;
/// Returned from [`Arena::into_entries`]
$item_vis type IntoEntries<T> = imp::IntoEntries<T, Identifier, Version, Key>;
impl<T> VacantEntry<'_, T> {
/// see [`VacantEntry::key`](imp::VacantEntry::key)
pub fn key(&self) -> Key { self.0.key() }
/// see [`VacantEntry::insert`](imp::VacantEntry::insert)
pub fn insert(self, value: T) -> Key { self.0.insert(value) }
}
impl<T> $crate::core::default::Default for Arena<T> {
fn default() -> Self { Self::new() }
}
impl<T> Arena<T> {
/// Create a new slab
pub fn new() -> Self {
Self(BaseArena::with_ident(super::$name::oneshot()))
}
/// see [`Arena::is_empty`](imp::Arena::is_empty)
pub fn is_empty(&self) -> bool { self.0.is_empty() }
/// see [`Arena::len`](imp::Arena::is_empty)
pub fn len(&self) -> usize { self.0.len() }
/// see [`Arena::capacity`](imp::Arena::capacity)
pub fn capacity(&self) -> usize { self.0.capacity() }
/// see [`Arena::reserve`](imp::Arena::reserve)
pub fn reserve(&mut self, additional: usize) { self.0.reserve(additional) }
/// see [`Arena::vacant_entry`](imp::Arena::vacant_entry)
pub fn vacant_entry(&mut self) -> VacantEntry<'_, T> { VacantEntry(self.0.vacant_entry()) }
/// see [`Arena::insert`](imp::Arena::insert)
pub fn insert(&mut self, value: T) -> Key { self.0.insert(value) }
/// see [`Arena::contains`](imp::Arena::contains)
pub fn contains(&self, key: Key) -> bool { self.0.contains(key) }
/// see [`Arena::remove`](imp::Arena::remove)
pub fn remove(&mut self, key: Key) -> T { self.0.remove(key) }
/// see [`Arena::try_remove`](imp::Arena::try_remove)
pub fn try_remove(&mut self, key: Key) -> Option<T> { self.0.try_remove(key) }
/// see [`Arena::delete`](imp::Arena::delete)
pub fn delete(&mut self, key: Key) -> bool { self.0.delete(key) }
/// see [`Arena::get`](imp::Arena::get)
pub fn get(&self, key: Key) -> Option<&T> { self.0.get(key) }
/// see [`Arena::get_mut`](imp::Arena::get_mut)
pub fn get_mut(&mut self, key: Key) -> Option<&mut T> { self.0.get_mut(key) }
/// see [`Arena::get_unchecked`](imp::Arena::get_unchecked)
#[allow(clippy::missing_safety_doc)]
pub unsafe fn get_unchecked(&self, index: usize) -> &T { self.0.get_unchecked(index) }
/// see [`Arena::get_unchecked_mut`](imp::Arena::get_unchecked_mut)
#[allow(clippy::missing_safety_doc)]
pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T { self.0.get_unchecked_mut(index) }
/// see [`Arena::delete_all`](imp::Arena::delete_all)
pub fn delete_all(&mut self) { self.0.delete_all() }
/// see [`Arena::retain`](imp::Arena::retain)
pub fn retain<F: FnMut(&mut T) -> bool>(&mut self, f: F) { self.0.retain(f) }
/// see [`Arena::keys`](imp::Arena::keys)
pub fn keys(&self) -> Keys<'_ $(, $keys)?> { self.0.keys() }
/// see [`Arena::iter`](imp::Arena::iter)
pub fn iter(&self) -> Iter<'_, T> { self.0.iter() }
/// see [`Arena::iter_mut`](imp::Arena::iter_mut)
pub fn iter_mut(&mut self) -> IterMut<'_, T> { self.0.iter_mut() }
/// see [`Arena::drain`](imp::Arena::drain)
pub fn drain(&mut self) -> Drain<'_, T> { self.0.drain() }
/// see [`Arena::drain_filter`](imp::Arena::drain_filter)
pub fn drain_filter<F: FnMut(&mut T) -> bool>(&mut self, filter: F) -> DrainFilter<'_, T, F> { self.0.drain_filter(filter) }
/// see [`Arena::entries`](imp::Arena::entries)
pub fn entries(&self) -> Entries<'_, T> { self.0.entries() }
/// see [`Arena::entries_mut`](imp::Arena::entries_mut)
pub fn entries_mut(&mut self) -> EntriesMut<'_, T> { self.0.entries_mut() }
/// see [`Arena::into_entries`](imp::Arena::into_entries)
pub fn into_entries(self) -> IntoEntries<T> { self.0.into_entries() }
}
impl<T> $crate::core::iter::IntoIterator for Arena<T> {
type IntoIter = IntoIter<T>;
type Item = T;
fn into_iter(self) -> Self::IntoIter { self.0.into_iter() }
}
impl<T> Index<Key> for Arena<T> {
type Output = T;
fn index(&self, key: Key) -> &Self::Output { &self.0[key] }
}
impl<T> IndexMut<Key> for Arena<T> {
fn index_mut(&mut self, key: Key) -> &mut Self::Output { &mut self.0[key] }
}
};
(@build_module ($mod_vis:vis) ($item_vis:vis) $name:ident, $version:ty) => {
/// a sparse arena
///
/// see [`pui_arena::base::sparse`](sparse::imp) for details
$mod_vis mod sparse {
use $crate::core::ops::*;
#[doc(hidden)]
pub(super) use $crate::base::sparse as imp;
/// The version for [`Arena`]
$item_vis type Version = $version;
/// Returned from [`Arena::iter`]
$item_vis type Iter<'a, T> = imp::Iter<'a, T, Version>;
/// Returned from [`Arena::iter_mut`]
$item_vis type IterMut<'a, T> = imp::IterMut<'a, T, Version>;
/// Returned from [`Arena::into_iter`]
$item_vis type IntoIter<T> = imp::IntoIter<T, Version>;
/// Returned from [`Arena::drain`]
$item_vis type Drain<'a, T> = imp::Drain<'a, T, Version>;
/// Returned from [`Arena::drain_filter`]
$item_vis type DrainFilter<'a, T, F> = imp::DrainFilter<'a, T, Version, F>;
/// Returned from [`Arena::keys`]
$item_vis type Keys<'a, T> = imp::Keys<'a, T, Identifier, Version, Key>;
$crate::__newtype! {
@forward
($item_vis) $name
slots: slots
T
}
}
/// a hop arena
///
/// see [`pui_arena::base::hop`](hop::imp) for details
$mod_vis mod hop {
use $crate::core::ops::*;
#[doc(hidden)]
pub(super) use $crate::base::hop as imp;
/// The version for [`Arena`]
$item_vis type Version = $version;
/// Returned from [`Arena::iter`]
$item_vis type Iter<'a, T> = imp::Iter<'a, T, Version>;
/// Returned from [`Arena::iter_mut`]
$item_vis type IterMut<'a, T> = imp::IterMut<'a, T, Version>;
/// Returned from [`Arena::into_iter`]
$item_vis type IntoIter<T> = imp::IntoIter<T, Version>;
/// Returned from [`Arena::drain`]
$item_vis type Drain<'a, T> = imp::Drain<'a, T, Version>;
/// Returned from [`Arena::drain_filter`]
$item_vis type DrainFilter<'a, T, F> = imp::DrainFilter<'a, T, Version, F>;
/// Returned from [`Arena::keys`]
$item_vis type Keys<'a, T> = imp::Keys<'a, T, Identifier, Version, Key>;
$crate::__newtype! {
@forward
($item_vis) $name
slots: len
T
}
}
/// a dense arena
///
/// see [`pui_arena::base::dense`](dense::imp) for details
$mod_vis mod dense {
use $crate::core::ops::*;
#[doc(hidden)]
pub(super) use $crate::base::dense as imp;
/// The version for [`Arena`]
$item_vis type Version = $version;
/// Returned from [`Arena::iter`]
$item_vis type Iter<'a, T> = $crate::core::slice::Iter<'a, T>;
/// Returned from [`Arena::iter_mut`]
$item_vis type IterMut<'a, T> = $crate::core::slice::IterMut<'a, T>;
/// Returned from [`Arena::into_iter`]
$item_vis type IntoIter<T> = $crate::std::vec::IntoIter<T>;
/// Returned from [`Arena::drain`]
$item_vis type Drain<'a, T> = imp::Drain<'a, T, Identifier, Version>;
/// Returned from [`Arena::drain_filter`]
$item_vis type DrainFilter<'a, T, F> = imp::DrainFilter<'a, T, Identifier, Version, F>;
/// Returned from [`Arena::keys`]
$item_vis type Keys<'a> = imp::Keys<'a, Identifier, Version, Key>;
$crate::__newtype! {
@forward
($item_vis) $name
slots: len
}
}
};
}
| 43.03301 | 162 | 0.581401 |
487c87843ba73c7518e96ff86559d33b6e9ebae0
| 2,616 |
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::constants::{SSH_PORT, SSH_PRIV},
crate::target::TargetAddr,
anyhow::{anyhow, Result},
ffx_config::{file, get},
std::process::Command,
};
static DEFAULT_SSH_OPTIONS: &'static [&str] = &[
"-o CheckHostIP=no",
"-o StrictHostKeyChecking=no",
"-o UserKnownHostsFile=/dev/null",
"-o ServerAliveInterval=1",
"-o ServerAliveCountMax=10",
"-o LogLevel=ERROR",
];
pub async fn build_ssh_command(addrs: Vec<TargetAddr>, command: Vec<&str>) -> Result<Command> {
if command.is_empty() {
return Err(anyhow!("missing SSH command"));
}
let port: Option<String> = get(SSH_PORT).await?;
let key: String = file(SSH_PRIV).await?;
let mut c = Command::new("ssh");
if let Some(p) = port {
c.arg("-p").arg(p);
}
c.arg("-i").arg(key);
let addr = addrs.iter().next().ok_or(anyhow!("no IP's for chosen target"))?;
c.args(DEFAULT_SSH_OPTIONS).arg(format!("{}", addr)).args(&command);
return Ok(c);
}
#[cfg(test)]
mod test {
use {
super::build_ssh_command,
crate::target::TargetAddr,
anyhow::Result,
std::net::{IpAddr, Ipv4Addr},
};
#[fuchsia_async::run_singlethreaded(test)]
async fn test_empty_command_vec_produces_error() {
let result = build_ssh_command(Vec::new(), vec![]).await;
assert!(result.is_err(), "empty command vec should produce an error");
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_no_ips_produces_error() {
let result = build_ssh_command(Vec::new(), vec!["ls"]).await;
assert!(result.is_err(), "target with no IP's should produce an error");
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_valid_inputs() -> Result<()> {
let key_path = std::env::current_exe().unwrap();
let key_path = key_path.to_str().take().unwrap();
std::env::set_var("FUCHSIA_SSH_PORT", "1234");
std::env::set_var("FUCHSIA_SSH_KEY", key_path);
let ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1));
let mut addrs = Vec::new();
addrs.push(TargetAddr::from((ip, 0)));
let result = build_ssh_command(addrs, vec!["ls"]).await.unwrap();
let dbgstr = format!("{:?}", result);
assert!(dbgstr.contains(&format!("\"-p\" \"1234\" \"-i\" \"{}\"", key_path)), "{}", dbgstr);
assert!(dbgstr.contains(&ip.to_string()), "{}", dbgstr);
Ok(())
}
}
| 31.518072 | 100 | 0.607416 |
c1f0c6dcd0066d17517c22c6ee17637cb34f0508
| 3,896 |
// blinky timer using interrupts on TIM2
//
// This demo based off of the following demo:
// - https://github.com/stm32-rs/stm32f0xx-hal/blob/master/examples/blinky_timer_irq.rs
// with some information about STM32F1 interrupts/peripherals from:
// - https://github.com/geomatsi/rust-blue-pill-tests/blob/master/src/bin/blink-timer-irq-safe.rs
#![no_main]
#![no_std]
use panic_halt as _;
use stm32f1xx_hal as hal;
use crate::hal::{
gpio::*,
prelude::*,
stm32::{interrupt, Interrupt, Peripherals, TIM2},
timer::*,
};
use core::cell::RefCell;
use cortex_m::{
asm::wfi,
interrupt::Mutex,
peripheral::Peripherals as c_m_Peripherals};
use cortex_m_rt::entry;
// NOTE You can uncomment 'hprintln' here and in the code below for a bit more
// verbosity at runtime, at the cost of throwing off the timing of the blink
// (using 'semihosting' for printing debug info anywhere slows program
// execution down)
//use cortex_m_semihosting::hprintln;
// A type definition for the GPIO pin to be used for our LED
type LEDPIN = gpioc::PC13<Output<PushPull>>;
// Make LED pin globally available
static G_LED: Mutex<RefCell<Option<LEDPIN>>> = Mutex::new(RefCell::new(None));
// Make timer interrupt registers globally available
static G_TIM: Mutex<RefCell<Option<CountDownTimer<TIM2>>>> = Mutex::new(RefCell::new(None));
// Define an interupt handler, i.e. function to call when interrupt occurs.
// This specific interrupt will "trip" when the timer TIM2 times out
#[interrupt]
fn TIM2() {
static mut LED: Option<LEDPIN> = None;
static mut TIM: Option<CountDownTimer<TIM2>> = None;
let led = LED.get_or_insert_with(|| {
cortex_m::interrupt::free(|cs| {
// Move LED pin here, leaving a None in its place
G_LED.borrow(cs).replace(None).unwrap()
})
});
let tim = TIM.get_or_insert_with(|| {
cortex_m::interrupt::free(|cs| {
// Move LED pin here, leaving a None in its place
G_TIM.borrow(cs).replace(None).unwrap()
})
});
//hprintln!("TIM2 IRQ fired").unwrap();
led.toggle().ok();
tim.wait().ok();
}
#[entry]
fn main() -> ! {
if let (Some(dp), Some(cp)) = (Peripherals::take(), c_m_Peripherals::take()) {
cortex_m::interrupt::free(move |cs| {
let mut rcc = dp.RCC.constrain();
let mut flash = dp.FLASH.constrain();
let clocks = rcc
.cfgr
.sysclk(8.mhz())
.pclk1(8.mhz())
.freeze(&mut flash.acr);
// Configure PC13 pin to blink LED
let mut gpioc = dp.GPIOC.split(&mut rcc.apb2);
let led = gpioc.pc13.into_push_pull_output(&mut gpioc.crh);
// Move the pin into our global storage
*G_LED.borrow(cs).borrow_mut() = Some(led);
// Set up a timer expiring after 1s
let mut timer = Timer::tim2(dp.TIM2, &clocks, &mut rcc.apb1).start_count_down(1.hz());
// Generate an interrupt when the timer expires
timer.listen(Event::Update);
// Move the timer into our global storage
*G_TIM.borrow(cs).borrow_mut() = Some(timer);
// Enable TIM2 IRQ, set prio 1 and clear any pending IRQs
let mut nvic = cp.NVIC;
// Calling 'set_priority()' and 'unmask()' requires 'unsafe {}'
// - https://docs.rs/stm32f1xx-hal/0.5.3/stm32f1xx_hal/stm32/struct.NVIC.html#method.set_priority
unsafe {
nvic.set_priority(Interrupt::TIM2, 1);
cortex_m::peripheral::NVIC::unmask(Interrupt::TIM2);
}
// Clear the interrupt state
cortex_m::peripheral::NVIC::unpend(Interrupt::TIM2);
});
}
//hprintln!("Entering main loop...").unwrap();
loop {
// From 'cortex_m::asm::wfi'
wfi();
}
}
| 33.299145 | 109 | 0.613706 |
87f6b0540617a04c0e670a1ebd08c5ed9fd8ae91
| 2,281 |
use regex::Regex;
use std::str::FromStr;
/// Represents a size as a number of bytes
#[derive(Clone, Copy, Debug)]
pub struct Bytes(pub u32);
fn scale(quantity: u32, unit: &str) -> u32 {
match unit {
"K" => quantity * 1_000,
"M" => quantity * 1_000_000,
"G" => quantity * 1_000_000_000,
_ => unreachable!(),
}
}
impl FromStr for Bytes {
type Err = ();
fn from_str(src: &str) -> Result<Bytes, ()> {
let human_readable: Regex = Regex::new(r"^\s*(\d+)([GKM])?\s*$").unwrap();
match human_readable.captures(src) {
Some(captures) => {
let quantity: u32 = captures.get(1).unwrap().as_str().parse().unwrap();
match captures.get(2) {
Some(unit) => Ok(Bytes(scale(quantity, unit.as_str()))),
None => Ok(Bytes(quantity)),
}
}
None => Err(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::{quickcheck, Arbitrary, Gen};
#[test]
fn test_bytes_from_str() {
let assert = |src, expected| {
assert_eq!(Bytes::from_str(src).map(|by| by.0), expected);
};
assert("10M", Ok(10_000_000));
assert("10", Ok(10));
assert("33", Ok(33));
assert("1G", Ok(1_000_000_000));
}
#[derive(Clone, Debug)]
struct Unit(char);
impl Arbitrary for Unit {
fn arbitrary<G: Gen>(gen: &mut G) -> Unit {
let choices = ['K', 'M', 'G'];
Unit(choices[(gen.size() / usize::max_value()) as usize])
}
}
quickcheck! {
fn human_size_with_arbitrary_input_never_panics(src: String) -> bool {
match Bytes::from_str(&src) {
Ok(_) => true,
Err(()) => true,
}
}
fn human_size_without_unit_roundtrips(quantity: u32) -> bool {
let src = format!("{}", quantity);
Bytes::from_str(&src).unwrap().0 == quantity
}
fn human_size_with_unit_roundtrips(quantity: u32, unit: Unit) -> bool {
let src = format!("{}{}", quantity, unit.0.to_string());
Bytes::from_str(&src).unwrap().0 == scale(quantity, &unit.0.to_string())
}
}
}
| 27.481928 | 87 | 0.507234 |
bbdf63bd1fbe1c2a596bfa718b5b5e13670e1b23
| 353 |
fn main() {
let v = vec![1, 2, 3, 4, 5];
let third: &i32 = &v[2];
println!("The third item in the vector is: {}", third);
let i = 9;
let does_not_exist = &v[100];
match v.get(i) {
Some(_) => { println!("Reachable element at index: {}", i) },
None => { println!("Unreachable element at index: {}", i) }
}
}
| 25.214286 | 70 | 0.501416 |
016bef967e26f02f0ee37df7093bf4977980f35b
| 3,375 |
#![allow(unused_imports)]
use super::*;
use wasm_bindgen::prelude::*;
#[cfg(web_sys_unstable_apis)]
#[wasm_bindgen]
extern "wasm-bindgen" {
# [wasm_bindgen (extends = :: js_sys :: Object , js_name = GPUTextureUsage , typescript_type = "GPUTextureUsage")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc = "The `GpuTextureUsage` class."]
#[doc = ""]
#[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/GPUTextureUsage)"]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `GpuTextureUsage`*"]
#[doc = ""]
#[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"]
#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"]
pub type GpuTextureUsage;
}
#[cfg(web_sys_unstable_apis)]
impl GpuTextureUsage {
#[cfg(web_sys_unstable_apis)]
#[doc = "The `GPUTextureUsage.COPY_SRC` const."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `GpuTextureUsage`*"]
#[doc = ""]
#[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"]
#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"]
pub const COPY_SRC: u32 = 1u64 as u32;
#[cfg(web_sys_unstable_apis)]
#[doc = "The `GPUTextureUsage.COPY_DST` const."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `GpuTextureUsage`*"]
#[doc = ""]
#[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"]
#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"]
pub const COPY_DST: u32 = 2u64 as u32;
#[cfg(web_sys_unstable_apis)]
#[doc = "The `GPUTextureUsage.SAMPLED` const."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `GpuTextureUsage`*"]
#[doc = ""]
#[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"]
#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"]
pub const SAMPLED: u32 = 4u64 as u32;
#[cfg(web_sys_unstable_apis)]
#[doc = "The `GPUTextureUsage.STORAGE` const."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `GpuTextureUsage`*"]
#[doc = ""]
#[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"]
#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"]
pub const STORAGE: u32 = 8u64 as u32;
#[cfg(web_sys_unstable_apis)]
#[doc = "The `GPUTextureUsage.OUTPUT_ATTACHMENT` const."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `GpuTextureUsage`*"]
#[doc = ""]
#[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"]
#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"]
pub const OUTPUT_ATTACHMENT: u32 = 16u64 as u32;
}
| 54.435484 | 128 | 0.666963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.