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
|
---|---|---|---|---|---|
fe2958fa9655de5c2b00777e560bbc4507ca91b4
| 2,502 |
#![feature(crate_visibility_modifier)]
#![doc(html_root_url = "https://api.rocket.rs/v0.5")]
#![doc(html_favicon_url = "https://rocket.rs/v0.5/images/favicon.ico")]
#![doc(html_logo_url = "https://rocket.rs/v0.5/images/logo-boxed.png")]
#![warn(rust_2018_idioms)]
#![allow(unused_extern_crates)]
//! This crate contains officially sanctioned contributor libraries that provide
//! functionality commonly used by Rocket applications.
//!
//! These libraries are always kept in-sync with the core Rocket library. They
//! provide common, but not fundamental, abstractions to be used by Rocket
//! applications.
//!
//! Each module in this library is held behind a feature flag, with the most
//! common modules exposed by default. The present feature list is below, with
//! an asterisk next to the features that are enabled by default:
//!
//! * [json*](type@json) - JSON (de)serialization
//! * [serve*](serve) - Static File Serving
//! * [msgpack](msgpack) - MessagePack (de)serialization
//! * [handlebars_templates](templates) - Handlebars Templating
//! * [tera_templates](templates) - Tera Templating
//! * [uuid](uuid) - UUID (de)serialization
//! * [${database}_pool](databases) - Database Configuration and Pooling
//! * [helmet](helmet) - Fairing for Security and Privacy Headers
//! * [compression](compression) - Response compression
//!
//! The recommend way to include features from this crate via Cargo in your
//! project is by adding a `[dependencies.rocket_contrib]` section to your
//! `Cargo.toml` file, setting `default-features` to false, and specifying
//! features manually. For example, to use the JSON module, you would add:
//!
//! ```toml
//! [dependencies.rocket_contrib]
//! version = "0.5.0-dev"
//! default-features = false
//! features = ["json"]
//! ```
//!
//! This crate is expected to grow with time, bringing in outside crates to be
//! officially supported by Rocket.
#[allow(unused_imports)] #[macro_use] extern crate log;
#[allow(unused_imports)] #[macro_use] extern crate rocket;
#[cfg(feature="json")] #[macro_use] pub mod json;
#[cfg(feature="serve")] pub mod serve;
#[cfg(feature="msgpack")] pub mod msgpack;
#[cfg(feature="templates")] pub mod templates;
#[cfg(feature="uuid")] pub mod uuid;
#[cfg(feature="databases")] pub mod databases;
#[cfg(feature = "helmet")] pub mod helmet;
#[cfg(any(feature="brotli_compression", feature="gzip_compression"))] pub mod compression;
#[cfg(feature="databases")] #[doc(hidden)] pub use rocket_contrib_codegen::*;
| 42.40678 | 90 | 0.715028 |
f929fc43010c1e8e2ea3c4a19065966ab8950e7e
| 4,555 |
use crate::utility::SifisError;
use crate::utility::COMPLEXITY;
use rust_code_analysis::FuncSpace;
use serde_json::Value;
// This function find the minimum space for a line i in the file
// Tt returns the space
fn get_min_space(root: &FuncSpace, i: usize) -> FuncSpace {
let mut min_space: FuncSpace = root.clone();
let mut stack: Vec<FuncSpace> = vec![root.clone()];
while let Some(space) = stack.pop() {
for s in space.spaces.into_iter() {
if i >= s.start_line && i <= s.end_line {
min_space = s.clone();
stack.push(s);
}
}
}
min_space
}
/// Calculate the SIFIS plain value for the given file(only rust language)
/// Return the value in case of success and an specif error in case of fails
pub fn sifis_plain(
root: &FuncSpace,
covs: &[Value],
metric: COMPLEXITY,
) -> Result<f64, SifisError> {
let ploc = root.metrics.loc.ploc();
let comp = match metric {
COMPLEXITY::CYCLOMATIC => root.metrics.cyclomatic.cyclomatic_sum(),
COMPLEXITY::COGNITIVE => root.metrics.cognitive.cognitive_sum(),
};
let mut sum = 0.0;
for i in 0..covs.len() {
let is_null = match covs.get(i) {
Some(val) => val.is_null(),
None => return Err(SifisError::ConversionError()),
};
if !is_null {
let cov = match covs.get(i).unwrap().as_u64() {
Some(cov) => cov,
None => return Err(SifisError::ConversionError()),
};
if cov > 0 {
sum += comp;
}
}
}
Ok(sum / ploc)
}
/// Calculate the SIFIS quantized value for the given file(only rust language)
/// Return the value in case of success and an specif error in case of fails
pub fn sifis_quantized(
root: &FuncSpace,
covs: &[Value],
metric: COMPLEXITY,
) -> Result<f64, SifisError> {
let ploc = root.metrics.loc.ploc();
let mut sum = 0.0;
let threshold = 15.;
//for each line find the minimun space and get complexity value then sum 1 if comp>threshold else sum 1
for i in 0..covs.len() {
let is_null = match covs.get(i) {
Some(val) => val.is_null(),
None => return Err(SifisError::ConversionError()),
};
if !is_null {
let cov = match covs.get(i).unwrap().as_u64() {
Some(cov) => cov,
None => return Err(SifisError::ConversionError()),
};
if cov > 0 {
let min_space: FuncSpace = get_min_space(root, i);
let comp = match metric {
COMPLEXITY::CYCLOMATIC => min_space.metrics.cyclomatic.cyclomatic(),
COMPLEXITY::COGNITIVE => min_space.metrics.cognitive.cognitive(),
};
if comp > threshold {
sum += 2.;
} else {
sum += 1.;
}
}
}
}
Ok(sum / ploc)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::utility::{get_root, read_json};
use std::fs;
const JSON: &str = "./data/data.json";
const PREFIX: &str = "../rust-data-structures-main/";
const SIMPLE: &str = "../rust-data-structures-main/data/simple_main.rs";
const FILE: &str = "./data/simple_main.rs";
const COMP: COMPLEXITY = COMPLEXITY::CYCLOMATIC;
const COGN: COMPLEXITY = COMPLEXITY::COGNITIVE;
#[test]
fn test_sifis_plain() {
let file = fs::read_to_string(JSON).unwrap();
let covs = read_json(file, PREFIX).unwrap();
let mut path = PathBuf::new();
path.push(FILE);
let root = get_root(&path).unwrap();
let vec = covs.get(SIMPLE).unwrap().to_vec();
let sifis = sifis_plain(&root, &vec, COMP).unwrap();
assert_eq!(sifis, 24. / 10.);
let sifis_cogn = sifis_plain(&root, &vec, COGN).unwrap();
assert_eq!(sifis_cogn, 18. / 10.);
}
#[test]
fn test_sifis_quantized() {
let file = fs::read_to_string(JSON).unwrap();
let covs = read_json(file, PREFIX).unwrap();
let mut path = PathBuf::new();
path.push(FILE);
let root = get_root(&path).unwrap();
let vec = covs.get(SIMPLE).unwrap().to_vec();
let sifis = sifis_quantized(&root, &vec, COMP).unwrap();
assert_eq!(sifis, 6. / 10.);
let sifis_cogn = sifis_quantized(&root, &vec, COGN).unwrap();
assert_eq!(sifis_cogn, 6. / 10.);
}
}
| 33.492647 | 108 | 0.559385 |
5d44b13311022e286ac0a9c258f0dc3be8fbcafe
| 8,802 |
#![allow(unused)]
use coins_ledger::{
common::{APDUAnswer, APDUCommand, APDUData},
transports::{Ledger, LedgerAsync},
};
use futures_executor::block_on;
use futures_util::lock::Mutex;
use ethers_core::{
types::{
Address, NameOrAddress, Signature, Transaction, TransactionRequest, TxHash, H256, U256,
},
utils::keccak256,
};
use std::convert::TryFrom;
use thiserror::Error;
use super::types::*;
/// A Ledger Ethereum App.
///
/// This is a simple wrapper around the [Ledger transport](Ledger)
#[derive(Debug)]
pub struct LedgerEthereum {
transport: Mutex<Ledger>,
derivation: DerivationType,
pub(crate) chain_id: u64,
pub(crate) address: Address,
}
impl LedgerEthereum {
/// Instantiate the application by acquiring a lock on the ledger device.
///
///
/// ```
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// use ethers::signers::{Ledger, HDPath};
///
/// let ledger = Ledger::new(HDPath::LedgerLive(0), 1).await?;
/// # Ok(())
/// # }
/// ```
pub async fn new(derivation: DerivationType, chain_id: u64) -> Result<Self, LedgerError> {
let transport = Ledger::init().await?;
let address = Self::get_address_with_path_transport(&transport, &derivation).await?;
Ok(Self {
transport: Mutex::new(transport),
derivation,
chain_id,
address,
})
}
/// Consume self and drop the ledger mutex
pub fn close(self) {}
/// Get the account which corresponds to our derivation path
pub async fn get_address(&self) -> Result<Address, LedgerError> {
self.get_address_with_path(&self.derivation).await
}
/// Gets the account which corresponds to the provided derivation path
pub async fn get_address_with_path(
&self,
derivation: &DerivationType,
) -> Result<Address, LedgerError> {
let data = APDUData::new(&Self::path_to_bytes(&derivation));
let transport = self.transport.lock().await;
Self::get_address_with_path_transport(&transport, derivation).await
}
async fn get_address_with_path_transport(
transport: &Ledger,
derivation: &DerivationType,
) -> Result<Address, LedgerError> {
let data = APDUData::new(&Self::path_to_bytes(&derivation));
let command = APDUCommand {
ins: INS::GET_PUBLIC_KEY as u8,
p1: P1::NON_CONFIRM as u8,
p2: P2::NO_CHAINCODE as u8,
data,
response_len: None,
};
let answer = block_on(transport.exchange(&command))?;
let result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?;
let address = {
// extract the address from the response
let offset = 1 + result[0] as usize;
let address_str = &result[offset + 1..offset + 1 + result[offset] as usize];
let mut address = [0; 20];
address.copy_from_slice(&hex::decode(address_str)?);
Address::from(address)
};
Ok(address)
}
/// Returns the semver of the Ethereum ledger app
pub async fn version(&self) -> Result<String, LedgerError> {
let transport = self.transport.lock().await;
let command = APDUCommand {
ins: INS::GET_APP_CONFIGURATION as u8,
p1: P1::NON_CONFIRM as u8,
p2: P2::NO_CHAINCODE as u8,
data: APDUData::new(&[]),
response_len: None,
};
let answer = block_on(transport.exchange(&command))?;
let result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?;
Ok(format!("{}.{}.{}", result[1], result[2], result[3]))
}
/// Signs an Ethereum transaction (requires confirmation on the ledger)
pub async fn sign_tx(&self, tx: &TransactionRequest) -> Result<Signature, LedgerError> {
let mut payload = Self::path_to_bytes(&self.derivation);
payload.extend_from_slice(tx.rlp(self.chain_id).as_ref());
self.sign_payload(INS::SIGN, payload).await
}
/// Signs an ethereum personal message
pub async fn sign_message<S: AsRef<[u8]>>(&self, message: S) -> Result<Signature, LedgerError> {
let message = message.as_ref();
let mut payload = Self::path_to_bytes(&self.derivation);
payload.extend_from_slice(&(message.len() as u32).to_be_bytes());
payload.extend_from_slice(message);
self.sign_payload(INS::SIGN_PERSONAL_MESSAGE, payload).await
}
// Helper function for signing either transaction data or personal messages
async fn sign_payload(
&self,
command: INS,
mut payload: Vec<u8>,
) -> Result<Signature, LedgerError> {
let transport = self.transport.lock().await;
let mut command = APDUCommand {
ins: command as u8,
p1: P1_FIRST,
p2: P2::NO_CHAINCODE as u8,
data: APDUData::new(&[]),
response_len: None,
};
let mut result = Vec::new();
// Iterate in 255 byte chunks
while !payload.is_empty() {
let chunk_size = std::cmp::min(payload.len(), 255);
let data = payload.drain(0..chunk_size).collect::<Vec<_>>();
command.data = APDUData::new(&data);
let answer = block_on(transport.exchange(&command))?;
result = answer
.data()
.ok_or(LedgerError::UnexpectedNullResponse)?
.to_vec();
// We need more data
command.p1 = P1::MORE as u8;
}
let v = result[0] as u64;
let r = H256::from_slice(&result[1..33]);
let s = H256::from_slice(&result[33..]);
Ok(Signature { r, s, v })
}
// helper which converts a derivation path to bytes
fn path_to_bytes(derivation: &DerivationType) -> Vec<u8> {
let derivation = derivation.to_string();
let elements = derivation.split('/').skip(1).collect::<Vec<_>>();
let depth = elements.len();
let mut bytes = vec![depth as u8];
for derivation_index in elements {
let hardened = derivation_index.contains('\'');
let mut index = derivation_index.replace("'", "").parse::<u32>().unwrap();
if hardened {
index |= 0x80000000;
}
bytes.extend(&index.to_be_bytes());
}
bytes
}
}
#[cfg(all(test, feature = "ledger"))]
mod tests {
use super::*;
use crate::Signer;
use ethers::prelude::*;
use std::str::FromStr;
#[tokio::test]
#[ignore]
// Replace this with your ETH addresses.
async fn test_get_address() {
// Instantiate it with the default ledger derivation path
let ledger = LedgerEthereum::new(DerivationType::LedgerLive(0), 1)
.await
.unwrap();
assert_eq!(
ledger.get_address().await.unwrap(),
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee".parse().unwrap()
);
assert_eq!(
ledger
.get_address_with_path(&DerivationType::Legacy(0))
.await
.unwrap(),
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee".parse().unwrap()
);
}
#[tokio::test]
#[ignore]
async fn test_sign_tx() {
let ledger = LedgerEthereum::new(DerivationType::LedgerLive(0), 1)
.await
.unwrap();
// approve uni v2 router 0xff
let data = hex::decode("095ea7b30000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap();
let tx_req = TransactionRequest::new()
.to("2ed7afa17473e17ac59908f088b4371d28585476"
.parse::<Address>()
.unwrap())
.gas(1000000)
.gas_price(400e9 as u64)
.nonce(5)
.data(data)
.value(ethers_core::utils::parse_ether(100).unwrap());
let tx = ledger.sign_transaction(&tx_req).await.unwrap();
}
#[tokio::test]
#[ignore]
async fn test_version() {
let ledger = LedgerEthereum::new(DerivationType::LedgerLive(0), 1)
.await
.unwrap();
let version = ledger.version().await.unwrap();
assert_eq!(version, "1.3.7");
}
#[tokio::test]
#[ignore]
async fn test_sign_message() {
let ledger = LedgerEthereum::new(DerivationType::Legacy(0), 1)
.await
.unwrap();
let message = "hello world";
let sig = ledger.sign_message(message).await.unwrap();
let addr = ledger.get_address().await.unwrap();
sig.verify(message, addr).unwrap();
}
}
| 32.479705 | 180 | 0.58748 |
91c7bbe547efb0055006e2c1fb29023af718f3d3
| 1,061 |
#![no_std]
#![no_main]
mod http;
mod net;
mod parser;
mod url;
extern crate alloc;
use alloc::string::ToString;
use liumlib::*;
use crate::net::udp_response;
use crate::parser::render;
use crate::url::ParsedUrl;
fn help_message() {
println!("Usage: browser-rs.bin [ OPTIONS ]");
println!(" -u, --url URL. Default: http://127.0.0.1:8888/index.html");
exit(0);
}
entry_point!(main);
fn main() {
let mut url = "http://127.0.0.1:8888/index.html";
let help_flag = "--help".to_string();
let url_flag = "--url".to_string();
let args = env::args();
for i in 1..args.len() {
if help_flag == args[i] {
help_message();
}
if url_flag == args[i] {
if i + 1 >= args.len() {
help_message();
}
url = args[i + 1];
}
}
let parsed_url = ParsedUrl::new(url.to_string());
let response = udp_response(&parsed_url);
println!("----- receiving a response -----");
println!("{}", response);
render(response);
}
| 19.648148 | 85 | 0.540999 |
1adce315bfc2ea2c28d4af7f0fdb1a1766fbc0ac
| 966 |
// Copyright 2018-2020 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::peer::interconnect::NetworkMessageSender;
use super::{MessageSender, PeerId};
impl MessageSender<PeerId> for NetworkMessageSender {
fn send(&self, recipient: PeerId, message: Vec<u8>) -> Result<(), (PeerId, Vec<u8>)> {
NetworkMessageSender::send(self, recipient.into(), message)
.map_err(|(id, msg)| (id.into(), msg))
}
}
| 38.64 | 90 | 0.716356 |
d64d3bdad5d13ea1b1cd98db0f718dd54edc01f2
| 885 |
use {
crate::crocol::{LCodegen, LNodeResult},
inkwell::values::BasicValueEnum,
};
use crate::crocol::CrocolNode;
use crate::{ast::node::AssignmentNode, error::CrocoError};
impl CrocolNode for AssignmentNode {
fn crocol<'ctx>(
&mut self,
codegen: &mut LCodegen<'ctx>,
) -> Result<LNodeResult<'ctx>, CrocoError> {
let var_ptr = self.var.crocol(codegen)?.into_var(&self.code_pos)?;
let expr = self
.expr
.crocol(codegen)?
.into_symbol(codegen, &self.code_pos)?;
if expr.symbol_type != var_ptr.symbol_type {
return Err(CrocoError::type_change_error(&self.code_pos));
}
let expr_value: BasicValueEnum = expr.value;
codegen
.builder
.build_store(var_ptr.value.into_pointer_value(), expr_value);
Ok(LNodeResult::Void)
}
}
| 26.818182 | 74 | 0.60678 |
9b9573cf78fb7f17aa76516493f55bdd7a0c3fe3
| 640 |
use std::mem;
fn analyze_slice(slice: &[i32]) {
println!("first elt of slice {}", slice[0]);
println!("slice has {} elts", slice.len());
}
fn main() {
let xs = [1, 2, 3, 4, 5];
let ys = [0; 500];
println!("first elt of arr {}", xs[0]);
println!("second elt of arr {}", xs[1]);
println!("array size: {}", xs.len());
println!("array occupies {} bytes", mem::size_of_val(&xs));
println!("borrow the whole array as a slice");
analyze_slice(&xs);
println!("borrow a section of the array as a slice");
analyze_slice(&ys[1..4]);
// out of bounds indexing
// println!("{}", xs[5]);
}
| 22.857143 | 63 | 0.554688 |
188b564810f2e332e40dcc92429dde8d5c0a1b45
| 634 |
// Copyright (c) The Dijets Core Contributors
// SPDX-License-Identifier: Apache-2.0
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct Module {
#[serde(with = "serde_bytes")]
code: Vec<u8>,
}
impl Module {
pub fn new(code: Vec<u8>) -> Module {
Module { code }
}
pub fn code(&self) -> &[u8] {
&self.code
}
}
impl fmt::Debug for Module {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Module")
.field("code", &hex::encode(&self.code))
.finish()
}
}
| 21.133333 | 62 | 0.574132 |
f934e0723015cf139f2e392a6213932f98c5e0ea
| 2,764 |
use hal::image::{Access as ImageAccess, Layout as ImageLayout, Usage as ImageUsage};
use hal::pso::PipelineStage;
use resource::{Access, Layout, Usage};
impl Access for ImageAccess {
fn none() -> Self {
Self::empty()
}
fn all() -> Self {
Self::all()
}
fn is_write(&self) -> bool {
self.contains(Self::COLOR_ATTACHMENT_WRITE)
|| self.contains(Self::DEPTH_STENCIL_ATTACHMENT_WRITE)
|| self.contains(Self::TRANSFER_WRITE)
|| self.contains(Self::SHADER_WRITE)
|| self.contains(Self::HOST_WRITE)
|| self.contains(Self::MEMORY_WRITE)
}
fn is_read(&self) -> bool {
self.contains(Self::COLOR_ATTACHMENT_READ)
|| self.contains(Self::DEPTH_STENCIL_ATTACHMENT_READ)
|| self.contains(Self::TRANSFER_READ)
|| self.contains(Self::SHADER_READ)
|| self.contains(Self::HOST_READ)
|| self.contains(Self::MEMORY_READ)
|| self.contains(Self::INPUT_ATTACHMENT_READ)
}
fn supported_pipeline_stages(&self) -> PipelineStage {
type PS = PipelineStage;
match *self {
Self::COLOR_ATTACHMENT_READ | Self::COLOR_ATTACHMENT_WRITE => {
PS::COLOR_ATTACHMENT_OUTPUT
}
Self::TRANSFER_READ | Self::TRANSFER_WRITE => PS::TRANSFER,
Self::SHADER_READ | Self::SHADER_WRITE => {
PS::VERTEX_SHADER | PS::GEOMETRY_SHADER | PS::FRAGMENT_SHADER | PS::COMPUTE_SHADER
}
Self::DEPTH_STENCIL_ATTACHMENT_READ | Self::DEPTH_STENCIL_ATTACHMENT_WRITE => {
PS::EARLY_FRAGMENT_TESTS | PS::LATE_FRAGMENT_TESTS
}
Self::HOST_READ | Self::HOST_WRITE => PS::HOST,
Self::MEMORY_READ | Self::MEMORY_WRITE => PS::empty(),
Self::INPUT_ATTACHMENT_READ => PS::FRAGMENT_SHADER,
_ => panic!("Only one bit must be set"),
}
}
}
impl Layout for ImageLayout {
fn merge(self, other: ImageLayout) -> Option<ImageLayout> {
match (self, other) {
(x, y) if x == y => Some(x),
(ImageLayout::Present, _) | (_, ImageLayout::Present) => None,
(ImageLayout::ShaderReadOnlyOptimal, ImageLayout::DepthStencilReadOnlyOptimal)
| (ImageLayout::DepthStencilReadOnlyOptimal, ImageLayout::ShaderReadOnlyOptimal) => {
Some(ImageLayout::DepthStencilReadOnlyOptimal)
}
(_, _) => Some(ImageLayout::General),
}
}
fn discard_content() -> Self {
ImageLayout::Undefined
}
}
impl Usage for ImageUsage {
fn none() -> Self {
ImageUsage::empty()
}
fn all() -> Self {
ImageUsage::all()
}
}
| 34.55 | 98 | 0.586469 |
5058c02e4815497e30f9e3bef1cfa2f812bfee37
| 6,271 |
use crate::dsl::{FnJitter, VariantValue};
use hashbrown::HashMap;
use serde_json::Value;
use std::cell::RefCell;
use std::collections::BTreeMap;
struct NodeCandidateResolver {
index: usize,
condition: FnJitter,
}
impl NodeCandidateResolver {
pub fn new(index: usize, on: &str) -> anyhow::Result<Self> {
let jitter = FnJitter::new(on)?;
Ok(Self {
index,
condition: jitter,
})
}
pub unsafe fn free_memory(self) {
self.condition.free_memory();
}
}
pub struct JsonConfigResolver {
condition_path: String,
value_path: String,
json: Value,
node_resolvers: BTreeMap<String, RefCell<Vec<NodeCandidateResolver>>>,
}
impl JsonConfigResolver {
pub fn new(json: Value) -> anyhow::Result<JsonConfigResolver> {
Self::new_with_custom_path(json, "if".to_owned(), "value".to_owned())
}
pub fn new_with_custom_path(
json: Value,
condition_path: String,
value_path: String,
) -> anyhow::Result<Self> {
let mut r = Self {
condition_path,
value_path,
json: Value::default(),
node_resolvers: BTreeMap::new(),
};
r.set_json(json)?;
Ok(r)
}
pub fn resolve(&self, ctx: &HashMap<String, VariantValue>) -> Value {
let mut ret = self.json.clone();
if self.node_resolvers.len() > 0 {
for (path, resolvers) in self.node_resolvers.iter().rev() {
if let Some(ptr_mut) = ret.pointer_mut(path) {
let mut match_value = Value::Null;
for resolver in resolvers.borrow().iter() {
if resolver.condition.evaluate(ctx) {
let k = format!("/{}/{}", resolver.index, self.value_path);
if let Some(v) = ptr_mut.pointer(&k) {
match_value = v.clone();
break;
}
}
}
*ptr_mut = match_value;
}
}
}
ret
}
fn set_json(&mut self, json: Value) -> anyhow::Result<()> {
let mut path = Vec::new();
self.parse_variants(&json, &mut path)?;
self.json = json;
Ok(())
}
fn parse_variants(&mut self, node: &Value, path: &mut Vec<String>) -> anyhow::Result<()> {
match node {
Value::Array(vec) => {
if vec.len() > 0 {
let is_variant_array = vec.iter().all(|i| self.is_variant_array(i));
let mut node_resolvers: Vec<NodeCandidateResolver>;
if is_variant_array {
node_resolvers = Vec::with_capacity(vec.len());
} else {
node_resolvers = Vec::with_capacity(0);
}
for (idx, item) in vec.iter().enumerate() {
if is_variant_array {
let value = item.get(&self.value_path).unwrap();
if let Some(v) = item.get(&self.condition_path) {
match v {
Value::String(on) => {
let r = NodeCandidateResolver::new(idx, &on)?;
node_resolvers.push(r);
}
Value::Null => {
let r = NodeCandidateResolver::new(idx, "1")?;
node_resolvers.push(r);
}
Value::Bool(true) => {
let r = NodeCandidateResolver::new(idx, "1")?;
node_resolvers.push(r);
}
Value::Number(n) => {
let r = NodeCandidateResolver::new(idx, &n.to_string())?;
node_resolvers.push(r);
}
_ => {}
}
}
path.push(format!("{}", idx));
path.push(format!("{}", self.value_path));
self.parse_variants(value, path)?;
path.pop();
path.pop();
} else {
path.push(format!("{}", idx));
self.parse_variants(item, path)?;
path.pop();
}
}
if is_variant_array {
self.node_resolvers
.insert(merge_json_path(path), RefCell::new(node_resolvers));
}
}
}
Value::Object(map) => {
for (k, v) in map {
path.push(k.clone());
self.parse_variants(v, path)?;
path.pop();
}
}
_ => {}
}
Ok(())
}
fn is_variant_array(&self, v: &Value) -> bool {
if v.is_object() {
if let Some(_) = v.get(&self.value_path) {
if let Some(c) = v.get(&self.condition_path) {
return !c.is_array() && !c.is_object();
}
}
}
return false;
}
fn get_keys(&self) -> Vec<String> {
self.node_resolvers.keys().cloned().collect()
}
}
impl Drop for JsonConfigResolver {
fn drop(&mut self) {
for k in self.get_keys() {
if let Some(v) = self.node_resolvers.remove(&k) {
let mut vec = v.borrow_mut();
while vec.len() > 0 {
let r = vec.remove(0);
unsafe { r.free_memory() };
}
}
}
}
}
fn merge_json_path(path: &Vec<String>) -> String {
format!("/{}", path.join("/"))
}
| 34.838889 | 97 | 0.411258 |
9c569a0fc727b25400f7b185571ec3eccbf6da23
| 11,597 |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Suppose we have the following data structure in a smart contract:
//!
//! struct B {
//! Map<String, String> mymap;
//! }
//!
//! struct A {
//! B b;
//! int my_int;
//! }
//!
//! struct C {
//! List<int> mylist;
//! }
//!
//! A a;
//! C c;
//!
//! and the data belongs to Alice. Then an access to `a.b.mymap` would be translated to an access
//! to an entry in key-value store whose key is `<Alice>/a/b/mymap`. In the same way, the access to
//! `c.mylist` would need to query `<Alice>/c/mylist`.
//!
//! So an account stores its data in a directory structure, for example:
//! <Alice>/balance: 10
//! <Alice>/a/b/mymap: {"Bob" => "abcd", "Carol" => "efgh"}
//! <Alice>/a/myint: 20
//! <Alice>/c/mylist: [3, 5, 7, 9]
//!
//! If someone needs to query the map above and find out what value associated with "Bob" is,
//! `address` will be set to Alice and `path` will be set to "/a/b/mymap/Bob".
//!
//! On the other hand, if you want to query only <Alice>/a/*, `address` will be set to Alice and
//! `path` will be set to "/a" and use the `get_prefix()` method from statedb
// This is caused by deriving Arbitrary for AccessPath.
#![allow(clippy::unit_arg)]
use crate::{
account_address::AccountAddress,
account_config::{
account_received_event_path, account_resource_path, account_sent_event_path,
association_address,
},
language_storage::{CodeKey, ResourceKey, StructTag},
validator_set::validator_set_path,
};
use canonical_serialization::{
CanonicalDeserialize, CanonicalDeserializer, CanonicalSerialize, CanonicalSerializer,
};
use crypto::hash::{CryptoHash, HashValue};
use failure::prelude::*;
use hex;
use lazy_static::lazy_static;
use proptest_derive::Arbitrary;
use proto_conv::{FromProto, IntoProto};
use radix_trie::TrieKey;
use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Formatter},
slice::Iter,
str::{self, FromStr},
};
#[derive(Default, Serialize, Deserialize, Debug, PartialEq, Hash, Eq, Clone, Ord, PartialOrd)]
pub struct Field(String);
impl Field {
pub fn new(s: &str) -> Field {
Field(s.to_string())
}
pub fn name(&self) -> &String {
&self.0
}
}
impl From<String> for Field {
fn from(s: String) -> Self {
Field(s)
}
}
impl fmt::Display for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Eq, Hash, Serialize, Deserialize, Debug, Clone, PartialEq, Ord, PartialOrd)]
pub enum Access {
Field(Field),
Index(u64),
}
impl Access {
pub fn new(s: &str) -> Self {
Access::Field(Field::new(s))
}
}
impl FromStr for Access {
type Err = ::std::num::ParseIntError;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
if let Ok(idx) = s.parse::<u64>() {
Ok(Access::Index(idx))
} else {
Ok(Access::Field(Field::new(s)))
}
}
}
impl fmt::Display for Access {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Access::Field(field) => write!(f, "\"{}\"", field),
Access::Index(i) => write!(f, "{}", i),
}
}
}
/// Non-empty sequence of field accesses
#[derive(Eq, Hash, Serialize, Deserialize, Debug, Clone, PartialEq, Ord, PartialOrd)]
pub struct Accesses(Vec<Access>);
/// SEPARATOR is used as a delimeter between fields. It should not be a legal part of any identifier
/// in the language
const SEPARATOR: char = '/';
impl Accesses {
pub fn empty() -> Self {
Accesses(vec![])
}
pub fn new(field: Field) -> Self {
Accesses(vec![Access::Field(field)])
}
/// Add a field to the end of the sequence
pub fn add_field_to_back(&mut self, field: Field) {
self.0.push(Access::Field(field))
}
/// Add an index to the end of the sequence
pub fn add_index_to_back(&mut self, idx: u64) {
self.0.push(Access::Index(idx))
}
pub fn append(&mut self, accesses: &mut Accesses) {
self.0.append(&mut accesses.0)
}
/// Returns the first field in the sequence and reference to the remaining fields
pub fn split_first(&self) -> (&Access, &[Access]) {
self.0.split_first().unwrap()
}
/// Return the last access in the sequence
pub fn last(&self) -> &Access {
self.0.last().unwrap() // guaranteed not to fail because sequence is non-empty
}
pub fn iter(&self) -> Iter<'_, Access> {
self.0.iter()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn as_separated_string(&self) -> String {
let mut path = String::new();
for access in self.0.iter() {
match access {
Access::Field(s) => {
let access_str = s.name().as_ref();
assert!(access_str != "");
path.push_str(access_str)
}
Access::Index(i) => path.push_str(i.to_string().as_ref()),
};
path.push(SEPARATOR);
}
path
}
pub fn take_nth(&self, new_len: usize) -> Accesses {
assert!(self.0.len() >= new_len);
Accesses(self.0.clone().into_iter().take(new_len).collect())
}
}
impl<'a> IntoIterator for &'a Accesses {
type Item = &'a Access;
type IntoIter = Iter<'a, Access>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl From<Vec<Access>> for Accesses {
fn from(accesses: Vec<Access>) -> Accesses {
Accesses(accesses)
}
}
impl From<Vec<u8>> for Accesses {
fn from(mut raw_bytes: Vec<u8>) -> Accesses {
let access_str = String::from_utf8(raw_bytes.split_off(HashValue::LENGTH + 1)).unwrap();
let fields_str = access_str.split(SEPARATOR).collect::<Vec<&str>>();
let mut accesses = vec![];
for access_str in fields_str.into_iter() {
if access_str != "" {
accesses.push(Access::from_str(access_str).unwrap());
}
}
Accesses::from(accesses)
}
}
impl TrieKey for Accesses {
fn encode_bytes(&self) -> Vec<u8> {
self.as_separated_string().into_bytes()
}
}
lazy_static! {
/// The access path where the Validator Set resource is stored.
pub static ref VALIDATOR_SET_ACCESS_PATH: AccessPath =
AccessPath::new(association_address(), validator_set_path());
}
#[derive(
Clone,
Eq,
PartialEq,
Default,
Hash,
Serialize,
Deserialize,
Ord,
PartialOrd,
Arbitrary,
FromProto,
IntoProto,
)]
#[ProtoType(crate::proto::access_path::AccessPath)]
pub struct AccessPath {
pub address: AccountAddress,
pub path: Vec<u8>,
}
impl AccessPath {
const CODE_TAG: u8 = 0;
const RESOURCE_TAG: u8 = 1;
pub fn new(address: AccountAddress, path: Vec<u8>) -> Self {
AccessPath { address, path }
}
/// Given an address, returns the corresponding access path that stores the Account resource.
pub fn new_for_account(address: AccountAddress) -> Self {
Self::new(address, account_resource_path())
}
/// Create an AccessPath for a ContractEvent.
/// That is an AccessPah that uniquely identifies a given event for a published resource.
pub fn new_for_event(address: AccountAddress, root: &[u8], key: &[u8]) -> Self {
let mut path: Vec<u8> = Vec::new();
path.extend_from_slice(root);
path.push(b'/');
path.extend_from_slice(key);
path.push(b'/');
Self::new(address, path)
}
/// Create an AccessPath to the event for the sender account in a deposit operation.
/// The sent counter in LibraAccount.T (LibraAccount.T.sent_events_count) is used to generate
/// the AccessPath.
/// That AccessPath can be used as a key into the event storage to retrieve all sent
/// events for a given account.
pub fn new_for_sent_event(address: AccountAddress) -> Self {
Self::new(address, account_sent_event_path())
}
/// Create an AccessPath to the event for the target account (the receiver)
/// in a deposit operation.
/// The received counter in LibraAccount.T (LibraAccount.T.received_events_count) is used to
/// generate the AccessPath.
/// That AccessPath can be used as a key into the event storage to retrieve all received
/// events for a given account.
pub fn new_for_received_event(address: AccountAddress) -> Self {
Self::new(address, account_received_event_path())
}
pub fn resource_access_vec(tag: &StructTag, accesses: &Accesses) -> Vec<u8> {
let mut key = vec![];
key.push(Self::RESOURCE_TAG);
key.append(&mut tag.hash().to_vec());
// We don't need accesses in production right now. Accesses are appended here just for
// passing the old tests.
key.append(&mut accesses.as_separated_string().into_bytes());
key
}
/// Convert Accesses into a byte offset which would be used by the storage layer to resolve
/// where fields are stored.
pub fn resource_access_path(key: &ResourceKey, accesses: &Accesses) -> AccessPath {
let path = AccessPath::resource_access_vec(&key.type_(), accesses);
AccessPath {
address: key.address().to_owned(),
path,
}
}
fn code_access_path_vec(key: &CodeKey) -> Vec<u8> {
let mut root = vec![];
root.push(Self::CODE_TAG);
root.append(&mut key.hash().to_vec());
root
}
pub fn code_access_path(key: &CodeKey) -> AccessPath {
let path = AccessPath::code_access_path_vec(key);
AccessPath {
address: *key.address(),
path,
}
}
}
impl fmt::Debug for AccessPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"AccessPath {{ address: {:x}, path: {} }}",
self.address,
hex::encode(&self.path)
)
}
}
impl fmt::Display for AccessPath {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.path.len() < 1 + HashValue::LENGTH {
write!(f, "{:?}", self)
} else {
write!(f, "AccessPath {{ address: {:x}, ", self.address)?;
match self.path[0] {
Self::RESOURCE_TAG => write!(f, "type: Resource, ")?,
Self::CODE_TAG => write!(f, "type: Module, ")?,
tag => write!(f, "type: {:?}, ", tag)?,
};
write!(
f,
"hash: {:?}, ",
hex::encode(&self.path[1..=HashValue::LENGTH])
)?;
write!(
f,
"suffix: {:?} }} ",
String::from_utf8_lossy(&self.path[1 + HashValue::LENGTH..])
)
}
}
}
impl CanonicalSerialize for AccessPath {
fn serialize(&self, serializer: &mut impl CanonicalSerializer) -> Result<()> {
serializer
.encode_struct(&self.address)?
.encode_variable_length_bytes(&self.path)?;
Ok(())
}
}
impl CanonicalDeserialize for AccessPath {
fn deserialize(deserializer: &mut impl CanonicalDeserializer) -> Result<Self> {
let address = deserializer.decode_struct::<AccountAddress>()?;
let path = deserializer.decode_variable_length_bytes()?;
Ok(Self { address, path })
}
}
| 29.43401 | 100 | 0.592136 |
69b3cb9c17515415e37d02c6a1c87f40e35ad685
| 3,028 |
#![allow(unreachable_pub)]
use crate::install::{ClientOpt, Malloc, ServerOpt};
xflags::xflags! {
src "./src/flags.rs"
/// Run custom build command.
cmd xtask {
default cmd help {
/// Print help information.
optional -h, --help
}
/// Install rust-analyzer server or editor plugin.
cmd install {
/// Install only VS Code plugin.
optional --client
/// One of 'code', 'code-exploration', 'code-insiders', 'codium', or 'code-oss'.
optional --code-bin name: String
/// Install only the language server.
optional --server
/// Use mimalloc allocator for server
optional --mimalloc
/// Use jemalloc allocator for server
optional --jemalloc
}
cmd fuzz-tests {}
cmd release {
optional --dry-run
}
cmd promote {
optional --dry-run
}
cmd dist {
optional --client-patch-version version: String
}
cmd metrics {
optional --dry-run
}
/// Builds a benchmark version of rust-analyzer and puts it into `./target`.
cmd bb
required suffix: String
{}
}
}
// generated start
// The following code is generated by `xflags` macro.
// Run `env UPDATE_XFLAGS=1 cargo build` to regenerate.
#[derive(Debug)]
pub struct Xtask {
pub subcommand: XtaskCmd,
}
#[derive(Debug)]
pub enum XtaskCmd {
Help(Help),
Install(Install),
FuzzTests(FuzzTests),
Release(Release),
Promote(Promote),
Dist(Dist),
Metrics(Metrics),
Bb(Bb),
}
#[derive(Debug)]
pub struct Help {
pub help: bool,
}
#[derive(Debug)]
pub struct Install {
pub client: bool,
pub code_bin: Option<String>,
pub server: bool,
pub mimalloc: bool,
pub jemalloc: bool,
}
#[derive(Debug)]
pub struct FuzzTests;
#[derive(Debug)]
pub struct Release {
pub dry_run: bool,
}
#[derive(Debug)]
pub struct Promote {
pub dry_run: bool,
}
#[derive(Debug)]
pub struct Dist {
pub client_patch_version: Option<String>,
}
#[derive(Debug)]
pub struct Metrics {
pub dry_run: bool,
}
#[derive(Debug)]
pub struct Bb {
pub suffix: String,
}
impl Xtask {
pub const HELP: &'static str = Self::HELP_;
pub fn from_env() -> xflags::Result<Self> {
Self::from_env_()
}
}
// generated end
impl Install {
pub(crate) fn server(&self) -> Option<ServerOpt> {
if self.client && !self.server {
return None;
}
let malloc = if self.mimalloc {
Malloc::Mimalloc
} else if self.jemalloc {
Malloc::Jemalloc
} else {
Malloc::System
};
Some(ServerOpt { malloc })
}
pub(crate) fn client(&self) -> Option<ClientOpt> {
if !self.client && self.server {
return None;
}
Some(ClientOpt { code_bin: self.code_bin.clone() })
}
}
| 21.174825 | 92 | 0.560106 |
e2e4415fff70472f5254f858830f95528aaf970c
| 1,431 |
pub struct IconLibraryBooks {
props: crate::Props,
}
impl yew::Component for IconLibraryBooks {
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="M4 6H2v16h16v-2H4V6zm18-4H6v16h16V2zm-3 9H9V9h10v2zm-4 4H9v-2h6v2zm4-8H9V5h10v2z"/></svg>
</svg>
}
}
}
| 31.108696 | 232 | 0.583508 |
08de098897045d44286282bfddd57c0edfc906c9
| 9,580 |
// Copyright 2018 the Deno authors. All rights reserved. MIT license.
// Think of Resources as File Descriptors. They are integers that are allocated
// by the privileged side of Deno to refer to various resources. The simplest
// example are standard file system files and stdio - but there will be other
// resources added in the future that might not correspond to operating system
// level File Descriptors. To avoid confusion we call them "resources" not "file
// descriptors". This module implements a global resource table. Ops (AKA
// handlers) look up resources by their integer id here.
#[cfg(unix)]
use eager_unix as eager;
use errors::bad_resource;
use errors::DenoError;
use errors::DenoResult;
use repl::Repl;
use tokio_util;
use tokio_write;
use futures;
use futures::future::{Either, FutureResult};
use futures::Poll;
use std;
use std::collections::HashMap;
use std::io::{Error, Read, Write};
use std::net::{Shutdown, SocketAddr};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Mutex;
use tokio;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio_io;
pub type ResourceId = u32; // Sometimes referred to RID.
// These store Deno's file descriptors. These are not necessarily the operating
// system ones.
type ResourceTable = HashMap<ResourceId, Repr>;
lazy_static! {
// Starts at 3 because stdio is [0-2].
static ref NEXT_RID: AtomicUsize = AtomicUsize::new(3);
static ref RESOURCE_TABLE: Mutex<ResourceTable> = Mutex::new({
let mut m = HashMap::new();
// TODO Load these lazily during lookup?
m.insert(0, Repr::Stdin(tokio::io::stdin()));
m.insert(1, Repr::Stdout(tokio::io::stdout()));
m.insert(2, Repr::Stderr(tokio::io::stderr()));
m
});
}
// Internal representation of Resource.
enum Repr {
Stdin(tokio::io::Stdin),
Stdout(tokio::io::Stdout),
Stderr(tokio::io::Stderr),
FsFile(tokio::fs::File),
TcpListener(tokio::net::TcpListener),
TcpStream(tokio::net::TcpStream),
Repl(Repl),
}
pub fn table_entries() -> Vec<(u32, String)> {
let table = RESOURCE_TABLE.lock().unwrap();
table
.iter()
.map(|(key, value)| (*key, inspect_repr(&value)))
.collect()
}
#[test]
fn test_table_entries() {
let mut entries = table_entries();
entries.sort();
assert_eq!(entries.len(), 3);
assert_eq!(entries[0], (0, String::from("stdin")));
assert_eq!(entries[1], (1, String::from("stdout")));
assert_eq!(entries[2], (2, String::from("stderr")));
}
fn inspect_repr(repr: &Repr) -> String {
let h_repr = match repr {
Repr::Stdin(_) => "stdin",
Repr::Stdout(_) => "stdout",
Repr::Stderr(_) => "stderr",
Repr::FsFile(_) => "fsFile",
Repr::TcpListener(_) => "tcpListener",
Repr::TcpStream(_) => "tcpStream",
Repr::Repl(_) => "repl",
};
String::from(h_repr)
}
// Abstract async file interface.
// Ideally in unix, if Resource represents an OS rid, it will be the same.
#[derive(Debug)]
pub struct Resource {
pub rid: ResourceId,
}
impl Resource {
// TODO Should it return a Resource instead of net::TcpStream?
pub fn poll_accept(&mut self) -> Poll<(TcpStream, SocketAddr), Error> {
let mut table = RESOURCE_TABLE.lock().unwrap();
let maybe_repr = table.get_mut(&self.rid);
match maybe_repr {
None => panic!("bad rid"),
Some(repr) => match repr {
Repr::TcpListener(ref mut s) => s.poll_accept(),
_ => panic!("Cannot accept"),
},
}
}
// close(2) is done by dropping the value. Therefore we just need to remove
// the resource from the RESOURCE_TABLE.
pub fn close(&mut self) {
let mut table = RESOURCE_TABLE.lock().unwrap();
let r = table.remove(&self.rid);
assert!(r.is_some());
}
pub fn shutdown(&mut self, how: Shutdown) -> Result<(), DenoError> {
let mut table = RESOURCE_TABLE.lock().unwrap();
let maybe_repr = table.get_mut(&self.rid);
match maybe_repr {
None => panic!("bad rid"),
Some(repr) => match repr {
Repr::TcpStream(ref mut f) => {
TcpStream::shutdown(f, how).map_err(DenoError::from)
}
_ => panic!("Cannot shutdown"),
},
}
}
}
impl Read for Resource {
fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
unimplemented!();
}
}
impl AsyncRead for Resource {
fn poll_read(&mut self, buf: &mut [u8]) -> Poll<usize, Error> {
let mut table = RESOURCE_TABLE.lock().unwrap();
let maybe_repr = table.get_mut(&self.rid);
match maybe_repr {
None => panic!("bad rid"),
Some(repr) => match repr {
Repr::FsFile(ref mut f) => f.poll_read(buf),
Repr::Stdin(ref mut f) => f.poll_read(buf),
Repr::TcpStream(ref mut f) => f.poll_read(buf),
_ => panic!("Cannot read"),
},
}
}
}
impl Write for Resource {
fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
unimplemented!()
}
fn flush(&mut self) -> std::io::Result<()> {
unimplemented!()
}
}
impl AsyncWrite for Resource {
fn poll_write(&mut self, buf: &[u8]) -> Poll<usize, Error> {
let mut table = RESOURCE_TABLE.lock().unwrap();
let maybe_repr = table.get_mut(&self.rid);
match maybe_repr {
None => panic!("bad rid"),
Some(repr) => match repr {
Repr::FsFile(ref mut f) => f.poll_write(buf),
Repr::Stdout(ref mut f) => f.poll_write(buf),
Repr::Stderr(ref mut f) => f.poll_write(buf),
Repr::TcpStream(ref mut f) => f.poll_write(buf),
_ => panic!("Cannot write"),
},
}
}
fn shutdown(&mut self) -> futures::Poll<(), std::io::Error> {
unimplemented!()
}
}
fn new_rid() -> ResourceId {
let next_rid = NEXT_RID.fetch_add(1, Ordering::SeqCst);
next_rid as ResourceId
}
pub fn add_fs_file(fs_file: tokio::fs::File) -> Resource {
let rid = new_rid();
let mut tg = RESOURCE_TABLE.lock().unwrap();
match tg.insert(rid, Repr::FsFile(fs_file)) {
Some(_) => panic!("There is already a file with that rid"),
None => Resource { rid },
}
}
pub fn add_tcp_listener(listener: tokio::net::TcpListener) -> Resource {
let rid = new_rid();
let mut tg = RESOURCE_TABLE.lock().unwrap();
let r = tg.insert(rid, Repr::TcpListener(listener));
assert!(r.is_none());
Resource { rid }
}
pub fn add_tcp_stream(stream: tokio::net::TcpStream) -> Resource {
let rid = new_rid();
let mut tg = RESOURCE_TABLE.lock().unwrap();
let r = tg.insert(rid, Repr::TcpStream(stream));
assert!(r.is_none());
Resource { rid }
}
pub fn add_repl(repl: Repl) -> Resource {
let rid = new_rid();
let mut tg = RESOURCE_TABLE.lock().unwrap();
let r = tg.insert(rid, Repr::Repl(repl));
assert!(r.is_none());
Resource { rid }
}
pub fn readline(rid: ResourceId, prompt: &str) -> DenoResult<String> {
let mut table = RESOURCE_TABLE.lock().unwrap();
let maybe_repr = table.get_mut(&rid);
match maybe_repr {
Some(Repr::Repl(ref mut r)) => {
let line = r.readline(&prompt)?;
Ok(line)
}
_ => Err(bad_resource()),
}
}
pub fn lookup(rid: ResourceId) -> Option<Resource> {
let table = RESOURCE_TABLE.lock().unwrap();
table.get(&rid).map(|_| Resource { rid })
}
pub type EagerRead<R, T> =
Either<tokio_io::io::Read<R, T>, FutureResult<(R, T, usize), std::io::Error>>;
pub type EagerWrite<R, T> =
Either<tokio_write::Write<R, T>, FutureResult<(R, T, usize), std::io::Error>>;
pub type EagerAccept = Either<
tokio_util::Accept,
FutureResult<(tokio::net::TcpStream, std::net::SocketAddr), std::io::Error>,
>;
#[cfg(not(unix))]
#[allow(unused_mut)]
pub fn eager_read<T: AsMut<[u8]>>(
resource: Resource,
mut buf: T,
) -> EagerRead<Resource, T> {
Either::A(tokio_io::io::read(resource, buf)).into()
}
#[cfg(not(unix))]
pub fn eager_write<T: AsRef<[u8]>>(
resource: Resource,
buf: T,
) -> EagerWrite<Resource, T> {
Either::A(tokio_write::write(resource, buf)).into()
}
#[cfg(not(unix))]
pub fn eager_accept(resource: Resource) -> EagerAccept {
Either::A(tokio_util::accept(resource)).into()
}
// This is an optimization that Tokio should do.
// Attempt to call read() on the main thread.
#[cfg(unix)]
pub fn eager_read<T: AsMut<[u8]>>(
resource: Resource,
buf: T,
) -> EagerRead<Resource, T> {
let mut table = RESOURCE_TABLE.lock().unwrap();
let maybe_repr = table.get_mut(&resource.rid);
match maybe_repr {
None => panic!("bad rid"),
Some(repr) => match repr {
Repr::TcpStream(ref mut tcp_stream) => {
eager::tcp_read(tcp_stream, resource, buf)
}
_ => Either::A(tokio_io::io::read(resource, buf)),
},
}
}
// This is an optimization that Tokio should do.
// Attempt to call write() on the main thread.
#[cfg(unix)]
pub fn eager_write<T: AsRef<[u8]>>(
resource: Resource,
buf: T,
) -> EagerWrite<Resource, T> {
let mut table = RESOURCE_TABLE.lock().unwrap();
let maybe_repr = table.get_mut(&resource.rid);
match maybe_repr {
None => panic!("bad rid"),
Some(repr) => match repr {
Repr::TcpStream(ref mut tcp_stream) => {
eager::tcp_write(tcp_stream, resource, buf)
}
_ => Either::A(tokio_write::write(resource, buf)),
},
}
}
#[cfg(unix)]
pub fn eager_accept(resource: Resource) -> EagerAccept {
let mut table = RESOURCE_TABLE.lock().unwrap();
let maybe_repr = table.get_mut(&resource.rid);
match maybe_repr {
None => panic!("bad rid"),
Some(repr) => match repr {
Repr::TcpListener(ref mut tcp_listener) => {
eager::tcp_accept(tcp_listener, resource)
}
_ => Either::A(tokio_util::accept(resource)),
},
}
}
| 28.4273 | 80 | 0.638935 |
48940a339308e3e30989f90c1b1d766d25c814ee
| 1,947 |
use super::{IntersectionStats, Ray, Shape};
use crate::maths::Vector;
use std::cmp::{Ord, Ordering};
#[derive(Debug, Copy, Clone)]
pub struct Intersection {
t: f64,
shape: Shape,
}
impl Intersection {
pub fn new(t: f64, shape: Shape) -> Intersection {
if t.is_nan() {
panic!("Intersection does not support NaN t values");
}
Intersection { t, shape }
}
pub fn t(&self) -> f64 {
self.t
}
pub fn object(&self) -> Shape {
self.shape
}
pub fn hit(mut intersections: Vec<Intersection>) -> Option<Intersection> {
// Sort by t value
intersections.sort_unstable_by(|a, b| a.t().partial_cmp(&b.t()).unwrap());
// Get the first t value < 0
intersections.into_iter().find(|a| a.t() >= 0.0)
}
pub fn prepare_computations(&self, ray: Ray) -> IntersectionStats {
let point = ray.position(self.t);
let eyev = -ray.direction();
let mut normalv = self.object().normal_at(point);
let inside;
if Vector::dot(normalv, eyev) < 0.0 {
inside = true;
normalv = -normalv;
} else {
inside = false;
}
let over_point = point + normalv * f32::EPSILON as f64;
IntersectionStats::new(self.t, self.shape, point, eyev, normalv, inside, over_point)
}
}
impl PartialEq for Intersection {
fn eq(&self, other: &Self) -> bool {
use crate::maths::is_same;
is_same(self.t, other.t) && self.shape == other.shape
}
}
impl Eq for Intersection {}
impl PartialOrd for Intersection {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.t.partial_cmp(&other.t)
}
}
impl Ord for Intersection {
fn cmp(&self, other: &Self) -> Ordering {
// This is a bit risky but I don't think we should ever
// have a t value of NaN
self.t.partial_cmp(&other.t).unwrap()
}
}
| 25.618421 | 92 | 0.576271 |
8977ad2ea57b52edcdd107382a0f131c09b6a86f
| 3,434 |
// Copyright (c) 2020 White Leaf
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
use anyhow::Error;
use indicatif::ProgressIterator;
use mongodb::bson::{doc, to_bson, Bson};
use mongodb::sync::Client;
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
fn main() -> Result<(), Error> {
let vars: HashMap<String, String> = dotenv::vars().collect();
let mongo_url = &vars["MONGO_URL"];
let mongo_db = &vars["MONGO_DB"];
let client = Client::with_uri_str(mongo_url)?;
let db = client.database(mongo_db);
let collection = db.collection("users_who_rated");
let file = File::open("data/ratings-by-items.csv")?;
let reader = BufReader::new(file);
let mut csv = csv::ReaderBuilder::new()
.has_headers(true)
.delimiter(b',')
.from_reader(reader);
let mut current_item = None;
let mut current_ratings = HashMap::new();
for record in csv.records().progress() {
if let Ok(record) = record {
let user_id: i32 = record[0].parse()?;
let movie_id: i32 = record[1].parse()?;
let score: f64 = record[2].parse()?;
if let Some(current_item) = &mut current_item {
if *current_item != movie_id {
let data = to_bson(¤t_ratings)?;
collection
.insert_one(doc! { "item_id": *current_item, "scores": data }, None)?;
*current_item = movie_id;
current_ratings.clear();
}
} else {
current_item = Some(movie_id);
}
current_ratings.insert(user_id.to_string(), Bson::Double(score));
}
}
if let Some(current_item) = current_item {
if !current_ratings.is_empty() {
let data = to_bson(¤t_ratings)?;
collection.insert_one(doc! { "item_id": current_item, "scores": data}, None)?;
}
}
let collection = db.collection("users_ratings");
let file = File::open("data/ratings.csv")?;
let reader = BufReader::new(file);
let mut csv = csv::ReaderBuilder::new()
.has_headers(true)
.delimiter(b',')
.from_reader(reader);
let mut current_user = None;
let mut current_ratings = HashMap::new();
for record in csv.records().progress() {
if let Ok(record) = record {
let user_id: i32 = record[0].parse()?;
let movie_id: i32 = record[1].parse()?;
let score: f64 = record[2].parse()?;
if let Some(current_user) = &mut current_user {
if *current_user != user_id {
let data = to_bson(¤t_ratings)?;
collection
.insert_one(doc! { "user_id": *current_user, "scores": data }, None)?;
*current_user = user_id;
current_ratings.clear();
}
} else {
current_user = Some(user_id);
}
current_ratings.insert(movie_id.to_string(), Bson::Double(score));
}
}
if let Some(current_user) = current_user {
if !current_ratings.is_empty() {
let data = to_bson(¤t_ratings)?;
collection.insert_one(doc! { "user_id": current_user, "scores": data}, None)?;
}
}
Ok(())
}
| 32.093458 | 94 | 0.553582 |
39c61dfb27ab50b57ac474239a62ecc6ce7119eb
| 21,108 |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::chained_bft::{
network::{NetworkReceivers, NetworkSender},
network_interface::{ConsensusMsg, ConsensusNetworkEvents, ConsensusNetworkSender},
test_utils::{self, consensus_runtime, placeholder_ledger_info, timed_block_on},
};
use channel::{self, libra_channel, message_queues::QueueStyle};
use consensus_types::{
block::{block_test_utils::certificate_for_genesis, Block},
common::{Author, Payload},
proposal_msg::ProposalMsg,
sync_info::SyncInfo,
vote::Vote,
vote_data::VoteData,
vote_msg::VoteMsg,
};
use futures::{channel::mpsc, SinkExt, StreamExt};
use libra_types::{block_info::BlockInfo, PeerId};
use network::{
peer_manager::{
conn_status_channel, ConnectionRequestSender, PeerManagerNotification, PeerManagerRequest,
PeerManagerRequestSender,
},
protocols::rpc::InboundRpcRequest,
ProtocolId,
};
use std::{
collections::{HashMap, HashSet},
num::NonZeroUsize,
sync::{Arc, Mutex, RwLock},
time::Duration,
};
use tokio::runtime::Handle;
/// `NetworkPlayground` mocks the network implementation and provides convenience
/// methods for testing. Test clients can use `wait_for_messages` or
/// `deliver_messages` to inspect the direct-send messages sent between peers.
/// They can also configure network messages to be dropped between specific peers.
///
/// Currently, RPC messages are delivered immediately and are not controlled by
/// `wait_for_messages` or `deliver_messages` for delivery. They are also not
/// currently dropped according to the `NetworkPlayground`'s drop config.
pub struct NetworkPlayground {
/// Maps each Author to a Sender of their inbound network notifications.
/// These events will usually be handled by the event loop spawned in
/// `ConsensusNetworkImpl`.
node_consensus_txs: Arc<
Mutex<
HashMap<Author, libra_channel::Sender<(PeerId, ProtocolId), PeerManagerNotification>>,
>,
>,
/// Nodes' outbound handlers forward their outbound non-rpc messages to this
/// queue.
outbound_msgs_tx: mpsc::Sender<(Author, PeerManagerRequest)>,
/// NetworkPlayground reads all nodes' outbound messages through this queue.
outbound_msgs_rx: mpsc::Receiver<(Author, PeerManagerRequest)>,
/// Allow test code to drop direct-send messages between peers.
drop_config: Arc<RwLock<DropConfig>>,
/// An executor for spawning node outbound network event handlers
executor: Handle,
}
impl NetworkPlayground {
pub fn new(executor: Handle) -> Self {
let (outbound_msgs_tx, outbound_msgs_rx) = mpsc::channel(1_024);
NetworkPlayground {
node_consensus_txs: Arc::new(Mutex::new(HashMap::new())),
outbound_msgs_tx,
outbound_msgs_rx,
drop_config: Arc::new(RwLock::new(DropConfig(HashMap::new()))),
executor,
}
}
/// Create a new async task that handles outbound messages sent by a node.
///
/// All non-rpc messages are forwarded to the NetworkPlayground's
/// `outbound_msgs_rx` queue, which controls delivery through the
/// `deliver_messages` and `wait_for_messages` API's.
///
/// Rpc messages are immediately sent to the destination for handling, so
/// they don't block.
async fn start_node_outbound_handler(
drop_config: Arc<RwLock<DropConfig>>,
src: Author,
mut network_reqs_rx: libra_channel::Receiver<(PeerId, ProtocolId), PeerManagerRequest>,
mut outbound_msgs_tx: mpsc::Sender<(Author, PeerManagerRequest)>,
node_consensus_txs: Arc<
Mutex<
HashMap<
Author,
libra_channel::Sender<(PeerId, ProtocolId), PeerManagerNotification>,
>,
>,
>,
) {
while let Some(net_req) = network_reqs_rx.next().await {
let drop_rpc = drop_config
.read()
.unwrap()
.is_message_dropped(&src, &net_req);
match net_req {
// Immediately forward rpc requests for handling. Unfortunately,
// we can't handle rpc requests in `deliver_messages` due to
// blocking issues, e.g., I want to write:
// ```
// let block = sender.request_block(peer_id, block_id).await.unwrap();
// playground.wait_for_messages(1).await;
// ```
// but because the rpc call blocks and depends on the message
// delivery, we'd have to spawn the sending behaviour on a
// separate task, which is inconvenient.
PeerManagerRequest::SendRpc(dst, outbound_req) => {
if drop_rpc {
continue;
}
let mut node_consensus_tx = node_consensus_txs
.lock()
.unwrap()
.get(&dst)
.unwrap()
.clone();
let inbound_req = InboundRpcRequest {
protocol: outbound_req.protocol,
data: outbound_req.data,
res_tx: outbound_req.res_tx,
};
node_consensus_tx
.push(
(src, ProtocolId::ConsensusRpc),
PeerManagerNotification::RecvRpc(src, inbound_req),
)
.unwrap();
}
// Other PeerManagerRequest get buffered for `deliver_messages` to
// synchronously drain.
net_req => {
let _ = outbound_msgs_tx.send((src, net_req)).await;
}
}
}
}
/// Add a new node to the NetworkPlayground.
pub fn add_node(
&mut self,
author: Author,
// The `Sender` of inbound network events. The `Receiver` end of this
// queue is usually wrapped in a `ConsensusNetworkEvents` adapter.
consensus_tx: libra_channel::Sender<(PeerId, ProtocolId), PeerManagerNotification>,
// The `Receiver` of outbound network events this node sends. The
// `Sender` side of this queue is usually wrapped in a
// `ConsensusNetworkSender` adapter.
network_reqs_rx: libra_channel::Receiver<(PeerId, ProtocolId), PeerManagerRequest>,
conn_mgr_reqs_rx: channel::Receiver<network::ConnectivityRequest>,
) {
self.node_consensus_txs
.lock()
.unwrap()
.insert(author, consensus_tx);
self.drop_config.write().unwrap().add_node(author);
let fut1 = NetworkPlayground::start_node_outbound_handler(
Arc::clone(&self.drop_config),
author,
network_reqs_rx,
self.outbound_msgs_tx.clone(),
self.node_consensus_txs.clone(),
);
let fut2 = conn_mgr_reqs_rx.map(Ok).forward(::futures::sink::drain());
self.executor.spawn(futures::future::join(fut1, fut2));
}
/// Deliver a `PeerManagerRequest` from peer `src` to the destination peer.
/// Returns a copy of the delivered message and the sending peer id.
async fn deliver_message<T: Payload>(
&mut self,
src: Author,
msg: PeerManagerRequest,
) -> (Author, ConsensusMsg<T>) {
// extract destination peer
let dst = match &msg {
PeerManagerRequest::SendMessage(dst, _) => *dst,
msg => panic!(
"[network playground] Unexpected PeerManagerRequest: {:?}",
msg
),
};
// get his sender
let mut node_consensus_tx = self
.node_consensus_txs
.lock()
.unwrap()
.get(&dst)
.unwrap()
.clone();
// convert PeerManagerRequest to corresponding PeerManagerNotification
let msg_notif = match msg {
PeerManagerRequest::SendMessage(_dst, msg) => {
PeerManagerNotification::RecvMessage(src, msg)
}
msg => panic!(
"[network playground] Unexpected PeerManagerRequest: {:?}",
msg
),
};
// copy message data
let msg_copy = match &msg_notif {
PeerManagerNotification::RecvMessage(src, msg) => {
let msg: ConsensusMsg<T> = lcs::from_bytes(&msg.mdata).unwrap();
(*src, msg)
}
msg_notif => panic!(
"[network playground] Unexpected PeerManagerNotification: {:?}",
msg_notif
),
};
node_consensus_tx
.push((src, ProtocolId::ConsensusDirectSend), msg_notif)
.unwrap();
msg_copy
}
/// Wait for exactly `num_messages` to be enqueued and delivered. Return a
/// copy of all messages for verification.
/// While all the sent messages are delivered, only the messages that satisfy the given
/// msg inspector are counted.
pub async fn wait_for_messages<T: Payload, F>(
&mut self,
num_messages: usize,
msg_inspector: F,
) -> Vec<(Author, ConsensusMsg<T>)>
where
F: Fn(&(Author, ConsensusMsg<T>)) -> bool,
{
let mut msg_copies = vec![];
while msg_copies.len() < num_messages {
// Take the next queued message
let (src, net_req) = self.outbound_msgs_rx.next().await
.expect("[network playground] waiting for messages, but message queue has shutdown unexpectedly");
// Deliver and copy message it if it's not dropped
if !self.is_message_dropped(&src, &net_req) {
let msg_copy = self.deliver_message(src, net_req).await;
if msg_inspector(&msg_copy) {
msg_copies.push(msg_copy);
}
}
}
assert_eq!(msg_copies.len(), num_messages);
msg_copies
}
/// Returns true for any message
pub fn take_all<T>(_msg_copy: &(Author, ConsensusMsg<T>)) -> bool {
true
}
/// Returns true for any message other than timeout
pub fn exclude_timeout_msg<T>(msg_copy: &(Author, ConsensusMsg<T>)) -> bool {
!Self::timeout_votes_only(msg_copy)
}
/// Returns true for proposal messages only.
pub fn proposals_only<T>(msg: &(Author, ConsensusMsg<T>)) -> bool {
matches!(&msg.1, ConsensusMsg::ProposalMsg(_))
}
/// Returns true for vote messages only.
pub fn votes_only<T>(msg: &(Author, ConsensusMsg<T>)) -> bool {
matches!(&msg.1, ConsensusMsg::VoteMsg(_))
}
/// Returns true for vote messages that carry round signatures only.
pub fn timeout_votes_only<T>(msg: &(Author, ConsensusMsg<T>)) -> bool {
matches!(
&msg.1,
// Timeout votes carry non-empty round signatures.
ConsensusMsg::VoteMsg(vote_msg) if vote_msg.vote().timeout_signature().is_some()
)
}
/// Returns true for sync info messages only.
pub fn sync_info_only<T>(msg: &(Author, ConsensusMsg<T>)) -> bool {
matches!(&msg.1, ConsensusMsg::SyncInfo(_))
}
pub fn epoch_change_only<T>(msg: &(Author, ConsensusMsg<T>)) -> bool {
matches!(&msg.1, ConsensusMsg::ValidatorChangeProof(_))
}
fn is_message_dropped(&self, src: &Author, net_req: &PeerManagerRequest) -> bool {
self.drop_config
.read()
.unwrap()
.is_message_dropped(src, net_req)
}
pub fn drop_message_for(&mut self, src: &Author, dst: Author) -> bool {
self.drop_config.write().unwrap().drop_message_for(src, dst)
}
pub fn stop_drop_message_for(&mut self, src: &Author, dst: &Author) -> bool {
self.drop_config
.write()
.unwrap()
.stop_drop_message_for(src, dst)
}
}
struct DropConfig(HashMap<Author, HashSet<Author>>);
impl DropConfig {
pub fn is_message_dropped(&self, src: &Author, net_req: &PeerManagerRequest) -> bool {
match net_req {
PeerManagerRequest::SendMessage(dst, _) => self.0.get(src).unwrap().contains(&dst),
PeerManagerRequest::SendRpc(dst, _) => self.0.get(src).unwrap().contains(&dst),
}
}
pub fn drop_message_for(&mut self, src: &Author, dst: Author) -> bool {
self.0.get_mut(src).unwrap().insert(dst)
}
pub fn stop_drop_message_for(&mut self, src: &Author, dst: &Author) -> bool {
self.0.get_mut(src).unwrap().remove(dst)
}
fn add_node(&mut self, src: Author) {
self.0.insert(src, HashSet::new());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chained_bft::{network::NetworkTask, test_utils::TestPayload};
use consensus_types::block_retrieval::{
BlockRetrievalRequest, BlockRetrievalResponse, BlockRetrievalStatus,
};
use libra_crypto::HashValue;
use libra_types::validator_verifier::random_validator_verifier;
#[test]
fn test_network_api() {
let mut runtime = consensus_runtime();
let num_nodes = 5;
let mut receivers: Vec<NetworkReceivers<TestPayload>> = Vec::new();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
let mut nodes = Vec::new();
let (signers, validator_verifier) = random_validator_verifier(num_nodes, None, false);
let peers: Vec<_> = signers.iter().map(|signer| signer.author()).collect();
let validators = Arc::new(validator_verifier);
for peer in &peers {
let (network_reqs_tx, network_reqs_rx) =
libra_channel::new(QueueStyle::FIFO, NonZeroUsize::new(8).unwrap(), None);
let (connection_reqs_tx, _) =
libra_channel::new(QueueStyle::FIFO, NonZeroUsize::new(8).unwrap(), None);
let (consensus_tx, consensus_rx) =
libra_channel::new(QueueStyle::FIFO, NonZeroUsize::new(8).unwrap(), None);
let (conn_mgr_reqs_tx, conn_mgr_reqs_rx) = channel::new_test(8);
let (_, conn_status_rx) = conn_status_channel::new();
let network_sender = ConsensusNetworkSender::new(
PeerManagerRequestSender::new(network_reqs_tx),
ConnectionRequestSender::new(connection_reqs_tx),
conn_mgr_reqs_tx,
);
let network_events = ConsensusNetworkEvents::new(consensus_rx, conn_status_rx);
playground.add_node(*peer, consensus_tx, network_reqs_rx, conn_mgr_reqs_rx);
let (self_sender, self_receiver) = channel::new_test(8);
let node =
NetworkSender::new(*peer, network_sender, self_sender, Arc::clone(&validators));
let (task, receiver) = NetworkTask::new(network_events, self_receiver);
receivers.push(receiver);
runtime.handle().spawn(task.start());
nodes.push(node);
}
let vote_msg = VoteMsg::new(
Vote::new(
VoteData::new(BlockInfo::random(1), BlockInfo::random(0)),
peers[0],
placeholder_ledger_info(),
&signers[0],
),
test_utils::placeholder_sync_info(),
);
let previous_qc = certificate_for_genesis();
let proposal = ProposalMsg::new(
Block::new_proposal(vec![0], 1, 1, previous_qc.clone(), &signers[0]),
SyncInfo::new(previous_qc.clone(), previous_qc, None),
);
timed_block_on(&mut runtime, async {
nodes[0]
.send_vote(vote_msg.clone(), peers[2..5].to_vec())
.await;
playground
.wait_for_messages(3, NetworkPlayground::take_all::<TestPayload>)
.await;
for r in receivers.iter_mut().take(5).skip(2) {
let (_, msg) = r.consensus_messages.next().await.unwrap();
match msg {
ConsensusMsg::VoteMsg(v) => assert_eq!(*v, vote_msg),
_ => panic!("unexpected messages"),
}
}
nodes[0].broadcast_proposal(proposal.clone()).await;
playground
.wait_for_messages(4, NetworkPlayground::take_all::<TestPayload>)
.await;
for r in receivers.iter_mut().take(num_nodes - 1) {
let (_, msg) = r.consensus_messages.next().await.unwrap();
match msg {
ConsensusMsg::ProposalMsg(p) => assert_eq!(*p, proposal),
_ => panic!("unexpected messages"),
}
}
});
}
#[test]
fn test_rpc() {
let mut runtime = consensus_runtime();
let num_nodes = 2;
let mut senders = Vec::new();
let mut receivers: Vec<NetworkReceivers<TestPayload>> = Vec::new();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
let mut nodes = Vec::new();
let (signers, validator_verifier) = random_validator_verifier(num_nodes, None, false);
let validators = Arc::new(validator_verifier);
let peers: Vec<_> = signers.iter().map(|signer| signer.author()).collect();
for peer in peers.iter() {
let (network_reqs_tx, network_reqs_rx) =
libra_channel::new(QueueStyle::FIFO, NonZeroUsize::new(8).unwrap(), None);
let (connection_reqs_tx, _) =
libra_channel::new(QueueStyle::FIFO, NonZeroUsize::new(8).unwrap(), None);
let (consensus_tx, consensus_rx) =
libra_channel::new(QueueStyle::FIFO, NonZeroUsize::new(8).unwrap(), None);
let (conn_mgr_reqs_tx, conn_mgr_reqs_rx) = channel::new_test(8);
let (_, conn_status_rx) = conn_status_channel::new();
let network_sender = ConsensusNetworkSender::new(
PeerManagerRequestSender::new(network_reqs_tx),
ConnectionRequestSender::new(connection_reqs_tx),
conn_mgr_reqs_tx,
);
let network_events = ConsensusNetworkEvents::new(consensus_rx, conn_status_rx);
playground.add_node(*peer, consensus_tx, network_reqs_rx, conn_mgr_reqs_rx);
let (self_sender, self_receiver) = channel::new_test(8);
let node = NetworkSender::<TestPayload>::new(
*peer,
network_sender.clone(),
self_sender,
Arc::clone(&validators),
);
let (task, receiver) = NetworkTask::new(network_events, self_receiver);
senders.push(network_sender);
receivers.push(receiver);
runtime.handle().spawn(task.start());
nodes.push(node);
}
let receiver_1 = receivers.remove(1);
let node0 = nodes[0].clone();
let peer1 = peers[1];
let vote_msg = VoteMsg::new(
Vote::new(
VoteData::new(BlockInfo::random(1), BlockInfo::random(0)),
peers[0],
placeholder_ledger_info(),
&signers[0],
),
test_utils::placeholder_sync_info(),
);
// verify request block rpc
let mut block_retrieval = receiver_1.block_retrieval;
let on_request_block = async move {
while let Some(request) = block_retrieval.next().await {
// make sure the network task is not blocked during RPC
// we limit the network notification queue size to 1 so if it's blocked,
// we can not process 2 votes and the test will timeout
node0.send_vote(vote_msg.clone(), vec![peer1]).await;
node0.send_vote(vote_msg.clone(), vec![peer1]).await;
playground
.wait_for_messages(2, NetworkPlayground::votes_only::<TestPayload>)
.await;
let response = BlockRetrievalResponse::<TestPayload>::new(
BlockRetrievalStatus::IdNotFound,
vec![],
);
let response = ConsensusMsg::BlockRetrievalResponse(Box::new(response));
let bytes = lcs::to_bytes(&response).unwrap();
request.response_sender.send(Ok(bytes.into())).unwrap();
}
};
runtime.handle().spawn(on_request_block);
let peer = peers[1];
timed_block_on(&mut runtime, async {
let response = nodes[0]
.request_block(
BlockRetrievalRequest::new(HashValue::zero(), 1),
peer,
Duration::from_secs(5),
)
.await
.unwrap();
assert_eq!(response.status(), BlockRetrievalStatus::IdNotFound);
});
}
}
| 40.592308 | 114 | 0.582291 |
9176c90ae9c0fd955d655d7f3a24413106fc344a
| 86,653 |
//! The core of the module-level name resolution algorithm.
//!
//! `DefCollector::collect` contains the fixed-point iteration loop which
//! resolves imports and expands macros.
use std::iter;
use base_db::{CrateId, Edition, FileId, ProcMacroId};
use cfg::{CfgExpr, CfgOptions};
use hir_expand::{
ast_id_map::FileAstId,
builtin_attr_macro::find_builtin_attr,
builtin_derive_macro::find_builtin_derive,
builtin_fn_macro::find_builtin_macro,
name::{name, AsName, Name},
proc_macro::ProcMacroExpander,
ExpandTo, HirFileId, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
};
use hir_expand::{InFile, MacroCallLoc};
use itertools::Itertools;
use la_arena::Idx;
use limit::Limit;
use rustc_hash::{FxHashMap, FxHashSet};
use syntax::ast;
use crate::{
attr::{Attr, AttrId, AttrInput, Attrs},
attr_macro_as_call_id,
db::DefDatabase,
derive_macro_as_call_id,
intern::Interned,
item_scope::{ImportType, PerNsGlobImports},
item_tree::{
self, Fields, FileItemTreeId, ImportKind, ItemTree, ItemTreeId, ItemTreeNode, MacroCall,
MacroDef, MacroRules, Mod, ModItem, ModKind, TreeId,
},
macro_call_as_call_id,
nameres::{
diagnostics::DefDiagnostic,
mod_resolution::ModDir,
path_resolution::ReachedFixedPoint,
proc_macro::{ProcMacroDef, ProcMacroKind},
BuiltinShadowMode, DefMap, ModuleData, ModuleOrigin, ResolveMode,
},
path::{ImportAlias, ModPath, PathKind},
per_ns::PerNs,
visibility::{RawVisibility, Visibility},
AdtId, AstId, AstIdWithPath, ConstLoc, EnumLoc, EnumVariantId, ExternBlockLoc, FunctionLoc,
ImplLoc, Intern, ItemContainerId, LocalModuleId, ModuleDefId, StaticLoc, StructLoc, TraitLoc,
TypeAliasLoc, UnionLoc, UnresolvedMacro,
};
static GLOB_RECURSION_LIMIT: Limit = Limit::new(100);
static EXPANSION_DEPTH_LIMIT: Limit = Limit::new(128);
static FIXED_POINT_LIMIT: Limit = Limit::new(8192);
pub(super) fn collect_defs(db: &dyn DefDatabase, mut def_map: DefMap, tree_id: TreeId) -> DefMap {
let crate_graph = db.crate_graph();
let mut deps = FxHashMap::default();
// populate external prelude and dependency list
for dep in &crate_graph[def_map.krate].dependencies {
tracing::debug!("crate dep {:?} -> {:?}", dep.name, dep.crate_id);
let dep_def_map = db.crate_def_map(dep.crate_id);
let dep_root = dep_def_map.module_id(dep_def_map.root);
deps.insert(dep.as_name(), dep_root.into());
if dep.is_prelude() && !tree_id.is_block() {
def_map.extern_prelude.insert(dep.as_name(), dep_root.into());
}
}
let cfg_options = &crate_graph[def_map.krate].cfg_options;
let proc_macros = &crate_graph[def_map.krate].proc_macro;
let proc_macros = proc_macros
.iter()
.enumerate()
.map(|(idx, it)| {
// FIXME: a hacky way to create a Name from string.
let name = tt::Ident { text: it.name.clone(), id: tt::TokenId::unspecified() };
(name.as_name(), ProcMacroExpander::new(def_map.krate, ProcMacroId(idx as u32)))
})
.collect();
let mut collector = DefCollector {
db,
def_map,
deps,
glob_imports: FxHashMap::default(),
unresolved_imports: Vec::new(),
resolved_imports: Vec::new(),
unresolved_macros: Vec::new(),
mod_dirs: FxHashMap::default(),
cfg_options,
proc_macros,
exports_proc_macros: false,
from_glob_import: Default::default(),
skip_attrs: Default::default(),
derive_helpers_in_scope: Default::default(),
};
if tree_id.is_block() {
collector.seed_with_inner(tree_id);
} else {
collector.seed_with_top_level();
}
collector.collect();
let mut def_map = collector.finish();
def_map.shrink_to_fit();
def_map
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum PartialResolvedImport {
/// None of any namespaces is resolved
Unresolved,
/// One of namespaces is resolved
Indeterminate(PerNs),
/// All namespaces are resolved, OR it comes from other crate
Resolved(PerNs),
}
impl PartialResolvedImport {
fn namespaces(self) -> PerNs {
match self {
PartialResolvedImport::Unresolved => PerNs::none(),
PartialResolvedImport::Indeterminate(ns) | PartialResolvedImport::Resolved(ns) => ns,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum ImportSource {
Import { id: ItemTreeId<item_tree::Import>, use_tree: Idx<ast::UseTree> },
ExternCrate(ItemTreeId<item_tree::ExternCrate>),
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct Import {
path: Interned<ModPath>,
alias: Option<ImportAlias>,
visibility: RawVisibility,
kind: ImportKind,
is_prelude: bool,
is_extern_crate: bool,
is_macro_use: bool,
source: ImportSource,
}
impl Import {
fn from_use(
db: &dyn DefDatabase,
krate: CrateId,
tree: &ItemTree,
id: ItemTreeId<item_tree::Import>,
) -> Vec<Self> {
let it = &tree[id.value];
let attrs = &tree.attrs(db, krate, ModItem::from(id.value).into());
let visibility = &tree[it.visibility];
let is_prelude = attrs.by_key("prelude_import").exists();
let mut res = Vec::new();
it.use_tree.expand(|idx, path, kind, alias| {
res.push(Self {
path: Interned::new(path), // FIXME this makes little sense
alias,
visibility: visibility.clone(),
kind,
is_prelude,
is_extern_crate: false,
is_macro_use: false,
source: ImportSource::Import { id, use_tree: idx },
});
});
res
}
fn from_extern_crate(
db: &dyn DefDatabase,
krate: CrateId,
tree: &ItemTree,
id: ItemTreeId<item_tree::ExternCrate>,
) -> Self {
let it = &tree[id.value];
let attrs = &tree.attrs(db, krate, ModItem::from(id.value).into());
let visibility = &tree[it.visibility];
Self {
path: Interned::new(ModPath::from_segments(
PathKind::Plain,
iter::once(it.name.clone()),
)),
alias: it.alias.clone(),
visibility: visibility.clone(),
kind: ImportKind::Plain,
is_prelude: false,
is_extern_crate: true,
is_macro_use: attrs.by_key("macro_use").exists(),
source: ImportSource::ExternCrate(id),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ImportDirective {
module_id: LocalModuleId,
import: Import,
status: PartialResolvedImport,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct MacroDirective {
module_id: LocalModuleId,
depth: usize,
kind: MacroDirectiveKind,
container: ItemContainerId,
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum MacroDirectiveKind {
FnLike { ast_id: AstIdWithPath<ast::MacroCall>, expand_to: ExpandTo },
Derive { ast_id: AstIdWithPath<ast::Adt>, derive_attr: AttrId, derive_pos: usize },
Attr { ast_id: AstIdWithPath<ast::Item>, attr: Attr, mod_item: ModItem, tree: TreeId },
}
/// Walks the tree of module recursively
struct DefCollector<'a> {
db: &'a dyn DefDatabase,
def_map: DefMap,
deps: FxHashMap<Name, ModuleDefId>,
glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility)>>,
unresolved_imports: Vec<ImportDirective>,
resolved_imports: Vec<ImportDirective>,
unresolved_macros: Vec<MacroDirective>,
mod_dirs: FxHashMap<LocalModuleId, ModDir>,
cfg_options: &'a CfgOptions,
/// List of procedural macros defined by this crate. This is read from the dynamic library
/// built by the build system, and is the list of proc. macros we can actually expand. It is
/// empty when proc. macro support is disabled (in which case we still do name resolution for
/// them).
proc_macros: Vec<(Name, ProcMacroExpander)>,
exports_proc_macros: bool,
from_glob_import: PerNsGlobImports,
/// If we fail to resolve an attribute on a `ModItem`, we fall back to ignoring the attribute.
/// This map is used to skip all attributes up to and including the one that failed to resolve,
/// in order to not expand them twice.
///
/// This also stores the attributes to skip when we resolve derive helpers and non-macro
/// non-builtin attributes in general.
skip_attrs: FxHashMap<InFile<ModItem>, AttrId>,
/// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
/// attributes.
derive_helpers_in_scope: FxHashMap<AstId<ast::Item>, Vec<Name>>,
}
impl DefCollector<'_> {
fn seed_with_top_level(&mut self) {
let _p = profile::span("seed_with_top_level");
let file_id = self.db.crate_graph()[self.def_map.krate].root_file_id;
let item_tree = self.db.file_item_tree(file_id.into());
let module_id = self.def_map.root;
let attrs = item_tree.top_level_attrs(self.db, self.def_map.krate);
if attrs.cfg().map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false)) {
self.inject_prelude(&attrs);
// Process other crate-level attributes.
for attr in &*attrs {
let attr_name = match attr.path.as_ident() {
Some(name) => name,
None => continue,
};
if *attr_name == hir_expand::name![recursion_limit] {
if let Some(input) = &attr.input {
if let AttrInput::Literal(limit) = &**input {
if let Ok(limit) = limit.parse() {
self.def_map.recursion_limit = Some(limit);
}
}
}
continue;
}
let attr_is_register_like = *attr_name == hir_expand::name![register_attr]
|| *attr_name == hir_expand::name![register_tool];
if !attr_is_register_like {
continue;
}
let registered_name = match attr.input.as_deref() {
Some(AttrInput::TokenTree(subtree, _)) => match &*subtree.token_trees {
[tt::TokenTree::Leaf(tt::Leaf::Ident(name))] => name.as_name(),
_ => continue,
},
_ => continue,
};
if *attr_name == hir_expand::name![register_attr] {
self.def_map.registered_attrs.push(registered_name.to_smol_str());
cov_mark::hit!(register_attr);
} else {
self.def_map.registered_tools.push(registered_name.to_smol_str());
cov_mark::hit!(register_tool);
}
}
ModCollector {
def_collector: self,
macro_depth: 0,
module_id,
tree_id: TreeId::new(file_id.into(), None),
item_tree: &item_tree,
mod_dir: ModDir::root(),
}
.collect_in_top_module(item_tree.top_level_items());
}
}
fn seed_with_inner(&mut self, tree_id: TreeId) {
let item_tree = tree_id.item_tree(self.db);
let module_id = self.def_map.root;
let is_cfg_enabled = item_tree
.top_level_attrs(self.db, self.def_map.krate)
.cfg()
.map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false));
if is_cfg_enabled {
ModCollector {
def_collector: self,
macro_depth: 0,
module_id,
tree_id,
item_tree: &item_tree,
mod_dir: ModDir::root(),
}
.collect_in_top_module(item_tree.top_level_items());
}
}
fn resolution_loop(&mut self) {
let _p = profile::span("DefCollector::resolution_loop");
// main name resolution fixed-point loop.
let mut i = 0;
'outer: loop {
loop {
self.db.unwind_if_cancelled();
{
let _p = profile::span("resolve_imports loop");
loop {
if self.resolve_imports() == ReachedFixedPoint::Yes {
break;
}
}
}
if self.resolve_macros() == ReachedFixedPoint::Yes {
break;
}
i += 1;
if FIXED_POINT_LIMIT.check(i).is_err() {
tracing::error!("name resolution is stuck");
break 'outer;
}
}
if self.reseed_with_unresolved_attribute() == ReachedFixedPoint::Yes {
break;
}
}
}
fn collect(&mut self) {
let _p = profile::span("DefCollector::collect");
self.resolution_loop();
// Resolve all indeterminate resolved imports again
// As some of the macros will expand newly import shadowing partial resolved imports
// FIXME: We maybe could skip this, if we handle the indeterminate imports in `resolve_imports`
// correctly
let partial_resolved = self.resolved_imports.iter().filter_map(|directive| {
if let PartialResolvedImport::Indeterminate(_) = directive.status {
let mut directive = directive.clone();
directive.status = PartialResolvedImport::Unresolved;
Some(directive)
} else {
None
}
});
self.unresolved_imports.extend(partial_resolved);
self.resolve_imports();
let unresolved_imports = std::mem::take(&mut self.unresolved_imports);
// show unresolved imports in completion, etc
for directive in &unresolved_imports {
self.record_resolved_import(directive)
}
self.unresolved_imports = unresolved_imports;
// FIXME: This condition should instead check if this is a `proc-macro` type crate.
if self.exports_proc_macros {
// A crate exporting procedural macros is not allowed to export anything else.
//
// Additionally, while the proc macro entry points must be `pub`, they are not publicly
// exported in type/value namespace. This function reduces the visibility of all items
// in the crate root that aren't proc macros.
let root = self.def_map.root;
let module_id = self.def_map.module_id(root);
let root = &mut self.def_map.modules[root];
root.scope.censor_non_proc_macros(module_id);
}
}
/// When the fixed-point loop reaches a stable state, we might still have some unresolved
/// attributes (or unexpanded attribute proc macros) left over. This takes one of them, and
/// feeds the item it's applied to back into name resolution.
///
/// This effectively ignores the fact that the macro is there and just treats the items as
/// normal code.
///
/// This improves UX when proc macros are turned off or don't work, and replicates the behavior
/// before we supported proc. attribute macros.
fn reseed_with_unresolved_attribute(&mut self) -> ReachedFixedPoint {
cov_mark::hit!(unresolved_attribute_fallback);
let mut unresolved_macros = std::mem::take(&mut self.unresolved_macros);
let pos = unresolved_macros.iter().position(|directive| {
if let MacroDirectiveKind::Attr { ast_id, mod_item, attr, tree } = &directive.kind {
self.skip_attrs.insert(ast_id.ast_id.with_value(*mod_item), attr.id);
let item_tree = tree.item_tree(self.db);
let mod_dir = self.mod_dirs[&directive.module_id].clone();
ModCollector {
def_collector: self,
macro_depth: directive.depth,
module_id: directive.module_id,
tree_id: *tree,
item_tree: &item_tree,
mod_dir,
}
.collect(&[*mod_item], directive.container);
true
} else {
false
}
});
if let Some(pos) = pos {
unresolved_macros.remove(pos);
}
// The collection above might add new unresolved macros (eg. derives), so merge the lists.
self.unresolved_macros.extend(unresolved_macros);
if pos.is_some() {
// Continue name resolution with the new data.
ReachedFixedPoint::No
} else {
ReachedFixedPoint::Yes
}
}
fn inject_prelude(&mut self, crate_attrs: &Attrs) {
// See compiler/rustc_builtin_macros/src/standard_library_imports.rs
if crate_attrs.by_key("no_core").exists() {
// libcore does not get a prelude.
return;
}
let krate = if crate_attrs.by_key("no_std").exists() {
name![core]
} else {
let std = name![std];
if self.def_map.extern_prelude().any(|(name, _)| *name == std) {
std
} else {
// If `std` does not exist for some reason, fall back to core. This mostly helps
// keep r-a's own tests minimal.
name![core]
}
};
let edition = match self.def_map.edition {
Edition::Edition2015 => name![rust_2015],
Edition::Edition2018 => name![rust_2018],
Edition::Edition2021 => name![rust_2021],
};
let path_kind = if self.def_map.edition == Edition::Edition2015 {
PathKind::Plain
} else {
PathKind::Abs
};
let path = ModPath::from_segments(
path_kind.clone(),
[krate.clone(), name![prelude], edition].into_iter(),
);
// Fall back to the older `std::prelude::v1` for compatibility with Rust <1.52.0
// FIXME remove this fallback
let fallback_path =
ModPath::from_segments(path_kind, [krate, name![prelude], name![v1]].into_iter());
for path in &[path, fallback_path] {
let (per_ns, _) = self.def_map.resolve_path(
self.db,
self.def_map.root,
path,
BuiltinShadowMode::Other,
);
match per_ns.types {
Some((ModuleDefId::ModuleId(m), _)) => {
self.def_map.prelude = Some(m);
return;
}
types => {
tracing::debug!(
"could not resolve prelude path `{}` to module (resolved to {:?})",
path,
types
);
}
}
}
}
/// Adds a definition of procedural macro `name` to the root module.
///
/// # Notes on procedural macro resolution
///
/// Procedural macro functionality is provided by the build system: It has to build the proc
/// macro and pass the resulting dynamic library to rust-analyzer.
///
/// When procedural macro support is enabled, the list of proc macros exported by a crate is
/// known before we resolve names in the crate. This list is stored in `self.proc_macros` and is
/// derived from the dynamic library.
///
/// However, we *also* would like to be able to at least *resolve* macros on our own, without
/// help by the build system. So, when the macro isn't found in `self.proc_macros`, we instead
/// use a dummy expander that always errors. This comes with the drawback of macros potentially
/// going out of sync with what the build system sees (since we resolve using VFS state, but
/// Cargo builds only on-disk files). We could and probably should add diagnostics for that.
fn export_proc_macro(&mut self, def: ProcMacroDef, ast_id: AstId<ast::Fn>) {
let kind = def.kind.to_basedb_kind();
self.exports_proc_macros = true;
let macro_def = match self.proc_macros.iter().find(|(n, _)| n == &def.name) {
Some(&(_, expander)) => MacroDefId {
krate: self.def_map.krate,
kind: MacroDefKind::ProcMacro(expander, kind, ast_id),
local_inner: false,
},
None => MacroDefId {
krate: self.def_map.krate,
kind: MacroDefKind::ProcMacro(
ProcMacroExpander::dummy(self.def_map.krate),
kind,
ast_id,
),
local_inner: false,
},
};
self.define_proc_macro(def.name.clone(), macro_def);
self.def_map.exported_proc_macros.insert(macro_def, def);
}
/// Define a macro with `macro_rules`.
///
/// It will define the macro in legacy textual scope, and if it has `#[macro_export]`,
/// then it is also defined in the root module scope.
/// You can `use` or invoke it by `crate::macro_name` anywhere, before or after the definition.
///
/// It is surprising that the macro will never be in the current module scope.
/// These code fails with "unresolved import/macro",
/// ```rust,compile_fail
/// mod m { macro_rules! foo { () => {} } }
/// use m::foo as bar;
/// ```
///
/// ```rust,compile_fail
/// macro_rules! foo { () => {} }
/// self::foo!();
/// crate::foo!();
/// ```
///
/// Well, this code compiles, because the plain path `foo` in `use` is searched
/// in the legacy textual scope only.
/// ```rust
/// macro_rules! foo { () => {} }
/// use foo as bar;
/// ```
fn define_macro_rules(
&mut self,
module_id: LocalModuleId,
name: Name,
macro_: MacroDefId,
export: bool,
) {
// Textual scoping
self.define_legacy_macro(module_id, name.clone(), macro_);
self.def_map.modules[module_id].scope.declare_macro(macro_);
// Module scoping
// In Rust, `#[macro_export]` macros are unconditionally visible at the
// crate root, even if the parent modules is **not** visible.
if export {
self.update(
self.def_map.root,
&[(Some(name), PerNs::macros(macro_, Visibility::Public))],
Visibility::Public,
ImportType::Named,
);
}
}
/// Define a legacy textual scoped macro in module
///
/// We use a map `legacy_macros` to store all legacy textual scoped macros visible per module.
/// It will clone all macros from parent legacy scope, whose definition is prior to
/// the definition of current module.
/// And also, `macro_use` on a module will import all legacy macros visible inside to
/// current legacy scope, with possible shadowing.
fn define_legacy_macro(&mut self, module_id: LocalModuleId, name: Name, mac: MacroDefId) {
// Always shadowing
self.def_map.modules[module_id].scope.define_legacy_macro(name, mac);
}
/// Define a macro 2.0 macro
///
/// The scoped of macro 2.0 macro is equal to normal function
fn define_macro_def(
&mut self,
module_id: LocalModuleId,
name: Name,
macro_: MacroDefId,
vis: &RawVisibility,
) {
let vis =
self.def_map.resolve_visibility(self.db, module_id, vis).unwrap_or(Visibility::Public);
self.def_map.modules[module_id].scope.declare_macro(macro_);
self.update(module_id, &[(Some(name), PerNs::macros(macro_, vis))], vis, ImportType::Named);
}
/// Define a proc macro
///
/// A proc macro is similar to normal macro scope, but it would not visible in legacy textual scoped.
/// And unconditionally exported.
fn define_proc_macro(&mut self, name: Name, macro_: MacroDefId) {
self.def_map.modules[self.def_map.root].scope.declare_macro(macro_);
self.update(
self.def_map.root,
&[(Some(name), PerNs::macros(macro_, Visibility::Public))],
Visibility::Public,
ImportType::Named,
);
}
/// Import macros from `#[macro_use] extern crate`.
fn import_macros_from_extern_crate(
&mut self,
current_module_id: LocalModuleId,
extern_crate: &item_tree::ExternCrate,
) {
tracing::debug!(
"importing macros from extern crate: {:?} ({:?})",
extern_crate,
self.def_map.edition,
);
let res = self.resolve_extern_crate(&extern_crate.name);
if let Some(ModuleDefId::ModuleId(m)) = res.take_types() {
if m == self.def_map.module_id(current_module_id) {
cov_mark::hit!(ignore_macro_use_extern_crate_self);
return;
}
cov_mark::hit!(macro_rules_from_other_crates_are_visible_with_macro_use);
self.import_all_macros_exported(current_module_id, m.krate);
}
}
/// Import all exported macros from another crate
///
/// Exported macros are just all macros in the root module scope.
/// Note that it contains not only all `#[macro_export]` macros, but also all aliases
/// created by `use` in the root module, ignoring the visibility of `use`.
fn import_all_macros_exported(&mut self, current_module_id: LocalModuleId, krate: CrateId) {
let def_map = self.db.crate_def_map(krate);
for (name, def) in def_map[def_map.root].scope.macros() {
// `macro_use` only bring things into legacy scope.
self.define_legacy_macro(current_module_id, name.clone(), def);
}
}
/// Tries to resolve every currently unresolved import.
fn resolve_imports(&mut self) -> ReachedFixedPoint {
let mut res = ReachedFixedPoint::Yes;
let imports = std::mem::take(&mut self.unresolved_imports);
let imports = imports
.into_iter()
.filter_map(|mut directive| {
directive.status = self.resolve_import(directive.module_id, &directive.import);
match directive.status {
PartialResolvedImport::Indeterminate(_) => {
self.record_resolved_import(&directive);
// FIXME: For avoid performance regression,
// we consider an imported resolved if it is indeterminate (i.e not all namespace resolved)
self.resolved_imports.push(directive);
res = ReachedFixedPoint::No;
None
}
PartialResolvedImport::Resolved(_) => {
self.record_resolved_import(&directive);
self.resolved_imports.push(directive);
res = ReachedFixedPoint::No;
None
}
PartialResolvedImport::Unresolved => Some(directive),
}
})
.collect();
self.unresolved_imports = imports;
res
}
fn resolve_import(&self, module_id: LocalModuleId, import: &Import) -> PartialResolvedImport {
let _p = profile::span("resolve_import").detail(|| format!("{}", import.path));
tracing::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
if import.is_extern_crate {
let name = import
.path
.as_ident()
.expect("extern crate should have been desugared to one-element path");
let res = self.resolve_extern_crate(name);
if res.is_none() {
PartialResolvedImport::Unresolved
} else {
PartialResolvedImport::Resolved(res)
}
} else {
let res = self.def_map.resolve_path_fp_with_macro(
self.db,
ResolveMode::Import,
module_id,
&import.path,
BuiltinShadowMode::Module,
);
let def = res.resolved_def;
if res.reached_fixedpoint == ReachedFixedPoint::No || def.is_none() {
return PartialResolvedImport::Unresolved;
}
if let Some(krate) = res.krate {
if krate != self.def_map.krate {
return PartialResolvedImport::Resolved(
def.filter_visibility(|v| matches!(v, Visibility::Public)),
);
}
}
// Check whether all namespace is resolved
if def.take_types().is_some()
&& def.take_values().is_some()
&& def.take_macros().is_some()
{
PartialResolvedImport::Resolved(def)
} else {
PartialResolvedImport::Indeterminate(def)
}
}
}
fn resolve_extern_crate(&self, name: &Name) -> PerNs {
if *name == name!(self) {
cov_mark::hit!(extern_crate_self_as);
let root = match self.def_map.block {
Some(_) => {
let def_map = self.def_map.crate_root(self.db).def_map(self.db);
def_map.module_id(def_map.root())
}
None => self.def_map.module_id(self.def_map.root()),
};
PerNs::types(root.into(), Visibility::Public)
} else {
self.deps.get(name).map_or(PerNs::none(), |&it| PerNs::types(it, Visibility::Public))
}
}
fn record_resolved_import(&mut self, directive: &ImportDirective) {
let _p = profile::span("record_resolved_import");
let module_id = directive.module_id;
let import = &directive.import;
let mut def = directive.status.namespaces();
let vis = self
.def_map
.resolve_visibility(self.db, module_id, &directive.import.visibility)
.unwrap_or(Visibility::Public);
match import.kind {
ImportKind::Plain | ImportKind::TypeOnly => {
let name = match &import.alias {
Some(ImportAlias::Alias(name)) => Some(name),
Some(ImportAlias::Underscore) => None,
None => match import.path.segments().last() {
Some(last_segment) => Some(last_segment),
None => {
cov_mark::hit!(bogus_paths);
return;
}
},
};
if import.kind == ImportKind::TypeOnly {
def.values = None;
def.macros = None;
}
tracing::debug!("resolved import {:?} ({:?}) to {:?}", name, import, def);
// extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658
if import.is_extern_crate && module_id == self.def_map.root {
if let (Some(def), Some(name)) = (def.take_types(), name) {
self.def_map.extern_prelude.insert(name.clone(), def);
}
}
self.update(module_id, &[(name.cloned(), def)], vis, ImportType::Named);
}
ImportKind::Glob => {
tracing::debug!("glob import: {:?}", import);
match def.take_types() {
Some(ModuleDefId::ModuleId(m)) => {
if import.is_prelude {
// Note: This dodgily overrides the injected prelude. The rustc
// implementation seems to work the same though.
cov_mark::hit!(std_prelude);
self.def_map.prelude = Some(m);
} else if m.krate != self.def_map.krate {
cov_mark::hit!(glob_across_crates);
// glob import from other crate => we can just import everything once
let item_map = m.def_map(self.db);
let scope = &item_map[m.local_id].scope;
// Module scoped macros is included
let items = scope
.resolutions()
// only keep visible names...
.map(|(n, res)| {
(n, res.filter_visibility(|v| v.is_visible_from_other_crate()))
})
.filter(|(_, res)| !res.is_none())
.collect::<Vec<_>>();
self.update(module_id, &items, vis, ImportType::Glob);
} else {
// glob import from same crate => we do an initial
// import, and then need to propagate any further
// additions
let def_map;
let scope = if m.block == self.def_map.block_id() {
&self.def_map[m.local_id].scope
} else {
def_map = m.def_map(self.db);
&def_map[m.local_id].scope
};
// Module scoped macros is included
let items = scope
.resolutions()
// only keep visible names...
.map(|(n, res)| {
(
n,
res.filter_visibility(|v| {
v.is_visible_from_def_map(
self.db,
&self.def_map,
module_id,
)
}),
)
})
.filter(|(_, res)| !res.is_none())
.collect::<Vec<_>>();
self.update(module_id, &items, vis, ImportType::Glob);
// record the glob import in case we add further items
let glob = self.glob_imports.entry(m.local_id).or_default();
if !glob.iter().any(|(mid, _)| *mid == module_id) {
glob.push((module_id, vis));
}
}
}
Some(ModuleDefId::AdtId(AdtId::EnumId(e))) => {
cov_mark::hit!(glob_enum);
// glob import from enum => just import all the variants
// XXX: urgh, so this works by accident! Here, we look at
// the enum data, and, in theory, this might require us to
// look back at the crate_def_map, creating a cycle. For
// example, `enum E { crate::some_macro!(); }`. Luckily, the
// only kind of macro that is allowed inside enum is a
// `cfg_macro`, and we don't need to run name resolution for
// it, but this is sheer luck!
let enum_data = self.db.enum_data(e);
let resolutions = enum_data
.variants
.iter()
.map(|(local_id, variant_data)| {
let name = variant_data.name.clone();
let variant = EnumVariantId { parent: e, local_id };
let res = PerNs::both(variant.into(), variant.into(), vis);
(Some(name), res)
})
.collect::<Vec<_>>();
self.update(module_id, &resolutions, vis, ImportType::Glob);
}
Some(d) => {
tracing::debug!("glob import {:?} from non-module/enum {:?}", import, d);
}
None => {
tracing::debug!("glob import {:?} didn't resolve as type", import);
}
}
}
}
}
fn update(
&mut self,
module_id: LocalModuleId,
resolutions: &[(Option<Name>, PerNs)],
vis: Visibility,
import_type: ImportType,
) {
self.db.unwind_if_cancelled();
self.update_recursive(module_id, resolutions, vis, import_type, 0)
}
fn update_recursive(
&mut self,
module_id: LocalModuleId,
resolutions: &[(Option<Name>, PerNs)],
// All resolutions are imported with this visibility; the visibilities in
// the `PerNs` values are ignored and overwritten
vis: Visibility,
import_type: ImportType,
depth: usize,
) {
if GLOB_RECURSION_LIMIT.check(depth).is_err() {
// prevent stack overflows (but this shouldn't be possible)
panic!("infinite recursion in glob imports!");
}
let mut changed = false;
for (name, res) in resolutions {
match name {
Some(name) => {
let scope = &mut self.def_map.modules[module_id].scope;
changed |= scope.push_res_with_import(
&mut self.from_glob_import,
(module_id, name.clone()),
res.with_visibility(vis),
import_type,
);
}
None => {
let tr = match res.take_types() {
Some(ModuleDefId::TraitId(tr)) => tr,
Some(other) => {
tracing::debug!("non-trait `_` import of {:?}", other);
continue;
}
None => continue,
};
let old_vis = self.def_map.modules[module_id].scope.unnamed_trait_vis(tr);
let should_update = match old_vis {
None => true,
Some(old_vis) => {
let max_vis = old_vis.max(vis, &self.def_map).unwrap_or_else(|| {
panic!("`Tr as _` imports with unrelated visibilities {:?} and {:?} (trait {:?})", old_vis, vis, tr);
});
if max_vis == old_vis {
false
} else {
cov_mark::hit!(upgrade_underscore_visibility);
true
}
}
};
if should_update {
changed = true;
self.def_map.modules[module_id].scope.push_unnamed_trait(tr, vis);
}
}
}
}
if !changed {
return;
}
let glob_imports = self
.glob_imports
.get(&module_id)
.into_iter()
.flat_map(|v| v.iter())
.filter(|(glob_importing_module, _)| {
// we know all resolutions have the same visibility (`vis`), so we
// just need to check that once
vis.is_visible_from_def_map(self.db, &self.def_map, *glob_importing_module)
})
.cloned()
.collect::<Vec<_>>();
for (glob_importing_module, glob_import_vis) in glob_imports {
self.update_recursive(
glob_importing_module,
resolutions,
glob_import_vis,
ImportType::Glob,
depth + 1,
);
}
}
fn resolve_macros(&mut self) -> ReachedFixedPoint {
let mut macros = std::mem::take(&mut self.unresolved_macros);
let mut resolved = Vec::new();
let mut push_resolved = |directive: &MacroDirective, call_id| {
resolved.push((directive.module_id, directive.depth, directive.container, call_id));
};
let mut res = ReachedFixedPoint::Yes;
macros.retain(|directive| {
let resolver = |path| {
let resolved_res = self.def_map.resolve_path_fp_with_macro(
self.db,
ResolveMode::Other,
directive.module_id,
&path,
BuiltinShadowMode::Module,
);
resolved_res.resolved_def.take_macros()
};
match &directive.kind {
MacroDirectiveKind::FnLike { ast_id, expand_to } => {
let call_id = macro_call_as_call_id(
self.db,
ast_id,
*expand_to,
self.def_map.krate,
&resolver,
&mut |_err| (),
);
if let Ok(Ok(call_id)) = call_id {
push_resolved(directive, call_id);
res = ReachedFixedPoint::No;
return false;
}
}
MacroDirectiveKind::Derive { ast_id, derive_attr, derive_pos } => {
let call_id = derive_macro_as_call_id(
self.db,
ast_id,
*derive_attr,
*derive_pos as u32,
self.def_map.krate,
&resolver,
);
if let Ok(call_id) = call_id {
self.def_map.modules[directive.module_id].scope.set_derive_macro_invoc(
ast_id.ast_id,
call_id,
*derive_attr,
*derive_pos,
);
push_resolved(directive, call_id);
res = ReachedFixedPoint::No;
return false;
}
}
MacroDirectiveKind::Attr { ast_id: file_ast_id, mod_item, attr, tree } => {
let &AstIdWithPath { ast_id, ref path } = file_ast_id;
let file_id = ast_id.file_id;
let mut recollect_without = |collector: &mut Self| {
// Remove the original directive since we resolved it.
let mod_dir = collector.mod_dirs[&directive.module_id].clone();
collector.skip_attrs.insert(InFile::new(file_id, *mod_item), attr.id);
let item_tree = tree.item_tree(self.db);
ModCollector {
def_collector: collector,
macro_depth: directive.depth,
module_id: directive.module_id,
tree_id: *tree,
item_tree: &item_tree,
mod_dir,
}
.collect(&[*mod_item], directive.container);
res = ReachedFixedPoint::No;
false
};
if let Some(ident) = path.as_ident() {
if let Some(helpers) = self.derive_helpers_in_scope.get(&ast_id) {
if helpers.contains(ident) {
cov_mark::hit!(resolved_derive_helper);
// Resolved to derive helper. Collect the item's attributes again,
// starting after the derive helper.
return recollect_without(self);
}
}
}
let def = match resolver(path.clone()) {
Some(def) if def.is_attribute() => def,
_ => return true,
};
if matches!(
def,
MacroDefId { kind:MacroDefKind::BuiltInAttr(expander, _),.. }
if expander.is_derive()
) {
// Resolved to `#[derive]`
let item_tree = tree.item_tree(self.db);
let ast_adt_id: FileAstId<ast::Adt> = match *mod_item {
ModItem::Struct(strukt) => item_tree[strukt].ast_id().upcast(),
ModItem::Union(union) => item_tree[union].ast_id().upcast(),
ModItem::Enum(enum_) => item_tree[enum_].ast_id().upcast(),
_ => {
let diag = DefDiagnostic::invalid_derive_target(
directive.module_id,
ast_id,
attr.id,
);
self.def_map.diagnostics.push(diag);
return recollect_without(self);
}
};
let ast_id = ast_id.with_value(ast_adt_id);
match attr.parse_path_comma_token_tree() {
Some(derive_macros) => {
let mut len = 0;
for (idx, path) in derive_macros.enumerate() {
let ast_id = AstIdWithPath::new(file_id, ast_id.value, path);
self.unresolved_macros.push(MacroDirective {
module_id: directive.module_id,
depth: directive.depth + 1,
kind: MacroDirectiveKind::Derive {
ast_id,
derive_attr: attr.id,
derive_pos: idx,
},
container: directive.container,
});
len = idx;
}
// We treat the #[derive] macro as an attribute call, but we do not resolve it for nameres collection.
// This is just a trick to be able to resolve the input to derives as proper paths.
// Check the comment in [`builtin_attr_macro`].
let call_id = attr_macro_as_call_id(
self.db,
file_ast_id,
attr,
self.def_map.krate,
def,
true,
);
self.def_map.modules[directive.module_id]
.scope
.init_derive_attribute(ast_id, attr.id, call_id, len + 1);
}
None => {
let diag = DefDiagnostic::malformed_derive(
directive.module_id,
ast_id,
attr.id,
);
self.def_map.diagnostics.push(diag);
}
}
return recollect_without(self);
}
if !self.db.enable_proc_attr_macros() {
return true;
}
// Not resolved to a derive helper or the derive attribute, so try to treat as a normal attribute.
let call_id = attr_macro_as_call_id(
self.db,
file_ast_id,
attr,
self.def_map.krate,
def,
false,
);
let loc: MacroCallLoc = self.db.lookup_intern_macro_call(call_id);
// Skip #[test]/#[bench] expansion, which would merely result in more memory usage
// due to duplicating functions into macro expansions
if matches!(
loc.def.kind,
MacroDefKind::BuiltInAttr(expander, _)
if expander.is_test() || expander.is_bench()
) {
return recollect_without(self);
}
if let MacroDefKind::ProcMacro(exp, ..) = loc.def.kind {
if exp.is_dummy() {
// Proc macros that cannot be expanded are treated as not
// resolved, in order to fall back later.
self.def_map.diagnostics.push(DefDiagnostic::unresolved_proc_macro(
directive.module_id,
loc.kind,
));
return recollect_without(self);
}
}
self.def_map.modules[directive.module_id]
.scope
.add_attr_macro_invoc(ast_id, call_id);
push_resolved(directive, call_id);
res = ReachedFixedPoint::No;
return false;
}
}
true
});
// Attribute resolution can add unresolved macro invocations, so concatenate the lists.
self.unresolved_macros.extend(macros);
for (module_id, depth, container, macro_call_id) in resolved {
self.collect_macro_expansion(module_id, macro_call_id, depth, container);
}
res
}
fn collect_macro_expansion(
&mut self,
module_id: LocalModuleId,
macro_call_id: MacroCallId,
depth: usize,
container: ItemContainerId,
) {
if EXPANSION_DEPTH_LIMIT.check(depth).is_err() {
cov_mark::hit!(macro_expansion_overflow);
tracing::warn!("macro expansion is too deep");
return;
}
let file_id = macro_call_id.as_file();
// First, fetch the raw expansion result for purposes of error reporting. This goes through
// `macro_expand_error` to avoid depending on the full expansion result (to improve
// incrementality).
let loc: MacroCallLoc = self.db.lookup_intern_macro_call(macro_call_id);
let err = self.db.macro_expand_error(macro_call_id);
if let Some(err) = err {
let diag = match err {
hir_expand::ExpandError::UnresolvedProcMacro => {
// Missing proc macros are non-fatal, so they are handled specially.
DefDiagnostic::unresolved_proc_macro(module_id, loc.kind.clone())
}
_ => DefDiagnostic::macro_error(module_id, loc.kind.clone(), err.to_string()),
};
self.def_map.diagnostics.push(diag);
}
// If we've just resolved a derive, record its helper attributes.
if let MacroCallKind::Derive { ast_id, .. } = &loc.kind {
if loc.def.krate != self.def_map.krate {
let def_map = self.db.crate_def_map(loc.def.krate);
if let Some(def) = def_map.exported_proc_macros.get(&loc.def) {
if let ProcMacroKind::CustomDerive { helpers } = &def.kind {
self.derive_helpers_in_scope
.entry(ast_id.map(|it| it.upcast()))
.or_default()
.extend(helpers.iter().cloned());
}
}
}
}
// Then, fetch and process the item tree. This will reuse the expansion result from above.
let item_tree = self.db.file_item_tree(file_id);
let mod_dir = self.mod_dirs[&module_id].clone();
ModCollector {
def_collector: &mut *self,
macro_depth: depth,
tree_id: TreeId::new(file_id, None),
module_id,
item_tree: &item_tree,
mod_dir,
}
.collect(item_tree.top_level_items(), container);
}
fn finish(mut self) -> DefMap {
// Emit diagnostics for all remaining unexpanded macros.
let _p = profile::span("DefCollector::finish");
for directive in &self.unresolved_macros {
match &directive.kind {
MacroDirectiveKind::FnLike { ast_id, expand_to } => {
let macro_call_as_call_id = macro_call_as_call_id(
self.db,
ast_id,
*expand_to,
self.def_map.krate,
|path| {
let resolved_res = self.def_map.resolve_path_fp_with_macro(
self.db,
ResolveMode::Other,
directive.module_id,
&path,
BuiltinShadowMode::Module,
);
resolved_res.resolved_def.take_macros()
},
&mut |_| (),
);
if let Err(UnresolvedMacro { path }) = macro_call_as_call_id {
self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call(
directive.module_id,
ast_id.ast_id,
path,
));
}
}
MacroDirectiveKind::Derive { .. } | MacroDirectiveKind::Attr { .. } => {
// FIXME: we might want to diagnose this too
}
}
}
// Emit diagnostics for all remaining unresolved imports.
// We'd like to avoid emitting a diagnostics avalanche when some `extern crate` doesn't
// resolve. We first emit diagnostics for unresolved extern crates and collect the missing
// crate names. Then we emit diagnostics for unresolved imports, but only if the import
// doesn't start with an unresolved crate's name. Due to renaming and reexports, this is a
// heuristic, but it works in practice.
let mut diagnosed_extern_crates = FxHashSet::default();
for directive in &self.unresolved_imports {
if let ImportSource::ExternCrate(krate) = directive.import.source {
let item_tree = krate.item_tree(self.db);
let extern_crate = &item_tree[krate.value];
diagnosed_extern_crates.insert(extern_crate.name.clone());
self.def_map.diagnostics.push(DefDiagnostic::unresolved_extern_crate(
directive.module_id,
InFile::new(krate.file_id(), extern_crate.ast_id),
));
}
}
for directive in &self.unresolved_imports {
if let ImportSource::Import { id: import, use_tree } = directive.import.source {
if matches!(
(directive.import.path.segments().first(), &directive.import.path.kind),
(Some(krate), PathKind::Plain | PathKind::Abs) if diagnosed_extern_crates.contains(krate)
) {
continue;
}
self.def_map.diagnostics.push(DefDiagnostic::unresolved_import(
directive.module_id,
import,
use_tree,
));
}
}
self.def_map
}
}
/// Walks a single module, populating defs, imports and macros
struct ModCollector<'a, 'b> {
def_collector: &'a mut DefCollector<'b>,
macro_depth: usize,
module_id: LocalModuleId,
tree_id: TreeId,
item_tree: &'a ItemTree,
mod_dir: ModDir,
}
impl ModCollector<'_, '_> {
fn collect_in_top_module(&mut self, items: &[ModItem]) {
let module = self.def_collector.def_map.module_id(self.module_id);
self.collect(items, module.into())
}
fn collect(&mut self, items: &[ModItem], container: ItemContainerId) {
let krate = self.def_collector.def_map.krate;
// Note: don't assert that inserted value is fresh: it's simply not true
// for macros.
self.def_collector.mod_dirs.insert(self.module_id, self.mod_dir.clone());
// Prelude module is always considered to be `#[macro_use]`.
if let Some(prelude_module) = self.def_collector.def_map.prelude {
if prelude_module.krate != krate {
cov_mark::hit!(prelude_is_macro_use);
self.def_collector.import_all_macros_exported(self.module_id, prelude_module.krate);
}
}
// This should be processed eagerly instead of deferred to resolving.
// `#[macro_use] extern crate` is hoisted to imports macros before collecting
// any other items.
for &item in items {
let attrs = self.item_tree.attrs(self.def_collector.db, krate, item.into());
if attrs.cfg().map_or(true, |cfg| self.is_cfg_enabled(&cfg)) {
if let ModItem::ExternCrate(id) = item {
let import = &self.item_tree[id];
let attrs = self.item_tree.attrs(
self.def_collector.db,
krate,
ModItem::from(id).into(),
);
if attrs.by_key("macro_use").exists() {
self.def_collector.import_macros_from_extern_crate(self.module_id, import);
}
}
}
}
for &item in items {
let attrs = self.item_tree.attrs(self.def_collector.db, krate, item.into());
if let Some(cfg) = attrs.cfg() {
if !self.is_cfg_enabled(&cfg) {
self.emit_unconfigured_diagnostic(item, &cfg);
continue;
}
}
if let Err(()) = self.resolve_attributes(&attrs, item, container) {
// Do not process the item. It has at least one non-builtin attribute, so the
// fixed-point algorithm is required to resolve the rest of them.
continue;
}
let db = self.def_collector.db;
let module = self.def_collector.def_map.module_id(self.module_id);
let def_map = &mut self.def_collector.def_map;
let update_def =
|def_collector: &mut DefCollector, id, name: &Name, vis, has_constructor| {
def_collector.def_map.modules[self.module_id].scope.declare(id);
def_collector.update(
self.module_id,
&[(Some(name.clone()), PerNs::from_def(id, vis, has_constructor))],
vis,
ImportType::Named,
)
};
let resolve_vis = |def_map: &DefMap, visibility| {
def_map
.resolve_visibility(db, self.module_id, visibility)
.unwrap_or(Visibility::Public)
};
match item {
ModItem::Mod(m) => self.collect_module(&self.item_tree[m], &attrs),
ModItem::Import(import_id) => {
let imports = Import::from_use(
db,
krate,
self.item_tree,
ItemTreeId::new(self.tree_id, import_id),
);
self.def_collector.unresolved_imports.extend(imports.into_iter().map(
|import| ImportDirective {
module_id: self.module_id,
import,
status: PartialResolvedImport::Unresolved,
},
));
}
ModItem::ExternCrate(import_id) => {
self.def_collector.unresolved_imports.push(ImportDirective {
module_id: self.module_id,
import: Import::from_extern_crate(
db,
krate,
self.item_tree,
ItemTreeId::new(self.tree_id, import_id),
),
status: PartialResolvedImport::Unresolved,
})
}
ModItem::ExternBlock(block) => self.collect(
&self.item_tree[block].children,
ItemContainerId::ExternBlockId(
ExternBlockLoc {
container: module,
id: ItemTreeId::new(self.tree_id, block),
}
.intern(db),
),
),
ModItem::MacroCall(mac) => self.collect_macro_call(&self.item_tree[mac], container),
ModItem::MacroRules(id) => self.collect_macro_rules(id),
ModItem::MacroDef(id) => self.collect_macro_def(id),
ModItem::Impl(imp) => {
let module = self.def_collector.def_map.module_id(self.module_id);
let impl_id =
ImplLoc { container: module, id: ItemTreeId::new(self.tree_id, imp) }
.intern(db);
self.def_collector.def_map.modules[self.module_id].scope.define_impl(impl_id)
}
ModItem::Function(id) => {
let it = &self.item_tree[id];
let is_proc_macro = attrs.parse_proc_macro_decl(&it.name);
let vis = match is_proc_macro {
Some(proc_macro) => {
// FIXME: this should only be done in the root module of `proc-macro` crates, not everywhere
let ast_id = InFile::new(self.tree_id.file_id(), it.ast_id);
let module_id = def_map.module_id(def_map.root());
self.def_collector.export_proc_macro(proc_macro, ast_id);
Visibility::Module(module_id)
}
None => resolve_vis(def_map, &self.item_tree[it.visibility]),
};
update_def(
self.def_collector,
FunctionLoc { container, id: ItemTreeId::new(self.tree_id, id) }
.intern(db)
.into(),
&it.name,
vis,
false,
);
}
ModItem::Struct(id) => {
let it = &self.item_tree[id];
let vis = resolve_vis(def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
StructLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
.intern(db)
.into(),
&it.name,
vis,
!matches!(it.fields, Fields::Record(_)),
);
}
ModItem::Union(id) => {
let it = &self.item_tree[id];
let vis = resolve_vis(def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
UnionLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
.intern(db)
.into(),
&it.name,
vis,
false,
);
}
ModItem::Enum(id) => {
let it = &self.item_tree[id];
let vis = resolve_vis(def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
EnumLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
.intern(db)
.into(),
&it.name,
vis,
false,
);
}
ModItem::Const(id) => {
let it = &self.item_tree[id];
let const_id =
ConstLoc { container, id: ItemTreeId::new(self.tree_id, id) }.intern(db);
match &it.name {
Some(name) => {
let vis = resolve_vis(def_map, &self.item_tree[it.visibility]);
update_def(self.def_collector, const_id.into(), name, vis, false);
}
None => {
// const _: T = ...;
self.def_collector.def_map.modules[self.module_id]
.scope
.define_unnamed_const(const_id);
}
}
}
ModItem::Static(id) => {
let it = &self.item_tree[id];
let vis = resolve_vis(def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
StaticLoc { container, id: ItemTreeId::new(self.tree_id, id) }
.intern(db)
.into(),
&it.name,
vis,
false,
);
}
ModItem::Trait(id) => {
let it = &self.item_tree[id];
let vis = resolve_vis(def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
TraitLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
.intern(db)
.into(),
&it.name,
vis,
false,
);
}
ModItem::TypeAlias(id) => {
let it = &self.item_tree[id];
let vis = resolve_vis(def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
TypeAliasLoc { container, id: ItemTreeId::new(self.tree_id, id) }
.intern(db)
.into(),
&it.name,
vis,
false,
);
}
}
}
}
fn collect_module(&mut self, module: &Mod, attrs: &Attrs) {
let path_attr = attrs.by_key("path").string_value();
let is_macro_use = attrs.by_key("macro_use").exists();
match &module.kind {
// inline module, just recurse
ModKind::Inline { items } => {
let module_id = self.push_child_module(
module.name.clone(),
AstId::new(self.file_id(), module.ast_id),
None,
&self.item_tree[module.visibility],
);
if let Some(mod_dir) = self.mod_dir.descend_into_definition(&module.name, path_attr)
{
ModCollector {
def_collector: &mut *self.def_collector,
macro_depth: self.macro_depth,
module_id,
tree_id: self.tree_id,
item_tree: self.item_tree,
mod_dir,
}
.collect_in_top_module(&*items);
if is_macro_use {
self.import_all_legacy_macros(module_id);
}
}
}
// out of line module, resolve, parse and recurse
ModKind::Outline {} => {
let ast_id = AstId::new(self.tree_id.file_id(), module.ast_id);
let db = self.def_collector.db;
match self.mod_dir.resolve_declaration(db, self.file_id(), &module.name, path_attr)
{
Ok((file_id, is_mod_rs, mod_dir)) => {
let item_tree = db.file_item_tree(file_id.into());
let krate = self.def_collector.def_map.krate;
let is_enabled = item_tree
.top_level_attrs(db, krate)
.cfg()
.map_or(true, |cfg| self.is_cfg_enabled(&cfg));
if is_enabled {
let module_id = self.push_child_module(
module.name.clone(),
ast_id,
Some((file_id, is_mod_rs)),
&self.item_tree[module.visibility],
);
ModCollector {
def_collector: self.def_collector,
macro_depth: self.macro_depth,
module_id,
tree_id: TreeId::new(file_id.into(), None),
item_tree: &item_tree,
mod_dir,
}
.collect_in_top_module(item_tree.top_level_items());
let is_macro_use = is_macro_use
|| item_tree
.top_level_attrs(db, krate)
.by_key("macro_use")
.exists();
if is_macro_use {
self.import_all_legacy_macros(module_id);
}
}
}
Err(candidate) => {
self.def_collector.def_map.diagnostics.push(
DefDiagnostic::unresolved_module(self.module_id, ast_id, candidate),
);
}
};
}
}
}
fn push_child_module(
&mut self,
name: Name,
declaration: AstId<ast::Module>,
definition: Option<(FileId, bool)>,
visibility: &crate::visibility::RawVisibility,
) -> LocalModuleId {
let def_map = &mut self.def_collector.def_map;
let vis = def_map
.resolve_visibility(self.def_collector.db, self.module_id, visibility)
.unwrap_or(Visibility::Public);
let modules = &mut def_map.modules;
let origin = match definition {
None => ModuleOrigin::Inline { definition: declaration },
Some((definition, is_mod_rs)) => {
ModuleOrigin::File { declaration, definition, is_mod_rs }
}
};
let res = modules.alloc(ModuleData::new(origin, vis));
modules[res].parent = Some(self.module_id);
for (name, mac) in modules[self.module_id].scope.collect_legacy_macros() {
modules[res].scope.define_legacy_macro(name, mac)
}
modules[self.module_id].children.insert(name.clone(), res);
let module = def_map.module_id(res);
let def = ModuleDefId::from(module);
def_map.modules[self.module_id].scope.declare(def);
self.def_collector.update(
self.module_id,
&[(Some(name), PerNs::from_def(def, vis, false))],
vis,
ImportType::Named,
);
res
}
/// Resolves attributes on an item.
///
/// Returns `Err` when some attributes could not be resolved to builtins and have been
/// registered as unresolved.
///
/// If `ignore_up_to` is `Some`, attributes preceding and including that attribute will be
/// assumed to be resolved already.
fn resolve_attributes(
&mut self,
attrs: &Attrs,
mod_item: ModItem,
container: ItemContainerId,
) -> Result<(), ()> {
let mut ignore_up_to =
self.def_collector.skip_attrs.get(&InFile::new(self.file_id(), mod_item)).copied();
let iter = attrs
.iter()
.dedup_by(|a, b| {
// FIXME: this should not be required, all attributes on an item should have a
// unique ID!
// Still, this occurs because `#[cfg_attr]` can "expand" to multiple attributes:
// #[cfg_attr(not(off), unresolved, unresolved)]
// struct S;
// We should come up with a different way to ID attributes.
a.id == b.id
})
.skip_while(|attr| match ignore_up_to {
Some(id) if attr.id == id => {
ignore_up_to = None;
true
}
Some(_) => true,
None => false,
});
for attr in iter {
if self.def_collector.def_map.is_builtin_or_registered_attr(&attr.path) {
continue;
}
tracing::debug!("non-builtin attribute {}", attr.path);
let ast_id = AstIdWithPath::new(
self.file_id(),
mod_item.ast_id(self.item_tree),
attr.path.as_ref().clone(),
);
self.def_collector.unresolved_macros.push(MacroDirective {
module_id: self.module_id,
depth: self.macro_depth + 1,
kind: MacroDirectiveKind::Attr {
ast_id,
attr: attr.clone(),
mod_item,
tree: self.tree_id,
},
container,
});
return Err(());
}
Ok(())
}
fn collect_macro_rules(&mut self, id: FileItemTreeId<MacroRules>) {
let krate = self.def_collector.def_map.krate;
let mac = &self.item_tree[id];
let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
let export_attr = attrs.by_key("macro_export");
let is_export = export_attr.exists();
let is_local_inner = if is_export {
export_attr.tt_values().flat_map(|it| &it.token_trees).any(|it| match it {
tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
ident.text.contains("local_inner_macros")
}
_ => false,
})
} else {
false
};
// Case 1: builtin macros
if attrs.by_key("rustc_builtin_macro").exists() {
// `#[rustc_builtin_macro = "builtin_name"]` overrides the `macro_rules!` name.
let name;
let name = match attrs.by_key("rustc_builtin_macro").string_value() {
Some(it) => {
// FIXME: a hacky way to create a Name from string.
name = tt::Ident { text: it.clone(), id: tt::TokenId::unspecified() }.as_name();
&name
}
None => {
let explicit_name =
attrs.by_key("rustc_builtin_macro").tt_values().next().and_then(|tt| {
match tt.token_trees.first() {
Some(tt::TokenTree::Leaf(tt::Leaf::Ident(name))) => Some(name),
_ => None,
}
});
match explicit_name {
Some(ident) => {
name = ident.as_name();
&name
}
None => &mac.name,
}
}
};
let krate = self.def_collector.def_map.krate;
match find_builtin_macro(name, krate, ast_id) {
Some(macro_id) => {
self.def_collector.define_macro_rules(
self.module_id,
mac.name.clone(),
macro_id,
is_export,
);
return;
}
None => {
self.def_collector
.def_map
.diagnostics
.push(DefDiagnostic::unimplemented_builtin_macro(self.module_id, ast_id));
}
}
}
// Case 2: normal `macro_rules!` macro
let macro_id = MacroDefId {
krate: self.def_collector.def_map.krate,
kind: MacroDefKind::Declarative(ast_id),
local_inner: is_local_inner,
};
self.def_collector.define_macro_rules(
self.module_id,
mac.name.clone(),
macro_id,
is_export,
);
}
fn collect_macro_def(&mut self, id: FileItemTreeId<MacroDef>) {
let krate = self.def_collector.def_map.krate;
let mac = &self.item_tree[id];
let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
// Case 1: builtin macros
let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
if attrs.by_key("rustc_builtin_macro").exists() {
let macro_id = find_builtin_macro(&mac.name, krate, ast_id)
.or_else(|| find_builtin_derive(&mac.name, krate, ast_id))
.or_else(|| find_builtin_attr(&mac.name, krate, ast_id));
match macro_id {
Some(macro_id) => {
self.def_collector.define_macro_def(
self.module_id,
mac.name.clone(),
macro_id,
&self.item_tree[mac.visibility],
);
return;
}
None => {
self.def_collector
.def_map
.diagnostics
.push(DefDiagnostic::unimplemented_builtin_macro(self.module_id, ast_id));
}
}
}
// Case 2: normal `macro`
let macro_id = MacroDefId {
krate: self.def_collector.def_map.krate,
kind: MacroDefKind::Declarative(ast_id),
local_inner: false,
};
self.def_collector.define_macro_def(
self.module_id,
mac.name.clone(),
macro_id,
&self.item_tree[mac.visibility],
);
}
fn collect_macro_call(&mut self, mac: &MacroCall, container: ItemContainerId) {
let ast_id = AstIdWithPath::new(self.file_id(), mac.ast_id, ModPath::clone(&mac.path));
// Case 1: try to resolve in legacy scope and expand macro_rules
let mut error = None;
match macro_call_as_call_id(
self.def_collector.db,
&ast_id,
mac.expand_to,
self.def_collector.def_map.krate,
|path| {
path.as_ident().and_then(|name| {
self.def_collector.def_map.with_ancestor_maps(
self.def_collector.db,
self.module_id,
&mut |map, module| map[module].scope.get_legacy_macro(name),
)
})
},
&mut |err| {
error.get_or_insert(err);
},
) {
Ok(Ok(macro_call_id)) => {
// Legacy macros need to be expanded immediately, so that any macros they produce
// are in scope.
self.def_collector.collect_macro_expansion(
self.module_id,
macro_call_id,
self.macro_depth + 1,
container,
);
if let Some(err) = error {
self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
self.module_id,
MacroCallKind::FnLike { ast_id: ast_id.ast_id, expand_to: mac.expand_to },
err.to_string(),
));
}
return;
}
Ok(Err(_)) => {
// Built-in macro failed eager expansion.
self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
self.module_id,
MacroCallKind::FnLike { ast_id: ast_id.ast_id, expand_to: mac.expand_to },
error.unwrap().to_string(),
));
return;
}
Err(UnresolvedMacro { .. }) => (),
}
// Case 2: resolve in module scope, expand during name resolution.
self.def_collector.unresolved_macros.push(MacroDirective {
module_id: self.module_id,
depth: self.macro_depth + 1,
kind: MacroDirectiveKind::FnLike { ast_id, expand_to: mac.expand_to },
container,
});
}
fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) {
let macros = self.def_collector.def_map[module_id].scope.collect_legacy_macros();
for (name, macro_) in macros {
self.def_collector.define_legacy_macro(self.module_id, name.clone(), macro_);
}
}
fn is_cfg_enabled(&self, cfg: &CfgExpr) -> bool {
self.def_collector.cfg_options.check(cfg) != Some(false)
}
fn emit_unconfigured_diagnostic(&mut self, item: ModItem, cfg: &CfgExpr) {
let ast_id = item.ast_id(self.item_tree);
let ast_id = InFile::new(self.file_id(), ast_id);
self.def_collector.def_map.diagnostics.push(DefDiagnostic::unconfigured_code(
self.module_id,
ast_id,
cfg.clone(),
self.def_collector.cfg_options.clone(),
));
}
fn file_id(&self) -> HirFileId {
self.tree_id.file_id()
}
}
#[cfg(test)]
mod tests {
use crate::{db::DefDatabase, test_db::TestDB};
use base_db::{fixture::WithFixture, SourceDatabase};
use super::*;
fn do_collect_defs(db: &dyn DefDatabase, def_map: DefMap) -> DefMap {
let mut collector = DefCollector {
db,
def_map,
deps: FxHashMap::default(),
glob_imports: FxHashMap::default(),
unresolved_imports: Vec::new(),
resolved_imports: Vec::new(),
unresolved_macros: Vec::new(),
mod_dirs: FxHashMap::default(),
cfg_options: &CfgOptions::default(),
proc_macros: Default::default(),
exports_proc_macros: false,
from_glob_import: Default::default(),
skip_attrs: Default::default(),
derive_helpers_in_scope: Default::default(),
};
collector.seed_with_top_level();
collector.collect();
collector.def_map
}
fn do_resolve(not_ra_fixture: &str) -> DefMap {
let (db, file_id) = TestDB::with_single_file(not_ra_fixture);
let krate = db.test_crate();
let edition = db.crate_graph()[krate].edition;
let module_origin = ModuleOrigin::CrateRoot { definition: file_id };
let def_map = DefMap::empty(krate, edition, module_origin);
do_collect_defs(&db, def_map)
}
#[test]
fn test_macro_expand_will_stop_1() {
do_resolve(
r#"
macro_rules! foo {
($($ty:ty)*) => { foo!($($ty)*); }
}
foo!(KABOOM);
"#,
);
do_resolve(
r#"
macro_rules! foo {
($($ty:ty)*) => { foo!(() $($ty)*); }
}
foo!(KABOOM);
"#,
);
}
#[ignore]
#[test]
fn test_macro_expand_will_stop_2() {
// FIXME: this test does succeed, but takes quite a while: 90 seconds in
// the release mode. That's why the argument is not an ra_fixture --
// otherwise injection highlighting gets stuck.
//
// We need to find a way to fail this faster.
do_resolve(
r#"
macro_rules! foo {
($($ty:ty)*) => { foo!($($ty)* $($ty)*); }
}
foo!(KABOOM);
"#,
);
}
}
| 40.397669 | 134 | 0.49187 |
386fba55573660e184ed380fa8052a31e8df98f2
| 1,939 |
use assert_fs::fixture::FixtureError;
use assert_fs::fixture::{ChildPath, PathChild};
use assert_fs::TempDir;
use std::path::{Path, PathBuf};
use thiserror::Error;
pub enum TestingDirectory {
Temp(TempDir),
User(PathBuf),
}
impl TestingDirectory {
#[allow(dead_code)]
pub fn path(&self) -> &Path {
match self {
TestingDirectory::User(path_buf) => path_buf,
TestingDirectory::Temp(temp_dir) => temp_dir.path(),
}
}
pub fn new_temp() -> Result<Self, FixtureError> {
Ok(Self::Temp(TempDir::new()?))
}
pub fn from_temp(temp_dir: TempDir) -> Self {
Self::Temp(temp_dir)
}
pub fn into_persistent(self) -> Self {
if let Self::Temp(temp_dir) = self {
return Self::Temp(temp_dir.into_persistent());
}
self
}
}
impl PathChild for TestingDirectory {
fn child<P>(&self, path: P) -> ChildPath
where
P: AsRef<Path>,
{
match self {
Self::User(dir_path) => ChildPath::new(dir_path.join(path)),
Self::Temp(temp_dir) => temp_dir.child(path),
}
}
}
impl From<PathBuf> for TestingDirectory {
fn from(path: PathBuf) -> Self {
Self::User(path)
}
}
impl From<Option<PathBuf>> for TestingDirectory {
fn from(maybe_path: Option<PathBuf>) -> Self {
if let Some(testing_directory) = maybe_path {
testing_directory.into()
} else {
Default::default()
}
}
}
impl Clone for TestingDirectory {
fn clone(&self) -> Self {
match self {
Self::User(dir_path) => dir_path.to_path_buf().into(),
Self::Temp(_) => Default::default(),
}
}
}
impl Default for TestingDirectory {
fn default() -> Self {
Self::new_temp().unwrap()
}
}
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
Fixture(#[from] FixtureError),
}
| 22.811765 | 72 | 0.577617 |
d692f3a87e457b385f956ccb62d0aae6e599803e
| 617 |
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that constant expressions can be used in vec repeat syntax.
pub fn main() {
const FOO: uint = 2;
let _v = [0i; FOO*3*2/2];
}
| 32.473684 | 69 | 0.714749 |
bb60cc14b4b881207c02e85f69b215b4190a010f
| 1,476 |
// codeaccesspermission.rs - MIT License
// MIT License
// Copyright (c) 2018 Tyler Laing (ZerothLaw)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use winapi::um::oaidl::{IDispatch, IDispatchVtbl};
RIDL!{#[uuid(0x4803ce39, 0x2f30, 0x31fc, 0xb8, 0x4b, 0x5a, 0x01, 0x41, 0x38, 0x52, 0x69)]
interface _CodeAccessPermission(_CodeAccessPermissionVtbl): IDispatch(IDispatchVtbl)
{}} //IPermission, ISecurityEncodable, IStackWalk
| 54.666667 | 89 | 0.756775 |
1e1597e532b9adcd63de0ecf90bd9346abbea7e0
| 878 |
use std::error::Error;
use byteorder::{ByteOrder, LittleEndian};
use cpu::CPU;
use mmu::MemoryManagementUnit;
mod mmu;
mod cpu;
mod io;
mod lcd;
fn print_eeprom(eeprom: &[u8], length: usize) {
for b in eeprom[0..length].iter() {
println!("{:#04x}", b);
}
}
pub struct DoubleBarrel {
file_name: String,
cpu: CPU,
}
impl DoubleBarrel {
pub fn new(file_name: String) -> Option<Self> {
let rom = std::fs::read(&file_name).unwrap();
print_eeprom(&rom, 20);
if rom.len() != 0x8000 {
println!("Invalid ROM size: ROM must be {} bytes, found {}", 0x8000, rom.len());
return None;
}
let cpu = CPU::new(rom);
Some(DoubleBarrel { file_name, cpu })
}
pub fn start(&mut self) {
println!("\nStart Program\n");
loop {
self.cpu.tick();
}
}
}
| 21.414634 | 92 | 0.551253 |
db6571d85bd20d6fd6b53dfb077599c2c136cf1c
| 6,584 |
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::UESTA1SET {
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
}
#[doc = r" Proxy"]
pub struct _TXINISW<'a> {
w: &'a mut W,
}
impl<'a> _TXINISW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _RXOUTISW<'a> {
w: &'a mut W,
}
impl<'a> _RXOUTISW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _RXSTPISW<'a> {
w: &'a mut W,
}
impl<'a> _RXSTPISW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _NAKOUTISW<'a> {
w: &'a mut W,
}
impl<'a> _NAKOUTISW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _NAKINISW<'a> {
w: &'a mut W,
}
impl<'a> _NAKINISW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _STALLEDISW<'a> {
w: &'a mut W,
}
impl<'a> _STALLEDISW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _RAMACERISW<'a> {
w: &'a mut W,
}
impl<'a> _RAMACERISW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _NBUSYBKSW<'a> {
w: &'a mut W,
}
impl<'a> _NBUSYBKSW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - TXINI Set"]
#[inline]
pub fn txinis(&mut self) -> _TXINISW {
_TXINISW { w: self }
}
#[doc = "Bit 1 - RXOUTI Set"]
#[inline]
pub fn rxoutis(&mut self) -> _RXOUTISW {
_RXOUTISW { w: self }
}
#[doc = "Bit 2 - RXSTPI Set"]
#[inline]
pub fn rxstpis(&mut self) -> _RXSTPISW {
_RXSTPISW { w: self }
}
#[doc = "Bit 3 - NAKOUTI Set"]
#[inline]
pub fn nakoutis(&mut self) -> _NAKOUTISW {
_NAKOUTISW { w: self }
}
#[doc = "Bit 4 - NAKINI Set"]
#[inline]
pub fn nakinis(&mut self) -> _NAKINISW {
_NAKINISW { w: self }
}
#[doc = "Bit 6 - STALLEDI Set"]
#[inline]
pub fn stalledis(&mut self) -> _STALLEDISW {
_STALLEDISW { w: self }
}
#[doc = "Bit 11 - RAMACERI Set"]
#[inline]
pub fn ramaceris(&mut self) -> _RAMACERISW {
_RAMACERISW { w: self }
}
#[doc = "Bit 12 - NBUSYBK Set"]
#[inline]
pub fn nbusybks(&mut self) -> _NBUSYBKSW {
_NBUSYBKSW { w: self }
}
}
| 25.92126 | 59 | 0.501367 |
fb1cf7f71e70add8b15b788e9eac2aa8cd04c2e4
| 543 |
struct Foo;
impl Foo {
fn bar(&self) {}
}
trait MyTrait {
fn trait_bar() {}
}
impl MyTrait for Foo {}
fn main() {
match 0u32 {
Foo::bar => {}
//~^ ERROR expected unit struct/variant or constant, found method `<Foo>::bar`
}
match 0u32 {
<Foo>::bar => {}
//~^ ERROR expected unit struct/variant or constant, found method `<Foo>::bar`
}
match 0u32 {
<Foo>::trait_bar => {}
//~^ ERROR expected unit struct/variant or constant, found method `<Foo>::trait_bar`
}
}
| 20.111111 | 92 | 0.550645 |
6a0bfd1d60d683521fd1caddd4c8f2d2e521af39
| 1,544 |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub struct Logon {
/// MsgType = A
#[serde(flatten)]
pub standard_message_header: super::super::standard_message_header::StandardMessageHeader<'A'>,
/// (Always unencrypted)
#[serde(rename = "98")]
pub encrypt_method: EncryptMethod,
/// HeartBtInt
#[serde(deserialize_with = "fix_common::workarounds::from_str")]// https://github.com/serde-rs/serde/issues/1183
#[serde(rename = "108")]
pub heart_bt_int: i32,
/// Required for some authentication methods
#[serde(rename = "95")]
/// Required for some authentication methods
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(alias = "96")]
pub raw_data: Option<fix_common::EncodedText<96>>,
/// Standard Message Trailer
#[serde(flatten)]
pub standard_message_trailer: super::super::standard_message_trailer::StandardMessageTrailer,
}
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
pub enum EncryptMethod {
/// None / other
#[serde(rename = "0")]
NoneOther,
/// PKCS (proprietary)
#[serde(rename = "1")]
Pkcs,
/// DES (ECB mode)
#[serde(rename = "2")]
Des,
/// PKCS/DES (proprietary)
#[serde(rename = "3")]
PkcsDes,
/// PGP/DES (defunct)
#[serde(rename = "4")]
PgpDes,
/// PGP/DES-MD5 (see app note on FIX web site)
#[serde(rename = "5")]
PgpDesMd5,
/// PEM/DES-MD5 (see app note on FIX web site)
#[serde(rename = "6")]
PemDesMd5,
}
impl Default for EncryptMethod {
fn default() -> Self {
EncryptMethod::NoneOther
}
}
| 27.087719 | 113 | 0.688472 |
e94b8450bfd056ab87f8cb52e226147f91a80fd7
| 4,319 |
use hir::Node;
use rustc_hir as hir;
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::subst::GenericArgKind;
use rustc_middle::ty::{self, CratePredicatesMap, ToPredicate, TyCtxt};
use rustc_span::symbol::sym;
use rustc_span::Span;
mod explicit;
mod implicit_infer;
/// Code to write unit test for outlives.
pub mod test;
mod utils;
pub fn provide(providers: &mut Providers) {
*providers = Providers { inferred_outlives_of, inferred_outlives_crate, ..*providers };
}
fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[(ty::Predicate<'_>, Span)] {
let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
match tcx.hir().get(id) {
Node::Item(item) => match item.kind {
hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..) => {
let crate_map = tcx.inferred_outlives_crate(LOCAL_CRATE);
let predicates = crate_map.predicates.get(&item_def_id).copied().unwrap_or(&[]);
if tcx.has_attr(item_def_id, sym::rustc_outlives) {
let mut pred: Vec<String> = predicates
.iter()
.map(|(out_pred, _)| match out_pred.kind().skip_binder() {
ty::PredicateKind::RegionOutlives(p) => p.to_string(),
ty::PredicateKind::TypeOutlives(p) => p.to_string(),
err => bug!("unexpected predicate {:?}", err),
})
.collect();
pred.sort();
let span = tcx.def_span(item_def_id);
let mut err = tcx.sess.struct_span_err(span, "rustc_outlives");
for p in &pred {
err.note(p);
}
err.emit();
}
debug!("inferred_outlives_of({:?}) = {:?}", item_def_id, predicates);
predicates
}
_ => &[],
},
_ => &[],
}
}
fn inferred_outlives_crate(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CratePredicatesMap<'_> {
assert_eq!(crate_num, LOCAL_CRATE);
// Compute a map from each struct/enum/union S to the **explicit**
// outlives predicates (`T: 'a`, `'a: 'b`) that the user wrote.
// Typically there won't be many of these, except in older code where
// they were mandatory. Nonetheless, we have to ensure that every such
// predicate is satisfied, so they form a kind of base set of requirements
// for the type.
// Compute the inferred predicates
let mut exp_map = explicit::ExplicitPredicatesMap::new();
let global_inferred_outlives = implicit_infer::infer_predicates(tcx, &mut exp_map);
// Convert the inferred predicates into the "collected" form the
// global data structure expects.
//
// FIXME -- consider correcting impedance mismatch in some way,
// probably by updating the global data structure.
let predicates = global_inferred_outlives
.iter()
.map(|(&def_id, set)| {
let predicates = &*tcx.arena.alloc_from_iter(set.iter().filter_map(
|(ty::OutlivesPredicate(kind1, region2), &span)| {
match kind1.unpack() {
GenericArgKind::Type(ty1) => Some((
ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty1, region2))
.to_predicate(tcx),
span,
)),
GenericArgKind::Lifetime(region1) => Some((
ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
region1, region2,
))
.to_predicate(tcx),
span,
)),
GenericArgKind::Const(_) => {
// Generic consts don't impose any constraints.
None
}
}
},
));
(def_id, predicates)
})
.collect();
ty::CratePredicatesMap { predicates }
}
| 38.5625 | 96 | 0.528132 |
db37c70b70de43fe6fccf697ce4adb96625a45c5
| 1,623 |
use std::error::Error;
use wiremock_client::*;
use wiremock_client::stubbing::Scenario;
// Examples from: http://wiremock.org/docs/stateful-behaviour/
pub fn main() -> Result<(), Box<dyn Error>> {
let wire_mock = WireMockBuilder::new()
.port(8181) // If running on another port - the default is: 8080
.build();
// Scenarios
wire_mock.stub_for(get(url_equal_to("/todo/items")).in_scenario("To do list")
.when_scenario_state_is(Scenario::STARTED)
.will_return(a_response()
.with_body("<items>".to_string() +
" <item>Buy milk</item>" +
"</items>")))?;
wire_mock.stub_for(post(url_equal_to("/todo/items")).in_scenario("To do list")
.when_scenario_state_is(Scenario::STARTED)
.with_request_body(containing("Cancel newspaper subscription"))
.will_return(a_response().with_status(201))
.will_set_state_to("Cancel newspaper item added"))?;
wire_mock.stub_for(get(url_equal_to("/todo/items")).in_scenario("To do list")
.when_scenario_state_is("Cancel newspaper item added")
.will_return(a_response()
.with_body("<items>".to_string() +
" <item>Buy milk</item>" +
" <item>Cancel newspaper subscription</item>" +
"</items>")))?;
// Getting scenario state
let _all_scenarios: Vec<Scenario> = wire_mock.get_scenarios()?;
// Resetting scenarios
wire_mock.reset_scenarios()?;
// Reset mappings in case the integration tests are run afterwards
wire_mock.reset_to_default_mappings()?;
Ok(())
}
| 36.066667 | 82 | 0.633395 |
893dfac8568fa7f48844462abb74d7dd96f38cb0
| 3,486 |
#![allow(non_snake_case, non_upper_case_globals)]
#![allow(non_camel_case_types)]
//! Floting point unit
//!
//! Used by: stm32g431, stm32g441, stm32g471, stm32g473, stm32g474, stm32g483, stm32g484, stm32g491, stm32g4a1
#[cfg(not(feature = "nosync"))]
pub use crate::stm32g4::peripherals::fpu::Instance;
pub use crate::stm32g4::peripherals::fpu::{RegisterBlock, ResetValues};
pub use crate::stm32g4::peripherals::fpu::{FPCAR, FPCCR, FPSCR};
/// Access functions for the FPU peripheral instance
pub mod FPU {
use super::ResetValues;
#[cfg(not(feature = "nosync"))]
use super::Instance;
#[cfg(not(feature = "nosync"))]
const INSTANCE: Instance = Instance {
addr: 0xe000ef34,
_marker: ::core::marker::PhantomData,
};
/// Reset values for each field in FPU
pub const reset: ResetValues = ResetValues {
FPCCR: 0x00000000,
FPCAR: 0x00000000,
FPSCR: 0x00000000,
};
#[cfg(not(feature = "nosync"))]
#[allow(renamed_and_removed_lints)]
#[allow(private_no_mangle_statics)]
#[no_mangle]
static mut FPU_TAKEN: bool = false;
/// Safe access to FPU
///
/// This function returns `Some(Instance)` if this instance is not
/// currently taken, and `None` if it is. This ensures that if you
/// do get `Some(Instance)`, you are ensured unique access to
/// the peripheral and there cannot be data races (unless other
/// code uses `unsafe`, of course). You can then pass the
/// `Instance` around to other functions as required. When you're
/// done with it, you can call `release(instance)` to return it.
///
/// `Instance` itself dereferences to a `RegisterBlock`, which
/// provides access to the peripheral's registers.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn take() -> Option<Instance> {
external_cortex_m::interrupt::free(|_| unsafe {
if FPU_TAKEN {
None
} else {
FPU_TAKEN = true;
Some(INSTANCE)
}
})
}
/// Release exclusive access to FPU
///
/// This function allows you to return an `Instance` so that it
/// is available to `take()` again. This function will panic if
/// you return a different `Instance` or if this instance is not
/// already taken.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn release(inst: Instance) {
external_cortex_m::interrupt::free(|_| unsafe {
if FPU_TAKEN && inst.addr == INSTANCE.addr {
FPU_TAKEN = false;
} else {
panic!("Released a peripheral which was not taken");
}
});
}
/// Unsafely steal FPU
///
/// This function is similar to take() but forcibly takes the
/// Instance, marking it as taken irregardless of its previous
/// state.
#[cfg(not(feature = "nosync"))]
#[inline]
pub unsafe fn steal() -> Instance {
FPU_TAKEN = true;
INSTANCE
}
}
/// Raw pointer to FPU
///
/// Dereferencing this is unsafe because you are not ensured unique
/// access to the peripheral, so you may encounter data races with
/// other users of this peripheral. It is up to you to ensure you
/// will not cause data races.
///
/// This constant is provided for ease of use in unsafe code: you can
/// simply call for example `write_reg!(gpio, GPIOA, ODR, 1);`.
pub const FPU: *const RegisterBlock = 0xe000ef34 as *const _;
| 33.519231 | 110 | 0.623064 |
50abda8d45e979fbd68914e04e4b0552a56f3560
| 24,264 |
//! Checks that meta-variables in macro definition are correctly declared and used.
//!
//! # What is checked
//!
//! ## Meta-variables must not be bound twice
//!
//! ```
//! macro_rules! foo { ($x:tt $x:tt) => { $x }; }
//! ```
//!
//! This check is sound (no false-negative) and complete (no false-positive).
//!
//! ## Meta-variables must not be free
//!
//! ```
//! macro_rules! foo { () => { $x }; }
//! ```
//!
//! This check is also done at macro instantiation but only if the branch is taken.
//!
//! ## Meta-variables must repeat at least as many times as their binder
//!
//! ```
//! macro_rules! foo { ($($x:tt)*) => { $x }; }
//! ```
//!
//! This check is also done at macro instantiation but only if the branch is taken.
//!
//! ## Meta-variables must repeat with the same Kleene operators as their binder
//!
//! ```
//! macro_rules! foo { ($($x:tt)+) => { $($x)* }; }
//! ```
//!
//! This check is not done at macro instantiation.
//!
//! # Disclaimer
//!
//! In the presence of nested macros (a macro defined in a macro), those checks may have false
//! positives and false negatives. We try to detect those cases by recognizing potential macro
//! definitions in RHSes, but nested macros may be hidden through the use of particular values of
//! meta-variables.
//!
//! ## Examples of false positive
//!
//! False positives can come from cases where we don't recognize a nested macro, because it depends
//! on particular values of meta-variables. In the following example, we think both instances of
//! `$x` are free, which is a correct statement if `$name` is anything but `macro_rules`. But when
//! `$name` is `macro_rules`, like in the instantiation below, then `$x:tt` is actually a binder of
//! the nested macro and `$x` is bound to it.
//!
//! ```
//! macro_rules! foo { ($name:ident) => { $name! bar { ($x:tt) => { $x }; } }; }
//! foo!(macro_rules);
//! ```
//!
//! False positives can also come from cases where we think there is a nested macro while there
//! isn't. In the following example, we think `$x` is free, which is incorrect because `bar` is not
//! a nested macro since it is not evaluated as code by `stringify!`.
//!
//! ```
//! macro_rules! foo { () => { stringify!(macro_rules! bar { () => { $x }; }) }; }
//! ```
//!
//! ## Examples of false negative
//!
//! False negatives can come from cases where we don't recognize a meta-variable, because it depends
//! on particular values of meta-variables. In the following examples, we don't see that if `$d` is
//! instantiated with `$` then `$d z` becomes `$z` in the nested macro definition and is thus a free
//! meta-variable. Note however, that if `foo` is instantiated, then we would check the definition
//! of `bar` and would see the issue.
//!
//! ```
//! macro_rules! foo { ($d:tt) => { macro_rules! bar { ($y:tt) => { $d z }; } }; }
//! ```
//!
//! # How it is checked
//!
//! There are 3 main functions: `check_binders`, `check_occurrences`, and `check_nested_macro`. They
//! all need some kind of environment.
//!
//! ## Environments
//!
//! Environments are used to pass information.
//!
//! ### From LHS to RHS
//!
//! When checking a LHS with `check_binders`, we produce (and use) an environment for binders,
//! namely `Binders`. This is a mapping from binder name to information about that binder: the span
//! of the binder for error messages and the stack of Kleene operators under which it was bound in
//! the LHS.
//!
//! This environment is used by both the LHS and RHS. The LHS uses it to detect duplicate binders.
//! The RHS uses it to detect the other errors.
//!
//! ### From outer macro to inner macro
//!
//! When checking the RHS of an outer macro and we detect a nested macro definition, we push the
//! current state, namely `MacroState`, to an environment of nested macro definitions. Each state
//! stores the LHS binders when entering the macro definition as well as the stack of Kleene
//! operators under which the inner macro is defined in the RHS.
//!
//! This environment is a stack representing the nesting of macro definitions. As such, the stack of
//! Kleene operators under which a meta-variable is repeating is the concatenation of the stacks
//! stored when entering a macro definition starting from the state in which the meta-variable is
//! bound.
use crate::mbe::{KleeneToken, TokenTree};
use syntax::ast::NodeId;
use syntax::early_buffered_lints::BufferedEarlyLintId;
use syntax::parse::token::{DelimToken, Token, TokenKind};
use syntax::sess::ParseSess;
use syntax::symbol::{kw, sym};
use rustc_data_structures::fx::FxHashMap;
use smallvec::SmallVec;
use syntax_pos::{symbol::Ident, MultiSpan, Span};
/// Stack represented as linked list.
///
/// Those are used for environments because they grow incrementally and are not mutable.
enum Stack<'a, T> {
/// Empty stack.
Empty,
/// A non-empty stack.
Push {
/// The top element.
top: T,
/// The previous elements.
prev: &'a Stack<'a, T>,
},
}
impl<'a, T> Stack<'a, T> {
/// Returns whether a stack is empty.
fn is_empty(&self) -> bool {
match *self {
Stack::Empty => true,
_ => false,
}
}
/// Returns a new stack with an element of top.
fn push(&'a self, top: T) -> Stack<'a, T> {
Stack::Push { top, prev: self }
}
}
impl<'a, T> Iterator for &'a Stack<'a, T> {
type Item = &'a T;
// Iterates from top to bottom of the stack.
fn next(&mut self) -> Option<&'a T> {
match *self {
Stack::Empty => None,
Stack::Push { ref top, ref prev } => {
*self = prev;
Some(top)
}
}
}
}
impl From<&Stack<'_, KleeneToken>> for SmallVec<[KleeneToken; 1]> {
fn from(ops: &Stack<'_, KleeneToken>) -> SmallVec<[KleeneToken; 1]> {
let mut ops: SmallVec<[KleeneToken; 1]> = ops.cloned().collect();
// The stack is innermost on top. We want outermost first.
ops.reverse();
ops
}
}
/// Information attached to a meta-variable binder in LHS.
struct BinderInfo {
/// The span of the meta-variable in LHS.
span: Span,
/// The stack of Kleene operators (outermost first).
ops: SmallVec<[KleeneToken; 1]>,
}
/// An environment of meta-variables to their binder information.
type Binders = FxHashMap<Ident, BinderInfo>;
/// The state at which we entered a macro definition in the RHS of another macro definition.
struct MacroState<'a> {
/// The binders of the branch where we entered the macro definition.
binders: &'a Binders,
/// The stack of Kleene operators (outermost first) where we entered the macro definition.
ops: SmallVec<[KleeneToken; 1]>,
}
/// Checks that meta-variables are used correctly in a macro definition.
///
/// Arguments:
/// - `sess` is used to emit diagnostics and lints
/// - `node_id` is used to emit lints
/// - `span` is used when no spans are available
/// - `lhses` and `rhses` should have the same length and represent the macro definition
pub(super) fn check_meta_variables(
sess: &ParseSess,
node_id: NodeId,
span: Span,
lhses: &[TokenTree],
rhses: &[TokenTree],
) -> bool {
if lhses.len() != rhses.len() {
sess.span_diagnostic.span_bug(span, "length mismatch between LHSes and RHSes")
}
let mut valid = true;
for (lhs, rhs) in lhses.iter().zip(rhses.iter()) {
let mut binders = Binders::default();
check_binders(sess, node_id, lhs, &Stack::Empty, &mut binders, &Stack::Empty, &mut valid);
check_occurrences(sess, node_id, rhs, &Stack::Empty, &binders, &Stack::Empty, &mut valid);
}
valid
}
/// Checks `lhs` as part of the LHS of a macro definition, extends `binders` with new binders, and
/// sets `valid` to false in case of errors.
///
/// Arguments:
/// - `sess` is used to emit diagnostics and lints
/// - `node_id` is used to emit lints
/// - `lhs` is checked as part of a LHS
/// - `macros` is the stack of possible outer macros
/// - `binders` contains the binders of the LHS
/// - `ops` is the stack of Kleene operators from the LHS
/// - `valid` is set in case of errors
fn check_binders(
sess: &ParseSess,
node_id: NodeId,
lhs: &TokenTree,
macros: &Stack<'_, MacroState<'_>>,
binders: &mut Binders,
ops: &Stack<'_, KleeneToken>,
valid: &mut bool,
) {
match *lhs {
TokenTree::Token(..) => {}
// This can only happen when checking a nested macro because this LHS is then in the RHS of
// the outer macro. See ui/macros/macro-of-higher-order.rs where $y:$fragment in the
// LHS of the nested macro (and RHS of the outer macro) is parsed as MetaVar(y) Colon
// MetaVar(fragment) and not as MetaVarDecl(y, fragment).
TokenTree::MetaVar(span, name) => {
if macros.is_empty() {
sess.span_diagnostic.span_bug(span, "unexpected MetaVar in lhs");
}
// There are 3 possibilities:
if let Some(prev_info) = binders.get(&name) {
// 1. The meta-variable is already bound in the current LHS: This is an error.
let mut span = MultiSpan::from_span(span);
span.push_span_label(prev_info.span, "previous declaration".into());
buffer_lint(sess, span, node_id, "duplicate matcher binding");
} else if get_binder_info(macros, binders, name).is_none() {
// 2. The meta-variable is free: This is a binder.
binders.insert(name, BinderInfo { span, ops: ops.into() });
} else {
// 3. The meta-variable is bound: This is an occurrence.
check_occurrences(sess, node_id, lhs, macros, binders, ops, valid);
}
}
// Similarly, this can only happen when checking a toplevel macro.
TokenTree::MetaVarDecl(span, name, _kind) => {
if !macros.is_empty() {
sess.span_diagnostic.span_bug(span, "unexpected MetaVarDecl in nested lhs");
}
if let Some(prev_info) = get_binder_info(macros, binders, name) {
// Duplicate binders at the top-level macro definition are errors. The lint is only
// for nested macro definitions.
sess.span_diagnostic
.struct_span_err(span, "duplicate matcher binding")
.span_note(prev_info.span, "previous declaration was here")
.emit();
*valid = false;
} else {
binders.insert(name, BinderInfo { span, ops: ops.into() });
}
}
TokenTree::Delimited(_, ref del) => {
for tt in &del.tts {
check_binders(sess, node_id, tt, macros, binders, ops, valid);
}
}
TokenTree::Sequence(_, ref seq) => {
let ops = ops.push(seq.kleene);
for tt in &seq.tts {
check_binders(sess, node_id, tt, macros, binders, &ops, valid);
}
}
}
}
/// Returns the binder information of a meta-variable.
///
/// Arguments:
/// - `macros` is the stack of possible outer macros
/// - `binders` contains the current binders
/// - `name` is the name of the meta-variable we are looking for
fn get_binder_info<'a>(
mut macros: &'a Stack<'a, MacroState<'a>>,
binders: &'a Binders,
name: Ident,
) -> Option<&'a BinderInfo> {
binders.get(&name).or_else(|| macros.find_map(|state| state.binders.get(&name)))
}
/// Checks `rhs` as part of the RHS of a macro definition and sets `valid` to false in case of
/// errors.
///
/// Arguments:
/// - `sess` is used to emit diagnostics and lints
/// - `node_id` is used to emit lints
/// - `rhs` is checked as part of a RHS
/// - `macros` is the stack of possible outer macros
/// - `binders` contains the binders of the associated LHS
/// - `ops` is the stack of Kleene operators from the RHS
/// - `valid` is set in case of errors
fn check_occurrences(
sess: &ParseSess,
node_id: NodeId,
rhs: &TokenTree,
macros: &Stack<'_, MacroState<'_>>,
binders: &Binders,
ops: &Stack<'_, KleeneToken>,
valid: &mut bool,
) {
match *rhs {
TokenTree::Token(..) => {}
TokenTree::MetaVarDecl(span, _name, _kind) => {
sess.span_diagnostic.span_bug(span, "unexpected MetaVarDecl in rhs")
}
TokenTree::MetaVar(span, name) => {
check_ops_is_prefix(sess, node_id, macros, binders, ops, span, name);
}
TokenTree::Delimited(_, ref del) => {
check_nested_occurrences(sess, node_id, &del.tts, macros, binders, ops, valid);
}
TokenTree::Sequence(_, ref seq) => {
let ops = ops.push(seq.kleene);
check_nested_occurrences(sess, node_id, &seq.tts, macros, binders, &ops, valid);
}
}
}
/// Represents the processed prefix of a nested macro.
#[derive(Clone, Copy, PartialEq, Eq)]
enum NestedMacroState {
/// Nothing that matches a nested macro definition was processed yet.
Empty,
/// The token `macro_rules` was processed.
MacroRules,
/// The tokens `macro_rules!` were processed.
MacroRulesNot,
/// The tokens `macro_rules!` followed by a name were processed. The name may be either directly
/// an identifier or a meta-variable (that hopefully would be instantiated by an identifier).
MacroRulesNotName,
/// The keyword `macro` was processed.
Macro,
/// The keyword `macro` followed by a name was processed.
MacroName,
/// The keyword `macro` followed by a name and a token delimited by parentheses was processed.
MacroNameParen,
}
/// Checks `tts` as part of the RHS of a macro definition, tries to recognize nested macro
/// definitions, and sets `valid` to false in case of errors.
///
/// Arguments:
/// - `sess` is used to emit diagnostics and lints
/// - `node_id` is used to emit lints
/// - `tts` is checked as part of a RHS and may contain macro definitions
/// - `macros` is the stack of possible outer macros
/// - `binders` contains the binders of the associated LHS
/// - `ops` is the stack of Kleene operators from the RHS
/// - `valid` is set in case of errors
fn check_nested_occurrences(
sess: &ParseSess,
node_id: NodeId,
tts: &[TokenTree],
macros: &Stack<'_, MacroState<'_>>,
binders: &Binders,
ops: &Stack<'_, KleeneToken>,
valid: &mut bool,
) {
let mut state = NestedMacroState::Empty;
let nested_macros = macros.push(MacroState { binders, ops: ops.into() });
let mut nested_binders = Binders::default();
for tt in tts {
match (state, tt) {
(
NestedMacroState::Empty,
&TokenTree::Token(Token { kind: TokenKind::Ident(name, false), .. }),
) => {
if name == sym::macro_rules {
state = NestedMacroState::MacroRules;
} else if name == kw::Macro {
state = NestedMacroState::Macro;
}
}
(
NestedMacroState::MacroRules,
&TokenTree::Token(Token { kind: TokenKind::Not, .. }),
) => {
state = NestedMacroState::MacroRulesNot;
}
(
NestedMacroState::MacroRulesNot,
&TokenTree::Token(Token { kind: TokenKind::Ident(..), .. }),
) => {
state = NestedMacroState::MacroRulesNotName;
}
(NestedMacroState::MacroRulesNot, &TokenTree::MetaVar(..)) => {
state = NestedMacroState::MacroRulesNotName;
// We check that the meta-variable is correctly used.
check_occurrences(sess, node_id, tt, macros, binders, ops, valid);
}
(NestedMacroState::MacroRulesNotName, &TokenTree::Delimited(_, ref del))
| (NestedMacroState::MacroName, &TokenTree::Delimited(_, ref del))
if del.delim == DelimToken::Brace =>
{
let legacy = state == NestedMacroState::MacroRulesNotName;
state = NestedMacroState::Empty;
let rest =
check_nested_macro(sess, node_id, legacy, &del.tts, &nested_macros, valid);
// If we did not check the whole macro definition, then check the rest as if outside
// the macro definition.
check_nested_occurrences(
sess,
node_id,
&del.tts[rest..],
macros,
binders,
ops,
valid,
);
}
(
NestedMacroState::Macro,
&TokenTree::Token(Token { kind: TokenKind::Ident(..), .. }),
) => {
state = NestedMacroState::MacroName;
}
(NestedMacroState::Macro, &TokenTree::MetaVar(..)) => {
state = NestedMacroState::MacroName;
// We check that the meta-variable is correctly used.
check_occurrences(sess, node_id, tt, macros, binders, ops, valid);
}
(NestedMacroState::MacroName, &TokenTree::Delimited(_, ref del))
if del.delim == DelimToken::Paren =>
{
state = NestedMacroState::MacroNameParen;
nested_binders = Binders::default();
check_binders(
sess,
node_id,
tt,
&nested_macros,
&mut nested_binders,
&Stack::Empty,
valid,
);
}
(NestedMacroState::MacroNameParen, &TokenTree::Delimited(_, ref del))
if del.delim == DelimToken::Brace =>
{
state = NestedMacroState::Empty;
check_occurrences(
sess,
node_id,
tt,
&nested_macros,
&nested_binders,
&Stack::Empty,
valid,
);
}
(_, ref tt) => {
state = NestedMacroState::Empty;
check_occurrences(sess, node_id, tt, macros, binders, ops, valid);
}
}
}
}
/// Checks the body of nested macro, returns where the check stopped, and sets `valid` to false in
/// case of errors.
///
/// The token trees are checked as long as they look like a list of (LHS) => {RHS} token trees. This
/// check is a best-effort to detect a macro definition. It returns the position in `tts` where we
/// stopped checking because we detected we were not in a macro definition anymore.
///
/// Arguments:
/// - `sess` is used to emit diagnostics and lints
/// - `node_id` is used to emit lints
/// - `legacy` specifies whether the macro is legacy
/// - `tts` is checked as a list of (LHS) => {RHS}
/// - `macros` is the stack of outer macros
/// - `valid` is set in case of errors
fn check_nested_macro(
sess: &ParseSess,
node_id: NodeId,
legacy: bool,
tts: &[TokenTree],
macros: &Stack<'_, MacroState<'_>>,
valid: &mut bool,
) -> usize {
let n = tts.len();
let mut i = 0;
let separator = if legacy { TokenKind::Semi } else { TokenKind::Comma };
loop {
// We expect 3 token trees: `(LHS) => {RHS}`. The separator is checked after.
if i + 2 >= n
|| !tts[i].is_delimited()
|| !tts[i + 1].is_token(&TokenKind::FatArrow)
|| !tts[i + 2].is_delimited()
{
break;
}
let lhs = &tts[i];
let rhs = &tts[i + 2];
let mut binders = Binders::default();
check_binders(sess, node_id, lhs, macros, &mut binders, &Stack::Empty, valid);
check_occurrences(sess, node_id, rhs, macros, &binders, &Stack::Empty, valid);
// Since the last semicolon is optional for legacy macros and decl_macro are not terminated,
// we increment our checked position by how many token trees we already checked (the 3
// above) before checking for the separator.
i += 3;
if i == n || !tts[i].is_token(&separator) {
break;
}
// We increment our checked position for the semicolon.
i += 1;
}
i
}
/// Checks that a meta-variable occurrence is valid.
///
/// Arguments:
/// - `sess` is used to emit diagnostics and lints
/// - `node_id` is used to emit lints
/// - `macros` is the stack of possible outer macros
/// - `binders` contains the binders of the associated LHS
/// - `ops` is the stack of Kleene operators from the RHS
/// - `span` is the span of the meta-variable to check
/// - `name` is the name of the meta-variable to check
fn check_ops_is_prefix(
sess: &ParseSess,
node_id: NodeId,
macros: &Stack<'_, MacroState<'_>>,
binders: &Binders,
ops: &Stack<'_, KleeneToken>,
span: Span,
name: Ident,
) {
let macros = macros.push(MacroState { binders, ops: ops.into() });
// Accumulates the stacks the operators of each state until (and including when) the
// meta-variable is found. The innermost stack is first.
let mut acc: SmallVec<[&SmallVec<[KleeneToken; 1]>; 1]> = SmallVec::new();
for state in ¯os {
acc.push(&state.ops);
if let Some(binder) = state.binders.get(&name) {
// This variable concatenates the stack of operators from the RHS of the LHS where the
// meta-variable was defined to where it is used (in possibly nested macros). The
// outermost operator is first.
let mut occurrence_ops: SmallVec<[KleeneToken; 2]> = SmallVec::new();
// We need to iterate from the end to start with outermost stack.
for ops in acc.iter().rev() {
occurrence_ops.extend_from_slice(ops);
}
ops_is_prefix(sess, node_id, span, name, &binder.ops, &occurrence_ops);
return;
}
}
buffer_lint(sess, span.into(), node_id, &format!("unknown macro variable `{}`", name));
}
/// Returns whether `binder_ops` is a prefix of `occurrence_ops`.
///
/// The stack of Kleene operators of a meta-variable occurrence just needs to have the stack of
/// Kleene operators of its binder as a prefix.
///
/// Consider $i in the following example:
///
/// ( $( $i:ident = $($j:ident),+ );* ) => { $($( $i += $j; )+)* }
///
/// It occurs under the Kleene stack ["*", "+"] and is bound under ["*"] only.
///
/// Arguments:
/// - `sess` is used to emit diagnostics and lints
/// - `node_id` is used to emit lints
/// - `span` is the span of the meta-variable being check
/// - `name` is the name of the meta-variable being check
/// - `binder_ops` is the stack of Kleene operators for the binder
/// - `occurrence_ops` is the stack of Kleene operators for the occurrence
fn ops_is_prefix(
sess: &ParseSess,
node_id: NodeId,
span: Span,
name: Ident,
binder_ops: &[KleeneToken],
occurrence_ops: &[KleeneToken],
) {
for (i, binder) in binder_ops.iter().enumerate() {
if i >= occurrence_ops.len() {
let mut span = MultiSpan::from_span(span);
span.push_span_label(binder.span, "expected repetition".into());
let message = &format!("variable '{}' is still repeating at this depth", name);
buffer_lint(sess, span, node_id, message);
return;
}
let occurrence = &occurrence_ops[i];
if occurrence.op != binder.op {
let mut span = MultiSpan::from_span(span);
span.push_span_label(binder.span, "expected repetition".into());
span.push_span_label(occurrence.span, "conflicting repetition".into());
let message = "meta-variable repeats with different Kleene operator";
buffer_lint(sess, span, node_id, message);
return;
}
}
}
fn buffer_lint(sess: &ParseSess, span: MultiSpan, node_id: NodeId, message: &str) {
sess.buffer_lint(BufferedEarlyLintId::MetaVariableMisuse, span, node_id, message);
}
| 38.698565 | 100 | 0.597222 |
5b5466a3badff7d9c9b2c1e44c4621f6dae8b0ae
| 8,149 |
use crate::bech32::{self, Bech32};
use hex::FromHexError;
use rand_core::{CryptoRng, RngCore};
use std::fmt;
use std::hash::Hash;
use std::str::FromStr;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SecretKeyError {
SizeInvalid,
StructureInvalid,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PublicKeyError {
SizeInvalid,
StructureInvalid,
}
#[derive(Debug, Clone, PartialEq)]
pub enum PublicKeyFromStrError {
HexMalformed(FromHexError),
KeyInvalid(PublicKeyError),
}
pub trait AsymmetricPublicKey {
type Public: AsRef<[u8]> + Clone + PartialEq + Eq + Hash;
const PUBLIC_BECH32_HRP: &'static str;
const PUBLIC_KEY_SIZE: usize;
fn public_from_binary(data: &[u8]) -> Result<Self::Public, PublicKeyError>;
}
pub trait AsymmetricKey {
// The name of the public key Algorithm to represent the public key
// where PubAlg::Public is the public key type.
type PubAlg: AsymmetricPublicKey;
// the secret key type
type Secret: AsRef<[u8]> + Clone;
const SECRET_BECH32_HRP: &'static str;
fn generate<T: RngCore + CryptoRng>(rng: T) -> Self::Secret;
fn compute_public(secret: &Self::Secret) -> <Self::PubAlg as AsymmetricPublicKey>::Public;
fn secret_from_binary(data: &[u8]) -> Result<Self::Secret, SecretKeyError>;
}
pub trait SecretKeySizeStatic: AsymmetricKey {
const SECRET_KEY_SIZE: usize;
}
pub struct SecretKey<A: AsymmetricKey>(pub(crate) A::Secret);
pub struct PublicKey<A: AsymmetricPublicKey>(pub(crate) A::Public);
pub struct KeyPair<A: AsymmetricKey>(SecretKey<A>, PublicKey<A::PubAlg>);
impl<A: AsymmetricKey> KeyPair<A> {
pub fn private_key(&self) -> &SecretKey<A> {
&self.0
}
pub fn public_key(&self) -> &PublicKey<A::PubAlg> {
&self.1
}
pub fn into_keys(self) -> (SecretKey<A>, PublicKey<A::PubAlg>) {
(self.0, self.1)
}
pub fn generate<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
let sk = A::generate(rng);
let pk = A::compute_public(&sk);
KeyPair(SecretKey(sk), PublicKey(pk))
}
}
impl<A: AsymmetricKey> std::fmt::Debug for KeyPair<A> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "KeyPair(<secret key>, {:?})", self.public_key())
}
}
impl<A: AsymmetricKey> std::fmt::Display for KeyPair<A> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "KeyPair(<secret key>, {})", self.public_key())
}
}
impl<A: AsymmetricPublicKey> fmt::Debug for PublicKey<A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", hex::encode(self.0.as_ref()))
}
}
impl<A: AsymmetricPublicKey> fmt::Display for PublicKey<A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", hex::encode(self.0.as_ref()))
}
}
impl<A: AsymmetricPublicKey> FromStr for PublicKey<A> {
type Err = PublicKeyFromStrError;
fn from_str(hex: &str) -> Result<Self, Self::Err> {
let bytes = hex::decode(hex).map_err(PublicKeyFromStrError::HexMalformed)?;
Self::from_binary(&bytes).map_err(PublicKeyFromStrError::KeyInvalid)
}
}
impl fmt::Display for SecretKeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SecretKeyError::SizeInvalid => write!(f, "Invalid Secret Key size"),
SecretKeyError::StructureInvalid => write!(f, "Invalid Secret Key structure"),
}
}
}
impl fmt::Display for PublicKeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PublicKeyError::SizeInvalid => write!(f, "Invalid Public Key size"),
PublicKeyError::StructureInvalid => write!(f, "Invalid Public Key structure"),
}
}
}
impl fmt::Display for PublicKeyFromStrError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PublicKeyFromStrError::HexMalformed(_) => "hex encoding malformed",
PublicKeyFromStrError::KeyInvalid(_) => "invalid public key data",
}
.fmt(f)
}
}
impl std::error::Error for SecretKeyError {}
impl std::error::Error for PublicKeyError {}
impl std::error::Error for PublicKeyFromStrError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
PublicKeyFromStrError::HexMalformed(e) => Some(e),
PublicKeyFromStrError::KeyInvalid(e) => Some(e),
}
}
}
impl<A: AsymmetricPublicKey> AsRef<[u8]> for PublicKey<A> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl<A: AsymmetricKey> From<SecretKey<A>> for KeyPair<A> {
fn from(secret_key: SecretKey<A>) -> Self {
let public_key = secret_key.to_public();
KeyPair(secret_key, public_key)
}
}
impl<A: AsymmetricKey> SecretKey<A> {
pub fn generate<T: RngCore + CryptoRng>(rng: T) -> Self {
SecretKey(A::generate(rng))
}
pub fn to_public(&self) -> PublicKey<A::PubAlg> {
PublicKey(<A as AsymmetricKey>::compute_public(&self.0))
}
pub fn from_binary(data: &[u8]) -> Result<Self, SecretKeyError> {
Ok(SecretKey(<A as AsymmetricKey>::secret_from_binary(data)?))
}
// get ownership of the secret key, allowing to get its byte representation.
// On the other hand, this may allow unintentionally logging keys through
// AsRef
pub fn leak_secret(self) -> A::Secret {
self.0
}
}
impl<A: AsymmetricPublicKey> PublicKey<A> {
pub fn from_binary(data: &[u8]) -> Result<Self, PublicKeyError> {
Ok(PublicKey(<A as AsymmetricPublicKey>::public_from_binary(
data,
)?))
}
pub fn inner(self) -> A::Public {
self.0
}
}
impl<A: AsymmetricKey> Clone for SecretKey<A> {
fn clone(&self) -> Self {
SecretKey(self.0.clone())
}
}
impl<A: AsymmetricPublicKey> Clone for PublicKey<A> {
fn clone(&self) -> Self {
PublicKey(self.0.clone())
}
}
impl<A: AsymmetricKey> Clone for KeyPair<A> {
fn clone(&self) -> Self {
KeyPair(self.0.clone(), self.1.clone())
}
}
impl<A: AsymmetricPublicKey> std::cmp::PartialEq<Self> for PublicKey<A> {
fn eq(&self, other: &Self) -> bool {
self.0.as_ref().eq(other.0.as_ref())
}
}
impl<A: AsymmetricPublicKey> std::cmp::Eq for PublicKey<A> {}
impl<A: AsymmetricPublicKey> std::cmp::PartialOrd<Self> for PublicKey<A> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.0.as_ref().partial_cmp(other.0.as_ref())
}
}
impl<A: AsymmetricPublicKey> std::cmp::Ord for PublicKey<A> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.as_ref().cmp(other.0.as_ref())
}
}
impl<A: AsymmetricPublicKey> Hash for PublicKey<A> {
fn hash<H>(&self, state: &mut H)
where
H: std::hash::Hasher,
{
self.0.as_ref().hash(state)
}
}
impl<A: AsymmetricPublicKey> Bech32 for PublicKey<A> {
const BECH32_HRP: &'static str = A::PUBLIC_BECH32_HRP;
fn try_from_bech32_str(bech32_str: &str) -> Result<Self, bech32::Error> {
let bytes = bech32::try_from_bech32_to_bytes::<Self>(bech32_str)?;
Self::from_binary(&bytes).map_err(bech32::Error::data_invalid)
}
fn to_bech32_str(&self) -> String {
bech32::to_bech32_from_bytes::<Self>(self.as_ref())
}
}
impl<A: AsymmetricKey> Bech32 for SecretKey<A> {
const BECH32_HRP: &'static str = A::SECRET_BECH32_HRP;
fn try_from_bech32_str(bech32_str: &str) -> Result<Self, bech32::Error> {
let bytes = bech32::try_from_bech32_to_bytes::<Self>(bech32_str)?;
Self::from_binary(&bytes).map_err(bech32::Error::data_invalid)
}
fn to_bech32_str(&self) -> String {
bech32::to_bech32_from_bytes::<Self>(self.0.as_ref())
}
}
#[cfg(test)]
mod test {
use super::*;
// ONLY ALLOWED WHEN TESTING
impl<A> std::fmt::Debug for SecretKey<A>
where
A: AsymmetricKey,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "SecretKey ({:?})", self.0.as_ref())
}
}
}
| 29.632727 | 94 | 0.628666 |
ded4142d58096f21878bdbb7d23290798000697f
| 3,439 |
extern crate env_logger;
extern crate clap;
extern crate crypto;
#[macro_use]
extern crate log;
extern crate mio;
extern crate num;
extern crate protobuf;
extern crate rand;
extern crate rustc_serialize;
extern crate time;
use std::collections::HashSet;
use std::io;
use std::net::ToSocketAddrs;
use std::sync::mpsc;
use std::thread;
use address::Address;
use client::Task;
use client::messages::TextMessage;
mod address;
mod client;
mod messages;
mod network;
mod node;
mod node_bucket;
mod routing_table;
mod servers;
mod stun;
mod transaction;
/// Starts a command line client.
///
/// Usage:
///
/// comm SECRET LOCAL_ADDR BOOTSTRAP_ADDR
///
/// Example:
///
/// comm alpha 0.0.0.0:6667 10.0.1.13
fn main() {
env_logger::init().unwrap();
let matches = clap::App::new("comm")
.version("0.1.0")
.author("Zac Stewart <[email protected]>")
.arg(clap::Arg::with_name("secret")
.long("secret")
.value_name("SECRET")
.required(true)
.takes_value(true))
.arg(clap::Arg::with_name("server")
.long("server")
.short("s")
.value_name("URL")
.takes_value(true)
.required(true)
.multiple(true))
.arg(clap::Arg::with_name("router")
.long("router")
.short("r")
.value_name("URL")
.takes_value(true)
.multiple(true))
.get_matches();
let secret = matches.value_of("server").expect("No secret");
let address = Address::for_content(secret);
let servers = matches
.values_of("server")
.expect("No servers")
.map(|url| servers::Server::create(url).expect("Invalid server spec"))
.collect();
let routers: Vec<node::Node> = match matches.values_of("router") {
Some(urls) => {
urls.map(|url| {
let mut transports = HashSet::new();
transports.insert(node::Transport::Udp(node::UdpTransport::new(
url.to_socket_addrs().unwrap().next().unwrap())));
node::Node::new(Address::null(), transports)
}).collect()
}
None => vec![]
};
let network = network::Network::new(address, servers, routers);
let mut client = client::Client::new(address);
let (event_sender, events) = mpsc::channel();
client.register_event_listener(event_sender);
let client_channel = client.run(network);
thread::spawn(move || {
for event in events {
println!("Event: {:?}", event);
}
});
loop {
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let parts: Vec<&str> = line.splitn(2, ' ').collect();
match parts.len() {
1 => {
client_channel.send(Task::Shutdown).expect("Couldn't send Shutdown")
}
2 => {
let recipient = Address::from_str(parts[0]).unwrap();
let message_text = parts[1].trim().to_string();
let text_message = TextMessage::new(address, message_text);
client_channel
.send(Task::ScheduleMessageDelivery(recipient, text_message))
.unwrap_or_else(|err| info!("Couldn't schedule message delivery: {:?}", err));
}
_ => {}
}
}
}
| 27.733871 | 98 | 0.555976 |
cc6d5dd4a3014ba1f291f8304a822b947b5e132b
| 3,444 |
use crate::support::prelude::*;
pub fn make_demo(dim: Rect<f32>, canvas: &mut SimpleCanvas) -> Demo {
let bots = support::make_rand_rect(200, dim, [5.0, 20.0], |rect| bbox(rect.inner_as(), ()))
.into_boxed_slice();
let mut tree = broccoli::container::TreeOwned::new_par(RayonJoin, bots);
let mut rects = canvas.rects();
for bot in tree.as_tree().get_elements().iter() {
rects.add(bot.rect.inner_as().into());
}
let rect_save = rects.save(canvas);
Demo::new(move |cursor, canvas, check_naive| {
rect_save
.uniforms(canvas)
.with_color([0.0, 1.0, 0.0, 0.2])
.draw();
let tree = tree.as_tree_mut();
let cc: Vec2<i32> = cursor.inner_as();
let r1 = axgeom::Rect::new(cc.x - 100, cc.x + 100, cc.y - 100, cc.y + 100);
let r2 = axgeom::Rect::new(100, 400, 100, 400);
if check_naive {
use broccoli::assert::*;
assert_for_all_in_rect_mut(tree, &r1);
assert_for_all_in_rect_mut(tree, &r2);
assert_for_all_intersect_rect_mut(tree, &r1);
assert_for_all_intersect_rect_mut(tree, &r2);
assert_for_all_not_in_rect_mut(tree, &r1);
}
//test MultiRect
{
let mut rects = tree.multi_rect();
let mut to_draw = Vec::new();
let _ = rects.for_all_in_rect_mut(r1, |a| to_draw.push(a));
let res = rects.for_all_in_rect_mut(r2, |a| {
to_draw.push(a);
});
match res {
Ok(()) => {
canvas
.rects()
.add(r1.inner_as().into())
.add(r2.inner_as().into())
.send_and_uniforms(canvas)
.with_color([0.0, 0.0, 0.0, 0.5])
.draw();
let mut rects = canvas.rects();
for r in to_draw.iter() {
rects.add(r.rect.inner_as().into());
}
rects
.send_and_uniforms(canvas)
.with_color([0.0, 0.0, 0.0, 0.2])
.draw();
}
Err(_) => {
canvas
.rects()
.add(r1.inner_as().into())
.add(r2.inner_as().into())
.send_and_uniforms(canvas)
.with_color([1.0, 0.0, 0.0, 0.5])
.draw();
}
}
}
//test for_all_intersect_rect
let mut rects = canvas.rects();
tree.for_all_intersect_rect(&r1, |a| {
rects.add(a.rect.inner_as().into());
});
rects
.send_and_uniforms(canvas)
.with_color([0.0, 0.0, 1.0, 0.2])
.draw();
canvas
.rects()
.add(r1.inner_as().into())
.send_and_uniforms(canvas)
.with_color([1.0, 0.0, 0.0, 0.2])
.draw();
//test for_all_not_in_rect_mut
let mut rects = canvas.rects();
tree.for_all_not_in_rect_mut(&r1, |b| {
rects.add(b.rect.inner_as().into());
});
rects
.send_and_uniforms(canvas)
.with_color([1.0, 0.0, 0.0, 0.5])
.draw();
})
}
| 32.186916 | 95 | 0.450639 |
bfe097cdacf57829333daaf31342a7e5acc80a45
| 3,183 |
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::engine::RocksEngine;
use crate::util;
use crate::{db_options::RocksTitanDBOptions, sst_partitioner::RocksSstPartitionerFactory};
use engine_traits::{CFOptionsExt, Result};
use engine_traits::{ColumnFamilyOptions, SstPartitionerFactory};
use rocksdb::ColumnFamilyOptions as RawCFOptions;
use tikv_util::box_err;
impl CFOptionsExt for RocksEngine {
type ColumnFamilyOptions = RocksColumnFamilyOptions;
fn get_options_cf(&self, cf: &str) -> Result<Self::ColumnFamilyOptions> {
let handle = util::get_cf_handle(self.as_inner(), cf)?;
Ok(RocksColumnFamilyOptions::from_raw(
self.as_inner().get_options_cf(handle),
))
}
fn set_options_cf(&self, cf: &str, options: &[(&str, &str)]) -> Result<()> {
let handle = util::get_cf_handle(self.as_inner(), cf)?;
self.as_inner()
.set_options_cf(handle, options)
.map_err(|e| box_err!(e))
}
}
#[derive(Clone)]
pub struct RocksColumnFamilyOptions(RawCFOptions);
impl RocksColumnFamilyOptions {
pub fn from_raw(raw: RawCFOptions) -> RocksColumnFamilyOptions {
RocksColumnFamilyOptions(raw)
}
pub fn into_raw(self) -> RawCFOptions {
self.0
}
pub fn as_raw_mut(&mut self) -> &mut RawCFOptions {
&mut self.0
}
}
impl ColumnFamilyOptions for RocksColumnFamilyOptions {
type TitanDBOptions = RocksTitanDBOptions;
fn new() -> Self {
RocksColumnFamilyOptions::from_raw(RawCFOptions::new())
}
fn get_max_write_buffer_number(&self) -> u32 {
self.0.get_max_write_buffer_number()
}
fn get_level_zero_slowdown_writes_trigger(&self) -> u32 {
self.0.get_level_zero_slowdown_writes_trigger()
}
fn get_level_zero_stop_writes_trigger(&self) -> u32 {
self.0.get_level_zero_stop_writes_trigger()
}
fn set_level_zero_file_num_compaction_trigger(&mut self, v: i32) {
self.0.set_level_zero_file_num_compaction_trigger(v)
}
fn get_soft_pending_compaction_bytes_limit(&self) -> u64 {
self.0.get_soft_pending_compaction_bytes_limit()
}
fn get_hard_pending_compaction_bytes_limit(&self) -> u64 {
self.0.get_hard_pending_compaction_bytes_limit()
}
fn get_block_cache_capacity(&self) -> u64 {
self.0.get_block_cache_capacity()
}
fn set_block_cache_capacity(&self, capacity: u64) -> std::result::Result<(), String> {
self.0.set_block_cache_capacity(capacity)
}
fn set_titandb_options(&mut self, opts: &Self::TitanDBOptions) {
self.0.set_titandb_options(opts.as_raw())
}
fn get_target_file_size_base(&self) -> u64 {
self.0.get_target_file_size_base()
}
fn set_disable_auto_compactions(&mut self, v: bool) {
self.0.set_disable_auto_compactions(v)
}
fn get_disable_auto_compactions(&self) -> bool {
self.0.get_disable_auto_compactions()
}
fn set_sst_partitioner_factory<F: SstPartitionerFactory>(&mut self, factory: F) {
self.0
.set_sst_partitioner_factory(RocksSstPartitionerFactory(factory));
}
}
| 30.028302 | 90 | 0.689287 |
0addecbb0105677a9eeee24f9e554e8bc4c9c646
| 9,609 |
// Generated from definition io.k8s.api.apps.v1.StatefulSetStatus
/// StatefulSetStatus represents the current state of a StatefulSet.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StatefulSetStatus {
/// collisionCount is the count of hash collisions for the StatefulSet. The StatefulSet controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ControllerRevision.
pub collision_count: Option<i32>,
/// Represents the latest available observations of a statefulset's current state.
pub conditions: Option<Vec<crate::api::apps::v1::StatefulSetCondition>>,
/// currentReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version indicated by currentRevision.
pub current_replicas: Option<i32>,
/// currentRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence \[0,currentReplicas).
pub current_revision: Option<String>,
/// observedGeneration is the most recent generation observed for this StatefulSet. It corresponds to the StatefulSet's generation, which is updated on mutation by the API Server.
pub observed_generation: Option<i64>,
/// readyReplicas is the number of Pods created by the StatefulSet controller that have a Ready Condition.
pub ready_replicas: Option<i32>,
/// replicas is the number of Pods created by the StatefulSet controller.
pub replicas: i32,
/// updateRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence \[replicas-updatedReplicas,replicas)
pub update_revision: Option<String>,
/// updatedReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version indicated by updateRevision.
pub updated_replicas: Option<i32>,
}
impl<'de> serde::Deserialize<'de> for StatefulSetStatus {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_collision_count,
Key_conditions,
Key_current_replicas,
Key_current_revision,
Key_observed_generation,
Key_ready_replicas,
Key_replicas,
Key_update_revision,
Key_updated_replicas,
Other,
}
impl<'de> serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
struct Visitor;
impl<'de> 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: serde::de::Error {
Ok(match v {
"collisionCount" => Field::Key_collision_count,
"conditions" => Field::Key_conditions,
"currentReplicas" => Field::Key_current_replicas,
"currentRevision" => Field::Key_current_revision,
"observedGeneration" => Field::Key_observed_generation,
"readyReplicas" => Field::Key_ready_replicas,
"replicas" => Field::Key_replicas,
"updateRevision" => Field::Key_update_revision,
"updatedReplicas" => Field::Key_updated_replicas,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = StatefulSetStatus;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("StatefulSetStatus")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
let mut value_collision_count: Option<i32> = None;
let mut value_conditions: Option<Vec<crate::api::apps::v1::StatefulSetCondition>> = None;
let mut value_current_replicas: Option<i32> = None;
let mut value_current_revision: Option<String> = None;
let mut value_observed_generation: Option<i64> = None;
let mut value_ready_replicas: Option<i32> = None;
let mut value_replicas: Option<i32> = None;
let mut value_update_revision: Option<String> = None;
let mut value_updated_replicas: Option<i32> = None;
while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_collision_count => value_collision_count = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_conditions => value_conditions = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_current_replicas => value_current_replicas = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_current_revision => value_current_revision = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_observed_generation => value_observed_generation = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_ready_replicas => value_ready_replicas = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_replicas => value_replicas = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Key_update_revision => value_update_revision = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_updated_replicas => value_updated_replicas = serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(StatefulSetStatus {
collision_count: value_collision_count,
conditions: value_conditions,
current_replicas: value_current_replicas,
current_revision: value_current_revision,
observed_generation: value_observed_generation,
ready_replicas: value_ready_replicas,
replicas: value_replicas.ok_or_else(|| serde::de::Error::missing_field("replicas"))?,
update_revision: value_update_revision,
updated_replicas: value_updated_replicas,
})
}
}
deserializer.deserialize_struct(
"StatefulSetStatus",
&[
"collisionCount",
"conditions",
"currentReplicas",
"currentRevision",
"observedGeneration",
"readyReplicas",
"replicas",
"updateRevision",
"updatedReplicas",
],
Visitor,
)
}
}
impl serde::Serialize for StatefulSetStatus {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
let mut state = serializer.serialize_struct(
"StatefulSetStatus",
1 +
self.collision_count.as_ref().map_or(0, |_| 1) +
self.conditions.as_ref().map_or(0, |_| 1) +
self.current_replicas.as_ref().map_or(0, |_| 1) +
self.current_revision.as_ref().map_or(0, |_| 1) +
self.observed_generation.as_ref().map_or(0, |_| 1) +
self.ready_replicas.as_ref().map_or(0, |_| 1) +
self.update_revision.as_ref().map_or(0, |_| 1) +
self.updated_replicas.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.collision_count {
serde::ser::SerializeStruct::serialize_field(&mut state, "collisionCount", value)?;
}
if let Some(value) = &self.conditions {
serde::ser::SerializeStruct::serialize_field(&mut state, "conditions", value)?;
}
if let Some(value) = &self.current_replicas {
serde::ser::SerializeStruct::serialize_field(&mut state, "currentReplicas", value)?;
}
if let Some(value) = &self.current_revision {
serde::ser::SerializeStruct::serialize_field(&mut state, "currentRevision", value)?;
}
if let Some(value) = &self.observed_generation {
serde::ser::SerializeStruct::serialize_field(&mut state, "observedGeneration", value)?;
}
if let Some(value) = &self.ready_replicas {
serde::ser::SerializeStruct::serialize_field(&mut state, "readyReplicas", value)?;
}
serde::ser::SerializeStruct::serialize_field(&mut state, "replicas", &self.replicas)?;
if let Some(value) = &self.update_revision {
serde::ser::SerializeStruct::serialize_field(&mut state, "updateRevision", value)?;
}
if let Some(value) = &self.updated_replicas {
serde::ser::SerializeStruct::serialize_field(&mut state, "updatedReplicas", value)?;
}
serde::ser::SerializeStruct::end(state)
}
}
| 50.573684 | 221 | 0.593714 |
ed0b41579cd21951826a43b50077c74a9242f832
| 504 |
pub fn run() -> String {
let comp = icc::Computer::load(0, &loader::load_integer_row_list("./day/02/input.csv")[0]);
let result = icc::input::find_cent(&comp, 19_690_720).expect("should give some value");
format!("{}", result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn truth() {
let comp = Computer::load(&loader::load_integer_row_list("./day/02/input.csv")[0]);
let actual = comp.find_cent(19_690_720).expect("should give some value");
assert_eq!(actual, 4019);
}
}
| 29.647059 | 93 | 0.644841 |
7a6239c835076b04f1819b2c13e4c3485320748f
| 1,703 |
// Internal Dependencies ------------------------------------------------------
use renderer::Renderer;
use shared::SharedEvent;
use shared::Lithium::Cobalt::ConnectionID;
use super::{Game, ClientHandle, ClientLevel, ClientEntity};
// Views ----------------------------------------------------------------------
mod connect;
mod init;
mod menu;
mod game;
pub use self::connect::ConnectView;
pub use self::init::InitView;
pub use self::menu::MenuView;
pub use self::game::GameView;
// View Trait -----------------------------------------------------------------
pub trait View {
fn name(&self) -> &str;
fn push(&mut self, _: &mut Game, _: &mut ClientHandle) {}
fn init(&mut self, _: &mut Game, _: &mut ClientHandle) {}
fn connect(&mut self, _: &mut Game, _: &mut ClientHandle) {}
fn disconnect(&mut self, _: &mut Game, _: &mut ClientHandle, _: bool, _: bool) {}
fn config(&mut self, _: &mut Game, _: &mut ClientHandle, _: &[u8]) {}
fn event(&mut self, _: &mut Game, _: &mut ClientHandle, _: ConnectionID, _: SharedEvent) {}
fn tick_before(&mut self, _: &mut Game, _: &mut ClientHandle) {}
fn tick_entity_before(
&mut self, _: &mut Game, _: &mut Renderer, _: &ClientLevel,
_: &mut ClientEntity, _: u8, _: f32
) {
}
fn tick_entity_after(
&mut self, _: &mut Game, _: &mut Renderer, _: &ClientLevel,
_: &mut ClientEntity, _: u8, _: f32
) {
}
fn tick_after(&mut self, _: &mut Game, _: &mut ClientHandle) {}
fn draw(&mut self, _: &mut Game, _: &mut ClientHandle) {}
fn destroy(&mut self, _: &mut Game, _: &mut ClientHandle) {}
fn pop(&mut self, _: &mut Game, _: &mut ClientHandle) {}
}
| 28.383333 | 95 | 0.55138 |
5bd9fd42662395bab1ea228baa6816af4eaaf1dc
| 7,031 |
//! The host kernel, responsible for dispatching requests to the local host
use std::convert::{TryFrom, TryInto};
use std::pin::Pin;
use bytes::Bytes;
use futures::Future;
use log::debug;
use safecast::{TryCastFrom, TryCastInto};
use tc_error::*;
use tc_transact::{Transact, Transaction};
use tcgeneric::*;
use crate::cluster::Cluster;
use crate::object::InstanceExt;
use crate::route::Public;
use crate::scalar::*;
use crate::state::*;
use crate::txn::*;
mod hosted;
use hosted::Hosted;
const HYPOTHETICAL: PathLabel = path_label(&["transact", "hypothetical"]);
type ExeScope<'a> = crate::scalar::Scope<'a, State>;
/// The host kernel, responsible for dispatching requests to the local host
pub struct Kernel {
actor: Actor,
hosted: Hosted,
}
impl Kernel {
/// Construct a new `Kernel` to host the given [`Cluster`]s.
pub fn new<I: IntoIterator<Item = InstanceExt<Cluster>>>(clusters: I) -> Self {
Self {
actor: Actor::new(Link::default().into()),
hosted: clusters.into_iter().collect(),
}
}
/// Route a GET request.
pub async fn get(&self, txn: &Txn, path: &[PathSegment], key: Value) -> TCResult<State> {
if path.is_empty() {
if key.is_none() {
Ok(Value::from(Bytes::copy_from_slice(self.actor.public_key().as_bytes())).into())
} else {
Err(TCError::method_not_allowed(TCPath::from(path)))
}
} else if let Some(class) = StateType::from_path(path) {
let err = format!("Cannot cast into {} from {}", class, key);
State::Scalar(Scalar::Value(key))
.into_type(class)
.ok_or_else(|| TCError::unsupported(err))
} else if let Some((suffix, cluster)) = self.hosted.get(path) {
debug!(
"GET {}: {} from cluster {}",
TCPath::from(suffix),
key,
cluster
);
cluster.get(&txn, suffix, key).await
} else if &path[0] == "error" && path.len() == 2 {
let message = String::try_cast_from(key, |v| {
TCError::bad_request("cannot cast into error message string from", v)
})?;
if let Some(err_type) = error_type(&path[1]) {
Err(TCError::new(err_type, message))
} else {
Err(TCError::not_found(TCPath::from(path)))
}
} else {
Err(TCError::not_found(TCPath::from(path)))
}
}
/// Route a PUT request.
pub async fn put(
&self,
txn: &Txn,
path: &[PathSegment],
key: Value,
value: State,
) -> TCResult<()> {
if path.is_empty() {
if key.is_none() {
if Link::can_cast_from(&value) {
// It's a synchronization message for a hypothetical transaction
return Ok(());
}
}
Err(TCError::method_not_allowed(TCPath::from(path)))
} else if let Some(class) = StateType::from_path(path) {
Err(TCError::method_not_allowed(class))
} else if let Some((suffix, cluster)) = self.hosted.get(path) {
debug!(
"PUT {}: {} <- {} to cluster {}",
TCPath::from(suffix),
key,
value,
cluster
);
execute(txn, cluster, |txn, cluster| async move {
cluster.put(&txn, suffix, key, value).await
})
.await
} else {
Err(TCError::not_found(TCPath::from(path)))
}
}
/// Route a POST request.
pub async fn post(&self, txn: &Txn, path: &[PathSegment], data: State) -> TCResult<State> {
if path.is_empty() {
if Map::try_from(data)?.is_empty() {
// it's a "commit" instruction for a hypothetical transaction
Ok(State::default())
} else {
Err(TCError::method_not_allowed(TCPath::from(path)))
}
} else if path == &HYPOTHETICAL[..] {
let txn = txn.clone().claim(&self.actor, TCPathBuf::default()).await?;
let context = Map::<State>::default();
if PostOp::can_cast_from(&data) {
OpDef::call(data.opt_cast_into().unwrap(), txn, context).await
} else {
data.resolve(&ExeScope::new(&State::default(), context), &txn)
.await
}
} else if let Some((suffix, cluster)) = self.hosted.get(path) {
let params: Map<State> = data.try_into()?;
debug!(
"POST {}: {} to cluster {}",
TCPath::from(suffix),
params,
cluster
);
if suffix.is_empty() && params.is_empty() {
// it's a "commit" instruction
cluster.post(&txn, suffix, params).await
} else {
execute(txn, cluster, |txn, cluster| async move {
cluster.post(&txn, suffix, params).await
})
.await
}
} else {
Err(TCError::not_found(TCPath::from(path)))
}
}
}
fn execute<
'a,
R: Send,
Fut: Future<Output = TCResult<R>> + Send,
F: FnOnce(Txn, &'a InstanceExt<Cluster>) -> Fut + Send + 'a,
>(
txn: &'a Txn,
cluster: &'a InstanceExt<Cluster>,
handler: F,
) -> Pin<Box<dyn Future<Output = TCResult<R>> + Send + 'a>> {
Box::pin(async move {
if let Some(owner_link) = txn.owner() {
let link = txn.link(cluster.path().to_vec().into());
if txn.is_owner(cluster.path()) {
debug!("{} owns this transaction, no need to notify", link);
} else {
txn.put(owner_link.clone(), Value::default(), link.into())
.await?;
}
handler(txn.clone(), cluster).await
} else {
// Claim and execute the transaction
let txn = cluster.claim(&txn).await?;
let state = handler(txn.clone(), cluster).await?;
let owner = cluster.owner(txn.id()).await?;
owner.commit(&txn).await?;
cluster.commit(txn.id()).await;
Ok(state)
}
})
}
fn error_type(err_type: &Id) -> Option<ErrorType> {
match err_type.as_str() {
"bad_gateway" => Some(ErrorType::BadGateway),
"bad_request" => Some(ErrorType::BadRequest),
"conflict" => Some(ErrorType::Conflict),
"forbidden" => Some(ErrorType::Forbidden),
"internal" => Some(ErrorType::Internal),
"method_not_allowed" => Some(ErrorType::MethodNotAllowed),
"not_found" => Some(ErrorType::NotFound),
"not_implemented" => Some(ErrorType::NotImplemented),
"timeout" => Some(ErrorType::Timeout),
"unauthorized" => Some(ErrorType::Unauthorized),
_ => None,
}
}
| 32.85514 | 98 | 0.518845 |
f7f58d7340e2dbf2bcb37fbd2764e33a14247500
| 5,074 |
//! Digest types for various sizes
use sigma_ser::vlq_encode::ReadSigmaVlqExt;
use sigma_ser::vlq_encode::WriteSigmaVlqExt;
use sigma_ser::ScorexParsingError;
use sigma_ser::ScorexSerializable;
use sigma_ser::ScorexSerializeResult;
use sigma_util::AsVecI8;
use std::convert::TryFrom;
use std::convert::TryInto;
use std::fmt::Formatter;
use thiserror::Error;
/// N-bytes array in a box. `Digest32` is most type synonym.
#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "json",
serde(
into = "crate::Base16EncodedBytes",
try_from = "crate::Base16DecodedBytes"
)
)]
#[derive(PartialEq, Eq, Hash, Clone)]
pub struct Digest<const N: usize>(pub Box<[u8; N]>);
/// 32 byte array used as ID of some value: block, transaction, etc.
/// Usually this is as blake2b hash of serialized form
pub type Digest32 = Digest<32>;
/// AVL tree digest: root hash along with tree height (33 bytes)
pub type ADDigest = Digest<33>;
impl<const N: usize> Digest<N> {
/// Digest size 32 bytes
pub const SIZE: usize = N;
/// All zeros
pub fn zero() -> Digest<N> {
Digest(Box::new([0u8; N]))
}
/// Parse Digest<N> from base64 encoded string
pub fn from_base64(s: &str) -> Result<Digest<N>, DigestNError> {
let bytes = base64::decode(s)?;
let arr: [u8; N] = bytes.as_slice().try_into()?;
Ok(Digest(Box::new(arr)))
}
}
impl<const N: usize> std::fmt::Debug for Digest<N> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
base16::encode_lower(&(*self.0)).fmt(f)
}
}
/// Blake2b256 hash (256 bit)
pub fn blake2b256_hash(bytes: &[u8]) -> Digest32 {
Digest(sigma_util::hash::blake2b256_hash(bytes))
}
impl<const N: usize> From<[u8; N]> for Digest<N> {
fn from(bytes: [u8; N]) -> Self {
Digest(Box::new(bytes))
}
}
impl<const N: usize> From<Box<[u8; N]>> for Digest<N> {
fn from(bytes: Box<[u8; N]>) -> Self {
Digest(bytes)
}
}
impl<const N: usize> From<Digest<N>> for Vec<i8> {
fn from(v: Digest<N>) -> Self {
v.0.to_vec().as_vec_i8()
}
}
impl<const N: usize> From<Digest<N>> for Vec<u8> {
fn from(v: Digest<N>) -> Self {
v.0.to_vec()
}
}
impl<const N: usize> From<Digest<N>> for [u8; N] {
fn from(v: Digest<N>) -> Self {
*v.0
}
}
impl<const N: usize> From<Digest<N>> for String {
fn from(v: Digest<N>) -> Self {
base16::encode_lower(&v.0.as_ref())
}
}
impl<const N: usize> TryFrom<String> for Digest<N> {
type Error = DigestNError;
fn try_from(value: String) -> Result<Self, Self::Error> {
let bytes = base16::decode(&value)?;
let arr: [u8; N] = bytes.as_slice().try_into()?;
Ok(Digest(Box::new(arr)))
}
}
impl<const N: usize> TryFrom<Vec<u8>> for Digest<N> {
type Error = DigestNError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
let bytes: [u8; N] = value.as_slice().try_into()?;
Ok(Digest::from(bytes))
}
}
impl<const N: usize> TryFrom<&[u8]> for Digest<N> {
type Error = DigestNError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let bytes: [u8; N] = value.try_into()?;
Ok(Digest::from(bytes))
}
}
impl<const N: usize> ScorexSerializable for Digest<N> {
fn scorex_serialize<W: WriteSigmaVlqExt>(&self, w: &mut W) -> ScorexSerializeResult {
w.write_all(self.0.as_ref())?;
Ok(())
}
fn scorex_parse<R: ReadSigmaVlqExt>(r: &mut R) -> Result<Self, ScorexParsingError> {
let mut bytes = [0; N];
r.read_exact(&mut bytes)?;
Ok(Self(bytes.into()))
}
}
impl AsRef<[u8]> for Digest32 {
fn as_ref(&self) -> &[u8] {
&self.0[..]
}
}
/// Invalid byte array size
#[derive(Error, Debug)]
pub enum DigestNError {
/// error decoding from Base16
#[error("error decoding from Base16: {0}")]
Base16DecodingError(#[from] base16::DecodeError),
/// Invalid byte array size
#[error("Invalid byte array size ({0})")]
InvalidSize(#[from] std::array::TryFromSliceError),
/// error decoding from Base64
#[error("error decoding from Base64: {0}")]
Base64DecodingError(#[from] base64::DecodeError),
}
/// Arbitrary
#[allow(clippy::unwrap_used)]
#[cfg(feature = "arbitrary")]
pub(crate) mod arbitrary {
use super::Digest;
use proptest::prelude::{Arbitrary, BoxedStrategy};
use proptest::{collection::vec, prelude::*};
use std::convert::TryInto;
impl<const N: usize> Arbitrary for Digest<N> {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
vec(any::<u8>(), Self::SIZE)
.prop_map(|v| Digest(Box::new(v.try_into().unwrap())))
.boxed()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_base64() {
let s = "KkctSmFOZFJnVWtYcDJzNXY4eS9CP0UoSCtNYlBlU2g=";
assert!(Digest32::from_base64(s).is_ok());
}
}
| 26.989362 | 89 | 0.606228 |
3aa71444ffbf0ac33c2dc870f197159555e67cba
| 3,447 |
use ring::aead::{self, AES_256_GCM, Aad, BoundKey, UnboundKey};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use crate::memguard;
use crate::utils;
use crate::nonceimpl::NonceSeqImpl;
use crate::keycrypt::KEY_LEN;
use tokio::fs::File;
use tokio::io::{ AsyncWriteExt, AsyncReadExt, AsyncSeekExt};
use std::{borrow::BorrowMut, sync::Arc};
use std::io::SeekFrom;
const CHUNK_LEN: u64 = 8192;
const CHUNK_N_TAG_LEN: u64 = CHUNK_LEN + aead::MAX_TAG_LEN as u64;
pub(crate) async fn encrypt_file(
mut infile: File,
mut outstream: File,
data_key: Arc<[u8; KEY_LEN]>,
nonce: Arc<[u8; aead::NONCE_LEN]>,
pb: ProgressBar)
-> Result<File, utils::Error> {
let nonces = NonceSeqImpl::new(nonce.as_ref())?;
let u_key = UnboundKey::new(&AES_256_GCM, data_key.as_ref())?;
let mut s_key = aead::SealingKey::new(u_key, nonces);
let mut buffer = [0u8; CHUNK_LEN as usize]; // no need to mlock, file exists in plain
let file_len = infile.metadata().await?.len();
let mut counter: usize = 0;
pb.set_length(file_len);
let remainder = loop {
let rem = file_len - infile.seek(SeekFrom::Current(0)).await?;
if rem < CHUNK_LEN {
break rem;
}
infile.read_exact(&mut buffer).await?;
let tag = s_key.seal_in_place_separate_tag(
Aad::from(counter.to_be_bytes()),
&mut buffer)?;
outstream.write_all(&buffer).await?;
outstream.write_all(tag.as_ref()).await?;
counter += 1;
pb.inc(CHUNK_LEN);
};
infile.read_exact(&mut buffer[..remainder as usize]).await?;
let tag = s_key.seal_in_place_separate_tag(
Aad::from(counter.to_be_bytes()),
&mut buffer[..remainder as usize])?;
outstream.write_all(&buffer[..remainder as usize]).await?;
outstream.write_all(tag.as_ref()).await?;
pb.inc(remainder);
pb.finish();
Ok(infile)
}
pub(crate) async fn decrypt_file<W: AsyncWriteExt + Unpin + Send + Sync + 'static>(
mut infile: File,
mut outstream: W,
data_key: Arc<[u8; KEY_LEN]>,
nonce: Arc<[u8; aead::NONCE_LEN]>,
pb: ProgressBar)
-> Result<W, utils::Error> {
let nonces = NonceSeqImpl::new(nonce.as_ref())?;
let u_key = UnboundKey::new(&AES_256_GCM, data_key.as_ref())?;
let mut o_key = aead::OpeningKey::new(u_key, nonces);
let mut buffer = [0u8; CHUNK_N_TAG_LEN as usize];
let file_len = infile.metadata().await?.len();
let mut counter: usize = 0;
pb.set_length(file_len);
memguard::mlock(&mut buffer)?; // should not be swapped as sometimes has plaintext in it
let remainder = loop {
let rem = file_len - infile.seek(SeekFrom::Current(0)).await?;
if rem < CHUNK_N_TAG_LEN {
break rem;
}
infile.read_exact(&mut buffer).await?;
let res = o_key.open_in_place(
Aad::from(counter.to_be_bytes()),
&mut buffer)?;
outstream.write_all(&res).await?;
counter += 1;
pb.inc(CHUNK_N_TAG_LEN);
};
infile.read_exact(&mut buffer[..remainder as usize]).await?;
let res = o_key.open_in_place(
Aad::from(counter.to_be_bytes()),
&mut buffer[..remainder as usize])?;
outstream.write_all(&res).await?;
memguard::shred(&mut buffer);
pb.inc(remainder);
pb.finish();
Ok(outstream)
}
| 27.141732 | 92 | 0.619089 |
56a6fe7f6f2b0e10659502e79f44b5ab6ec4f086
| 7,618 |
//! Salsa20 tests
use salsa20::Salsa20;
#[cfg(feature = "xsalsa20")]
use salsa20::XSalsa20;
use stream_cipher::generic_array::GenericArray;
use stream_cipher::{NewStreamCipher, StreamCipher, SyncStreamCipherSeek};
#[cfg(test)]
const KEY_BYTES: usize = 32;
#[cfg(test)]
const IV_BYTES: usize = 8;
#[cfg(feature = "xsalsa20")]
#[cfg(test)]
const IV_BYTES_XSALSA20: usize = 24;
#[cfg(test)]
const KEY0: [u8; KEY_BYTES] = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
#[cfg(test)]
const KEY1: [u8; KEY_BYTES] = [
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
#[cfg(test)]
const KEY_LONG: [u8; KEY_BYTES] = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32,
];
#[cfg(feature = "xsalsa20")]
#[cfg(test)]
const KEY_XSALSA20: [u8; KEY_BYTES] = *b"this is 32-byte key for xsalsa20";
#[cfg(test)]
const IV0: [u8; IV_BYTES] = [0; IV_BYTES];
#[cfg(test)]
const IV1: [u8; IV_BYTES] = [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
#[cfg(test)]
const IVHI: [u8; IV_BYTES] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01];
#[cfg(test)]
const IV_LONG: [u8; IV_BYTES] = [3, 1, 4, 1, 5, 9, 2, 6];
#[cfg(feature = "xsalsa20")]
#[cfg(test)]
const IV_XSALSA20: [u8; IV_BYTES_XSALSA20] = *b"24-byte nonce for xsalsa";
#[cfg(test)]
const EXPECTED_KEY1_IV0: [u8; 64] = [
0xe3, 0xbe, 0x8f, 0xdd, 0x8b, 0xec, 0xa2, 0xe3, 0xea, 0x8e, 0xf9, 0x47, 0x5b, 0x29, 0xa6, 0xe7,
0x00, 0x39, 0x51, 0xe1, 0x09, 0x7a, 0x5c, 0x38, 0xd2, 0x3b, 0x7a, 0x5f, 0xad, 0x9f, 0x68, 0x44,
0xb2, 0x2c, 0x97, 0x55, 0x9e, 0x27, 0x23, 0xc7, 0xcb, 0xbd, 0x3f, 0xe4, 0xfc, 0x8d, 0x9a, 0x07,
0x44, 0x65, 0x2a, 0x83, 0xe7, 0x2a, 0x9c, 0x46, 0x18, 0x76, 0xaf, 0x4d, 0x7e, 0xf1, 0xa1, 0x17,
];
#[cfg(test)]
const EXPECTED_KEY0_IV1: [u8; 64] = [
0x2a, 0xba, 0x3d, 0xc4, 0x5b, 0x49, 0x47, 0x00, 0x7b, 0x14, 0xc8, 0x51, 0xcd, 0x69, 0x44, 0x56,
0xb3, 0x03, 0xad, 0x59, 0xa4, 0x65, 0x66, 0x28, 0x03, 0x00, 0x67, 0x05, 0x67, 0x3d, 0x6c, 0x3e,
0x29, 0xf1, 0xd3, 0x51, 0x0d, 0xfc, 0x04, 0x05, 0x46, 0x3c, 0x03, 0x41, 0x4e, 0x0e, 0x07, 0xe3,
0x59, 0xf1, 0xf1, 0x81, 0x6c, 0x68, 0xb2, 0x43, 0x4a, 0x19, 0xd3, 0xee, 0xe0, 0x46, 0x48, 0x73,
];
#[cfg(test)]
const EXPECTED_KEY0_IVHI: [u8; 64] = [
0xb4, 0x7f, 0x96, 0xaa, 0x96, 0x78, 0x61, 0x35, 0x29, 0x7a, 0x3c, 0x4e, 0xc5, 0x6a, 0x61, 0x3d,
0x0b, 0x80, 0x09, 0x53, 0x24, 0xff, 0x43, 0x23, 0x9d, 0x68, 0x4c, 0x57, 0xff, 0xe4, 0x2e, 0x1c,
0x44, 0xf3, 0xcc, 0x01, 0x16, 0x13, 0xdb, 0x6c, 0xdc, 0x88, 0x09, 0x99, 0xa1, 0xe6, 0x5a, 0xed,
0x12, 0x87, 0xfc, 0xb1, 0x1c, 0x83, 0x9c, 0x37, 0x12, 0x07, 0x65, 0xaf, 0xa7, 0x3e, 0x50, 0x75,
];
#[cfg(test)]
const EXPECTED_LONG: [u8; 256] = [
0x6e, 0xbc, 0xbd, 0xbf, 0x76, 0xfc, 0xcc, 0x64, 0xab, 0x05, 0x54, 0x2b, 0xee, 0x8a, 0x67, 0xcb,
0xc2, 0x8f, 0xa2, 0xe1, 0x41, 0xfb, 0xef, 0xbb, 0x3a, 0x2f, 0x9b, 0x22, 0x19, 0x09, 0xc8, 0xd7,
0xd4, 0x29, 0x52, 0x58, 0xcb, 0x53, 0x97, 0x70, 0xdd, 0x24, 0xd7, 0xac, 0x34, 0x43, 0x76, 0x9f,
0xfa, 0x27, 0xa5, 0x0e, 0x60, 0x64, 0x42, 0x64, 0xdc, 0x8b, 0x6b, 0x61, 0x26, 0x83, 0x37, 0x2e,
0x08, 0x5d, 0x0a, 0x12, 0xbf, 0x24, 0x0b, 0x18, 0x9c, 0xe2, 0xb7, 0x82, 0x89, 0x86, 0x2b, 0x56,
0xfd, 0xc9, 0xfc, 0xff, 0xc3, 0x3b, 0xef, 0x93, 0x25, 0xa2, 0xe8, 0x1b, 0x98, 0xfb, 0x3f, 0xb9,
0xaa, 0x04, 0xcf, 0x43, 0x46, 0x15, 0xce, 0xff, 0xeb, 0x98, 0x5c, 0x1c, 0xb0, 0x8d, 0x84, 0x40,
0xe9, 0x0b, 0x1d, 0x56, 0xdd, 0xea, 0xea, 0x16, 0xd9, 0xe1, 0x5a, 0xff, 0xff, 0x1f, 0x69, 0x8c,
0x48, 0x3c, 0x7a, 0x46, 0x6a, 0xf1, 0xfe, 0x06, 0x25, 0x74, 0xad, 0xfd, 0x2b, 0x06, 0xa6, 0x2b,
0x4d, 0x98, 0x44, 0x07, 0x19, 0xea, 0x77, 0x63, 0x85, 0xc4, 0x70, 0x34, 0x9a, 0x7e, 0xd6, 0x96,
0x95, 0x83, 0x46, 0x3e, 0xd5, 0xd2, 0x6b, 0x8f, 0xef, 0xcc, 0xb2, 0x05, 0xda, 0x0f, 0x5b, 0xfa,
0x98, 0xc7, 0x78, 0x12, 0xfe, 0x75, 0x6b, 0x09, 0xea, 0xcc, 0x28, 0x2a, 0xa4, 0x2f, 0x4b, 0xaf,
0xa7, 0x96, 0x33, 0x18, 0x90, 0x46, 0xe2, 0xb2, 0x0f, 0x35, 0xb3, 0xe0, 0xe5, 0x4a, 0xa3, 0xb9,
0x29, 0xe2, 0x3c, 0x0f, 0x47, 0xdc, 0x7b, 0xcd, 0x4f, 0x92, 0x8b, 0x2a, 0x97, 0x64, 0xbe, 0x7d,
0x4b, 0x8a, 0x50, 0xf9, 0x80, 0xa5, 0x0b, 0x35, 0xad, 0x80, 0x87, 0x37, 0x5e, 0x0c, 0x55, 0x6e,
0xcb, 0xe6, 0xa7, 0x16, 0x1e, 0x86, 0x53, 0xce, 0x93, 0x91, 0xe1, 0xe6, 0x71, 0x0e, 0xd4, 0xf1,
];
#[cfg(feature = "xsalsa20")]
#[cfg(test)]
const EXPECTED_XSALSA20_ZEROS: [u8; 64] = [
0x48, 0x48, 0x29, 0x7f, 0xeb, 0x1f, 0xb5, 0x2f, 0xb6, 0x6d, 0x81, 0x60, 0x9b, 0xd5, 0x47, 0xfa,
0xbc, 0xbe, 0x70, 0x26, 0xed, 0xc8, 0xb5, 0xe5, 0xe4, 0x49, 0xd0, 0x88, 0xbf, 0xa6, 0x9c, 0x08,
0x8f, 0x5d, 0x8d, 0xa1, 0xd7, 0x91, 0x26, 0x7c, 0x2c, 0x19, 0x5a, 0x7f, 0x8c, 0xae, 0x9c, 0x4b,
0x40, 0x50, 0xd0, 0x8c, 0xe6, 0xd3, 0xa1, 0x51, 0xec, 0x26, 0x5f, 0x3a, 0x58, 0xe4, 0x76, 0x48,
];
#[cfg(feature = "xsalsa20")]
#[cfg(test)]
const EXPECTED_XSALSA20_HELLO_WORLD: [u8; 12] = [
0x00, 0x2d, 0x45, 0x13, 0x84, 0x3f, 0xc2, 0x40, 0xc4, 0x01, 0xe5, 0x41,
];
#[test]
fn salsa20_key1_iv0() {
let mut cipher = Salsa20::new(&GenericArray::from(KEY1), &GenericArray::from(IV0));
let mut buf = [0; 64];
cipher.encrypt(&mut buf);
for i in 0..64 {
assert_eq!(buf[i], EXPECTED_KEY1_IV0[i])
}
}
#[test]
fn salsa20_key0_iv1() {
let mut cipher = Salsa20::new(&GenericArray::from(KEY0), &GenericArray::from(IV1));
let mut buf = [0; 64];
cipher.encrypt(&mut buf);
for i in 0..64 {
assert_eq!(buf[i], EXPECTED_KEY0_IV1[i])
}
}
#[test]
fn salsa20_key0_ivhi() {
let mut cipher = Salsa20::new(&GenericArray::from(KEY0), &GenericArray::from(IVHI));
let mut buf = [0; 64];
cipher.encrypt(&mut buf);
for i in 0..64 {
assert_eq!(buf[i], EXPECTED_KEY0_IVHI[i])
}
}
#[test]
fn salsa20_long() {
let mut cipher = Salsa20::new(&GenericArray::from(KEY_LONG), &GenericArray::from(IV_LONG));
let mut buf = [0; 256];
cipher.encrypt(&mut buf);
for i in 0..256 {
assert_eq!(buf[i], EXPECTED_LONG[i])
}
}
#[test]
#[ignore]
fn salsa20_offsets() {
for idx in 0..256 {
for middle in idx..256 {
for last in middle..256 {
let mut cipher =
Salsa20::new(&GenericArray::from(KEY_LONG), &GenericArray::from(IV_LONG));
let mut buf = [0; 256];
cipher.seek(idx as u64);
cipher.encrypt(&mut buf[idx..middle]);
cipher.encrypt(&mut buf[middle..last]);
for k in idx..last {
assert_eq!(buf[k], EXPECTED_LONG[k])
}
}
}
}
}
#[cfg(feature = "xsalsa20")]
#[test]
fn xsalsa20_encrypt_zeros() {
let key = GenericArray::from(KEY_XSALSA20);
let iv = GenericArray::from(IV_XSALSA20);
let mut cipher = XSalsa20::new(&key, &iv);
let mut buf = [0; 64];
cipher.encrypt(&mut buf);
for i in 0..64 {
assert_eq!(buf[i], EXPECTED_XSALSA20_ZEROS[i]);
}
}
#[cfg(feature = "xsalsa20")]
#[test]
fn xsalsa20_encrypt_hello_world() {
let key = GenericArray::from(KEY_XSALSA20);
let iv = GenericArray::from(IV_XSALSA20);
let mut cipher = XSalsa20::new(&key, &iv);
let mut buf = *b"Hello world!";
cipher.encrypt(&mut buf);
assert_eq!(buf, EXPECTED_XSALSA20_HELLO_WORLD);
}
| 35.765258 | 99 | 0.617091 |
fe0a83f56b1f2b270cb0d8ba435026307cdd5747
| 86,663 |
pub type c_char = i8;
pub type c_long = i64;
pub type c_ulong = u64;
pub type clockid_t = ::c_int;
pub type blkcnt_t = ::c_long;
pub type clock_t = ::c_long;
pub type daddr_t = ::c_long;
pub type dev_t = ::c_ulong;
pub type fsblkcnt_t = ::c_ulong;
pub type fsfilcnt_t = ::c_ulong;
pub type ino_t = ::c_ulong;
pub type key_t = ::c_int;
pub type major_t = ::c_uint;
pub type minor_t = ::c_uint;
pub type mode_t = ::c_uint;
pub type nlink_t = ::c_uint;
pub type rlim_t = ::c_ulong;
pub type speed_t = ::c_uint;
pub type tcflag_t = ::c_uint;
pub type time_t = ::c_long;
pub type wchar_t = ::c_int;
pub type nfds_t = ::c_ulong;
pub type suseconds_t = ::c_long;
pub type off_t = ::c_long;
pub type useconds_t = ::c_uint;
pub type socklen_t = ::c_uint;
pub type sa_family_t = u16;
pub type pthread_t = ::c_uint;
pub type pthread_key_t = ::c_uint;
pub type blksize_t = ::c_int;
pub type nl_item = ::c_int;
pub type mqd_t = *mut ::c_void;
pub type id_t = ::c_int;
pub type idtype_t = ::c_uint;
pub type shmatt_t = ::c_ulong;
pub type door_attr_t = ::c_uint;
pub type door_id_t = ::c_ulonglong;
#[cfg_attr(feature = "extra_traits", derive(Debug))]
pub enum timezone {}
impl ::Copy for timezone {}
impl ::Clone for timezone {
fn clone(&self) -> timezone {
*self
}
}
s! {
pub struct in_addr {
pub s_addr: ::in_addr_t,
}
pub struct ip_mreq {
pub imr_multiaddr: in_addr,
pub imr_interface: in_addr,
}
pub struct ipc_perm {
pub uid: ::uid_t,
pub gid: ::gid_t,
pub cuid: ::uid_t,
pub cgid: ::gid_t,
pub mode: ::mode_t,
pub seq: ::c_uint,
pub key: ::key_t,
}
pub struct sockaddr {
pub sa_family: sa_family_t,
pub sa_data: [::c_char; 14],
}
pub struct sockaddr_in {
pub sin_family: sa_family_t,
pub sin_port: ::in_port_t,
pub sin_addr: ::in_addr,
pub sin_zero: [::c_char; 8]
}
pub struct sockaddr_in6 {
pub sin6_family: sa_family_t,
pub sin6_port: ::in_port_t,
pub sin6_flowinfo: u32,
pub sin6_addr: ::in6_addr,
pub sin6_scope_id: u32,
pub __sin6_src_id: u32
}
pub struct passwd {
pub pw_name: *mut ::c_char,
pub pw_passwd: *mut ::c_char,
pub pw_uid: ::uid_t,
pub pw_gid: ::gid_t,
pub pw_age: *mut ::c_char,
pub pw_comment: *mut ::c_char,
pub pw_gecos: *mut ::c_char,
pub pw_dir: *mut ::c_char,
pub pw_shell: *mut ::c_char
}
pub struct ifaddrs {
pub ifa_next: *mut ifaddrs,
pub ifa_name: *mut ::c_char,
pub ifa_flags: ::c_ulong,
pub ifa_addr: *mut ::sockaddr,
pub ifa_netmask: *mut ::sockaddr,
pub ifa_dstaddr: *mut ::sockaddr,
pub ifa_data: *mut ::c_void
}
pub struct tm {
pub tm_sec: ::c_int,
pub tm_min: ::c_int,
pub tm_hour: ::c_int,
pub tm_mday: ::c_int,
pub tm_mon: ::c_int,
pub tm_year: ::c_int,
pub tm_wday: ::c_int,
pub tm_yday: ::c_int,
pub tm_isdst: ::c_int
}
pub struct msghdr {
pub msg_name: *mut ::c_void,
pub msg_namelen: ::socklen_t,
pub msg_iov: *mut ::iovec,
pub msg_iovlen: ::c_int,
pub msg_control: *mut ::c_void,
pub msg_controllen: ::socklen_t,
pub msg_flags: ::c_int,
}
pub struct cmsghdr {
pub cmsg_len: ::socklen_t,
pub cmsg_level: ::c_int,
pub cmsg_type: ::c_int,
}
pub struct pthread_attr_t {
__pthread_attrp: *mut ::c_void
}
pub struct pthread_mutex_t {
__pthread_mutex_flag1: u16,
__pthread_mutex_flag2: u8,
__pthread_mutex_ceiling: u8,
__pthread_mutex_type: u16,
__pthread_mutex_magic: u16,
__pthread_mutex_lock: u64,
__pthread_mutex_data: u64
}
pub struct pthread_mutexattr_t {
__pthread_mutexattrp: *mut ::c_void
}
pub struct pthread_cond_t {
__pthread_cond_flag: [u8; 4],
__pthread_cond_type: u16,
__pthread_cond_magic: u16,
__pthread_cond_data: u64
}
pub struct pthread_condattr_t {
__pthread_condattrp: *mut ::c_void,
}
pub struct pthread_rwlock_t {
__pthread_rwlock_readers: i32,
__pthread_rwlock_type: u16,
__pthread_rwlock_magic: u16,
__pthread_rwlock_mutex: ::pthread_mutex_t,
__pthread_rwlock_readercv: ::pthread_cond_t,
__pthread_rwlock_writercv: ::pthread_cond_t
}
pub struct pthread_rwlockattr_t {
__pthread_rwlockattrp: *mut ::c_void,
}
pub struct dirent {
pub d_ino: ::ino_t,
pub d_off: ::off_t,
pub d_reclen: u16,
pub d_name: [::c_char; 3]
}
pub struct glob_t {
pub gl_pathc: ::size_t,
pub gl_pathv: *mut *mut ::c_char,
pub gl_offs: ::size_t,
__unused1: *mut ::c_void,
__unused2: ::c_int,
__unused3: ::c_int,
__unused4: ::c_int,
__unused5: *mut ::c_void,
__unused6: *mut ::c_void,
__unused7: *mut ::c_void,
__unused8: *mut ::c_void,
__unused9: *mut ::c_void,
__unused10: *mut ::c_void,
}
pub struct addrinfo {
pub ai_flags: ::c_int,
pub ai_family: ::c_int,
pub ai_socktype: ::c_int,
pub ai_protocol: ::c_int,
#[cfg(target_arch = "sparc64")]
__sparcv9_pad: ::c_int,
pub ai_addrlen: ::socklen_t,
pub ai_canonname: *mut ::c_char,
pub ai_addr: *mut ::sockaddr,
pub ai_next: *mut addrinfo,
}
pub struct shmid_ds {
pub shm_perm: ipc_perm,
pub shm_segsz: ::size_t,
#[cfg(target_os = "illumos")]
pub shm_amp: *mut ::c_void,
#[cfg(target_os = "solaris")]
pub shm_flags: ::uintptr_t,
pub shm_lkcnt: ::c_ushort,
pub shm_lpid: ::pid_t,
pub shm_cpid: ::pid_t,
pub shm_nattch: ::shmatt_t,
pub shm_cnattch: ::c_ulong,
pub shm_atime: ::time_t,
pub shm_dtime: ::time_t,
pub shm_ctime: ::time_t,
#[cfg(target_os = "illumos")]
pub shm_pad4: [i64; 4],
#[cfg(target_os = "solaris")]
pub shm_amp: *mut ::c_void,
#[cfg(target_os = "solaris")]
pub shm_gransize: u64,
#[cfg(target_os = "solaris")]
pub shm_allocated: u64,
#[cfg(target_os = "solaris")]
pub shm_pad4: [i64; 1],
}
pub struct sigset_t {
bits: [u32; 4],
}
pub struct sigaction {
pub sa_flags: ::c_int,
pub sa_sigaction: ::sighandler_t,
pub sa_mask: sigset_t,
}
pub struct stack_t {
pub ss_sp: *mut ::c_void,
pub ss_size: ::size_t,
pub ss_flags: ::c_int,
}
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_basetype: [::c_char; 16],
pub f_flag: ::c_ulong,
pub f_namemax: ::c_ulong,
pub f_fstr: [::c_char; 32]
}
pub struct sched_param {
pub sched_priority: ::c_int,
sched_pad: [::c_int; 8]
}
pub struct Dl_info {
pub dli_fname: *const ::c_char,
pub dli_fbase: *mut ::c_void,
pub dli_sname: *const ::c_char,
pub dli_saddr: *mut ::c_void,
}
pub struct stat {
pub st_dev: ::dev_t,
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,
pub st_size: ::off_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,
pub st_blksize: ::blksize_t,
pub st_blocks: ::blkcnt_t,
__unused: [::c_char; 16]
}
pub struct termios {
pub c_iflag: ::tcflag_t,
pub c_oflag: ::tcflag_t,
pub c_cflag: ::tcflag_t,
pub c_lflag: ::tcflag_t,
pub c_cc: [::cc_t; ::NCCS]
}
pub struct lconv {
pub decimal_point: *mut ::c_char,
pub thousands_sep: *mut ::c_char,
pub grouping: *mut ::c_char,
pub int_curr_symbol: *mut ::c_char,
pub currency_symbol: *mut ::c_char,
pub mon_decimal_point: *mut ::c_char,
pub mon_thousands_sep: *mut ::c_char,
pub mon_grouping: *mut ::c_char,
pub positive_sign: *mut ::c_char,
pub negative_sign: *mut ::c_char,
pub int_frac_digits: ::c_char,
pub frac_digits: ::c_char,
pub p_cs_precedes: ::c_char,
pub p_sep_by_space: ::c_char,
pub n_cs_precedes: ::c_char,
pub n_sep_by_space: ::c_char,
pub p_sign_posn: ::c_char,
pub n_sign_posn: ::c_char,
pub int_p_cs_precedes: ::c_char,
pub int_p_sep_by_space: ::c_char,
pub int_n_cs_precedes: ::c_char,
pub int_n_sep_by_space: ::c_char,
pub int_p_sign_posn: ::c_char,
pub int_n_sign_posn: ::c_char,
}
pub struct sem_t {
pub sem_count: u32,
pub sem_type: u16,
pub sem_magic: u16,
pub sem_pad1: [u64; 3],
pub sem_pad2: [u64; 2]
}
pub struct flock {
pub l_type: ::c_short,
pub l_whence: ::c_short,
pub l_start: ::off_t,
pub l_len: ::off_t,
pub l_sysid: ::c_int,
pub l_pid: ::pid_t,
pub l_pad: [::c_long; 4]
}
pub struct if_nameindex {
pub if_index: ::c_uint,
pub if_name: *mut ::c_char,
}
pub struct mq_attr {
pub mq_flags: ::c_long,
pub mq_maxmsg: ::c_long,
pub mq_msgsize: ::c_long,
pub mq_curmsgs: ::c_long,
_pad: [::c_int; 4]
}
pub struct port_event {
pub portev_events: ::c_int,
pub portev_source: ::c_ushort,
pub portev_pad: ::c_ushort,
pub portev_object: ::uintptr_t,
pub portev_user: *mut ::c_void,
}
pub struct door_desc_t__d_data__d_desc {
pub d_descriptor: ::c_int,
pub d_id: ::door_id_t
}
pub struct exit_status {
e_termination: ::c_short,
e_exit: ::c_short,
}
pub struct utmp {
pub ut_user: [::c_char; 8],
pub ut_id: [::c_char; 4],
pub ut_line: [::c_char; 12],
pub ut_pid: ::c_short,
pub ut_type: ::c_short,
pub ut_exit: exit_status,
pub ut_time: ::time_t,
}
pub struct timex {
pub modes: u32,
pub offset: i32,
pub freq: i32,
pub maxerror: i32,
pub esterror: i32,
pub status: i32,
pub constant: i32,
pub precision: i32,
pub tolerance: i32,
pub ppsfreq: i32,
pub jitter: i32,
pub shift: i32,
pub stabil: i32,
pub jitcnt: i32,
pub calcnt: i32,
pub errcnt: i32,
pub stbcnt: i32,
}
pub struct ntptimeval {
pub time: ::timeval,
pub maxerror: i32,
pub esterror: i32,
}
}
s_no_extra_traits! {
#[cfg_attr(any(target_arch = "x86", target_arch = "x86_64"), repr(packed))]
pub struct epoll_event {
pub events: u32,
pub u64: u64,
}
pub struct utmpx {
pub ut_user: [::c_char; _UTX_USERSIZE],
pub ut_id: [::c_char; _UTX_IDSIZE],
pub ut_line: [::c_char; _UTX_LINESIZE],
pub ut_pid: ::pid_t,
pub ut_type: ::c_short,
pub ut_exit: exit_status,
pub ut_tv: ::timeval,
pub ut_session: ::c_int,
pub ut_pad: [::c_int; _UTX_PADSIZE],
pub ut_syslen: ::c_short,
pub ut_host: [::c_char; _UTX_HOSTSIZE],
}
pub struct sockaddr_un {
pub sun_family: sa_family_t,
pub sun_path: [c_char; 108]
}
pub struct utsname {
pub sysname: [::c_char; 257],
pub nodename: [::c_char; 257],
pub release: [::c_char; 257],
pub version: [::c_char; 257],
pub machine: [::c_char; 257],
}
pub struct fd_set {
#[cfg(target_pointer_width = "64")]
fds_bits: [i64; FD_SETSIZE / 64],
#[cfg(target_pointer_width = "32")]
fds_bits: [i32; FD_SETSIZE / 32],
}
pub struct sockaddr_storage {
pub ss_family: ::sa_family_t,
__ss_pad1: [u8; 6],
__ss_align: i64,
__ss_pad2: [u8; 240],
}
pub struct siginfo_t {
pub si_signo: ::c_int,
pub si_code: ::c_int,
pub si_errno: ::c_int,
pub si_pad: ::c_int,
pub si_addr: *mut ::c_void,
__pad: [u8; 232],
}
pub struct sockaddr_dl {
pub sdl_family: ::c_ushort,
pub sdl_index: ::c_ushort,
pub sdl_type: ::c_uchar,
pub sdl_nlen: ::c_uchar,
pub sdl_alen: ::c_uchar,
pub sdl_slen: ::c_uchar,
pub sdl_data: [::c_char; 244],
}
pub struct sigevent {
pub sigev_notify: ::c_int,
pub sigev_signo: ::c_int,
pub sigev_value: ::sigval,
pub ss_sp: *mut ::c_void,
pub sigev_notify_attributes: *const ::pthread_attr_t,
__sigev_pad2: ::c_int,
}
#[cfg_attr(feature = "extra_traits", allow(missing_debug_implementations))]
pub union door_desc_t__d_data {
pub d_desc: door_desc_t__d_data__d_desc,
d_resv: [::c_int; 5], /* Check out /usr/include/sys/door.h */
}
#[cfg_attr(feature = "extra_traits", allow(missing_debug_implementations))]
pub struct door_desc_t {
pub d_attributes: door_attr_t,
pub d_data: door_desc_t__d_data,
}
#[cfg_attr(feature = "extra_traits", allow(missing_debug_implementations))]
pub struct door_arg_t {
pub data_ptr: *const ::c_char,
pub data_size: ::size_t,
pub desc_ptr: *const door_desc_t,
pub dec_num: ::c_uint,
pub rbuf: *const ::c_char,
pub rsize: ::size_t,
}
}
cfg_if! {
if #[cfg(feature = "extra_traits")] {
impl PartialEq for utmpx {
fn eq(&self, other: &utmpx) -> bool {
self.ut_type == other.ut_type
&& self.ut_pid == other.ut_pid
&& self.ut_user == other.ut_user
&& self.ut_line == other.ut_line
&& self.ut_id == other.ut_id
&& self.ut_exit == other.ut_exit
&& self.ut_session == other.ut_session
&& self.ut_tv == other.ut_tv
&& self.ut_syslen == other.ut_syslen
&& self.ut_pad == other.ut_pad
&& self
.ut_host
.iter()
.zip(other.ut_host.iter())
.all(|(a,b)| a == b)
}
}
impl Eq for utmpx {}
impl ::fmt::Debug for utmpx {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("utmpx")
.field("ut_user", &self.ut_user)
.field("ut_id", &self.ut_id)
.field("ut_line", &self.ut_line)
.field("ut_pid", &self.ut_pid)
.field("ut_type", &self.ut_type)
.field("ut_exit", &self.ut_exit)
.field("ut_tv", &self.ut_tv)
.field("ut_session", &self.ut_session)
.field("ut_pad", &self.ut_pad)
.field("ut_syslen", &self.ut_syslen)
.field("ut_host", &&self.ut_host[..])
.finish()
}
}
impl ::hash::Hash for utmpx {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
self.ut_user.hash(state);
self.ut_type.hash(state);
self.ut_pid.hash(state);
self.ut_line.hash(state);
self.ut_id.hash(state);
self.ut_host.hash(state);
self.ut_exit.hash(state);
self.ut_session.hash(state);
self.ut_tv.hash(state);
self.ut_syslen.hash(state);
self.ut_pad.hash(state);
}
}
impl PartialEq for epoll_event {
fn eq(&self, other: &epoll_event) -> bool {
self.events == other.events
&& self.u64 == other.u64
}
}
impl Eq for epoll_event {}
impl ::fmt::Debug for epoll_event {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
let events = self.events;
let u64 = self.u64;
f.debug_struct("epoll_event")
.field("events", &events)
.field("u64", &u64)
.finish()
}
}
impl ::hash::Hash for epoll_event {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
let events = self.events;
let u64 = self.u64;
events.hash(state);
u64.hash(state);
}
}
impl PartialEq for sockaddr_un {
fn eq(&self, other: &sockaddr_un) -> bool {
self.sun_family == other.sun_family
&& self
.sun_path
.iter()
.zip(other.sun_path.iter())
.all(|(a, b)| a == b)
}
}
impl Eq for sockaddr_un {}
impl ::fmt::Debug for sockaddr_un {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("sockaddr_un")
.field("sun_family", &self.sun_family)
// FIXME: .field("sun_path", &self.sun_path)
.finish()
}
}
impl ::hash::Hash for sockaddr_un {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
self.sun_family.hash(state);
self.sun_path.hash(state);
}
}
impl PartialEq for utsname {
fn eq(&self, other: &utsname) -> bool {
self.sysname
.iter()
.zip(other.sysname.iter())
.all(|(a, b)| a == b)
&& self
.nodename
.iter()
.zip(other.nodename.iter())
.all(|(a, b)| a == b)
&& self
.release
.iter()
.zip(other.release.iter())
.all(|(a, b)| a == b)
&& self
.version
.iter()
.zip(other.version.iter())
.all(|(a, b)| a == b)
&& self
.machine
.iter()
.zip(other.machine.iter())
.all(|(a, b)| a == b)
}
}
impl Eq for utsname {}
impl ::fmt::Debug for utsname {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("utsname")
// FIXME: .field("sysname", &self.sysname)
// FIXME: .field("nodename", &self.nodename)
// FIXME: .field("release", &self.release)
// FIXME: .field("version", &self.version)
// FIXME: .field("machine", &self.machine)
.finish()
}
}
impl ::hash::Hash for utsname {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
self.sysname.hash(state);
self.nodename.hash(state);
self.release.hash(state);
self.version.hash(state);
self.machine.hash(state);
}
}
impl PartialEq for fd_set {
fn eq(&self, other: &fd_set) -> bool {
self.fds_bits
.iter()
.zip(other.fds_bits.iter())
.all(|(a, b)| a == b)
}
}
impl Eq for fd_set {}
impl ::fmt::Debug for fd_set {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("fd_set")
// FIXME: .field("fds_bits", &self.fds_bits)
.finish()
}
}
impl ::hash::Hash for fd_set {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
self.fds_bits.hash(state);
}
}
impl PartialEq for sockaddr_storage {
fn eq(&self, other: &sockaddr_storage) -> bool {
self.ss_family == other.ss_family
&& self.__ss_pad1 == other.__ss_pad1
&& self.__ss_align == other.__ss_align
&& self
.__ss_pad2
.iter()
.zip(other.__ss_pad2.iter())
.all(|(a, b)| a == b)
}
}
impl Eq for sockaddr_storage {}
impl ::fmt::Debug for sockaddr_storage {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("sockaddr_storage")
.field("ss_family", &self.ss_family)
.field("__ss_pad1", &self.__ss_pad1)
.field("__ss_align", &self.__ss_align)
// FIXME: .field("__ss_pad2", &self.__ss_pad2)
.finish()
}
}
impl ::hash::Hash for sockaddr_storage {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
self.ss_family.hash(state);
self.__ss_pad1.hash(state);
self.__ss_align.hash(state);
self.__ss_pad2.hash(state);
}
}
impl PartialEq for siginfo_t {
fn eq(&self, other: &siginfo_t) -> bool {
self.si_signo == other.si_signo
&& self.si_code == other.si_code
&& self.si_errno == other.si_errno
&& self.si_addr == other.si_addr
&& self
.__pad
.iter()
.zip(other.__pad.iter())
.all(|(a, b)| a == b)
}
}
impl Eq for siginfo_t {}
impl ::fmt::Debug for siginfo_t {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("siginfo_t")
.field("si_signo", &self.si_signo)
.field("si_code", &self.si_code)
.field("si_errno", &self.si_errno)
.field("si_addr", &self.si_addr)
// FIXME: .field("__pad", &self.__pad)
.finish()
}
}
impl ::hash::Hash for siginfo_t {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
self.si_signo.hash(state);
self.si_code.hash(state);
self.si_errno.hash(state);
self.si_addr.hash(state);
self.__pad.hash(state);
}
}
impl PartialEq for sockaddr_dl {
fn eq(&self, other: &sockaddr_dl) -> bool {
self.sdl_family == other.sdl_family
&& self.sdl_index == other.sdl_index
&& self.sdl_type == other.sdl_type
&& self.sdl_nlen == other.sdl_nlen
&& self.sdl_alen == other.sdl_alen
&& self.sdl_slen == other.sdl_slen
&& self
.sdl_data
.iter()
.zip(other.sdl_data.iter())
.all(|(a,b)| a == b)
}
}
impl Eq for sockaddr_dl {}
impl ::fmt::Debug for sockaddr_dl {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("sockaddr_dl")
.field("sdl_family", &self.sdl_family)
.field("sdl_index", &self.sdl_index)
.field("sdl_type", &self.sdl_type)
.field("sdl_nlen", &self.sdl_nlen)
.field("sdl_alen", &self.sdl_alen)
.field("sdl_slen", &self.sdl_slen)
// FIXME: .field("sdl_data", &self.sdl_data)
.finish()
}
}
impl ::hash::Hash for sockaddr_dl {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
self.sdl_family.hash(state);
self.sdl_index.hash(state);
self.sdl_type.hash(state);
self.sdl_nlen.hash(state);
self.sdl_alen.hash(state);
self.sdl_slen.hash(state);
self.sdl_data.hash(state);
}
}
impl PartialEq for sigevent {
fn eq(&self, other: &sigevent) -> bool {
self.sigev_notify == other.sigev_notify
&& self.sigev_signo == other.sigev_signo
&& self.sigev_value == other.sigev_value
&& self.ss_sp == other.ss_sp
&& self.sigev_notify_attributes
== other.sigev_notify_attributes
}
}
impl Eq for sigevent {}
impl ::fmt::Debug for sigevent {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("sigevent")
.field("sigev_notify", &self.sigev_notify)
.field("sigev_signo", &self.sigev_signo)
.field("sigev_value", &self.sigev_value)
.field("ss_sp", &self.ss_sp)
.field("sigev_notify_attributes",
&self.sigev_notify_attributes)
.finish()
}
}
impl ::hash::Hash for sigevent {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
self.sigev_notify.hash(state);
self.sigev_signo.hash(state);
self.sigev_value.hash(state);
self.ss_sp.hash(state);
self.sigev_notify_attributes.hash(state);
}
}
}
}
pub const LC_CTYPE: ::c_int = 0;
pub const LC_NUMERIC: ::c_int = 1;
pub const LC_TIME: ::c_int = 2;
pub const LC_COLLATE: ::c_int = 3;
pub const LC_MONETARY: ::c_int = 4;
pub const LC_MESSAGES: ::c_int = 5;
pub const LC_ALL: ::c_int = 6;
pub const LC_CTYPE_MASK: ::c_int = 1 << LC_CTYPE;
pub const LC_NUMERIC_MASK: ::c_int = 1 << LC_NUMERIC;
pub const LC_TIME_MASK: ::c_int = 1 << LC_TIME;
pub const LC_COLLATE_MASK: ::c_int = 1 << LC_COLLATE;
pub const LC_MONETARY_MASK: ::c_int = 1 << LC_MONETARY;
pub const LC_MESSAGES_MASK: ::c_int = 1 << LC_MESSAGES;
pub const LC_ALL_MASK: ::c_int = LC_CTYPE_MASK
| LC_NUMERIC_MASK
| LC_TIME_MASK
| LC_COLLATE_MASK
| LC_MONETARY_MASK
| LC_MESSAGES_MASK;
pub const DAY_1: ::nl_item = 1;
pub const DAY_2: ::nl_item = 2;
pub const DAY_3: ::nl_item = 3;
pub const DAY_4: ::nl_item = 4;
pub const DAY_5: ::nl_item = 5;
pub const DAY_6: ::nl_item = 6;
pub const DAY_7: ::nl_item = 7;
pub const ABDAY_1: ::nl_item = 8;
pub const ABDAY_2: ::nl_item = 9;
pub const ABDAY_3: ::nl_item = 10;
pub const ABDAY_4: ::nl_item = 11;
pub const ABDAY_5: ::nl_item = 12;
pub const ABDAY_6: ::nl_item = 13;
pub const ABDAY_7: ::nl_item = 14;
pub const MON_1: ::nl_item = 15;
pub const MON_2: ::nl_item = 16;
pub const MON_3: ::nl_item = 17;
pub const MON_4: ::nl_item = 18;
pub const MON_5: ::nl_item = 19;
pub const MON_6: ::nl_item = 20;
pub const MON_7: ::nl_item = 21;
pub const MON_8: ::nl_item = 22;
pub const MON_9: ::nl_item = 23;
pub const MON_10: ::nl_item = 24;
pub const MON_11: ::nl_item = 25;
pub const MON_12: ::nl_item = 26;
pub const ABMON_1: ::nl_item = 27;
pub const ABMON_2: ::nl_item = 28;
pub const ABMON_3: ::nl_item = 29;
pub const ABMON_4: ::nl_item = 30;
pub const ABMON_5: ::nl_item = 31;
pub const ABMON_6: ::nl_item = 32;
pub const ABMON_7: ::nl_item = 33;
pub const ABMON_8: ::nl_item = 34;
pub const ABMON_9: ::nl_item = 35;
pub const ABMON_10: ::nl_item = 36;
pub const ABMON_11: ::nl_item = 37;
pub const ABMON_12: ::nl_item = 38;
pub const RADIXCHAR: ::nl_item = 39;
pub const THOUSEP: ::nl_item = 40;
pub const YESSTR: ::nl_item = 41;
pub const NOSTR: ::nl_item = 42;
pub const CRNCYSTR: ::nl_item = 43;
pub const D_T_FMT: ::nl_item = 44;
pub const D_FMT: ::nl_item = 45;
pub const T_FMT: ::nl_item = 46;
pub const AM_STR: ::nl_item = 47;
pub const PM_STR: ::nl_item = 48;
pub const CODESET: ::nl_item = 49;
pub const T_FMT_AMPM: ::nl_item = 50;
pub const ERA: ::nl_item = 51;
pub const ERA_D_FMT: ::nl_item = 52;
pub const ERA_D_T_FMT: ::nl_item = 53;
pub const ERA_T_FMT: ::nl_item = 54;
pub const ALT_DIGITS: ::nl_item = 55;
pub const YESEXPR: ::nl_item = 56;
pub const NOEXPR: ::nl_item = 57;
pub const _DATE_FMT: ::nl_item = 58;
pub const MAXSTRMSG: ::nl_item = 58;
pub const PATH_MAX: ::c_int = 1024;
pub const SA_ONSTACK: ::c_int = 0x00000001;
pub const SA_RESETHAND: ::c_int = 0x00000002;
pub const SA_RESTART: ::c_int = 0x00000004;
pub const SA_SIGINFO: ::c_int = 0x00000008;
pub const SA_NODEFER: ::c_int = 0x00000010;
pub const SA_NOCLDWAIT: ::c_int = 0x00010000;
pub const SA_NOCLDSTOP: ::c_int = 0x00020000;
pub const SS_ONSTACK: ::c_int = 1;
pub const SS_DISABLE: ::c_int = 2;
pub const FIOCLEX: ::c_int = 0x20006601;
pub const FIONCLEX: ::c_int = 0x20006602;
pub const FIONREAD: ::c_int = 0x4004667f;
pub const FIONBIO: ::c_int = 0x8004667e;
pub const FIOASYNC: ::c_int = 0x8004667d;
pub const FIOSETOWN: ::c_int = 0x8004667c;
pub const FIOGETOWN: ::c_int = 0x4004667b;
pub const SIGCHLD: ::c_int = 18;
pub const SIGBUS: ::c_int = 10;
pub const SIGINFO: ::c_int = 41;
pub const SIG_BLOCK: ::c_int = 1;
pub const SIG_UNBLOCK: ::c_int = 2;
pub const SIG_SETMASK: ::c_int = 3;
pub const SIGEV_NONE: ::c_int = 1;
pub const SIGEV_SIGNAL: ::c_int = 2;
pub const SIGEV_THREAD: ::c_int = 3;
pub const IPV6_UNICAST_HOPS: ::c_int = 0x5;
pub const IPV6_MULTICAST_IF: ::c_int = 0x6;
pub const IPV6_MULTICAST_HOPS: ::c_int = 0x7;
pub const IPV6_MULTICAST_LOOP: ::c_int = 0x8;
pub const IPV6_V6ONLY: ::c_int = 0x27;
cfg_if! {
if #[cfg(target_pointer_width = "64")] {
pub const FD_SETSIZE: usize = 65536;
} else {
pub const FD_SETSIZE: usize = 1024;
}
}
pub const ST_RDONLY: ::c_ulong = 1;
pub const ST_NOSUID: ::c_ulong = 2;
pub const NI_MAXHOST: ::socklen_t = 1025;
pub const EXIT_FAILURE: ::c_int = 1;
pub const EXIT_SUCCESS: ::c_int = 0;
pub const RAND_MAX: ::c_int = 32767;
pub const EOF: ::c_int = -1;
pub const SEEK_SET: ::c_int = 0;
pub const SEEK_CUR: ::c_int = 1;
pub const SEEK_END: ::c_int = 2;
pub const _IOFBF: ::c_int = 0;
pub const _IONBF: ::c_int = 4;
pub const _IOLBF: ::c_int = 64;
pub const BUFSIZ: ::c_uint = 1024;
pub const FOPEN_MAX: ::c_uint = 20;
pub const FILENAME_MAX: ::c_uint = 1024;
pub const L_tmpnam: ::c_uint = 25;
pub const TMP_MAX: ::c_uint = 17576;
pub const O_RDONLY: ::c_int = 0;
pub const O_WRONLY: ::c_int = 1;
pub const O_RDWR: ::c_int = 2;
pub const O_NDELAY: ::c_int = 0x04;
pub const O_APPEND: ::c_int = 8;
pub const O_DSYNC: ::c_int = 0x40;
pub const O_CREAT: ::c_int = 256;
pub const O_EXCL: ::c_int = 1024;
pub const O_NOCTTY: ::c_int = 2048;
pub const O_TRUNC: ::c_int = 512;
pub const O_NOFOLLOW: ::c_int = 0x200000;
pub const O_SEARCH: ::c_int = 0x200000;
pub const O_EXEC: ::c_int = 0x400000;
pub const O_CLOEXEC: ::c_int = 0x800000;
pub const O_ACCMODE: ::c_int = 0x600003;
pub const S_IFIFO: mode_t = 4096;
pub const S_IFCHR: mode_t = 8192;
pub const S_IFBLK: mode_t = 24576;
pub const S_IFDIR: mode_t = 16384;
pub const S_IFREG: mode_t = 32768;
pub const S_IFLNK: mode_t = 40960;
pub const S_IFSOCK: mode_t = 49152;
pub const S_IFMT: mode_t = 61440;
pub const S_IEXEC: mode_t = 64;
pub const S_IWRITE: mode_t = 128;
pub const S_IREAD: mode_t = 256;
pub const S_IRWXU: mode_t = 448;
pub const S_IXUSR: mode_t = 64;
pub const S_IWUSR: mode_t = 128;
pub const S_IRUSR: mode_t = 256;
pub const S_IRWXG: mode_t = 56;
pub const S_IXGRP: mode_t = 8;
pub const S_IWGRP: mode_t = 16;
pub const S_IRGRP: mode_t = 32;
pub const S_IRWXO: mode_t = 7;
pub const S_IXOTH: mode_t = 1;
pub const S_IWOTH: mode_t = 2;
pub const S_IROTH: mode_t = 4;
pub const F_OK: ::c_int = 0;
pub const R_OK: ::c_int = 4;
pub const W_OK: ::c_int = 2;
pub const X_OK: ::c_int = 1;
pub const STDIN_FILENO: ::c_int = 0;
pub const STDOUT_FILENO: ::c_int = 1;
pub const STDERR_FILENO: ::c_int = 2;
pub const F_LOCK: ::c_int = 1;
pub const F_TEST: ::c_int = 3;
pub const F_TLOCK: ::c_int = 2;
pub const F_ULOCK: ::c_int = 0;
pub const F_DUPFD_CLOEXEC: ::c_int = 37;
pub const F_SETLK: ::c_int = 6;
pub const F_SETLKW: ::c_int = 7;
pub const F_GETLK: ::c_int = 14;
pub const SIGHUP: ::c_int = 1;
pub const SIGINT: ::c_int = 2;
pub const SIGQUIT: ::c_int = 3;
pub const SIGILL: ::c_int = 4;
pub const SIGABRT: ::c_int = 6;
pub const SIGEMT: ::c_int = 7;
pub const SIGFPE: ::c_int = 8;
pub const SIGKILL: ::c_int = 9;
pub const SIGSEGV: ::c_int = 11;
pub const SIGSYS: ::c_int = 12;
pub const SIGPIPE: ::c_int = 13;
pub const SIGALRM: ::c_int = 14;
pub const SIGTERM: ::c_int = 15;
pub const SIGUSR1: ::c_int = 16;
pub const SIGUSR2: ::c_int = 17;
pub const SIGPWR: ::c_int = 19;
pub const SIGWINCH: ::c_int = 20;
pub const SIGURG: ::c_int = 21;
pub const SIGPOLL: ::c_int = 22;
pub const SIGIO: ::c_int = SIGPOLL;
pub const SIGSTOP: ::c_int = 23;
pub const SIGTSTP: ::c_int = 24;
pub const SIGCONT: ::c_int = 25;
pub const SIGTTIN: ::c_int = 26;
pub const SIGTTOU: ::c_int = 27;
pub const SIGVTALRM: ::c_int = 28;
pub const SIGPROF: ::c_int = 29;
pub const SIGXCPU: ::c_int = 30;
pub const SIGXFSZ: ::c_int = 31;
pub const WNOHANG: ::c_int = 0x40;
pub const WUNTRACED: ::c_int = 0x04;
pub const WEXITED: ::c_int = 0x01;
pub const WTRAPPED: ::c_int = 0x02;
pub const WSTOPPED: ::c_int = WUNTRACED;
pub const WCONTINUED: ::c_int = 0x08;
pub const WNOWAIT: ::c_int = 0x80;
pub const AT_FDCWD: ::c_int = 0xffd19553;
pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x1000;
pub const P_PID: idtype_t = 0;
pub const P_PPID: idtype_t = 1;
pub const P_PGID: idtype_t = 2;
pub const P_SID: idtype_t = 3;
pub const P_CID: idtype_t = 4;
pub const P_UID: idtype_t = 5;
pub const P_GID: idtype_t = 6;
pub const P_ALL: idtype_t = 7;
pub const P_LWPID: idtype_t = 8;
pub const P_TASKID: idtype_t = 9;
pub const P_PROJID: idtype_t = 10;
pub const P_POOLID: idtype_t = 11;
pub const P_ZONEID: idtype_t = 12;
pub const P_CTID: idtype_t = 13;
pub const P_CPUID: idtype_t = 14;
pub const P_PSETID: idtype_t = 15;
pub const UTIME_OMIT: c_long = -2;
pub const UTIME_NOW: c_long = -1;
pub const PROT_NONE: ::c_int = 0;
pub const PROT_READ: ::c_int = 1;
pub const PROT_WRITE: ::c_int = 2;
pub const PROT_EXEC: ::c_int = 4;
pub const MAP_FILE: ::c_int = 0;
pub const MAP_SHARED: ::c_int = 0x0001;
pub const MAP_PRIVATE: ::c_int = 0x0002;
pub const MAP_FIXED: ::c_int = 0x0010;
pub const MAP_NORESERVE: ::c_int = 0x40;
pub const MAP_ANON: ::c_int = 0x0100;
pub const MAP_ANONYMOUS: ::c_int = 0x0100;
pub const MAP_RENAME: ::c_int = 0x20;
pub const MAP_ALIGN: ::c_int = 0x200;
pub const MAP_TEXT: ::c_int = 0x400;
pub const MAP_INITDATA: ::c_int = 0x800;
pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void;
pub const MCL_CURRENT: ::c_int = 0x0001;
pub const MCL_FUTURE: ::c_int = 0x0002;
pub const MS_SYNC: ::c_int = 0x0004;
pub const MS_ASYNC: ::c_int = 0x0001;
pub const MS_INVALIDATE: ::c_int = 0x0002;
pub const MS_INVALCURPROC: ::c_int = 0x0008;
pub const EPERM: ::c_int = 1;
pub const ENOENT: ::c_int = 2;
pub const ESRCH: ::c_int = 3;
pub const EINTR: ::c_int = 4;
pub const EIO: ::c_int = 5;
pub const ENXIO: ::c_int = 6;
pub const E2BIG: ::c_int = 7;
pub const ENOEXEC: ::c_int = 8;
pub const EBADF: ::c_int = 9;
pub const ECHILD: ::c_int = 10;
pub const EAGAIN: ::c_int = 11;
pub const ENOMEM: ::c_int = 12;
pub const EACCES: ::c_int = 13;
pub const EFAULT: ::c_int = 14;
pub const ENOTBLK: ::c_int = 15;
pub const EBUSY: ::c_int = 16;
pub const EEXIST: ::c_int = 17;
pub const EXDEV: ::c_int = 18;
pub const ENODEV: ::c_int = 19;
pub const ENOTDIR: ::c_int = 20;
pub const EISDIR: ::c_int = 21;
pub const EINVAL: ::c_int = 22;
pub const ENFILE: ::c_int = 23;
pub const EMFILE: ::c_int = 24;
pub const ENOTTY: ::c_int = 25;
pub const ETXTBSY: ::c_int = 26;
pub const EFBIG: ::c_int = 27;
pub const ENOSPC: ::c_int = 28;
pub const ESPIPE: ::c_int = 29;
pub const EROFS: ::c_int = 30;
pub const EMLINK: ::c_int = 31;
pub const EPIPE: ::c_int = 32;
pub const EDOM: ::c_int = 33;
pub const ERANGE: ::c_int = 34;
pub const ENOMSG: ::c_int = 35;
pub const EIDRM: ::c_int = 36;
pub const ECHRNG: ::c_int = 37;
pub const EL2NSYNC: ::c_int = 38;
pub const EL3HLT: ::c_int = 39;
pub const EL3RST: ::c_int = 40;
pub const ELNRNG: ::c_int = 41;
pub const EUNATCH: ::c_int = 42;
pub const ENOCSI: ::c_int = 43;
pub const EL2HLT: ::c_int = 44;
pub const EDEADLK: ::c_int = 45;
pub const ENOLCK: ::c_int = 46;
pub const ECANCELED: ::c_int = 47;
pub const ENOTSUP: ::c_int = 48;
pub const EDQUOT: ::c_int = 49;
pub const EBADE: ::c_int = 50;
pub const EBADR: ::c_int = 51;
pub const EXFULL: ::c_int = 52;
pub const ENOANO: ::c_int = 53;
pub const EBADRQC: ::c_int = 54;
pub const EBADSLT: ::c_int = 55;
pub const EDEADLOCK: ::c_int = 56;
pub const EBFONT: ::c_int = 57;
pub const EOWNERDEAD: ::c_int = 58;
pub const ENOTRECOVERABLE: ::c_int = 59;
pub const ENOSTR: ::c_int = 60;
pub const ENODATA: ::c_int = 61;
pub const ETIME: ::c_int = 62;
pub const ENOSR: ::c_int = 63;
pub const ENONET: ::c_int = 64;
pub const ENOPKG: ::c_int = 65;
pub const EREMOTE: ::c_int = 66;
pub const ENOLINK: ::c_int = 67;
pub const EADV: ::c_int = 68;
pub const ESRMNT: ::c_int = 69;
pub const ECOMM: ::c_int = 70;
pub const EPROTO: ::c_int = 71;
pub const ELOCKUNMAPPED: ::c_int = 72;
pub const ENOTACTIVE: ::c_int = 73;
pub const EMULTIHOP: ::c_int = 74;
pub const EADI: ::c_int = 75;
pub const EBADMSG: ::c_int = 77;
pub const ENAMETOOLONG: ::c_int = 78;
pub const EOVERFLOW: ::c_int = 79;
pub const ENOTUNIQ: ::c_int = 80;
pub const EBADFD: ::c_int = 81;
pub const EREMCHG: ::c_int = 82;
pub const ELIBACC: ::c_int = 83;
pub const ELIBBAD: ::c_int = 84;
pub const ELIBSCN: ::c_int = 85;
pub const ELIBMAX: ::c_int = 86;
pub const ELIBEXEC: ::c_int = 87;
pub const EILSEQ: ::c_int = 88;
pub const ENOSYS: ::c_int = 89;
pub const ELOOP: ::c_int = 90;
pub const ERESTART: ::c_int = 91;
pub const ESTRPIPE: ::c_int = 92;
pub const ENOTEMPTY: ::c_int = 93;
pub const EUSERS: ::c_int = 94;
pub const ENOTSOCK: ::c_int = 95;
pub const EDESTADDRREQ: ::c_int = 96;
pub const EMSGSIZE: ::c_int = 97;
pub const EPROTOTYPE: ::c_int = 98;
pub const ENOPROTOOPT: ::c_int = 99;
pub const EPROTONOSUPPORT: ::c_int = 120;
pub const ESOCKTNOSUPPORT: ::c_int = 121;
pub const EOPNOTSUPP: ::c_int = 122;
pub const EPFNOSUPPORT: ::c_int = 123;
pub const EAFNOSUPPORT: ::c_int = 124;
pub const EADDRINUSE: ::c_int = 125;
pub const EADDRNOTAVAIL: ::c_int = 126;
pub const ENETDOWN: ::c_int = 127;
pub const ENETUNREACH: ::c_int = 128;
pub const ENETRESET: ::c_int = 129;
pub const ECONNABORTED: ::c_int = 130;
pub const ECONNRESET: ::c_int = 131;
pub const ENOBUFS: ::c_int = 132;
pub const EISCONN: ::c_int = 133;
pub const ENOTCONN: ::c_int = 134;
pub const ESHUTDOWN: ::c_int = 143;
pub const ETOOMANYREFS: ::c_int = 144;
pub const ETIMEDOUT: ::c_int = 145;
pub const ECONNREFUSED: ::c_int = 146;
pub const EHOSTDOWN: ::c_int = 147;
pub const EHOSTUNREACH: ::c_int = 148;
pub const EWOULDBLOCK: ::c_int = EAGAIN;
pub const EALREADY: ::c_int = 149;
pub const EINPROGRESS: ::c_int = 150;
pub const ESTALE: ::c_int = 151;
pub const EAI_AGAIN: ::c_int = 2;
pub const EAI_BADFLAGS: ::c_int = 3;
pub const EAI_FAIL: ::c_int = 4;
pub const EAI_FAMILY: ::c_int = 5;
pub const EAI_MEMORY: ::c_int = 6;
pub const EAI_NODATA: ::c_int = 7;
pub const EAI_NONAME: ::c_int = 8;
pub const EAI_SERVICE: ::c_int = 9;
pub const EAI_SOCKTYPE: ::c_int = 10;
pub const EAI_SYSTEM: ::c_int = 11;
pub const EAI_OVERFLOW: ::c_int = 12;
pub const F_DUPFD: ::c_int = 0;
pub const F_GETFD: ::c_int = 1;
pub const F_SETFD: ::c_int = 2;
pub const F_GETFL: ::c_int = 3;
pub const F_SETFL: ::c_int = 4;
pub const SIGTRAP: ::c_int = 5;
pub const GLOB_APPEND: ::c_int = 32;
pub const GLOB_DOOFFS: ::c_int = 16;
pub const GLOB_ERR: ::c_int = 1;
pub const GLOB_MARK: ::c_int = 2;
pub const GLOB_NOCHECK: ::c_int = 8;
pub const GLOB_NOSORT: ::c_int = 4;
pub const GLOB_NOESCAPE: ::c_int = 64;
pub const GLOB_NOSPACE: ::c_int = -2;
pub const GLOB_ABORTED: ::c_int = -1;
pub const GLOB_NOMATCH: ::c_int = -3;
pub const POLLIN: ::c_short = 0x1;
pub const POLLPRI: ::c_short = 0x2;
pub const POLLOUT: ::c_short = 0x4;
pub const POLLERR: ::c_short = 0x8;
pub const POLLHUP: ::c_short = 0x10;
pub const POLLNVAL: ::c_short = 0x20;
pub const POLLNORM: ::c_short = 0x0040;
pub const POLLRDNORM: ::c_short = 0x0040;
pub const POLLWRNORM: ::c_short = 0x4; /* POLLOUT */
pub const POLLRDBAND: ::c_short = 0x0080;
pub const POLLWRBAND: ::c_short = 0x0100;
pub const POSIX_MADV_NORMAL: ::c_int = 0;
pub const POSIX_MADV_RANDOM: ::c_int = 1;
pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2;
pub const POSIX_MADV_WILLNEED: ::c_int = 3;
pub const POSIX_MADV_DONTNEED: ::c_int = 4;
pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0;
pub const PTHREAD_CREATE_DETACHED: ::c_int = 0x40;
pub const PTHREAD_PROCESS_SHARED: ::c_int = 1;
pub const PTHREAD_PROCESS_PRIVATE: ::c_ushort = 0;
pub const PTHREAD_STACK_MIN: ::size_t = 4096;
pub const SIGSTKSZ: ::size_t = 8192;
// https://illumos.org/man/3c/clock_gettime
// https://github.com/illumos/illumos-gate/
// blob/HEAD/usr/src/lib/libc/amd64/sys/__clock_gettime.s
// clock_gettime(3c) doesn't seem to accept anything other than CLOCK_REALTIME
// or __CLOCK_REALTIME0
//
// https://github.com/illumos/illumos-gate/
// blob/HEAD/usr/src/uts/common/sys/time_impl.h
// Confusing! CLOCK_HIGHRES==CLOCK_MONOTONIC==4
// __CLOCK_REALTIME0==0 is an obsoleted version of CLOCK_REALTIME==3
pub const CLOCK_REALTIME: ::clockid_t = 3;
pub const CLOCK_MONOTONIC: ::clockid_t = 4;
pub const TIMER_RELTIME: ::c_int = 0;
pub const TIMER_ABSTIME: ::c_int = 1;
pub const RLIMIT_CPU: ::c_int = 0;
pub const RLIMIT_FSIZE: ::c_int = 1;
pub const RLIMIT_DATA: ::c_int = 2;
pub const RLIMIT_STACK: ::c_int = 3;
pub const RLIMIT_CORE: ::c_int = 4;
pub const RLIMIT_NOFILE: ::c_int = 5;
pub const RLIMIT_VMEM: ::c_int = 6;
pub const RLIMIT_AS: ::c_int = RLIMIT_VMEM;
#[deprecated(since = "0.2.64", note = "Not stable across OS versions")]
pub const RLIM_NLIMITS: rlim_t = 7;
pub const RLIM_INFINITY: rlim_t = 0x7fffffff;
pub const RUSAGE_SELF: ::c_int = 0;
pub const RUSAGE_CHILDREN: ::c_int = -1;
pub const MADV_NORMAL: ::c_int = 0;
pub const MADV_RANDOM: ::c_int = 1;
pub const MADV_SEQUENTIAL: ::c_int = 2;
pub const MADV_WILLNEED: ::c_int = 3;
pub const MADV_DONTNEED: ::c_int = 4;
pub const MADV_FREE: ::c_int = 5;
pub const AF_UNSPEC: ::c_int = 0;
pub const AF_UNIX: ::c_int = 1;
pub const AF_LOCAL: ::c_int = 0;
pub const AF_FILE: ::c_int = 0;
pub const AF_INET: ::c_int = 2;
pub const AF_IMPLINK: ::c_int = 3;
pub const AF_PUP: ::c_int = 4;
pub const AF_CHAOS: ::c_int = 5;
pub const AF_NS: ::c_int = 6;
pub const AF_NBS: ::c_int = 7;
pub const AF_ECMA: ::c_int = 8;
pub const AF_DATAKIT: ::c_int = 9;
pub const AF_CCITT: ::c_int = 10;
pub const AF_SNA: ::c_int = 11;
pub const AF_DECnet: ::c_int = 12;
pub const AF_DLI: ::c_int = 13;
pub const AF_LAT: ::c_int = 14;
pub const AF_HYLINK: ::c_int = 15;
pub const AF_APPLETALK: ::c_int = 16;
pub const AF_NIT: ::c_int = 17;
pub const AF_802: ::c_int = 18;
pub const AF_OSI: ::c_int = 19;
pub const AF_X25: ::c_int = 20;
pub const AF_OSINET: ::c_int = 21;
pub const AF_GOSIP: ::c_int = 22;
pub const AF_IPX: ::c_int = 23;
pub const AF_ROUTE: ::c_int = 24;
pub const AF_LINK: ::c_int = 25;
pub const AF_INET6: ::c_int = 26;
pub const AF_KEY: ::c_int = 27;
pub const AF_NCA: ::c_int = 28;
pub const AF_POLICY: ::c_int = 29;
pub const AF_INET_OFFLOAD: ::c_int = 30;
pub const AF_TRILL: ::c_int = 31;
pub const AF_PACKET: ::c_int = 32;
pub const AF_LX_NETLINK: ::c_int = 33;
pub const SOCK_DGRAM: ::c_int = 1;
pub const SOCK_STREAM: ::c_int = 2;
pub const SOCK_RAW: ::c_int = 4;
pub const SOCK_RDM: ::c_int = 5;
pub const SOCK_SEQPACKET: ::c_int = 6;
pub const IP_MULTICAST_IF: ::c_int = 16;
pub const IP_MULTICAST_TTL: ::c_int = 17;
pub const IP_MULTICAST_LOOP: ::c_int = 18;
pub const IP_TTL: ::c_int = 4;
pub const IP_HDRINCL: ::c_int = 2;
pub const IP_ADD_MEMBERSHIP: ::c_int = 19;
pub const IP_DROP_MEMBERSHIP: ::c_int = 20;
pub const IPV6_JOIN_GROUP: ::c_int = 9;
pub const IPV6_LEAVE_GROUP: ::c_int = 10;
pub const TCP_NODELAY: ::c_int = 1;
pub const TCP_KEEPIDLE: ::c_int = 34;
pub const SOL_SOCKET: ::c_int = 0xffff;
pub const SO_DEBUG: ::c_int = 0x01;
pub const SO_ACCEPTCONN: ::c_int = 0x0002;
pub const SO_REUSEADDR: ::c_int = 0x0004;
pub const SO_KEEPALIVE: ::c_int = 0x0008;
pub const SO_DONTROUTE: ::c_int = 0x0010;
pub const SO_BROADCAST: ::c_int = 0x0020;
pub const SO_USELOOPBACK: ::c_int = 0x0040;
pub const SO_LINGER: ::c_int = 0x0080;
pub const SO_OOBINLINE: ::c_int = 0x0100;
pub const SO_SNDBUF: ::c_int = 0x1001;
pub const SO_RCVBUF: ::c_int = 0x1002;
pub const SO_SNDLOWAT: ::c_int = 0x1003;
pub const SO_RCVLOWAT: ::c_int = 0x1004;
pub const SO_SNDTIMEO: ::c_int = 0x1005;
pub const SO_RCVTIMEO: ::c_int = 0x1006;
pub const SO_ERROR: ::c_int = 0x1007;
pub const SO_TYPE: ::c_int = 0x1008;
pub const SO_TIMESTAMP: ::c_int = 0x1013;
pub const SCM_RIGHTS: ::c_int = 0x1010;
pub const SCM_UCRED: ::c_int = 0x1012;
pub const SCM_TIMESTAMP: ::c_int = SO_TIMESTAMP;
pub const MSG_OOB: ::c_int = 0x1;
pub const MSG_PEEK: ::c_int = 0x2;
pub const MSG_DONTROUTE: ::c_int = 0x4;
pub const MSG_EOR: ::c_int = 0x8;
pub const MSG_CTRUNC: ::c_int = 0x10;
pub const MSG_TRUNC: ::c_int = 0x20;
pub const MSG_WAITALL: ::c_int = 0x40;
pub const MSG_DONTWAIT: ::c_int = 0x80;
pub const MSG_NOTIFICATION: ::c_int = 0x100;
pub const MSG_NOSIGNAL: ::c_int = 0x200;
pub const MSG_DUPCTRL: ::c_int = 0x800;
pub const MSG_XPG4_2: ::c_int = 0x8000;
pub const MSG_MAXIOVLEN: ::c_int = 16;
// https://docs.oracle.com/cd/E23824_01/html/821-1475/if-7p.html
pub const IFF_UP: ::c_int = 0x0000000001; // Address is up
pub const IFF_BROADCAST: ::c_int = 0x0000000002; // Broadcast address valid
pub const IFF_DEBUG: ::c_int = 0x0000000004; // Turn on debugging
pub const IFF_LOOPBACK: ::c_int = 0x0000000008; // Loopback net
pub const IFF_POINTOPOINT: ::c_int = 0x0000000010; // Interface is p-to-p
pub const IFF_NOTRAILERS: ::c_int = 0x0000000020; // Avoid use of trailers
pub const IFF_RUNNING: ::c_int = 0x0000000040; // Resources allocated
pub const IFF_NOARP: ::c_int = 0x0000000080; // No address res. protocol
pub const IFF_PROMISC: ::c_int = 0x0000000100; // Receive all packets
pub const IFF_ALLMULTI: ::c_int = 0x0000000200; // Receive all multicast pkts
pub const IFF_INTELLIGENT: ::c_int = 0x0000000400; // Protocol code on board
pub const IFF_MULTICAST: ::c_int = 0x0000000800; // Supports multicast
// Multicast using broadcst. add.
pub const IFF_MULTI_BCAST: ::c_int = 0x0000001000;
pub const IFF_UNNUMBERED: ::c_int = 0x0000002000; // Non-unique address
pub const IFF_DHCPRUNNING: ::c_int = 0x0000004000; // DHCP controls interface
pub const IFF_PRIVATE: ::c_int = 0x0000008000; // Do not advertise
pub const IFF_NOXMIT: ::c_int = 0x0000010000; // Do not transmit pkts
// No address - just on-link subnet
pub const IFF_NOLOCAL: ::c_int = 0x0000020000;
pub const IFF_DEPRECATED: ::c_int = 0x0000040000; // Address is deprecated
pub const IFF_ADDRCONF: ::c_int = 0x0000080000; // Addr. from stateless addrconf
pub const IFF_ROUTER: ::c_int = 0x0000100000; // Router on interface
pub const IFF_NONUD: ::c_int = 0x0000200000; // No NUD on interface
pub const IFF_ANYCAST: ::c_int = 0x0000400000; // Anycast address
pub const IFF_NORTEXCH: ::c_int = 0x0000800000; // Don't xchange rout. info
pub const IFF_IPV4: ::c_int = 0x0001000000; // IPv4 interface
pub const IFF_IPV6: ::c_int = 0x0002000000; // IPv6 interface
pub const IFF_NOFAILOVER: ::c_int = 0x0008000000; // in.mpathd test address
pub const IFF_FAILED: ::c_int = 0x0010000000; // Interface has failed
pub const IFF_STANDBY: ::c_int = 0x0020000000; // Interface is a hot-spare
pub const IFF_INACTIVE: ::c_int = 0x0040000000; // Functioning but not used
pub const IFF_OFFLINE: ::c_int = 0x0080000000; // Interface is offline
// If CoS marking is supported
pub const IFF_COS_ENABLED: ::c_longlong = 0x0200000000;
pub const IFF_PREFERRED: ::c_longlong = 0x0400000000; // Prefer as source addr.
pub const IFF_TEMPORARY: ::c_longlong = 0x0800000000; // RFC3041
pub const IFF_FIXEDMTU: ::c_longlong = 0x1000000000; // MTU set with SIOCSLIFMTU
pub const IFF_VIRTUAL: ::c_longlong = 0x2000000000; // Cannot send/receive pkts
pub const IFF_DUPLICATE: ::c_longlong = 0x4000000000; // Local address in use
pub const IFF_IPMP: ::c_longlong = 0x8000000000; // IPMP IP interface
// sys/ipc.h:
pub const IPC_ALLOC: ::c_int = 0x8000;
pub const IPC_CREAT: ::c_int = 0x200;
pub const IPC_EXCL: ::c_int = 0x400;
pub const IPC_NOWAIT: ::c_int = 0x800;
pub const IPC_PRIVATE: key_t = 0;
pub const IPC_RMID: ::c_int = 10;
pub const IPC_SET: ::c_int = 11;
pub const IPC_SEAT: ::c_int = 12;
pub const SHUT_RD: ::c_int = 0;
pub const SHUT_WR: ::c_int = 1;
pub const SHUT_RDWR: ::c_int = 2;
pub const LOCK_SH: ::c_int = 1;
pub const LOCK_EX: ::c_int = 2;
pub const LOCK_NB: ::c_int = 4;
pub const LOCK_UN: ::c_int = 8;
pub const F_RDLCK: ::c_short = 1;
pub const F_WRLCK: ::c_short = 2;
pub const F_UNLCK: ::c_short = 3;
pub const O_SYNC: ::c_int = 16;
pub const O_NONBLOCK: ::c_int = 128;
pub const IPPROTO_RAW: ::c_int = 255;
pub const _PC_LINK_MAX: ::c_int = 1;
pub const _PC_MAX_CANON: ::c_int = 2;
pub const _PC_MAX_INPUT: ::c_int = 3;
pub const _PC_NAME_MAX: ::c_int = 4;
pub const _PC_PATH_MAX: ::c_int = 5;
pub const _PC_PIPE_BUF: ::c_int = 6;
pub const _PC_NO_TRUNC: ::c_int = 7;
pub const _PC_VDISABLE: ::c_int = 8;
pub const _PC_CHOWN_RESTRICTED: ::c_int = 9;
pub const _PC_ASYNC_IO: ::c_int = 10;
pub const _PC_PRIO_IO: ::c_int = 11;
pub const _PC_SYNC_IO: ::c_int = 12;
pub const _PC_ALLOC_SIZE_MIN: ::c_int = 13;
pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14;
pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15;
pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16;
pub const _PC_REC_XFER_ALIGN: ::c_int = 17;
pub const _PC_SYMLINK_MAX: ::c_int = 18;
pub const _PC_2_SYMLINKS: ::c_int = 19;
pub const _PC_ACL_ENABLED: ::c_int = 20;
pub const _PC_MIN_HOLE_SIZE: ::c_int = 21;
pub const _PC_CASE_BEHAVIOR: ::c_int = 22;
pub const _PC_SATTR_ENABLED: ::c_int = 23;
pub const _PC_SATTR_EXISTS: ::c_int = 24;
pub const _PC_ACCESS_FILTERING: ::c_int = 25;
pub const _PC_TIMESTAMP_RESOLUTION: ::c_int = 26;
pub const _PC_FILESIZEBITS: ::c_int = 67;
pub const _PC_XATTR_ENABLED: ::c_int = 100;
pub const _PC_LAST: ::c_int = 101;
pub const _PC_XATTR_EXISTS: ::c_int = 101;
pub const _SC_ARG_MAX: ::c_int = 1;
pub const _SC_CHILD_MAX: ::c_int = 2;
pub const _SC_CLK_TCK: ::c_int = 3;
pub const _SC_NGROUPS_MAX: ::c_int = 4;
pub const _SC_OPEN_MAX: ::c_int = 5;
pub const _SC_JOB_CONTROL: ::c_int = 6;
pub const _SC_SAVED_IDS: ::c_int = 7;
pub const _SC_VERSION: ::c_int = 8;
pub const _SC_PASS_MAX: ::c_int = 9;
pub const _SC_LOGNAME_MAX: ::c_int = 10;
pub const _SC_PAGESIZE: ::c_int = 11;
pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE;
pub const _SC_XOPEN_VERSION: ::c_int = 12;
pub const _SC_NPROCESSORS_CONF: ::c_int = 14;
pub const _SC_NPROCESSORS_ONLN: ::c_int = 15;
pub const _SC_STREAM_MAX: ::c_int = 16;
pub const _SC_TZNAME_MAX: ::c_int = 17;
pub const _SC_AIO_LISTIO_MAX: ::c_int = 18;
pub const _SC_AIO_MAX: ::c_int = 19;
pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 20;
pub const _SC_ASYNCHRONOUS_IO: ::c_int = 21;
pub const _SC_DELAYTIMER_MAX: ::c_int = 22;
pub const _SC_FSYNC: ::c_int = 23;
pub const _SC_MAPPED_FILES: ::c_int = 24;
pub const _SC_MEMLOCK: ::c_int = 25;
pub const _SC_MEMLOCK_RANGE: ::c_int = 26;
pub const _SC_MEMORY_PROTECTION: ::c_int = 27;
pub const _SC_MESSAGE_PASSING: ::c_int = 28;
pub const _SC_MQ_OPEN_MAX: ::c_int = 29;
pub const _SC_MQ_PRIO_MAX: ::c_int = 30;
pub const _SC_PRIORITIZED_IO: ::c_int = 31;
pub const _SC_PRIORITY_SCHEDULING: ::c_int = 32;
pub const _SC_REALTIME_SIGNALS: ::c_int = 33;
pub const _SC_RTSIG_MAX: ::c_int = 34;
pub const _SC_SEMAPHORES: ::c_int = 35;
pub const _SC_SEM_NSEMS_MAX: ::c_int = 36;
pub const _SC_SEM_VALUE_MAX: ::c_int = 37;
pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 38;
pub const _SC_SIGQUEUE_MAX: ::c_int = 39;
pub const _SC_SIGRT_MIN: ::c_int = 40;
pub const _SC_SIGRT_MAX: ::c_int = 41;
pub const _SC_SYNCHRONIZED_IO: ::c_int = 42;
pub const _SC_TIMERS: ::c_int = 43;
pub const _SC_TIMER_MAX: ::c_int = 44;
pub const _SC_2_C_BIND: ::c_int = 45;
pub const _SC_2_C_DEV: ::c_int = 46;
pub const _SC_2_C_VERSION: ::c_int = 47;
pub const _SC_2_FORT_DEV: ::c_int = 48;
pub const _SC_2_FORT_RUN: ::c_int = 49;
pub const _SC_2_LOCALEDEF: ::c_int = 50;
pub const _SC_2_SW_DEV: ::c_int = 51;
pub const _SC_2_UPE: ::c_int = 52;
pub const _SC_2_VERSION: ::c_int = 53;
pub const _SC_BC_BASE_MAX: ::c_int = 54;
pub const _SC_BC_DIM_MAX: ::c_int = 55;
pub const _SC_BC_SCALE_MAX: ::c_int = 56;
pub const _SC_BC_STRING_MAX: ::c_int = 57;
pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 58;
pub const _SC_EXPR_NEST_MAX: ::c_int = 59;
pub const _SC_LINE_MAX: ::c_int = 60;
pub const _SC_RE_DUP_MAX: ::c_int = 61;
pub const _SC_XOPEN_CRYPT: ::c_int = 62;
pub const _SC_XOPEN_ENH_I18N: ::c_int = 63;
pub const _SC_XOPEN_SHM: ::c_int = 64;
pub const _SC_2_CHAR_TERM: ::c_int = 66;
pub const _SC_XOPEN_XCU_VERSION: ::c_int = 67;
pub const _SC_ATEXIT_MAX: ::c_int = 76;
pub const _SC_IOV_MAX: ::c_int = 77;
pub const _SC_XOPEN_UNIX: ::c_int = 78;
pub const _SC_T_IOV_MAX: ::c_int = 79;
pub const _SC_PHYS_PAGES: ::c_int = 500;
pub const _SC_AVPHYS_PAGES: ::c_int = 501;
pub const _SC_COHER_BLKSZ: ::c_int = 503;
pub const _SC_SPLIT_CACHE: ::c_int = 504;
pub const _SC_ICACHE_SZ: ::c_int = 505;
pub const _SC_DCACHE_SZ: ::c_int = 506;
pub const _SC_ICACHE_LINESZ: ::c_int = 507;
pub const _SC_DCACHE_LINESZ: ::c_int = 508;
pub const _SC_ICACHE_BLKSZ: ::c_int = 509;
pub const _SC_DCACHE_BLKSZ: ::c_int = 510;
pub const _SC_DCACHE_TBLKSZ: ::c_int = 511;
pub const _SC_ICACHE_ASSOC: ::c_int = 512;
pub const _SC_DCACHE_ASSOC: ::c_int = 513;
pub const _SC_MAXPID: ::c_int = 514;
pub const _SC_STACK_PROT: ::c_int = 515;
pub const _SC_NPROCESSORS_MAX: ::c_int = 516;
pub const _SC_CPUID_MAX: ::c_int = 517;
pub const _SC_EPHID_MAX: ::c_int = 518;
pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 568;
pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 569;
pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 570;
pub const _SC_LOGIN_NAME_MAX: ::c_int = 571;
pub const _SC_THREAD_KEYS_MAX: ::c_int = 572;
pub const _SC_THREAD_STACK_MIN: ::c_int = 573;
pub const _SC_THREAD_THREADS_MAX: ::c_int = 574;
pub const _SC_TTY_NAME_MAX: ::c_int = 575;
pub const _SC_THREADS: ::c_int = 576;
pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 577;
pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 578;
pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 579;
pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 580;
pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 581;
pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 582;
pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 583;
pub const _SC_XOPEN_LEGACY: ::c_int = 717;
pub const _SC_XOPEN_REALTIME: ::c_int = 718;
pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 719;
pub const _SC_XBS5_ILP32_OFF32: ::c_int = 720;
pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 721;
pub const _SC_XBS5_LP64_OFF64: ::c_int = 722;
pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 723;
pub const _SC_2_PBS: ::c_int = 724;
pub const _SC_2_PBS_ACCOUNTING: ::c_int = 725;
pub const _SC_2_PBS_CHECKPOINT: ::c_int = 726;
pub const _SC_2_PBS_LOCATE: ::c_int = 728;
pub const _SC_2_PBS_MESSAGE: ::c_int = 729;
pub const _SC_2_PBS_TRACK: ::c_int = 730;
pub const _SC_ADVISORY_INFO: ::c_int = 731;
pub const _SC_BARRIERS: ::c_int = 732;
pub const _SC_CLOCK_SELECTION: ::c_int = 733;
pub const _SC_CPUTIME: ::c_int = 734;
pub const _SC_HOST_NAME_MAX: ::c_int = 735;
pub const _SC_MONOTONIC_CLOCK: ::c_int = 736;
pub const _SC_READER_WRITER_LOCKS: ::c_int = 737;
pub const _SC_REGEXP: ::c_int = 738;
pub const _SC_SHELL: ::c_int = 739;
pub const _SC_SPAWN: ::c_int = 740;
pub const _SC_SPIN_LOCKS: ::c_int = 741;
pub const _SC_SPORADIC_SERVER: ::c_int = 742;
pub const _SC_SS_REPL_MAX: ::c_int = 743;
pub const _SC_SYMLOOP_MAX: ::c_int = 744;
pub const _SC_THREAD_CPUTIME: ::c_int = 745;
pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 746;
pub const _SC_TIMEOUTS: ::c_int = 747;
pub const _SC_TRACE: ::c_int = 748;
pub const _SC_TRACE_EVENT_FILTER: ::c_int = 749;
pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 750;
pub const _SC_TRACE_INHERIT: ::c_int = 751;
pub const _SC_TRACE_LOG: ::c_int = 752;
pub const _SC_TRACE_NAME_MAX: ::c_int = 753;
pub const _SC_TRACE_SYS_MAX: ::c_int = 754;
pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 755;
pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 756;
pub const _SC_V6_ILP32_OFF32: ::c_int = 757;
pub const _SC_V6_ILP32_OFFBIG: ::c_int = 758;
pub const _SC_V6_LP64_OFF64: ::c_int = 759;
pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 760;
pub const _SC_XOPEN_STREAMS: ::c_int = 761;
pub const _SC_IPV6: ::c_int = 762;
pub const _SC_RAW_SOCKETS: ::c_int = 763;
pub const _MUTEX_MAGIC: u16 = 0x4d58; // MX
pub const _COND_MAGIC: u16 = 0x4356; // CV
pub const _RWL_MAGIC: u16 = 0x5257; // RW
pub const NCCS: usize = 19;
pub const LOG_CRON: ::c_int = 15 << 3;
pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
__pthread_mutex_flag1: 0,
__pthread_mutex_flag2: 0,
__pthread_mutex_ceiling: 0,
__pthread_mutex_type: PTHREAD_PROCESS_PRIVATE,
__pthread_mutex_magic: _MUTEX_MAGIC,
__pthread_mutex_lock: 0,
__pthread_mutex_data: 0,
};
pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
__pthread_cond_flag: [0; 4],
__pthread_cond_type: PTHREAD_PROCESS_PRIVATE,
__pthread_cond_magic: _COND_MAGIC,
__pthread_cond_data: 0,
};
pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t {
__pthread_rwlock_readers: 0,
__pthread_rwlock_type: PTHREAD_PROCESS_PRIVATE,
__pthread_rwlock_magic: _RWL_MAGIC,
__pthread_rwlock_mutex: PTHREAD_MUTEX_INITIALIZER,
__pthread_rwlock_readercv: PTHREAD_COND_INITIALIZER,
__pthread_rwlock_writercv: PTHREAD_COND_INITIALIZER,
};
pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0;
pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2;
pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 4;
pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL;
pub const RTLD_NEXT: *mut ::c_void = -1isize as *mut ::c_void;
pub const RTLD_DEFAULT: *mut ::c_void = -2isize as *mut ::c_void;
pub const RTLD_SELF: *mut ::c_void = -3isize as *mut ::c_void;
pub const RTLD_PROBE: *mut ::c_void = -4isize as *mut ::c_void;
pub const RTLD_LAZY: ::c_int = 0x1;
pub const RTLD_NOW: ::c_int = 0x2;
pub const RTLD_NOLOAD: ::c_int = 0x4;
pub const RTLD_GLOBAL: ::c_int = 0x100;
pub const RTLD_LOCAL: ::c_int = 0x0;
pub const RTLD_PARENT: ::c_int = 0x200;
pub const RTLD_GROUP: ::c_int = 0x400;
pub const RTLD_WORLD: ::c_int = 0x800;
pub const RTLD_NODELETE: ::c_int = 0x1000;
pub const RTLD_FIRST: ::c_int = 0x2000;
pub const RTLD_CONFGEN: ::c_int = 0x10000;
pub const PORT_SOURCE_AIO: ::c_int = 1;
pub const PORT_SOURCE_TIMER: ::c_int = 2;
pub const PORT_SOURCE_USER: ::c_int = 3;
pub const PORT_SOURCE_FD: ::c_int = 4;
pub const PORT_SOURCE_ALERT: ::c_int = 5;
pub const PORT_SOURCE_MQ: ::c_int = 6;
pub const PORT_SOURCE_FILE: ::c_int = 7;
pub const PORT_SOURCE_POSTWAIT: ::c_int = 8;
pub const PORT_SOURCE_SIGNAL: ::c_int = 9;
pub const NONROOT_USR: ::c_short = 2;
pub const _UTX_USERSIZE: usize = 32;
pub const _UTX_LINESIZE: usize = 32;
pub const _UTX_PADSIZE: usize = 5;
pub const _UTX_IDSIZE: usize = 4;
pub const _UTX_HOSTSIZE: usize = 257;
pub const EMPTY: ::c_short = 0;
pub const RUN_LVL: ::c_short = 1;
pub const BOOT_TIME: ::c_short = 2;
pub const OLD_TIME: ::c_short = 3;
pub const NEW_TIME: ::c_short = 4;
pub const INIT_PROCESS: ::c_short = 5;
pub const LOGIN_PROCESS: ::c_short = 6;
pub const USER_PROCESS: ::c_short = 7;
pub const DEAD_PROCESS: ::c_short = 8;
pub const ACCOUNTING: ::c_short = 9;
pub const DOWN_TIME: ::c_short = 10;
const _TIOC: ::c_int = ('T' as i32) << 8;
const tIOC: ::c_int = ('t' as i32) << 8;
pub const TCGETA: ::c_int = _TIOC | 1;
pub const TCSETA: ::c_int = _TIOC | 2;
pub const TCSETAW: ::c_int = _TIOC | 3;
pub const TCSETAF: ::c_int = _TIOC | 4;
pub const TCSBRK: ::c_int = _TIOC | 5;
pub const TCXONC: ::c_int = _TIOC | 6;
pub const TCFLSH: ::c_int = _TIOC | 7;
pub const TCDSET: ::c_int = _TIOC | 32;
pub const TCGETS: ::c_int = _TIOC | 13;
pub const TCSETS: ::c_int = _TIOC | 14;
pub const TCSANOW: ::c_int = _TIOC | 14;
pub const TCSETSW: ::c_int = _TIOC | 15;
pub const TCSADRAIN: ::c_int = _TIOC | 15;
pub const TCSETSF: ::c_int = _TIOC | 16;
pub const TCSAFLUSH: ::c_int = _TIOC | 16;
pub const TCIFLUSH: ::c_int = 0;
pub const TCOFLUSH: ::c_int = 1;
pub const TCIOFLUSH: ::c_int = 2;
pub const TCOOFF: ::c_int = 0;
pub const TCOON: ::c_int = 1;
pub const TCIOFF: ::c_int = 2;
pub const TCION: ::c_int = 3;
pub const TIOC: ::c_int = _TIOC;
pub const TIOCKBON: ::c_int = _TIOC | 8;
pub const TIOCKBOF: ::c_int = _TIOC | 9;
pub const TIOCGWINSZ: ::c_int = _TIOC | 104;
pub const TIOCSWINSZ: ::c_int = _TIOC | 103;
pub const TIOCGSOFTCAR: ::c_int = _TIOC | 105;
pub const TIOCSSOFTCAR: ::c_int = _TIOC | 106;
pub const TIOCSETLD: ::c_int = _TIOC | 123;
pub const TIOCGETLD: ::c_int = _TIOC | 124;
pub const TIOCGPPS: ::c_int = _TIOC | 125;
pub const TIOCSPPS: ::c_int = _TIOC | 126;
pub const TIOCGPPSEV: ::c_int = _TIOC | 127;
pub const TIOCGETD: ::c_int = tIOC | 0;
pub const TIOCSETD: ::c_int = tIOC | 1;
pub const TIOCHPCL: ::c_int = tIOC | 2;
pub const TIOCGETP: ::c_int = tIOC | 8;
pub const TIOCSETP: ::c_int = tIOC | 9;
pub const TIOCSETN: ::c_int = tIOC | 10;
pub const TIOCEXCL: ::c_int = tIOC | 13;
pub const TIOCNXCL: ::c_int = tIOC | 14;
pub const TIOCFLUSH: ::c_int = tIOC | 16;
pub const TIOCSETC: ::c_int = tIOC | 17;
pub const TIOCGETC: ::c_int = tIOC | 18;
pub const TIOCLBIS: ::c_int = tIOC | 127;
pub const TIOCLBIC: ::c_int = tIOC | 126;
pub const TIOCLSET: ::c_int = tIOC | 125;
pub const TIOCLGET: ::c_int = tIOC | 124;
pub const TIOCSBRK: ::c_int = tIOC | 123;
pub const TIOCCBRK: ::c_int = tIOC | 122;
pub const TIOCSDTR: ::c_int = tIOC | 121;
pub const TIOCCDTR: ::c_int = tIOC | 120;
pub const TIOCSLTC: ::c_int = tIOC | 117;
pub const TIOCGLTC: ::c_int = tIOC | 116;
pub const TIOCOUTQ: ::c_int = tIOC | 115;
pub const TIOCNOTTY: ::c_int = tIOC | 113;
pub const TIOCSCTTY: ::c_int = tIOC | 132;
pub const TIOCSTOP: ::c_int = tIOC | 111;
pub const TIOCSTART: ::c_int = tIOC | 110;
pub const TIOCSILOOP: ::c_int = tIOC | 109;
pub const TIOCCILOOP: ::c_int = tIOC | 108;
pub const TIOCGPGRP: ::c_int = tIOC | 20;
pub const TIOCSPGRP: ::c_int = tIOC | 21;
pub const TIOCGSID: ::c_int = tIOC | 22;
pub const TIOCSTI: ::c_int = tIOC | 23;
pub const TIOCMSET: ::c_int = tIOC | 26;
pub const TIOCMBIS: ::c_int = tIOC | 27;
pub const TIOCMBIC: ::c_int = tIOC | 28;
pub const TIOCMGET: ::c_int = tIOC | 29;
pub const TIOCREMOTE: ::c_int = tIOC | 30;
pub const TIOCSIGNAL: ::c_int = tIOC | 31;
pub const EPOLLIN: ::c_int = 0x1;
pub const EPOLLPRI: ::c_int = 0x2;
pub const EPOLLOUT: ::c_int = 0x4;
pub const EPOLLRDNORM: ::c_int = 0x40;
pub const EPOLLRDBAND: ::c_int = 0x80;
pub const EPOLLWRNORM: ::c_int = 0x100;
pub const EPOLLWRBAND: ::c_int = 0x200;
pub const EPOLLMSG: ::c_int = 0x400;
pub const EPOLLERR: ::c_int = 0x8;
pub const EPOLLHUP: ::c_int = 0x10;
pub const EPOLLET: ::c_int = 0x80000000;
pub const EPOLLRDHUP: ::c_int = 0x2000;
pub const EPOLLEXCLUSIVE: ::c_int = 0x10000000;
pub const EPOLLONESHOT: ::c_int = 0x40000000;
pub const EPOLL_CLOEXEC: ::c_int = 0x80000;
pub const EPOLL_CTL_ADD: ::c_int = 1;
pub const EPOLL_CTL_MOD: ::c_int = 3;
pub const EPOLL_CTL_DEL: ::c_int = 2;
/* termios */
pub const B0: speed_t = 0;
pub const B50: speed_t = 1;
pub const B75: speed_t = 2;
pub const B110: speed_t = 3;
pub const B134: speed_t = 4;
pub const B150: speed_t = 5;
pub const B200: speed_t = 6;
pub const B300: speed_t = 7;
pub const B600: speed_t = 8;
pub const B1200: speed_t = 9;
pub const B1800: speed_t = 10;
pub const B2400: speed_t = 11;
pub const B4800: speed_t = 12;
pub const B9600: speed_t = 13;
pub const B19200: speed_t = 14;
pub const B38400: speed_t = 15;
pub const B57600: speed_t = 16;
pub const B76800: speed_t = 17;
pub const B115200: speed_t = 18;
pub const B153600: speed_t = 19;
pub const B230400: speed_t = 20;
pub const B307200: speed_t = 21;
pub const B460800: speed_t = 22;
pub const B921600: speed_t = 23;
pub const CSTART: ::tcflag_t = 021;
pub const CSTOP: ::tcflag_t = 023;
pub const CSWTCH: ::tcflag_t = 032;
pub const CSIZE: ::tcflag_t = 0o000060;
pub const CS5: ::tcflag_t = 0;
pub const CS6: ::tcflag_t = 0o000020;
pub const CS7: ::tcflag_t = 0o000040;
pub const CS8: ::tcflag_t = 0o000060;
pub const CSTOPB: ::tcflag_t = 0o000100;
pub const ECHO: ::tcflag_t = 0o000010;
pub const ECHOE: ::tcflag_t = 0o000020;
pub const ECHOK: ::tcflag_t = 0o000040;
pub const ECHONL: ::tcflag_t = 0o000100;
pub const ECHOCTL: ::tcflag_t = 0o001000;
pub const ECHOPRT: ::tcflag_t = 0o002000;
pub const ECHOKE: ::tcflag_t = 0o004000;
pub const EXTPROC: ::tcflag_t = 0o200000;
pub const IGNBRK: ::tcflag_t = 0o000001;
pub const BRKINT: ::tcflag_t = 0o000002;
pub const IGNPAR: ::tcflag_t = 0o000004;
pub const PARMRK: ::tcflag_t = 0o000010;
pub const INPCK: ::tcflag_t = 0o000020;
pub const ISTRIP: ::tcflag_t = 0o000040;
pub const INLCR: ::tcflag_t = 0o000100;
pub const IGNCR: ::tcflag_t = 0o000200;
pub const ICRNL: ::tcflag_t = 0o000400;
pub const IXON: ::tcflag_t = 0o002000;
pub const IXOFF: ::tcflag_t = 0o010000;
pub const IXANY: ::tcflag_t = 0o004000;
pub const IMAXBEL: ::tcflag_t = 0o020000;
pub const OPOST: ::tcflag_t = 0o000001;
pub const ONLCR: ::tcflag_t = 0o000004;
pub const OCRNL: ::tcflag_t = 0o000010;
pub const ONOCR: ::tcflag_t = 0o000020;
pub const ONLRET: ::tcflag_t = 0o000040;
pub const CREAD: ::tcflag_t = 0o000200;
pub const PARENB: ::tcflag_t = 0o000400;
pub const PARODD: ::tcflag_t = 0o001000;
pub const HUPCL: ::tcflag_t = 0o002000;
pub const CLOCAL: ::tcflag_t = 0o004000;
pub const CRTSCTS: ::tcflag_t = 0o20000000000;
pub const ISIG: ::tcflag_t = 0o000001;
pub const ICANON: ::tcflag_t = 0o000002;
pub const IEXTEN: ::tcflag_t = 0o100000;
pub const TOSTOP: ::tcflag_t = 0o000400;
pub const FLUSHO: ::tcflag_t = 0o020000;
pub const PENDIN: ::tcflag_t = 0o040000;
pub const NOFLSH: ::tcflag_t = 0o000200;
pub const VINTR: usize = 0;
pub const VQUIT: usize = 1;
pub const VERASE: usize = 2;
pub const VKILL: usize = 3;
pub const VEOF: usize = 4;
pub const VEOL: usize = 5;
pub const VEOL2: usize = 6;
pub const VMIN: usize = 4;
pub const VTIME: usize = 5;
pub const VSWTCH: usize = 7;
pub const VSTART: usize = 8;
pub const VSTOP: usize = 9;
pub const VSUSP: usize = 10;
pub const VDSUSP: usize = 11;
pub const VREPRINT: usize = 12;
pub const VDISCARD: usize = 13;
pub const VWERASE: usize = 14;
pub const VLNEXT: usize = 15;
pub const VSTATUS: usize = 16;
pub const VERASE2: usize = 17;
// 3SOCKET flags
pub const SOCK_CLOEXEC: ::c_int = 0x080000;
pub const SOCK_NONBLOCK: ::c_int = 0x100000;
pub const SOCK_NDELAY: ::c_int = 0x200000;
//<sys/timex.h>
pub const SCALE_KG: ::c_int = 1 << 6;
pub const SCALE_KF: ::c_int = 1 << 16;
pub const SCALE_KH: ::c_int = 1 << 2;
pub const MAXTC: ::c_int = 1 << 6;
pub const SCALE_PHASE: ::c_int = 1 << 22;
pub const SCALE_USEC: ::c_int = 1 << 16;
pub const SCALE_UPDATE: ::c_int = SCALE_KG * MAXTC;
pub const FINEUSEC: ::c_int = 1 << 22;
pub const MAXPHASE: ::c_int = 512000;
pub const MAXFREQ: ::c_int = 512 * SCALE_USEC;
pub const MAXTIME: ::c_int = 200 << PPS_AVG;
pub const MINSEC: ::c_int = 16;
pub const MAXSEC: ::c_int = 1200;
pub const PPS_AVG: ::c_int = 2;
pub const PPS_SHIFT: ::c_int = 2;
pub const PPS_SHIFTMAX: ::c_int = 8;
pub const PPS_VALID: ::c_int = 120;
pub const MAXGLITCH: ::c_int = 30;
pub const MOD_OFFSET: u32 = 0x0001;
pub const MOD_FREQUENCY: u32 = 0x0002;
pub const MOD_MAXERROR: u32 = 0x0004;
pub const MOD_ESTERROR: u32 = 0x0008;
pub const MOD_STATUS: u32 = 0x0010;
pub const MOD_TIMECONST: u32 = 0x0020;
pub const MOD_CLKB: u32 = 0x4000;
pub const MOD_CLKA: u32 = 0x8000;
pub const STA_PLL: u32 = 0x0001;
pub const STA_PPSFREQ: i32 = 0x0002;
pub const STA_PPSTIME: i32 = 0x0004;
pub const STA_FLL: i32 = 0x0008;
pub const STA_INS: i32 = 0x0010;
pub const STA_DEL: i32 = 0x0020;
pub const STA_UNSYNC: i32 = 0x0040;
pub const STA_FREQHOLD: i32 = 0x0080;
pub const STA_PPSSIGNAL: i32 = 0x0100;
pub const STA_PPSJITTER: i32 = 0x0200;
pub const STA_PPSWANDER: i32 = 0x0400;
pub const STA_PPSERROR: i32 = 0x0800;
pub const STA_CLOCKERR: i32 = 0x1000;
pub const STA_RONLY: i32 = STA_PPSSIGNAL
| STA_PPSJITTER
| STA_PPSWANDER
| STA_PPSERROR
| STA_CLOCKERR;
pub const TIME_OK: i32 = 0;
pub const TIME_INS: i32 = 1;
pub const TIME_DEL: i32 = 2;
pub const TIME_OOP: i32 = 3;
pub const TIME_WAIT: i32 = 4;
pub const TIME_ERROR: i32 = 5;
f! {
pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () {
let bits = ::mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
(*set).fds_bits[fd / bits] &= !(1 << (fd % bits));
return
}
pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool {
let bits = ::mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0
}
pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () {
let bits = ::mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
(*set).fds_bits[fd / bits] |= 1 << (fd % bits);
return
}
pub fn FD_ZERO(set: *mut fd_set) -> () {
for slot in (*set).fds_bits.iter_mut() {
*slot = 0;
}
}
pub fn WIFEXITED(status: ::c_int) -> bool {
(status & 0xFF) == 0
}
pub fn WEXITSTATUS(status: ::c_int) -> ::c_int {
(status >> 8) & 0xFF
}
pub fn WTERMSIG(status: ::c_int) -> ::c_int {
status & 0x7F
}
pub fn WIFCONTINUED(status: ::c_int) -> bool {
(status & 0xffff) == 0xffff
}
pub fn WSTOPSIG(status: ::c_int) -> ::c_int {
(status & 0xff00) >> 8
}
pub fn WIFSIGNALED(status: ::c_int) -> bool {
((status & 0xff) > 0) && (status & 0xff00 == 0)
}
pub fn WIFSTOPPED(status: ::c_int) -> bool {
((status & 0xff) == 0x7f) && ((status & 0xff00) != 0)
}
pub fn WCOREDUMP(status: ::c_int) -> bool {
(status & 0x80) != 0
}
}
extern "C" {
pub fn getrlimit(resource: ::c_int, rlim: *mut ::rlimit) -> ::c_int;
pub fn setrlimit(resource: ::c_int, rlim: *const ::rlimit) -> ::c_int;
pub fn strerror_r(
errnum: ::c_int,
buf: *mut c_char,
buflen: ::size_t,
) -> ::c_int;
pub fn sem_destroy(sem: *mut sem_t) -> ::c_int;
pub fn sem_init(
sem: *mut sem_t,
pshared: ::c_int,
value: ::c_uint,
) -> ::c_int;
pub fn abs(i: ::c_int) -> ::c_int;
pub fn acct(filename: *const ::c_char) -> ::c_int;
pub fn atof(s: *const ::c_char) -> ::c_double;
pub fn dirfd(dirp: *mut ::DIR) -> ::c_int;
pub fn labs(i: ::c_long) -> ::c_long;
pub fn rand() -> ::c_int;
pub fn srand(seed: ::c_uint);
pub fn gettimeofday(tp: *mut ::timeval, tz: *mut ::c_void) -> ::c_int;
pub fn settimeofday(tp: *const ::timeval, tz: *const ::c_void) -> ::c_int;
pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int;
pub fn freeifaddrs(ifa: *mut ::ifaddrs);
pub fn stack_getbounds(sp: *mut ::stack_t) -> ::c_int;
pub fn mincore(
addr: *const ::c_void,
len: ::size_t,
vec: *mut c_char,
) -> ::c_int;
pub fn initgroups(name: *const ::c_char, basegid: ::gid_t) -> ::c_int;
pub fn setgroups(ngroups: ::c_int, ptr: *const ::gid_t) -> ::c_int;
pub fn ioctl(fildes: ::c_int, request: ::c_int, ...) -> ::c_int;
pub fn mprotect(
addr: *const ::c_void,
len: ::size_t,
prot: ::c_int,
) -> ::c_int;
pub fn ___errno() -> *mut ::c_int;
pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int;
pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int;
pub fn clock_nanosleep(
clk_id: ::clockid_t,
flags: ::c_int,
rqtp: *const ::timespec,
rmtp: *mut ::timespec,
) -> ::c_int;
pub fn clock_settime(
clk_id: ::clockid_t,
tp: *const ::timespec,
) -> ::c_int;
pub fn getnameinfo(
sa: *const ::sockaddr,
salen: ::socklen_t,
host: *mut ::c_char,
hostlen: ::socklen_t,
serv: *mut ::c_char,
sevlen: ::socklen_t,
flags: ::c_int,
) -> ::c_int;
pub fn setpwent();
pub fn endpwent();
pub fn getpwent() -> *mut passwd;
pub fn fdatasync(fd: ::c_int) -> ::c_int;
pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t)
-> *mut ::c_char;
pub fn duplocale(base: ::locale_t) -> ::locale_t;
pub fn freelocale(loc: ::locale_t);
pub fn newlocale(
mask: ::c_int,
locale: *const ::c_char,
base: ::locale_t,
) -> ::locale_t;
pub fn uselocale(loc: ::locale_t) -> ::locale_t;
pub fn getprogname() -> *const ::c_char;
pub fn setprogname(name: *const ::c_char);
pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int;
pub fn getpriority(which: ::c_int, who: ::c_int) -> ::c_int;
pub fn setpriority(which: ::c_int, who: ::c_int, prio: ::c_int)
-> ::c_int;
pub fn mknodat(
dirfd: ::c_int,
pathname: *const ::c_char,
mode: ::mode_t,
dev: dev_t,
) -> ::c_int;
pub fn mkfifoat(
dirfd: ::c_int,
pathname: *const ::c_char,
mode: ::mode_t,
) -> ::c_int;
pub fn sethostname(name: *const ::c_char, len: ::c_int) -> ::c_int;
pub fn if_nameindex() -> *mut if_nameindex;
pub fn if_freenameindex(ptr: *mut if_nameindex);
pub fn pthread_create(
native: *mut ::pthread_t,
attr: *const ::pthread_attr_t,
f: extern "C" fn(*mut ::c_void) -> *mut ::c_void,
value: *mut ::c_void,
) -> ::c_int;
pub fn pthread_condattr_getclock(
attr: *const pthread_condattr_t,
clock_id: *mut clockid_t,
) -> ::c_int;
pub fn pthread_condattr_setclock(
attr: *mut pthread_condattr_t,
clock_id: ::clockid_t,
) -> ::c_int;
pub fn sem_timedwait(
sem: *mut sem_t,
abstime: *const ::timespec,
) -> ::c_int;
pub fn sem_getvalue(sem: *mut sem_t, sval: *mut ::c_int) -> ::c_int;
pub fn pthread_mutex_timedlock(
lock: *mut pthread_mutex_t,
abstime: *const ::timespec,
) -> ::c_int;
pub fn waitid(
idtype: idtype_t,
id: id_t,
infop: *mut ::siginfo_t,
options: ::c_int,
) -> ::c_int;
pub fn glob(
pattern: *const ::c_char,
flags: ::c_int,
errfunc: ::Option<
extern "C" fn(epath: *const ::c_char, errno: ::c_int) -> ::c_int,
>,
pglob: *mut ::glob_t,
) -> ::c_int;
pub fn globfree(pglob: *mut ::glob_t);
pub fn posix_madvise(
addr: *mut ::c_void,
len: ::size_t,
advice: ::c_int,
) -> ::c_int;
pub fn shmat(
shmid: ::c_int,
shmaddr: *const ::c_void,
shmflg: ::c_int,
) -> *mut ::c_void;
pub fn shmctl(
shmid: ::c_int,
cmd: ::c_int,
buf: *mut ::shmid_ds,
) -> ::c_int;
pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int;
pub fn shmget(key: key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int;
pub fn shm_open(
name: *const ::c_char,
oflag: ::c_int,
mode: ::mode_t,
) -> ::c_int;
pub fn shm_unlink(name: *const ::c_char) -> ::c_int;
pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long);
pub fn telldir(dirp: *mut ::DIR) -> ::c_long;
pub fn madvise(
addr: *mut ::c_void,
len: ::size_t,
advice: ::c_int,
) -> ::c_int;
pub fn msync(
addr: *mut ::c_void,
len: ::size_t,
flags: ::c_int,
) -> ::c_int;
pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void;
pub fn recvfrom(
socket: ::c_int,
buf: *mut ::c_void,
len: ::size_t,
flags: ::c_int,
addr: *mut ::sockaddr,
addrlen: *mut ::socklen_t,
) -> ::ssize_t;
pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int;
pub fn futimesat(
fd: ::c_int,
path: *const ::c_char,
times: *const ::timeval,
) -> ::c_int;
pub fn futimens(dirfd: ::c_int, times: *const ::timespec) -> ::c_int;
pub fn utimensat(
dirfd: ::c_int,
path: *const ::c_char,
times: *const ::timespec,
flag: ::c_int,
) -> ::c_int;
pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char;
#[cfg_attr(target_os = "illumos", link_name = "__xnet_bind")]
pub fn bind(
socket: ::c_int,
address: *const ::sockaddr,
address_len: ::socklen_t,
) -> ::c_int;
pub fn writev(
fd: ::c_int,
iov: *const ::iovec,
iovcnt: ::c_int,
) -> ::ssize_t;
pub fn readv(
fd: ::c_int,
iov: *const ::iovec,
iovcnt: ::c_int,
) -> ::ssize_t;
#[cfg_attr(target_os = "illumos", link_name = "__xnet_sendmsg")]
pub fn sendmsg(
fd: ::c_int,
msg: *const ::msghdr,
flags: ::c_int,
) -> ::ssize_t;
#[cfg_attr(target_os = "illumos", link_name = "__xnet_recvmsg")]
pub fn recvmsg(
fd: ::c_int,
msg: *mut ::msghdr,
flags: ::c_int,
) -> ::ssize_t;
pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t;
pub fn mq_close(mqd: ::mqd_t) -> ::c_int;
pub fn mq_unlink(name: *const ::c_char) -> ::c_int;
pub fn mq_receive(
mqd: ::mqd_t,
msg_ptr: *mut ::c_char,
msg_len: ::size_t,
msg_prio: *mut ::c_uint,
) -> ::ssize_t;
pub fn mq_timedreceive(
mqd: ::mqd_t,
msg_ptr: *mut ::c_char,
msg_len: ::size_t,
msg_prio: *mut ::c_uint,
abs_timeout: *const ::timespec,
) -> ::ssize_t;
pub fn mq_send(
mqd: ::mqd_t,
msg_ptr: *const ::c_char,
msg_len: ::size_t,
msg_prio: ::c_uint,
) -> ::c_int;
pub fn mq_timedsend(
mqd: ::mqd_t,
msg_ptr: *const ::c_char,
msg_len: ::size_t,
msg_prio: ::c_uint,
abs_timeout: *const ::timespec,
) -> ::c_int;
pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int;
pub fn mq_setattr(
mqd: ::mqd_t,
newattr: *const ::mq_attr,
oldattr: *mut ::mq_attr,
) -> ::c_int;
pub fn port_create() -> ::c_int;
pub fn port_associate(
port: ::c_int,
source: ::c_int,
object: ::uintptr_t,
events: ::c_int,
user: *mut ::c_void,
) -> ::c_int;
pub fn port_dissociate(
port: ::c_int,
source: ::c_int,
object: ::uintptr_t,
) -> ::c_int;
pub fn port_get(
port: ::c_int,
pe: *mut port_event,
timeout: *mut ::timespec,
) -> ::c_int;
pub fn port_getn(
port: ::c_int,
pe_list: *mut port_event,
max: ::c_uint,
nget: *mut ::c_uint,
timeout: *mut ::timespec,
) -> ::c_int;
pub fn port_send(
port: ::c_int,
events: ::c_int,
user: *mut ::c_void,
) -> ::c_int;
pub fn port_sendn(
port_list: *mut ::c_int,
error_list: *mut ::c_int,
nent: ::c_uint,
events: ::c_int,
user: *mut ::c_void,
) -> ::c_int;
pub fn fexecve(
fd: ::c_int,
argv: *const *const ::c_char,
envp: *const *const ::c_char,
) -> ::c_int;
#[cfg_attr(
any(target_os = "solaris", target_os = "illumos"),
link_name = "__posix_getgrgid_r"
)]
pub fn getgrgid_r(
gid: ::gid_t,
grp: *mut ::group,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut ::group,
) -> ::c_int;
pub fn sigaltstack(ss: *const stack_t, oss: *mut stack_t) -> ::c_int;
pub fn sem_close(sem: *mut sem_t) -> ::c_int;
pub fn getdtablesize() -> ::c_int;
// The epoll functions are actually only present on illumos. However,
// there are things using epoll on illumos (built using the
// x86_64-sun-solaris target) which would break until the illumos target is
// present in rustc.
pub fn epoll_pwait(
epfd: ::c_int,
events: *mut ::epoll_event,
maxevents: ::c_int,
timeout: ::c_int,
sigmask: *const ::sigset_t,
) -> ::c_int;
pub fn epoll_create(size: ::c_int) -> ::c_int;
pub fn epoll_create1(flags: ::c_int) -> ::c_int;
pub fn epoll_wait(
epfd: ::c_int,
events: *mut ::epoll_event,
maxevents: ::c_int,
timeout: ::c_int,
) -> ::c_int;
pub fn epoll_ctl(
epfd: ::c_int,
op: ::c_int,
fd: ::c_int,
event: *mut ::epoll_event,
) -> ::c_int;
#[cfg_attr(
any(target_os = "solaris", target_os = "illumos"),
link_name = "__posix_getgrnam_r"
)]
pub fn getgrnam_r(
name: *const ::c_char,
grp: *mut ::group,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut ::group,
) -> ::c_int;
pub fn pthread_sigmask(
how: ::c_int,
set: *const sigset_t,
oldset: *mut sigset_t,
) -> ::c_int;
pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t;
pub fn getgrnam(name: *const ::c_char) -> *mut ::group;
pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int;
pub fn sem_unlink(name: *const ::c_char) -> ::c_int;
pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int;
#[cfg_attr(
any(target_os = "solaris", target_os = "illumos"),
link_name = "__posix_getpwnam_r"
)]
pub fn getpwnam_r(
name: *const ::c_char,
pwd: *mut passwd,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut passwd,
) -> ::c_int;
#[cfg_attr(
any(target_os = "solaris", target_os = "illumos"),
link_name = "__posix_getpwuid_r"
)]
pub fn getpwuid_r(
uid: ::uid_t,
pwd: *mut passwd,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut passwd,
) -> ::c_int;
#[cfg_attr(
any(target_os = "solaris", target_os = "illumos"),
link_name = "__posix_getpwent_r"
)]
pub fn getpwent_r(
pwd: *mut passwd,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut passwd,
) -> ::c_int;
#[cfg_attr(
any(target_os = "solaris", target_os = "illumos"),
link_name = "__posix_getgrent_r"
)]
pub fn getgrent_r(
grp: *mut ::group,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut ::group,
) -> ::c_int;
#[cfg_attr(
any(target_os = "solaris", target_os = "illumos"),
link_name = "__posix_sigwait"
)]
pub fn sigwait(set: *const sigset_t, sig: *mut ::c_int) -> ::c_int;
pub fn pthread_atfork(
prepare: ::Option<unsafe extern "C" fn()>,
parent: ::Option<unsafe extern "C" fn()>,
child: ::Option<unsafe extern "C" fn()>,
) -> ::c_int;
pub fn getgrgid(gid: ::gid_t) -> *mut ::group;
pub fn setgrent();
pub fn endgrent();
pub fn getgrent() -> *mut ::group;
pub fn popen(command: *const c_char, mode: *const c_char) -> *mut ::FILE;
pub fn dup3(src: ::c_int, dst: ::c_int, flags: ::c_int) -> ::c_int;
pub fn uname(buf: *mut ::utsname) -> ::c_int;
pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int;
pub fn door_call(d: ::c_int, params: *const door_arg_t) -> ::c_int;
pub fn door_return(
data_ptr: *const ::c_char,
data_size: ::size_t,
desc_ptr: *const door_desc_t,
num_desc: ::c_uint,
);
pub fn door_create(
server_procedure: extern "C" fn(
cookie: *const ::c_void,
argp: *const ::c_char,
arg_size: ::size_t,
dp: *const door_desc_t,
n_desc: ::c_uint,
),
cookie: *const ::c_void,
attributes: door_attr_t,
) -> ::c_int;
pub fn fattach(fildes: ::c_int, path: *const ::c_char) -> ::c_int;
pub fn makeutx(ux: *const utmpx) -> *mut utmpx;
pub fn modutx(ux: *const utmpx) -> *mut utmpx;
pub fn updwtmpx(file: *const ::c_char, ut: *const utmpx) -> ::c_int;
pub fn utmpxname(file: *const ::c_char) -> ::c_int;
pub fn getutxent() -> *mut utmpx;
pub fn getutxid(ut: *const utmpx) -> *mut utmpx;
pub fn getutxline(ut: *const utmpx) -> *mut utmpx;
pub fn pututxline(ut: *const utmpx) -> *mut utmpx;
pub fn setutxent();
pub fn endutxent();
pub fn endutent();
pub fn getutent() -> *mut utmp;
pub fn getutid(u: *const utmp) -> *mut utmp;
pub fn getutline(u: *const utmp) -> *mut utmp;
pub fn pututline(u: *const utmp) -> *mut utmp;
pub fn setutent();
pub fn utmpname(file: *const ::c_char) -> ::c_int;
pub fn getutmp(ux: *const utmpx, u: *mut utmp);
pub fn getutmpx(u: *const utmp, ux: *mut utmpx);
pub fn updwtmp(file: *const ::c_char, u: *mut utmp);
pub fn ntp_adjtime(buf: *mut timex) -> ::c_int;
pub fn ntp_gettime(buf: *mut ntptimeval) -> ::c_int;
}
mod compat;
pub use self::compat::*;
| 33.370427 | 80 | 0.60951 |
917a3cce19ec766161943800c80722f3d0118f50
| 155 |
extern crate test_adder;
mod common;
#[test]
fn it_adds_two() {
common::setup();
assert_eq!(4, test_adder::add_two(2));
common::teardown();
}
| 15.5 | 42 | 0.645161 |
ac3f8db82ae5b5b44ca7789d9b6384fcb85ad84c
| 93,928 |
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::sync::Arc;
use std::time::Instant;
use std::{cmp, error, u64};
use engine_traits::CF_RAFT;
use engine_traits::{KvEngine, KvEngines, Mutable, Peekable, WriteBatch};
use keys::{self, enc_end_key, enc_start_key};
use kvproto::metapb::{self, Region};
use kvproto::raft_serverpb::{
MergeState, PeerState, RaftApplyState, RaftLocalState, RaftSnapshotData, RegionLocalState,
};
use protobuf::Message;
use raft::eraftpb::{ConfState, Entry, HardState, Snapshot};
use raft::{self, Error as RaftError, RaftState, Ready, Storage, StorageError};
use crate::store::fsm::GenSnapTask;
use crate::store::util::conf_state_from_region;
use crate::store::ProposalContext;
use crate::{Error, Result};
use into_other::into_other;
use tikv_util::worker::Scheduler;
use super::metrics::*;
use super::worker::RegionTask;
use super::{SnapEntry, SnapKey, SnapManager, SnapshotStatistics};
// When we create a region peer, we should initialize its log term/index > 0,
// so that we can force the follower peer to sync the snapshot first.
pub const RAFT_INIT_LOG_TERM: u64 = 5;
pub const RAFT_INIT_LOG_INDEX: u64 = 5;
const MAX_SNAP_TRY_CNT: usize = 5;
const RAFT_LOG_MULTI_GET_CNT: u64 = 8;
/// The initial region epoch version.
pub const INIT_EPOCH_VER: u64 = 1;
/// The initial region epoch conf_version.
pub const INIT_EPOCH_CONF_VER: u64 = 1;
// One extra slot for VecDeque internal usage.
const MAX_CACHE_CAPACITY: usize = 1024 - 1;
const SHRINK_CACHE_CAPACITY: usize = 64;
pub const JOB_STATUS_PENDING: usize = 0;
pub const JOB_STATUS_RUNNING: usize = 1;
pub const JOB_STATUS_CANCELLING: usize = 2;
pub const JOB_STATUS_CANCELLED: usize = 3;
pub const JOB_STATUS_FINISHED: usize = 4;
pub const JOB_STATUS_FAILED: usize = 5;
/// Possible status returned by `check_applying_snap`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CheckApplyingSnapStatus {
/// A snapshot is just applied.
Success,
/// A snapshot is being applied.
Applying,
/// No snapshot is being applied at all or the snapshot is cancelled
Idle,
}
#[derive(Debug)]
pub enum SnapState {
Relax,
Generating(Receiver<Snapshot>),
Applying(Arc<AtomicUsize>),
ApplyAborted,
}
impl PartialEq for SnapState {
fn eq(&self, other: &SnapState) -> bool {
match (self, other) {
(&SnapState::Relax, &SnapState::Relax)
| (&SnapState::ApplyAborted, &SnapState::ApplyAborted)
| (&SnapState::Generating(_), &SnapState::Generating(_)) => true,
(&SnapState::Applying(ref b1), &SnapState::Applying(ref b2)) => {
b1.load(Ordering::Relaxed) == b2.load(Ordering::Relaxed)
}
_ => false,
}
}
}
#[inline]
pub fn first_index(state: &RaftApplyState) -> u64 {
state.get_truncated_state().get_index() + 1
}
#[inline]
pub fn last_index(state: &RaftLocalState) -> u64 {
state.get_last_index()
}
pub const ENTRY_MEM_SIZE: usize = std::mem::size_of::<Entry>();
struct EntryCache {
cache: VecDeque<Entry>,
mem_size_change: i64,
}
impl EntryCache {
fn first_index(&self) -> Option<u64> {
self.cache.front().map(|e| e.get_index())
}
fn fetch_entries_to(
&self,
begin: u64,
end: u64,
mut fetched_size: u64,
max_size: u64,
ents: &mut Vec<Entry>,
) {
if begin >= end {
return;
}
assert!(!self.cache.is_empty());
let cache_low = self.cache.front().unwrap().get_index();
let start_idx = begin.checked_sub(cache_low).unwrap() as usize;
let limit_idx = end.checked_sub(cache_low).unwrap() as usize;
let mut end_idx = start_idx;
self.cache
.iter()
.skip(start_idx)
.take_while(|e| {
let cur_idx = end_idx as u64 + cache_low;
assert_eq!(e.get_index(), cur_idx);
let m = u64::from(e.compute_size());
fetched_size += m;
if fetched_size == m {
end_idx += 1;
fetched_size <= max_size && end_idx < limit_idx
} else if fetched_size <= max_size {
end_idx += 1;
end_idx < limit_idx
} else {
false
}
})
.count();
// Cache either is empty or contains latest log. Hence we don't need to fetch log
// from rocksdb anymore.
assert!(end_idx == limit_idx || fetched_size > max_size);
let (first, second) = tikv_util::slices_in_range(&self.cache, start_idx, end_idx);
ents.extend_from_slice(first);
ents.extend_from_slice(second);
}
fn append(&mut self, tag: &str, entries: &[Entry]) {
if entries.is_empty() {
return;
}
if let Some(cache_last_index) = self.cache.back().map(|e| e.get_index()) {
let first_index = entries[0].get_index();
if cache_last_index >= first_index {
if self.cache.front().unwrap().get_index() >= first_index {
self.update_mem_size_change_before_clear();
self.cache.clear();
} else {
let left = self.cache.len() - (cache_last_index - first_index + 1) as usize;
self.mem_size_change -= self
.cache
.iter()
.skip(left)
.map(|e| (e.data.capacity() + e.context.capacity()) as i64)
.sum::<i64>();
self.cache.truncate(left);
}
if self.cache.len() + entries.len() < SHRINK_CACHE_CAPACITY
&& self.cache.capacity() > SHRINK_CACHE_CAPACITY
{
let old_capacity = self.cache.capacity();
self.cache.shrink_to_fit();
self.mem_size_change += self.get_cache_vec_mem_size_change(
self.cache.capacity() as i64,
old_capacity as i64,
)
}
} else if cache_last_index + 1 < first_index {
panic!(
"{} unexpected hole: {} < {}",
tag, cache_last_index, first_index
);
}
}
let mut start_idx = 0;
if let Some(len) = (self.cache.len() + entries.len()).checked_sub(MAX_CACHE_CAPACITY) {
if len < self.cache.len() {
let mut drained_cache_entries_size = 0;
self.cache.drain(..len).for_each(|e| {
drained_cache_entries_size += (e.data.capacity() + e.context.capacity()) as i64
});
self.mem_size_change -= drained_cache_entries_size;
} else {
start_idx = len - self.cache.len();
self.update_mem_size_change_before_clear();
self.cache.clear();
}
}
let old_capacity = self.cache.capacity();
let mut entries_mem_size = 0;
for e in &entries[start_idx..] {
self.cache.push_back(e.to_owned());
entries_mem_size += (e.data.capacity() + e.context.capacity()) as i64;
}
self.mem_size_change += self
.get_cache_vec_mem_size_change(self.cache.capacity() as i64, old_capacity as i64)
+ entries_mem_size;
}
pub fn compact_to(&mut self, idx: u64) {
let cache_first_idx = self.first_index().unwrap_or(u64::MAX);
if cache_first_idx > idx {
return;
}
let mut drained_cache_entries_size = 0;
let cache_last_idx = self.cache.back().unwrap().get_index();
// Use `cache_last_idx + 1` to make sure cache can be cleared completely
// if necessary.
self.cache
.drain(..(cmp::min(cache_last_idx + 1, idx) - cache_first_idx) as usize)
.for_each(|e| {
drained_cache_entries_size += (e.data.capacity() + e.context.capacity()) as i64
});
self.mem_size_change -= drained_cache_entries_size;
if self.cache.len() < SHRINK_CACHE_CAPACITY && self.cache.capacity() > SHRINK_CACHE_CAPACITY
{
let old_capacity = self.cache.capacity();
// So the peer storage doesn't have much writes since the proposal of compaction,
// we can consider this peer is going to be inactive.
self.cache.shrink_to_fit();
self.mem_size_change += self
.get_cache_vec_mem_size_change(self.cache.capacity() as i64, old_capacity as i64)
}
}
fn update_mem_size_change_before_clear(&mut self) {
self.mem_size_change -= self
.cache
.iter()
.map(|e| (e.data.capacity() + e.context.capacity()) as i64)
.sum::<i64>();
}
fn get_cache_vec_mem_size_change(&self, new_capacity: i64, old_capacity: i64) -> i64 {
ENTRY_MEM_SIZE as i64 * (new_capacity - old_capacity)
}
fn get_total_mem_size(&self) -> i64 {
let data_size: usize = self
.cache
.iter()
.map(|e| e.data.capacity() + e.context.capacity())
.sum();
(ENTRY_MEM_SIZE * self.cache.capacity() + data_size) as i64
}
fn flush_mem_size_change(&mut self) {
if self.mem_size_change == 0 {
return;
}
RAFT_ENTRIES_CACHES_GAUGE.add(self.mem_size_change);
self.mem_size_change = 0;
}
#[inline]
fn is_empty(&self) -> bool {
self.cache.is_empty()
}
}
impl Default for EntryCache {
fn default() -> Self {
let cache = VecDeque::default();
RAFT_ENTRIES_CACHES_GAUGE.add((ENTRY_MEM_SIZE * cache.capacity()) as i64);
EntryCache {
cache,
mem_size_change: 0,
}
}
}
impl Drop for EntryCache {
fn drop(&mut self) {
self.flush_mem_size_change();
RAFT_ENTRIES_CACHES_GAUGE.sub(self.get_total_mem_size());
}
}
#[derive(Default)]
pub struct CacheQueryStats {
pub hit: Cell<u64>,
pub miss: Cell<u64>,
}
impl CacheQueryStats {
pub fn flush(&mut self) {
if self.hit.get() > 0 {
RAFT_ENTRY_FETCHES.hit.inc_by(self.hit.replace(0) as i64);
}
if self.miss.get() > 0 {
RAFT_ENTRY_FETCHES.miss.inc_by(self.miss.replace(0) as i64);
}
}
}
pub trait HandleRaftReadyContext<WK, WR>
where
WK: WriteBatch,
WR: WriteBatch,
{
/// Returns the mutable references of WriteBatch for both KvDB and RaftDB in one interface.
fn wb_mut(&mut self) -> (&mut WK, &mut WR);
fn kv_wb_mut(&mut self) -> &mut WK;
fn raft_wb_mut(&mut self) -> &mut WR;
fn sync_log(&self) -> bool;
fn set_sync_log(&mut self, sync: bool);
}
fn storage_error<E>(error: E) -> raft::Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
raft::Error::Store(StorageError::Other(error.into()))
}
impl From<Error> for RaftError {
fn from(err: Error) -> RaftError {
storage_error(err)
}
}
pub struct ApplySnapResult {
// prev_region is the region before snapshot applied.
pub prev_region: metapb::Region,
pub region: metapb::Region,
}
/// Returned by `PeerStorage::handle_raft_ready`, used for recording changed status of
/// `RaftLocalState` and `RaftApplyState`.
pub struct InvokeContext {
pub region_id: u64,
/// Changed RaftLocalState is stored into `raft_state`.
pub raft_state: RaftLocalState,
/// Changed RaftApplyState is stored into `apply_state`.
pub apply_state: RaftApplyState,
last_term: u64,
/// The old region is stored here if there is a snapshot.
pub snap_region: Option<Region>,
}
impl InvokeContext {
pub fn new(store: &PeerStorage<impl KvEngine, impl KvEngine>) -> InvokeContext {
InvokeContext {
region_id: store.get_region_id(),
raft_state: store.raft_state.clone(),
apply_state: store.apply_state.clone(),
last_term: store.last_term,
snap_region: None,
}
}
#[inline]
pub fn has_snapshot(&self) -> bool {
self.snap_region.is_some()
}
#[inline]
pub fn save_raft_state_to(&self, raft_wb: &mut impl WriteBatch) -> Result<()> {
raft_wb.put_msg(&keys::raft_state_key(self.region_id), &self.raft_state)?;
Ok(())
}
#[inline]
pub fn save_snapshot_raft_state_to(
&self,
snapshot_index: u64,
kv_wb: &mut impl WriteBatch,
) -> Result<()> {
let mut snapshot_raft_state = self.raft_state.clone();
snapshot_raft_state
.mut_hard_state()
.set_commit(snapshot_index);
snapshot_raft_state.set_last_index(snapshot_index);
kv_wb.put_msg_cf(
CF_RAFT,
&keys::snapshot_raft_state_key(self.region_id),
&snapshot_raft_state,
)?;
Ok(())
}
#[inline]
pub fn save_apply_state_to(&self, kv_wb: &mut impl WriteBatch) -> Result<()> {
kv_wb.put_msg_cf(
CF_RAFT,
&keys::apply_state_key(self.region_id),
&self.apply_state,
)?;
Ok(())
}
}
pub fn recover_from_applying_state(
engines: &KvEngines<impl KvEngine, impl KvEngine>,
raft_wb: &mut impl WriteBatch,
region_id: u64,
) -> Result<()> {
let snapshot_raft_state_key = keys::snapshot_raft_state_key(region_id);
let snapshot_raft_state: RaftLocalState =
match box_try!(engines.kv.get_msg_cf(CF_RAFT, &snapshot_raft_state_key)) {
Some(state) => state,
None => {
return Err(box_err!(
"[region {}] failed to get raftstate from kv engine, \
when recover from applying state",
region_id
));
}
};
let raft_state_key = keys::raft_state_key(region_id);
let raft_state: RaftLocalState = match box_try!(engines.raft.get_msg(&raft_state_key)) {
Some(state) => state,
None => RaftLocalState::default(),
};
// if we recv append log when applying snapshot, last_index in raft_local_state will
// larger than snapshot_index. since raft_local_state is written to raft engine, and
// raft write_batch is written after kv write_batch, raft_local_state may wrong if
// restart happen between the two write. so we copy raft_local_state to kv engine
// (snapshot_raft_state), and set snapshot_raft_state.last_index = snapshot_index.
// after restart, we need check last_index.
if last_index(&snapshot_raft_state) > last_index(&raft_state) {
raft_wb.put_msg(&raft_state_key, &snapshot_raft_state)?;
}
Ok(())
}
fn init_applied_index_term(
engines: &KvEngines<impl KvEngine, impl KvEngine>,
region: &Region,
apply_state: &RaftApplyState,
) -> Result<u64> {
if apply_state.applied_index == RAFT_INIT_LOG_INDEX {
return Ok(RAFT_INIT_LOG_TERM);
}
let truncated_state = apply_state.get_truncated_state();
if apply_state.applied_index == truncated_state.get_index() {
return Ok(truncated_state.get_term());
}
let state_key = keys::raft_log_key(region.get_id(), apply_state.applied_index);
match engines.raft.get_msg::<Entry>(&state_key)? {
Some(e) => Ok(e.term),
None => Err(box_err!(
"[region {}] entry at apply index {} doesn't exist, may lose data.",
region.get_id(),
apply_state.applied_index
)),
}
}
fn init_raft_state(
engines: &KvEngines<impl KvEngine, impl KvEngine>,
region: &Region,
) -> Result<RaftLocalState> {
let state_key = keys::raft_state_key(region.get_id());
Ok(match engines.raft.get_msg(&state_key)? {
Some(s) => s,
None => {
let mut raft_state = RaftLocalState::default();
if !region.get_peers().is_empty() {
// new split region
raft_state.set_last_index(RAFT_INIT_LOG_INDEX);
raft_state.mut_hard_state().set_term(RAFT_INIT_LOG_TERM);
raft_state.mut_hard_state().set_commit(RAFT_INIT_LOG_INDEX);
engines.raft.put_msg(&state_key, &raft_state)?;
}
raft_state
}
})
}
fn init_apply_state(
engines: &KvEngines<impl KvEngine, impl KvEngine>,
region: &Region,
) -> Result<RaftApplyState> {
Ok(
match engines
.kv
.get_msg_cf(CF_RAFT, &keys::apply_state_key(region.get_id()))?
{
Some(s) => s,
None => {
let mut apply_state = RaftApplyState::default();
if !region.get_peers().is_empty() {
apply_state.set_applied_index(RAFT_INIT_LOG_INDEX);
let state = apply_state.mut_truncated_state();
state.set_index(RAFT_INIT_LOG_INDEX);
state.set_term(RAFT_INIT_LOG_TERM);
}
apply_state
}
},
)
}
fn validate_states(
region_id: u64,
engines: &KvEngines<impl KvEngine, impl KvEngine>,
raft_state: &mut RaftLocalState,
apply_state: &RaftApplyState,
) -> Result<()> {
let last_index = raft_state.get_last_index();
let mut commit_index = raft_state.get_hard_state().get_commit();
let apply_index = apply_state.get_applied_index();
if commit_index < apply_state.get_last_commit_index() {
return Err(box_err!(
"raft state {:?} not match apply state {:?} and can't be recovered.",
raft_state,
apply_state
));
}
let recorded_commit_index = apply_state.get_commit_index();
if commit_index < recorded_commit_index {
let log_key = keys::raft_log_key(region_id, recorded_commit_index);
let entry = engines.raft.get_msg::<Entry>(&log_key)?;
if entry.map_or(true, |e| e.get_term() != apply_state.get_commit_term()) {
return Err(box_err!(
"log at recorded commit index [{}] {} doesn't exist, may lose data",
apply_state.get_commit_term(),
recorded_commit_index
));
}
info!("updating commit index"; "region_id" => region_id, "old" => commit_index, "new" => recorded_commit_index);
commit_index = recorded_commit_index;
}
if commit_index > last_index || apply_index > commit_index {
return Err(box_err!(
"raft state {:?} not match apply state {:?} and can't be recovered,",
raft_state,
apply_state
));
}
raft_state.mut_hard_state().set_commit(commit_index);
if raft_state.get_hard_state().get_term() < apply_state.get_commit_term() {
return Err(box_err!("raft state {:?} corrupted", raft_state));
}
Ok(())
}
fn init_last_term(
engines: &KvEngines<impl KvEngine, impl KvEngine>,
region: &Region,
raft_state: &RaftLocalState,
apply_state: &RaftApplyState,
) -> Result<u64> {
let last_idx = raft_state.get_last_index();
if last_idx == 0 {
return Ok(0);
} else if last_idx == RAFT_INIT_LOG_INDEX {
return Ok(RAFT_INIT_LOG_TERM);
} else if last_idx == apply_state.get_truncated_state().get_index() {
return Ok(apply_state.get_truncated_state().get_term());
} else {
assert!(last_idx > RAFT_INIT_LOG_INDEX);
}
let last_log_key = keys::raft_log_key(region.get_id(), last_idx);
let entry = engines.raft.get_msg::<Entry>(&last_log_key)?;
match entry {
None => Err(box_err!(
"[region {}] entry at {} doesn't exist, may lose data.",
region.get_id(),
last_idx
)),
Some(e) => Ok(e.get_term()),
}
}
pub struct PeerStorage<EK, ER>
where
EK: KvEngine,
{
pub engines: KvEngines<EK, ER>,
peer_id: u64,
region: metapb::Region,
raft_state: RaftLocalState,
apply_state: RaftApplyState,
applied_index_term: u64,
last_term: u64,
snap_state: RefCell<SnapState>,
gen_snap_task: RefCell<Option<GenSnapTask>>,
region_sched: Scheduler<RegionTask<EK::Snapshot>>,
snap_tried_cnt: RefCell<usize>,
cache: EntryCache,
stats: CacheQueryStats,
pub tag: String,
}
impl<EK, ER> Storage for PeerStorage<EK, ER>
where
EK: KvEngine,
ER: KvEngine,
{
fn initial_state(&self) -> raft::Result<RaftState> {
self.initial_state()
}
fn entries(
&self,
low: u64,
high: u64,
max_size: impl Into<Option<u64>>,
) -> raft::Result<Vec<Entry>> {
self.entries(low, high, max_size.into().unwrap_or(u64::MAX))
}
fn term(&self, idx: u64) -> raft::Result<u64> {
self.term(idx)
}
fn first_index(&self) -> raft::Result<u64> {
Ok(self.first_index())
}
fn last_index(&self) -> raft::Result<u64> {
Ok(self.last_index())
}
fn snapshot(&self, request_index: u64) -> raft::Result<Snapshot> {
self.snapshot(request_index)
}
}
impl<EK, ER> PeerStorage<EK, ER>
where
EK: KvEngine,
ER: KvEngine,
{
pub fn new(
engines: KvEngines<EK, ER>,
region: &metapb::Region,
region_sched: Scheduler<RegionTask<EK::Snapshot>>,
peer_id: u64,
tag: String,
) -> Result<PeerStorage<EK, ER>> {
debug!(
"creating storage on specified path";
"region_id" => region.get_id(),
"peer_id" => peer_id,
"path" => ?engines.kv.path(),
);
let mut raft_state = init_raft_state(&engines, region)?;
let apply_state = init_apply_state(&engines, region)?;
if let Err(e) = validate_states(region.get_id(), &engines, &mut raft_state, &apply_state) {
return Err(box_err!("{} validate state fail: {:?}", tag, e));
}
let last_term = init_last_term(&engines, region, &raft_state, &apply_state)?;
let applied_index_term = init_applied_index_term(&engines, region, &apply_state)?;
Ok(PeerStorage {
engines,
peer_id,
region: region.clone(),
raft_state,
apply_state,
snap_state: RefCell::new(SnapState::Relax),
gen_snap_task: RefCell::new(None),
region_sched,
snap_tried_cnt: RefCell::new(0),
tag,
applied_index_term,
last_term,
cache: EntryCache::default(),
stats: CacheQueryStats::default(),
})
}
pub fn is_initialized(&self) -> bool {
!self.region().get_peers().is_empty()
}
pub fn initial_state(&self) -> raft::Result<RaftState> {
let hard_state = self.raft_state.get_hard_state().clone();
if hard_state == HardState::default() {
assert!(
!self.is_initialized(),
"peer for region {:?} is initialized but local state {:?} has empty hard \
state",
self.region,
self.raft_state
);
return Ok(RaftState::new(hard_state, ConfState::default()));
}
Ok(RaftState::new(
hard_state,
conf_state_from_region(self.region()),
))
}
fn check_range(&self, low: u64, high: u64) -> raft::Result<()> {
if low > high {
return Err(storage_error(format!(
"low: {} is greater that high: {}",
low, high
)));
} else if low <= self.truncated_index() {
return Err(RaftError::Store(StorageError::Compacted));
} else if high > self.last_index() + 1 {
return Err(storage_error(format!(
"entries' high {} is out of bound lastindex {}",
high,
self.last_index()
)));
}
Ok(())
}
pub fn entries(&self, low: u64, high: u64, max_size: u64) -> raft::Result<Vec<Entry>> {
self.check_range(low, high)?;
let mut ents = Vec::with_capacity((high - low) as usize);
if low == high {
return Ok(ents);
}
let cache_low = self.cache.first_index().unwrap_or(u64::MAX);
let region_id = self.get_region_id();
if high <= cache_low {
// not overlap
self.stats.miss.update(|m| m + 1);
fetch_entries_to(
&self.engines.raft,
region_id,
low,
high,
max_size,
&mut ents,
)?;
return Ok(ents);
}
let mut fetched_size = 0;
let begin_idx = if low < cache_low {
self.stats.miss.update(|m| m + 1);
fetched_size = fetch_entries_to(
&self.engines.raft,
region_id,
low,
cache_low,
max_size,
&mut ents,
)?;
if fetched_size > max_size {
// max_size exceed.
return Ok(ents);
}
cache_low
} else {
low
};
self.stats.hit.update(|h| h + 1);
self.cache
.fetch_entries_to(begin_idx, high, fetched_size, max_size, &mut ents);
Ok(ents)
}
pub fn term(&self, idx: u64) -> raft::Result<u64> {
if idx == self.truncated_index() {
return Ok(self.truncated_term());
}
self.check_range(idx, idx + 1)?;
if self.truncated_term() == self.last_term || idx == self.last_index() {
return Ok(self.last_term);
}
let entries = self.entries(idx, idx + 1, raft::NO_LIMIT)?;
Ok(entries[0].get_term())
}
#[inline]
pub fn first_index(&self) -> u64 {
first_index(&self.apply_state)
}
#[inline]
pub fn last_index(&self) -> u64 {
last_index(&self.raft_state)
}
#[inline]
pub fn last_term(&self) -> u64 {
self.last_term
}
#[inline]
pub fn applied_index(&self) -> u64 {
self.apply_state.get_applied_index()
}
#[inline]
pub fn set_applied_state(&mut self, apply_state: RaftApplyState) {
self.apply_state = apply_state;
}
#[inline]
pub fn set_applied_term(&mut self, applied_index_term: u64) {
self.applied_index_term = applied_index_term;
}
#[inline]
pub fn apply_state(&self) -> &RaftApplyState {
&self.apply_state
}
#[inline]
pub fn applied_index_term(&self) -> u64 {
self.applied_index_term
}
#[inline]
pub fn committed_index(&self) -> u64 {
self.raft_state.get_hard_state().get_commit()
}
#[inline]
pub fn truncated_index(&self) -> u64 {
self.apply_state.get_truncated_state().get_index()
}
#[inline]
pub fn truncated_term(&self) -> u64 {
self.apply_state.get_truncated_state().get_term()
}
pub fn region(&self) -> &metapb::Region {
&self.region
}
pub fn set_region(&mut self, region: metapb::Region) {
self.region = region;
}
pub fn raw_snapshot(&self) -> EK::Snapshot {
self.engines.kv.snapshot()
}
fn validate_snap(&self, snap: &Snapshot, request_index: u64) -> bool {
let idx = snap.get_metadata().get_index();
if idx < self.truncated_index() || idx < request_index {
// stale snapshot, should generate again.
info!(
"snapshot is stale, generate again";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"snap_index" => idx,
"truncated_index" => self.truncated_index(),
"request_index" => request_index,
);
STORE_SNAPSHOT_VALIDATION_FAILURE_COUNTER.stale.inc();
return false;
}
let mut snap_data = RaftSnapshotData::default();
if let Err(e) = snap_data.merge_from_bytes(snap.get_data()) {
error!(
"failed to decode snapshot, it may be corrupted";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"err" => ?e,
);
STORE_SNAPSHOT_VALIDATION_FAILURE_COUNTER.decode.inc();
return false;
}
let snap_epoch = snap_data.get_region().get_region_epoch();
let latest_epoch = self.region().get_region_epoch();
if snap_epoch.get_conf_ver() < latest_epoch.get_conf_ver() {
info!(
"snapshot epoch is stale";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"snap_epoch" => ?snap_epoch,
"latest_epoch" => ?latest_epoch,
);
STORE_SNAPSHOT_VALIDATION_FAILURE_COUNTER.epoch.inc();
return false;
}
true
}
/// Gets a snapshot. Returns `SnapshotTemporarilyUnavailable` if there is no unavailable
/// snapshot.
pub fn snapshot(&self, request_index: u64) -> raft::Result<Snapshot> {
let mut snap_state = self.snap_state.borrow_mut();
let mut tried_cnt = self.snap_tried_cnt.borrow_mut();
let (mut tried, mut snap) = (false, None);
if let SnapState::Generating(ref recv) = *snap_state {
tried = true;
match recv.try_recv() {
Err(TryRecvError::Disconnected) => {}
Err(TryRecvError::Empty) => {
return Err(raft::Error::Store(
raft::StorageError::SnapshotTemporarilyUnavailable,
));
}
Ok(s) => snap = Some(s),
}
}
if tried {
*snap_state = SnapState::Relax;
match snap {
Some(s) => {
*tried_cnt = 0;
if self.validate_snap(&s, request_index) {
return Ok(s);
}
}
None => {
warn!(
"failed to try generating snapshot";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"times" => *tried_cnt,
);
}
}
}
if SnapState::Relax != *snap_state {
panic!("{} unexpected state: {:?}", self.tag, *snap_state);
}
if *tried_cnt >= MAX_SNAP_TRY_CNT {
let cnt = *tried_cnt;
*tried_cnt = 0;
return Err(raft::Error::Store(box_err!(
"failed to get snapshot after {} times",
cnt
)));
}
info!(
"requesting snapshot";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"request_index" => request_index,
);
*tried_cnt += 1;
let (tx, rx) = mpsc::sync_channel(1);
*snap_state = SnapState::Generating(rx);
let task = GenSnapTask::new(self.region.get_id(), self.committed_index(), tx);
let mut gen_snap_task = self.gen_snap_task.borrow_mut();
assert!(gen_snap_task.is_none());
*gen_snap_task = Some(task);
Err(raft::Error::Store(
raft::StorageError::SnapshotTemporarilyUnavailable,
))
}
pub fn take_gen_snap_task(&mut self) -> Option<GenSnapTask> {
self.gen_snap_task.get_mut().take()
}
// Append the given entries to the raft log using previous last index or self.last_index.
// Return the new last index for later update. After we commit in engine, we can set last_index
// to the return one.
pub fn append<H: HandleRaftReadyContext<EK::WriteBatch, ER::WriteBatch>>(
&mut self,
invoke_ctx: &mut InvokeContext,
entries: &[Entry],
ready_ctx: &mut H,
) -> Result<u64> {
debug!(
"append entries";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"count" => entries.len(),
);
let prev_last_index = invoke_ctx.raft_state.get_last_index();
if entries.is_empty() {
return Ok(prev_last_index);
}
let (last_index, last_term) = {
let e = entries.last().unwrap();
(e.get_index(), e.get_term())
};
for entry in entries {
if !ready_ctx.sync_log() {
ready_ctx.set_sync_log(get_sync_log_from_entry(entry));
}
ready_ctx.raft_wb_mut().put_msg(
&keys::raft_log_key(self.get_region_id(), entry.get_index()),
entry,
)?;
}
// Delete any previously appended log entries which never committed.
for i in (last_index + 1)..=prev_last_index {
// TODO: Wrap it as an engine::Error.
box_try!(ready_ctx
.raft_wb_mut()
.delete(&keys::raft_log_key(self.get_region_id(), i)));
}
invoke_ctx.raft_state.set_last_index(last_index);
invoke_ctx.last_term = last_term;
// TODO: if the writebatch is failed to commit, the cache will be wrong.
self.cache.append(&self.tag, entries);
Ok(last_index)
}
pub fn compact_to(&mut self, idx: u64) {
self.cache.compact_to(idx);
}
#[inline]
pub fn is_cache_empty(&self) -> bool {
self.cache.is_empty()
}
pub fn maybe_gc_cache(&mut self, replicated_idx: u64, apply_idx: u64) {
if replicated_idx == apply_idx {
// The region is inactive, clear the cache immediately.
self.cache.compact_to(apply_idx + 1);
} else {
let cache_first_idx = match self.cache.first_index() {
None => return,
Some(idx) => idx,
};
if cache_first_idx > replicated_idx + 1 {
// Catching up log requires accessing fs already, let's optimize for
// the common case.
// Maybe gc to second least replicated_idx is better.
self.cache.compact_to(apply_idx + 1);
}
}
}
#[inline]
pub fn flush_cache_metrics(&mut self) {
self.stats.flush();
self.cache.flush_mem_size_change();
}
// Apply the peer with given snapshot.
pub fn apply_snapshot(
&mut self,
ctx: &mut InvokeContext,
snap: &Snapshot,
kv_wb: &mut EK::WriteBatch,
raft_wb: &mut ER::WriteBatch,
) -> Result<()> {
info!(
"begin to apply snapshot";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
);
let mut snap_data = RaftSnapshotData::default();
snap_data.merge_from_bytes(snap.get_data())?;
let region_id = self.get_region_id();
let region = snap_data.take_region();
if region.get_id() != region_id {
return Err(box_err!(
"mismatch region id {} != {}",
region_id,
region.get_id()
));
}
if self.is_initialized() {
// we can only delete the old data when the peer is initialized.
self.clear_meta(kv_wb, raft_wb)?;
}
write_peer_state(kv_wb, ®ion, PeerState::Applying, None)?;
let last_index = snap.get_metadata().get_index();
ctx.raft_state.set_last_index(last_index);
ctx.last_term = snap.get_metadata().get_term();
ctx.apply_state.set_applied_index(last_index);
// The snapshot only contains log which index > applied index, so
// here the truncate state's (index, term) is in snapshot metadata.
ctx.apply_state.mut_truncated_state().set_index(last_index);
ctx.apply_state
.mut_truncated_state()
.set_term(snap.get_metadata().get_term());
info!(
"apply snapshot with state ok";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"region" => ?region,
"state" => ?ctx.apply_state,
);
fail_point!("before_apply_snap_update_region", |_| { Ok(()) });
ctx.snap_region = Some(region);
Ok(())
}
/// Delete all meta belong to the region. Results are stored in `wb`.
pub fn clear_meta(
&mut self,
kv_wb: &mut EK::WriteBatch,
raft_wb: &mut ER::WriteBatch,
) -> Result<()> {
let region_id = self.get_region_id();
clear_meta(&self.engines, kv_wb, raft_wb, region_id, &self.raft_state)?;
self.cache = EntryCache::default();
Ok(())
}
/// Delete all data belong to the region.
/// If return Err, data may get partial deleted.
pub fn clear_data(&self) -> Result<()> {
let (start_key, end_key) = (enc_start_key(self.region()), enc_end_key(self.region()));
let region_id = self.get_region_id();
box_try!(self
.region_sched
.schedule(RegionTask::destroy(region_id, start_key, end_key)));
Ok(())
}
/// Delete all data that is not covered by `new_region`.
fn clear_extra_data(&self, new_region: &metapb::Region) -> Result<()> {
let (old_start_key, old_end_key) =
(enc_start_key(self.region()), enc_end_key(self.region()));
let (new_start_key, new_end_key) = (enc_start_key(new_region), enc_end_key(new_region));
let region_id = new_region.get_id();
if old_start_key < new_start_key {
box_try!(self.region_sched.schedule(RegionTask::destroy(
region_id,
old_start_key,
new_start_key
)));
}
if new_end_key < old_end_key {
box_try!(self.region_sched.schedule(RegionTask::destroy(
region_id,
new_end_key,
old_end_key
)));
}
Ok(())
}
pub fn get_raft_engine(&self) -> ER {
self.engines.raft.clone()
}
/// Check whether the storage has finished applying snapshot.
#[inline]
pub fn is_applying_snapshot(&self) -> bool {
match *self.snap_state.borrow() {
SnapState::Applying(_) => true,
_ => false,
}
}
#[inline]
pub fn is_generating_snapshot(&self) -> bool {
fail_point!("is_generating_snapshot", |_| { true });
match *self.snap_state.borrow() {
SnapState::Generating(_) => true,
_ => false,
}
}
/// Check if the storage is applying a snapshot.
#[inline]
pub fn check_applying_snap(&mut self) -> CheckApplyingSnapStatus {
let mut res = CheckApplyingSnapStatus::Idle;
let new_state = match *self.snap_state.borrow() {
SnapState::Applying(ref status) => {
let s = status.load(Ordering::Relaxed);
if s == JOB_STATUS_FINISHED {
res = CheckApplyingSnapStatus::Success;
SnapState::Relax
} else if s == JOB_STATUS_CANCELLED {
SnapState::ApplyAborted
} else if s == JOB_STATUS_FAILED {
// TODO: cleanup region and treat it as tombstone.
panic!("{} applying snapshot failed", self.tag,);
} else {
return CheckApplyingSnapStatus::Applying;
}
}
_ => return res,
};
*self.snap_state.borrow_mut() = new_state;
res
}
#[inline]
pub fn is_canceling_snap(&self) -> bool {
match *self.snap_state.borrow() {
SnapState::Applying(ref status) => {
status.load(Ordering::Relaxed) == JOB_STATUS_CANCELLING
}
_ => false,
}
}
/// Cancel applying snapshot, return true if the job can be considered not be run again.
pub fn cancel_applying_snap(&mut self) -> bool {
let is_cancelled = match *self.snap_state.borrow() {
SnapState::Applying(ref status) => {
if status.compare_and_swap(
JOB_STATUS_PENDING,
JOB_STATUS_CANCELLING,
Ordering::SeqCst,
) == JOB_STATUS_PENDING
{
true
} else if status.compare_and_swap(
JOB_STATUS_RUNNING,
JOB_STATUS_CANCELLING,
Ordering::SeqCst,
) == JOB_STATUS_RUNNING
{
return false;
} else {
false
}
}
_ => return false,
};
if is_cancelled {
*self.snap_state.borrow_mut() = SnapState::ApplyAborted;
return true;
}
// now status can only be JOB_STATUS_CANCELLING, JOB_STATUS_CANCELLED,
// JOB_STATUS_FAILED and JOB_STATUS_FINISHED.
self.check_applying_snap() != CheckApplyingSnapStatus::Applying
}
#[inline]
pub fn set_snap_state(&mut self, state: SnapState) {
*self.snap_state.borrow_mut() = state
}
#[inline]
pub fn is_snap_state(&self, state: SnapState) -> bool {
*self.snap_state.borrow() == state
}
pub fn get_region_id(&self) -> u64 {
self.region().get_id()
}
pub fn schedule_applying_snapshot(&mut self) {
let status = Arc::new(AtomicUsize::new(JOB_STATUS_PENDING));
self.set_snap_state(SnapState::Applying(Arc::clone(&status)));
let task = RegionTask::Apply {
region_id: self.get_region_id(),
status,
};
// Don't schedule the snapshot to region worker.
fail_point!("skip_schedule_applying_snapshot", |_| {});
// TODO: gracefully remove region instead.
if let Err(e) = self.region_sched.schedule(task) {
info!(
"failed to to schedule apply job, are we shutting down?";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"err" => ?e,
);
}
}
/// Save memory states to disk.
///
/// This function only write data to `ready_ctx`'s `WriteBatch`. It's caller's duty to write
/// it explicitly to disk. If it's flushed to disk successfully, `post_ready` should be called
/// to update the memory states properly.
// Using `&Ready` here to make sure `Ready` struct is not modified in this function. This is
// a requirement to advance the ready object properly later.
pub fn handle_raft_ready<H: HandleRaftReadyContext<EK::WriteBatch, ER::WriteBatch>>(
&mut self,
ready_ctx: &mut H,
ready: &Ready,
) -> Result<InvokeContext> {
let mut ctx = InvokeContext::new(self);
let snapshot_index = if raft::is_empty_snap(ready.snapshot()) {
0
} else {
fail_point!("raft_before_apply_snap");
let (kv_wb, raft_wb) = ready_ctx.wb_mut();
self.apply_snapshot(&mut ctx, ready.snapshot(), kv_wb, raft_wb)?;
fail_point!("raft_after_apply_snap");
last_index(&ctx.raft_state)
};
if ready.must_sync() {
ready_ctx.set_sync_log(true);
}
if !ready.entries().is_empty() {
self.append(&mut ctx, ready.entries(), ready_ctx)?;
}
// Last index is 0 means the peer is created from raft message
// and has not applied snapshot yet, so skip persistent hard state.
if ctx.raft_state.get_last_index() > 0 {
if let Some(hs) = ready.hs() {
ctx.raft_state.set_hard_state(hs.clone());
}
}
// Save raft state if it has changed or peer has applied a snapshot.
if ctx.raft_state != self.raft_state || snapshot_index != 0 {
ctx.save_raft_state_to(ready_ctx.raft_wb_mut())?;
if snapshot_index > 0 {
// in case of restart happen when we just write region state to Applying,
// but not write raft_local_state to raft rocksdb in time.
// we write raft state to default rocksdb, with last index set to snap index,
// in case of recv raft log after snapshot.
ctx.save_snapshot_raft_state_to(snapshot_index, ready_ctx.kv_wb_mut())?;
}
}
// only when apply snapshot
if snapshot_index != 0 {
ctx.save_apply_state_to(ready_ctx.kv_wb_mut())?;
}
Ok(ctx)
}
/// Update the memory state after ready changes are flushed to disk successfully.
pub fn post_ready(&mut self, ctx: InvokeContext) -> Option<ApplySnapResult> {
self.raft_state = ctx.raft_state;
self.apply_state = ctx.apply_state;
self.last_term = ctx.last_term;
// If we apply snapshot ok, we should update some infos like applied index too.
let snap_region = match ctx.snap_region {
Some(r) => r,
None => return None,
};
// cleanup data before scheduling apply task
if self.is_initialized() {
if let Err(e) = self.clear_extra_data(self.region()) {
// No need panic here, when applying snapshot, the deletion will be tried
// again. But if the region range changes, like [a, c) -> [a, b) and [b, c),
// [b, c) will be kept in rocksdb until a covered snapshot is applied or
// store is restarted.
error!(
"failed to cleanup data, may leave some dirty data";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"err" => ?e,
);
}
}
self.schedule_applying_snapshot();
let prev_region = self.region().clone();
self.set_region(snap_region);
Some(ApplySnapResult {
prev_region,
region: self.region().clone(),
})
}
}
fn get_sync_log_from_entry(entry: &Entry) -> bool {
if entry.get_sync_log() {
return true;
}
let ctx = entry.get_context();
if !ctx.is_empty() {
let ctx = ProposalContext::from_bytes(ctx);
if ctx.contains(ProposalContext::SYNC_LOG) {
return true;
}
}
false
}
pub fn fetch_entries_to(
engine: &impl KvEngine,
region_id: u64,
low: u64,
high: u64,
max_size: u64,
buf: &mut Vec<Entry>,
) -> raft::Result<u64> {
let mut total_size: u64 = 0;
let mut next_index = low;
let mut exceeded_max_size = false;
if high - low <= RAFT_LOG_MULTI_GET_CNT {
// If election happens in inactive regions, they will just try
// to fetch one empty log.
for i in low..high {
let key = keys::raft_log_key(region_id, i);
match engine.get_value(&key) {
Ok(None) => return Err(RaftError::Store(StorageError::Unavailable)),
Ok(Some(v)) => {
let mut entry = Entry::default();
entry.merge_from_bytes(&v)?;
assert_eq!(entry.get_index(), i);
total_size += v.len() as u64;
if buf.is_empty() || total_size <= max_size {
buf.push(entry);
}
if total_size > max_size {
break;
}
}
Err(e) => return Err(storage_error(e)),
}
}
return Ok(total_size);
}
let start_key = keys::raft_log_key(region_id, low);
let end_key = keys::raft_log_key(region_id, high);
engine
.scan(
&start_key,
&end_key,
true, // fill_cache
|_, value| {
let mut entry = Entry::default();
entry.merge_from_bytes(value)?;
// May meet gap or has been compacted.
if entry.get_index() != next_index {
return Ok(false);
}
next_index += 1;
total_size += value.len() as u64;
exceeded_max_size = total_size > max_size;
if !exceeded_max_size || buf.is_empty() {
buf.push(entry);
}
Ok(!exceeded_max_size)
},
)
.map_err(|e| raft::Error::Store(raft::StorageError::Other(e.into())))?;
// If we get the correct number of entries, returns,
// or the total size almost exceeds max_size, returns.
if buf.len() == (high - low) as usize || exceeded_max_size {
return Ok(total_size);
}
// Here means we don't fetch enough entries.
Err(RaftError::Store(StorageError::Unavailable))
}
/// Delete all meta belong to the region. Results are stored in `wb`.
pub fn clear_meta<EK, ER>(
engines: &KvEngines<EK, ER>,
kv_wb: &mut EK::WriteBatch,
raft_wb: &mut ER::WriteBatch,
region_id: u64,
raft_state: &RaftLocalState,
) -> Result<()>
where
EK: KvEngine,
ER: KvEngine,
{
let t = Instant::now();
box_try!(kv_wb.delete_cf(CF_RAFT, &keys::region_state_key(region_id)));
box_try!(kv_wb.delete_cf(CF_RAFT, &keys::apply_state_key(region_id)));
let last_index = last_index(raft_state);
let mut first_index = last_index + 1;
let begin_log_key = keys::raft_log_key(region_id, 0);
let end_log_key = keys::raft_log_key(region_id, first_index);
engines
.raft
.scan(&begin_log_key, &end_log_key, false, |key, _| {
first_index = keys::raft_log_index(key).unwrap();
Ok(false)
})?;
for id in first_index..=last_index {
box_try!(raft_wb.delete(&keys::raft_log_key(region_id, id)));
}
box_try!(raft_wb.delete(&keys::raft_state_key(region_id)));
info!(
"finish clear peer meta";
"region_id" => region_id,
"meta_key" => 1,
"apply_key" => 1,
"raft_key" => 1,
"raft_logs" => last_index + 1 - first_index,
"takes" => ?t.elapsed(),
);
Ok(())
}
pub fn do_snapshot<E>(
mgr: SnapManager<E>,
engine: &E,
kv_snap: E::Snapshot,
region_id: u64,
last_applied_index_term: u64,
last_applied_state: RaftApplyState,
) -> raft::Result<Snapshot>
where
E: KvEngine,
{
debug!(
"begin to generate a snapshot";
"region_id" => region_id,
);
let msg = kv_snap
.get_msg_cf(CF_RAFT, &keys::apply_state_key(region_id))
.map_err(into_other::<_, raft::Error>)?;
let apply_state: RaftApplyState = match msg {
None => {
return Err(storage_error(format!(
"could not load raft state of region {}",
region_id
)));
}
Some(state) => state,
};
assert_eq!(apply_state, last_applied_state);
let key = SnapKey::new(
region_id,
last_applied_index_term,
apply_state.get_applied_index(),
);
mgr.register(key.clone(), SnapEntry::Generating);
defer!(mgr.deregister(&key, &SnapEntry::Generating));
let state: RegionLocalState = kv_snap
.get_msg_cf(CF_RAFT, &keys::region_state_key(key.region_id))
.and_then(|res| match res {
None => Err(box_err!("region {} could not find region info", region_id)),
Some(state) => Ok(state),
})
.map_err(into_other::<_, raft::Error>)?;
if state.get_state() != PeerState::Normal {
return Err(storage_error(format!(
"snap job for {} seems stale, skip.",
region_id
)));
}
let mut snapshot = Snapshot::default();
// Set snapshot metadata.
snapshot.mut_metadata().set_index(key.idx);
snapshot.mut_metadata().set_term(key.term);
let conf_state = conf_state_from_region(state.get_region());
snapshot.mut_metadata().set_conf_state(conf_state);
let mut s = mgr.get_snapshot_for_building(&key)?;
// Set snapshot data.
let mut snap_data = RaftSnapshotData::default();
snap_data.set_region(state.get_region().clone());
let mut stat = SnapshotStatistics::new();
s.build(
engine,
&kv_snap,
state.get_region(),
&mut snap_data,
&mut stat,
)?;
let v = snap_data.write_to_bytes()?;
snapshot.set_data(v);
SNAPSHOT_KV_COUNT_HISTOGRAM.observe(stat.kv_count as f64);
SNAPSHOT_SIZE_HISTOGRAM.observe(stat.size as f64);
Ok(snapshot)
}
// When we bootstrap the region we must call this to initialize region local state first.
pub fn write_initial_raft_state<T: Mutable>(raft_wb: &mut T, region_id: u64) -> Result<()> {
let mut raft_state = RaftLocalState::default();
raft_state.set_last_index(RAFT_INIT_LOG_INDEX);
raft_state.mut_hard_state().set_term(RAFT_INIT_LOG_TERM);
raft_state.mut_hard_state().set_commit(RAFT_INIT_LOG_INDEX);
raft_wb.put_msg(&keys::raft_state_key(region_id), &raft_state)?;
Ok(())
}
// When we bootstrap the region or handling split new region, we must
// call this to initialize region apply state first.
pub fn write_initial_apply_state<T: Mutable>(kv_wb: &mut T, region_id: u64) -> Result<()> {
let mut apply_state = RaftApplyState::default();
apply_state.set_applied_index(RAFT_INIT_LOG_INDEX);
apply_state
.mut_truncated_state()
.set_index(RAFT_INIT_LOG_INDEX);
apply_state
.mut_truncated_state()
.set_term(RAFT_INIT_LOG_TERM);
kv_wb.put_msg_cf(CF_RAFT, &keys::apply_state_key(region_id), &apply_state)?;
Ok(())
}
pub fn write_peer_state<T: Mutable>(
kv_wb: &mut T,
region: &metapb::Region,
state: PeerState,
merge_state: Option<MergeState>,
) -> Result<()> {
let region_id = region.get_id();
let mut region_state = RegionLocalState::default();
region_state.set_state(state);
region_state.set_region(region.clone());
if let Some(state) = merge_state {
region_state.set_merge_state(state);
}
debug!(
"writing merge state";
"region_id" => region_id,
"state" => ?region_state,
);
kv_wb.put_msg_cf(CF_RAFT, &keys::region_state_key(region_id), ®ion_state)?;
Ok(())
}
#[cfg(test)]
mod tests {
use crate::coprocessor::CoprocessorHost;
use crate::store::fsm::apply::compact_raft_log;
use crate::store::worker::RegionRunner;
use crate::store::worker::RegionTask;
use crate::store::{bootstrap_store, initial_region, prepare_bootstrap_cluster};
use engine::rocks::util::new_engine;
use engine::Engines;
use engine_rocks::{CloneCompat, Compat, RocksEngine, RocksSnapshot, RocksWriteBatch};
use engine_traits::{Iterable, SyncMutable, WriteBatchExt};
use engine_traits::{ALL_CFS, CF_DEFAULT};
use kvproto::raft_serverpb::RaftSnapshotData;
use raft::eraftpb::HardState;
use raft::eraftpb::{ConfState, Entry};
use raft::{Error as RaftError, StorageError};
use std::cell::RefCell;
use std::path::Path;
use std::sync::atomic::*;
use std::sync::mpsc::*;
use std::sync::*;
use std::time::Duration;
use tempfile::{Builder, TempDir};
use tikv_util::worker::{Scheduler, Worker};
use super::*;
fn new_storage(
sched: Scheduler<RegionTask<RocksSnapshot>>,
path: &TempDir,
) -> PeerStorage<RocksEngine, RocksEngine> {
let kv_db =
Arc::new(new_engine(path.path().to_str().unwrap(), None, ALL_CFS, None).unwrap());
let raft_path = path.path().join(Path::new("raft"));
let raft_db =
Arc::new(new_engine(raft_path.to_str().unwrap(), None, &[CF_DEFAULT], None).unwrap());
let shared_block_cache = false;
let engines = Engines::new(kv_db, raft_db, shared_block_cache);
bootstrap_store(&engines.c(), 1, 1).unwrap();
let region = initial_region(1, 1, 1);
prepare_bootstrap_cluster(&engines.c(), ®ion).unwrap();
PeerStorage::new(engines.c(), ®ion, sched, 0, "".to_owned()).unwrap()
}
struct ReadyContext {
kv_wb: RocksWriteBatch,
raft_wb: RocksWriteBatch,
sync_log: bool,
}
impl ReadyContext {
fn new(s: &PeerStorage<RocksEngine, RocksEngine>) -> ReadyContext {
ReadyContext {
kv_wb: s.engines.kv.write_batch(),
raft_wb: s.engines.raft.write_batch(),
sync_log: false,
}
}
}
impl HandleRaftReadyContext<RocksWriteBatch, RocksWriteBatch> for ReadyContext {
fn wb_mut(&mut self) -> (&mut RocksWriteBatch, &mut RocksWriteBatch) {
(&mut self.kv_wb, &mut self.raft_wb)
}
fn kv_wb_mut(&mut self) -> &mut RocksWriteBatch {
&mut self.kv_wb
}
fn raft_wb_mut(&mut self) -> &mut RocksWriteBatch {
&mut self.raft_wb
}
fn sync_log(&self) -> bool {
self.sync_log
}
fn set_sync_log(&mut self, sync: bool) {
self.sync_log = sync;
}
}
fn new_storage_from_ents(
sched: Scheduler<RegionTask<RocksSnapshot>>,
path: &TempDir,
ents: &[Entry],
) -> PeerStorage<RocksEngine, RocksEngine> {
let mut store = new_storage(sched, path);
let mut kv_wb = store.engines.kv.write_batch();
let mut ctx = InvokeContext::new(&store);
let mut ready_ctx = ReadyContext::new(&store);
store.append(&mut ctx, &ents[1..], &mut ready_ctx).unwrap();
ctx.apply_state
.mut_truncated_state()
.set_index(ents[0].get_index());
ctx.apply_state
.mut_truncated_state()
.set_term(ents[0].get_term());
ctx.apply_state
.set_applied_index(ents.last().unwrap().get_index());
ctx.save_apply_state_to(&mut kv_wb).unwrap();
store.engines.raft.write(&ready_ctx.raft_wb).unwrap();
store.engines.kv.write(&kv_wb).unwrap();
store.raft_state = ctx.raft_state;
store.apply_state = ctx.apply_state;
store
}
fn append_ents(store: &mut PeerStorage<RocksEngine, RocksEngine>, ents: &[Entry]) {
let mut ctx = InvokeContext::new(store);
let mut ready_ctx = ReadyContext::new(store);
store.append(&mut ctx, ents, &mut ready_ctx).unwrap();
ctx.save_raft_state_to(&mut ready_ctx.raft_wb).unwrap();
store.engines.raft.write(&ready_ctx.raft_wb).unwrap();
store.raft_state = ctx.raft_state;
}
fn validate_cache(store: &PeerStorage<RocksEngine, RocksEngine>, exp_ents: &[Entry]) {
assert_eq!(store.cache.cache, exp_ents);
for e in exp_ents {
let key = keys::raft_log_key(store.get_region_id(), e.get_index());
let bytes = store.engines.raft.get_value(&key).unwrap().unwrap();
let mut entry = Entry::default();
entry.merge_from_bytes(&bytes).unwrap();
assert_eq!(entry, *e);
}
}
fn new_entry(index: u64, term: u64) -> Entry {
let mut e = Entry::default();
e.set_index(index);
e.set_term(term);
e
}
fn size_of<T: protobuf::Message>(m: &T) -> u32 {
m.compute_size()
}
#[test]
fn test_storage_term() {
let ents = vec![new_entry(3, 3), new_entry(4, 4), new_entry(5, 5)];
let mut tests = vec![
(2, Err(RaftError::Store(StorageError::Compacted))),
(3, Ok(3)),
(4, Ok(4)),
(5, Ok(5)),
];
for (i, (idx, wterm)) in tests.drain(..).enumerate() {
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let store = new_storage_from_ents(sched, &td, &ents);
let t = store.term(idx);
if wterm != t {
panic!("#{}: expect res {:?}, got {:?}", i, wterm, t);
}
}
}
fn get_meta_key_count(store: &PeerStorage<RocksEngine, RocksEngine>) -> usize {
let region_id = store.get_region_id();
let mut count = 0;
let (meta_start, meta_end) = (
keys::region_meta_prefix(region_id),
keys::region_meta_prefix(region_id + 1),
);
store
.engines
.kv
.scan_cf(CF_RAFT, &meta_start, &meta_end, false, |_, _| {
count += 1;
Ok(true)
})
.unwrap();
let (raft_start, raft_end) = (
keys::region_raft_prefix(region_id),
keys::region_raft_prefix(region_id + 1),
);
store
.engines
.kv
.scan_cf(CF_RAFT, &raft_start, &raft_end, false, |_, _| {
count += 1;
Ok(true)
})
.unwrap();
store
.engines
.raft
.scan(&raft_start, &raft_end, false, |_, _| {
count += 1;
Ok(true)
})
.unwrap();
count
}
#[test]
fn test_storage_clear_meta() {
let td = Builder::new().prefix("tikv-store").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let mut store = new_storage_from_ents(sched, &td, &[new_entry(3, 3), new_entry(4, 4)]);
append_ents(&mut store, &[new_entry(5, 5), new_entry(6, 6)]);
assert_eq!(6, get_meta_key_count(&store));
let mut kv_wb = store.engines.kv.write_batch();
let mut raft_wb = store.engines.raft.write_batch();
store.clear_meta(&mut kv_wb, &mut raft_wb).unwrap();
store.engines.kv.write(&kv_wb).unwrap();
store.engines.raft.write(&raft_wb).unwrap();
assert_eq!(0, get_meta_key_count(&store));
}
#[test]
fn test_storage_entries() {
let ents = vec![
new_entry(3, 3),
new_entry(4, 4),
new_entry(5, 5),
new_entry(6, 6),
];
let max_u64 = u64::max_value();
let mut tests = vec![
(
2,
6,
max_u64,
Err(RaftError::Store(StorageError::Compacted)),
),
(
3,
4,
max_u64,
Err(RaftError::Store(StorageError::Compacted)),
),
(4, 5, max_u64, Ok(vec![new_entry(4, 4)])),
(4, 6, max_u64, Ok(vec![new_entry(4, 4), new_entry(5, 5)])),
(
4,
7,
max_u64,
Ok(vec![new_entry(4, 4), new_entry(5, 5), new_entry(6, 6)]),
),
// even if maxsize is zero, the first entry should be returned
(4, 7, 0, Ok(vec![new_entry(4, 4)])),
// limit to 2
(
4,
7,
u64::from(size_of(&ents[1]) + size_of(&ents[2])),
Ok(vec![new_entry(4, 4), new_entry(5, 5)]),
),
(
4,
7,
u64::from(size_of(&ents[1]) + size_of(&ents[2]) + size_of(&ents[3]) / 2),
Ok(vec![new_entry(4, 4), new_entry(5, 5)]),
),
(
4,
7,
u64::from(size_of(&ents[1]) + size_of(&ents[2]) + size_of(&ents[3]) - 1),
Ok(vec![new_entry(4, 4), new_entry(5, 5)]),
),
// all
(
4,
7,
u64::from(size_of(&ents[1]) + size_of(&ents[2]) + size_of(&ents[3])),
Ok(vec![new_entry(4, 4), new_entry(5, 5), new_entry(6, 6)]),
),
];
for (i, (lo, hi, maxsize, wentries)) in tests.drain(..).enumerate() {
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let store = new_storage_from_ents(sched, &td, &ents);
let e = store.entries(lo, hi, maxsize);
if e != wentries {
panic!("#{}: expect entries {:?}, got {:?}", i, wentries, e);
}
}
}
// last_index and first_index are not mutated by PeerStorage on its own,
// so we don't test them here.
#[test]
fn test_storage_compact() {
let ents = vec![new_entry(3, 3), new_entry(4, 4), new_entry(5, 5)];
let mut tests = vec![
(2, Err(RaftError::Store(StorageError::Compacted))),
(3, Err(RaftError::Store(StorageError::Compacted))),
(4, Ok(())),
(5, Ok(())),
];
for (i, (idx, werr)) in tests.drain(..).enumerate() {
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let store = new_storage_from_ents(sched, &td, &ents);
let mut ctx = InvokeContext::new(&store);
let res = store
.term(idx)
.map_err(From::from)
.and_then(|term| compact_raft_log(&store.tag, &mut ctx.apply_state, idx, term));
// TODO check exact error type after refactoring error.
if res.is_err() ^ werr.is_err() {
panic!("#{}: want {:?}, got {:?}", i, werr, res);
}
if res.is_ok() {
let mut kv_wb = store.engines.kv.write_batch();
ctx.save_apply_state_to(&mut kv_wb).unwrap();
store.engines.kv.write(&kv_wb).unwrap();
}
}
}
fn generate_and_schedule_snapshot(
gen_task: GenSnapTask,
engines: &KvEngines<RocksEngine, RocksEngine>,
sched: &Scheduler<RegionTask<RocksSnapshot>>,
) -> Result<()> {
let apply_state: RaftApplyState = engines
.kv
.get_msg_cf(CF_RAFT, &keys::apply_state_key(gen_task.region_id))
.unwrap()
.unwrap();
let idx = apply_state.get_applied_index();
let entry = engines
.raft
.get_msg::<Entry>(&keys::raft_log_key(gen_task.region_id, idx))
.unwrap()
.unwrap();
gen_task.generate_and_schedule_snapshot::<RocksEngine>(
engines.kv.clone().snapshot(),
entry.get_term(),
apply_state,
sched,
)
}
#[test]
fn test_storage_create_snapshot() {
let ents = vec![new_entry(3, 3), new_entry(4, 4), new_entry(5, 5)];
let mut cs = ConfState::default();
cs.set_voters(vec![1, 2, 3]);
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let snap_dir = Builder::new().prefix("snap_dir").tempdir().unwrap();
let mgr = SnapManager::new(snap_dir.path().to_str().unwrap(), None);
let mut worker = Worker::new("region-worker");
let sched = worker.scheduler();
let mut s = new_storage_from_ents(sched.clone(), &td, &ents);
let (router, _) = mpsc::sync_channel(100);
let runner = RegionRunner::new(
s.engines.clone(),
mgr,
0,
true,
CoprocessorHost::<RocksEngine>::default(),
router,
);
worker.start(runner).unwrap();
let snap = s.snapshot(0);
let unavailable = RaftError::Store(StorageError::SnapshotTemporarilyUnavailable);
assert_eq!(snap.unwrap_err(), unavailable);
assert_eq!(*s.snap_tried_cnt.borrow(), 1);
let gen_task = s.gen_snap_task.borrow_mut().take().unwrap();
generate_and_schedule_snapshot(gen_task, &s.engines, &sched).unwrap();
let snap = match *s.snap_state.borrow() {
SnapState::Generating(ref rx) => rx.recv_timeout(Duration::from_secs(3)).unwrap(),
ref s => panic!("unexpected state: {:?}", s),
};
assert_eq!(snap.get_metadata().get_index(), 5);
assert_eq!(snap.get_metadata().get_term(), 5);
assert!(!snap.get_data().is_empty());
let mut data = RaftSnapshotData::default();
protobuf::Message::merge_from_bytes(&mut data, snap.get_data()).unwrap();
assert_eq!(data.get_region().get_id(), 1);
assert_eq!(data.get_region().get_peers().len(), 1);
let (tx, rx) = channel();
s.set_snap_state(SnapState::Generating(rx));
// Empty channel should cause snapshot call to wait.
assert_eq!(s.snapshot(0).unwrap_err(), unavailable);
assert_eq!(*s.snap_tried_cnt.borrow(), 1);
tx.send(snap.clone()).unwrap();
assert_eq!(s.snapshot(0), Ok(snap.clone()));
assert_eq!(*s.snap_tried_cnt.borrow(), 0);
let (tx, rx) = channel();
tx.send(snap.clone()).unwrap();
s.set_snap_state(SnapState::Generating(rx));
// stale snapshot should be abandoned, snapshot index < request index.
assert_eq!(
s.snapshot(snap.get_metadata().get_index() + 1).unwrap_err(),
unavailable
);
assert_eq!(*s.snap_tried_cnt.borrow(), 1);
// Drop the task.
let _ = s.gen_snap_task.borrow_mut().take().unwrap();
let mut ctx = InvokeContext::new(&s);
let mut kv_wb = s.engines.kv.write_batch();
let mut ready_ctx = ReadyContext::new(&s);
s.append(
&mut ctx,
&[new_entry(6, 5), new_entry(7, 5)],
&mut ready_ctx,
)
.unwrap();
let mut hs = HardState::default();
hs.set_commit(7);
hs.set_term(5);
ctx.raft_state.set_hard_state(hs);
ctx.raft_state.set_last_index(7);
ctx.apply_state.set_applied_index(7);
ctx.save_raft_state_to(&mut ready_ctx.raft_wb).unwrap();
ctx.save_apply_state_to(&mut kv_wb).unwrap();
s.engines.kv.write(&kv_wb).unwrap();
s.engines.raft.write(&ready_ctx.raft_wb).unwrap();
s.apply_state = ctx.apply_state;
s.raft_state = ctx.raft_state;
ctx = InvokeContext::new(&s);
let term = s.term(7).unwrap();
compact_raft_log(&s.tag, &mut ctx.apply_state, 7, term).unwrap();
kv_wb = s.engines.kv.write_batch();
ctx.save_apply_state_to(&mut kv_wb).unwrap();
s.engines.kv.write(&kv_wb).unwrap();
s.apply_state = ctx.apply_state;
let (tx, rx) = channel();
tx.send(snap).unwrap();
s.set_snap_state(SnapState::Generating(rx));
*s.snap_tried_cnt.borrow_mut() = 1;
// stale snapshot should be abandoned, snapshot index < truncated index.
assert_eq!(s.snapshot(0).unwrap_err(), unavailable);
assert_eq!(*s.snap_tried_cnt.borrow(), 1);
let gen_task = s.gen_snap_task.borrow_mut().take().unwrap();
generate_and_schedule_snapshot(gen_task, &s.engines, &sched).unwrap();
match *s.snap_state.borrow() {
SnapState::Generating(ref rx) => {
rx.recv_timeout(Duration::from_secs(3)).unwrap();
worker.stop().unwrap().join().unwrap();
match rx.recv_timeout(Duration::from_secs(3)) {
Err(RecvTimeoutError::Disconnected) => {}
res => panic!("unexpected result: {:?}", res),
}
}
ref s => panic!("unexpected state {:?}", s),
}
// Disconnected channel should trigger another try.
assert_eq!(s.snapshot(0).unwrap_err(), unavailable);
let gen_task = s.gen_snap_task.borrow_mut().take().unwrap();
generate_and_schedule_snapshot(gen_task, &s.engines, &sched).unwrap_err();
assert_eq!(*s.snap_tried_cnt.borrow(), 2);
for cnt in 2..super::MAX_SNAP_TRY_CNT {
// Scheduled job failed should trigger .
assert_eq!(s.snapshot(0).unwrap_err(), unavailable);
let gen_task = s.gen_snap_task.borrow_mut().take().unwrap();
generate_and_schedule_snapshot(gen_task, &s.engines, &sched).unwrap_err();
assert_eq!(*s.snap_tried_cnt.borrow(), cnt + 1);
}
// When retry too many times, it should report a different error.
match s.snapshot(0) {
Err(RaftError::Store(StorageError::Other(_))) => {}
res => panic!("unexpected res: {:?}", res),
}
}
#[test]
fn test_storage_append() {
let ents = vec![new_entry(3, 3), new_entry(4, 4), new_entry(5, 5)];
let mut tests = vec![
(
vec![new_entry(3, 3), new_entry(4, 4), new_entry(5, 5)],
vec![new_entry(4, 4), new_entry(5, 5)],
),
(
vec![new_entry(3, 3), new_entry(4, 6), new_entry(5, 6)],
vec![new_entry(4, 6), new_entry(5, 6)],
),
(
vec![
new_entry(3, 3),
new_entry(4, 4),
new_entry(5, 5),
new_entry(6, 5),
],
vec![new_entry(4, 4), new_entry(5, 5), new_entry(6, 5)],
),
// truncate incoming entries, truncate the existing entries and append
(
vec![new_entry(2, 3), new_entry(3, 3), new_entry(4, 5)],
vec![new_entry(4, 5)],
),
// truncate the existing entries and append
(vec![new_entry(4, 5)], vec![new_entry(4, 5)]),
// direct append
(
vec![new_entry(6, 5)],
vec![new_entry(4, 4), new_entry(5, 5), new_entry(6, 5)],
),
];
for (i, (entries, wentries)) in tests.drain(..).enumerate() {
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let mut store = new_storage_from_ents(sched, &td, &ents);
append_ents(&mut store, &entries);
let li = store.last_index();
let actual_entries = store.entries(4, li + 1, u64::max_value()).unwrap();
if actual_entries != wentries {
panic!("#{}: want {:?}, got {:?}", i, wentries, actual_entries);
}
}
}
#[test]
fn test_storage_cache_fetch() {
let ents = vec![new_entry(3, 3), new_entry(4, 4), new_entry(5, 5)];
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let mut store = new_storage_from_ents(sched, &td, &ents);
store.cache.cache.clear();
// empty cache should fetch data from rocksdb directly.
let mut res = store.entries(4, 6, u64::max_value()).unwrap();
assert_eq!(*res, ents[1..]);
let entries = vec![new_entry(6, 5), new_entry(7, 5)];
append_ents(&mut store, &entries);
validate_cache(&store, &entries);
// direct cache access
res = store.entries(6, 8, u64::max_value()).unwrap();
assert_eq!(res, entries);
// size limit should be supported correctly.
res = store.entries(4, 8, 0).unwrap();
assert_eq!(res, vec![new_entry(4, 4)]);
let mut size = ents[1..].iter().map(|e| u64::from(e.compute_size())).sum();
res = store.entries(4, 8, size).unwrap();
let mut exp_res = ents[1..].to_vec();
assert_eq!(res, exp_res);
for e in &entries {
size += u64::from(e.compute_size());
exp_res.push(e.clone());
res = store.entries(4, 8, size).unwrap();
assert_eq!(res, exp_res);
}
// range limit should be supported correctly.
for low in 4..9 {
for high in low..9 {
let res = store.entries(low, high, u64::max_value()).unwrap();
assert_eq!(*res, exp_res[low as usize - 4..high as usize - 4]);
}
}
}
#[test]
fn test_storage_cache_update() {
let ents = vec![new_entry(3, 3), new_entry(4, 4), new_entry(5, 5)];
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let mut store = new_storage_from_ents(sched, &td, &ents);
store.cache.cache.clear();
// initial cache
let mut entries = vec![new_entry(6, 5), new_entry(7, 5)];
append_ents(&mut store, &entries);
validate_cache(&store, &entries);
// rewrite
entries = vec![new_entry(6, 6), new_entry(7, 6)];
append_ents(&mut store, &entries);
validate_cache(&store, &entries);
// rewrite old entry
entries = vec![new_entry(5, 6), new_entry(6, 6)];
append_ents(&mut store, &entries);
validate_cache(&store, &entries);
// partial rewrite
entries = vec![new_entry(6, 7), new_entry(7, 7)];
append_ents(&mut store, &entries);
let mut exp_res = vec![new_entry(5, 6), new_entry(6, 7), new_entry(7, 7)];
validate_cache(&store, &exp_res);
// direct append
entries = vec![new_entry(8, 7), new_entry(9, 7)];
append_ents(&mut store, &entries);
exp_res.extend_from_slice(&entries);
validate_cache(&store, &exp_res);
// rewrite middle
entries = vec![new_entry(7, 8)];
append_ents(&mut store, &entries);
exp_res.truncate(2);
exp_res.push(new_entry(7, 8));
validate_cache(&store, &exp_res);
let cap = MAX_CACHE_CAPACITY as u64;
// result overflow
entries = (3..=cap).map(|i| new_entry(i + 5, 8)).collect();
append_ents(&mut store, &entries);
exp_res.remove(0);
exp_res.extend_from_slice(&entries);
validate_cache(&store, &exp_res);
// input overflow
entries = (0..=cap).map(|i| new_entry(i + cap + 6, 8)).collect();
append_ents(&mut store, &entries);
exp_res = entries[entries.len() - cap as usize..].to_vec();
validate_cache(&store, &exp_res);
// compact
store.compact_to(cap + 10);
exp_res = (cap + 10..cap * 2 + 7).map(|i| new_entry(i, 8)).collect();
validate_cache(&store, &exp_res);
// compact shrink
assert!(store.cache.cache.capacity() >= cap as usize);
store.compact_to(cap * 2);
exp_res = (cap * 2..cap * 2 + 7).map(|i| new_entry(i, 8)).collect();
validate_cache(&store, &exp_res);
assert!(store.cache.cache.capacity() < cap as usize);
// append shrink
entries = (0..=cap).map(|i| new_entry(i, 8)).collect();
append_ents(&mut store, &entries);
assert!(store.cache.cache.capacity() >= cap as usize);
append_ents(&mut store, &[new_entry(6, 8)]);
exp_res = (1..7).map(|i| new_entry(i, 8)).collect();
validate_cache(&store, &exp_res);
assert!(store.cache.cache.capacity() < cap as usize);
// compact all
store.compact_to(cap + 2);
validate_cache(&store, &[]);
// invalid compaction should be ignored.
store.compact_to(cap);
}
#[test]
fn test_storage_apply_snapshot() {
let ents = vec![
new_entry(3, 3),
new_entry(4, 4),
new_entry(5, 5),
new_entry(6, 6),
];
let mut cs = ConfState::default();
cs.set_voters(vec![1, 2, 3]);
let td1 = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let snap_dir = Builder::new().prefix("snap").tempdir().unwrap();
let mgr = SnapManager::new(snap_dir.path().to_str().unwrap(), None);
let mut worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let s1 = new_storage_from_ents(sched.clone(), &td1, &ents);
let (router, _) = mpsc::sync_channel(100);
let runner = RegionRunner::new(
s1.engines.clone(),
mgr,
0,
true,
CoprocessorHost::<RocksEngine>::default(),
router,
);
worker.start(runner).unwrap();
assert!(s1.snapshot(0).is_err());
let gen_task = s1.gen_snap_task.borrow_mut().take().unwrap();
generate_and_schedule_snapshot(gen_task, &s1.engines, &sched).unwrap();
let snap1 = match *s1.snap_state.borrow() {
SnapState::Generating(ref rx) => rx.recv_timeout(Duration::from_secs(3)).unwrap(),
ref s => panic!("unexpected state: {:?}", s),
};
assert_eq!(s1.truncated_index(), 3);
assert_eq!(s1.truncated_term(), 3);
worker.stop().unwrap().join().unwrap();
let td2 = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let mut s2 = new_storage(sched.clone(), &td2);
assert_eq!(s2.first_index(), s2.applied_index() + 1);
let mut ctx = InvokeContext::new(&s2);
assert_ne!(ctx.last_term, snap1.get_metadata().get_term());
let mut kv_wb = s2.engines.kv.write_batch();
let mut raft_wb = s2.engines.raft.write_batch();
s2.apply_snapshot(&mut ctx, &snap1, &mut kv_wb, &mut raft_wb)
.unwrap();
assert_eq!(ctx.last_term, snap1.get_metadata().get_term());
assert_eq!(ctx.apply_state.get_applied_index(), 6);
assert_eq!(ctx.raft_state.get_last_index(), 6);
assert_eq!(ctx.apply_state.get_truncated_state().get_index(), 6);
assert_eq!(ctx.apply_state.get_truncated_state().get_term(), 6);
assert_eq!(s2.first_index(), s2.applied_index() + 1);
validate_cache(&s2, &[]);
let td3 = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let ents = &[new_entry(3, 3), new_entry(4, 3)];
let mut s3 = new_storage_from_ents(sched, &td3, ents);
validate_cache(&s3, &ents[1..]);
let mut ctx = InvokeContext::new(&s3);
assert_ne!(ctx.last_term, snap1.get_metadata().get_term());
let mut kv_wb = s3.engines.kv.write_batch();
let mut raft_wb = s3.engines.raft.write_batch();
s3.apply_snapshot(&mut ctx, &snap1, &mut kv_wb, &mut raft_wb)
.unwrap();
assert_eq!(ctx.last_term, snap1.get_metadata().get_term());
assert_eq!(ctx.apply_state.get_applied_index(), 6);
assert_eq!(ctx.raft_state.get_last_index(), 6);
assert_eq!(ctx.apply_state.get_truncated_state().get_index(), 6);
assert_eq!(ctx.apply_state.get_truncated_state().get_term(), 6);
validate_cache(&s3, &[]);
}
#[test]
fn test_canceling_snapshot() {
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let mut s = new_storage(sched, &td);
// PENDING can be canceled directly.
s.snap_state = RefCell::new(SnapState::Applying(Arc::new(AtomicUsize::new(
JOB_STATUS_PENDING,
))));
assert!(s.cancel_applying_snap());
assert_eq!(*s.snap_state.borrow(), SnapState::ApplyAborted);
// RUNNING can't be canceled directly.
s.snap_state = RefCell::new(SnapState::Applying(Arc::new(AtomicUsize::new(
JOB_STATUS_RUNNING,
))));
assert!(!s.cancel_applying_snap());
assert_eq!(
*s.snap_state.borrow(),
SnapState::Applying(Arc::new(AtomicUsize::new(JOB_STATUS_CANCELLING)))
);
// CANCEL can't be canceled again.
assert!(!s.cancel_applying_snap());
s.snap_state = RefCell::new(SnapState::Applying(Arc::new(AtomicUsize::new(
JOB_STATUS_CANCELLED,
))));
// canceled snapshot can be cancel directly.
assert!(s.cancel_applying_snap());
assert_eq!(*s.snap_state.borrow(), SnapState::ApplyAborted);
s.snap_state = RefCell::new(SnapState::Applying(Arc::new(AtomicUsize::new(
JOB_STATUS_FINISHED,
))));
assert!(s.cancel_applying_snap());
assert_eq!(*s.snap_state.borrow(), SnapState::Relax);
s.snap_state = RefCell::new(SnapState::Applying(Arc::new(AtomicUsize::new(
JOB_STATUS_FAILED,
))));
let res = panic_hook::recover_safe(|| s.cancel_applying_snap());
assert!(res.is_err());
}
#[test]
fn test_try_finish_snapshot() {
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let mut s = new_storage(sched, &td);
// PENDING can be finished.
let mut snap_state = SnapState::Applying(Arc::new(AtomicUsize::new(JOB_STATUS_PENDING)));
s.snap_state = RefCell::new(snap_state);
assert_eq!(s.check_applying_snap(), CheckApplyingSnapStatus::Applying);
assert_eq!(
*s.snap_state.borrow(),
SnapState::Applying(Arc::new(AtomicUsize::new(JOB_STATUS_PENDING)))
);
// RUNNING can't be finished.
snap_state = SnapState::Applying(Arc::new(AtomicUsize::new(JOB_STATUS_RUNNING)));
s.snap_state = RefCell::new(snap_state);
assert_eq!(s.check_applying_snap(), CheckApplyingSnapStatus::Applying);
assert_eq!(
*s.snap_state.borrow(),
SnapState::Applying(Arc::new(AtomicUsize::new(JOB_STATUS_RUNNING)))
);
snap_state = SnapState::Applying(Arc::new(AtomicUsize::new(JOB_STATUS_CANCELLED)));
s.snap_state = RefCell::new(snap_state);
assert_eq!(s.check_applying_snap(), CheckApplyingSnapStatus::Idle);
assert_eq!(*s.snap_state.borrow(), SnapState::ApplyAborted);
// ApplyAborted is not applying snapshot.
assert_eq!(s.check_applying_snap(), CheckApplyingSnapStatus::Idle);
assert_eq!(*s.snap_state.borrow(), SnapState::ApplyAborted);
s.snap_state = RefCell::new(SnapState::Applying(Arc::new(AtomicUsize::new(
JOB_STATUS_FINISHED,
))));
assert_eq!(s.check_applying_snap(), CheckApplyingSnapStatus::Success);
assert_eq!(*s.snap_state.borrow(), SnapState::Relax);
// Relax is not applying snapshot.
assert_eq!(s.check_applying_snap(), CheckApplyingSnapStatus::Idle);
assert_eq!(*s.snap_state.borrow(), SnapState::Relax);
s.snap_state = RefCell::new(SnapState::Applying(Arc::new(AtomicUsize::new(
JOB_STATUS_FAILED,
))));
let res = panic_hook::recover_safe(|| s.check_applying_snap());
assert!(res.is_err());
}
#[test]
fn test_sync_log() {
let mut tbl = vec![];
// Do not sync empty entrise.
tbl.push((Entry::default(), false));
// Sync if sync_log is set.
let mut e = Entry::default();
e.set_sync_log(true);
tbl.push((e, true));
// Sync if context is marked sync.
let context = ProposalContext::SYNC_LOG.to_vec();
let mut e = Entry::default();
e.set_context(context);
tbl.push((e.clone(), true));
// Sync if sync_log is set and context is marked sync_log.
e.set_sync_log(true);
tbl.push((e, true));
for (e, sync) in tbl {
assert_eq!(get_sync_log_from_entry(&e), sync, "{:?}", e);
}
}
#[test]
fn test_validate_states() {
let td = Builder::new().prefix("tikv-store-test").tempdir().unwrap();
let worker = Worker::new("snap-manager");
let sched = worker.scheduler();
let kv_db = Arc::new(new_engine(td.path().to_str().unwrap(), None, ALL_CFS, None).unwrap());
let raft_path = td.path().join(Path::new("raft"));
let raft_db =
Arc::new(new_engine(raft_path.to_str().unwrap(), None, &[CF_DEFAULT], None).unwrap());
let shared_block_cache = false;
let engines = Engines::new(kv_db, raft_db, shared_block_cache);
bootstrap_store(&engines.c(), 1, 1).unwrap();
let region = initial_region(1, 1, 1);
prepare_bootstrap_cluster(&engines.c(), ®ion).unwrap();
let build_storage = || -> Result<PeerStorage<RocksEngine, RocksEngine>> {
PeerStorage::new(engines.c(), ®ion, sched.clone(), 0, "".to_owned())
};
let mut s = build_storage().unwrap();
let mut raft_state = RaftLocalState::default();
raft_state.set_last_index(RAFT_INIT_LOG_INDEX);
raft_state.mut_hard_state().set_term(RAFT_INIT_LOG_TERM);
raft_state.mut_hard_state().set_commit(RAFT_INIT_LOG_INDEX);
let initial_state = s.initial_state().unwrap();
assert_eq!(initial_state.hard_state, *raft_state.get_hard_state());
// last_index < commit_index is invalid.
let raft_state_key = keys::raft_state_key(1);
raft_state.set_last_index(11);
let log_key = keys::raft_log_key(1, 11);
engines
.raft
.c()
.put_msg(&log_key, &new_entry(11, RAFT_INIT_LOG_TERM))
.unwrap();
raft_state.mut_hard_state().set_commit(12);
engines
.raft
.c()
.put_msg(&raft_state_key, &raft_state)
.unwrap();
assert!(build_storage().is_err());
let log_key = keys::raft_log_key(1, 20);
engines
.raft
.c()
.put_msg(&log_key, &new_entry(20, RAFT_INIT_LOG_TERM))
.unwrap();
raft_state.set_last_index(20);
engines
.raft
.c()
.put_msg(&raft_state_key, &raft_state)
.unwrap();
s = build_storage().unwrap();
let initial_state = s.initial_state().unwrap();
assert_eq!(initial_state.hard_state, *raft_state.get_hard_state());
// Missing last log is invalid.
engines.raft.c().delete(&log_key).unwrap();
assert!(build_storage().is_err());
engines
.raft
.c()
.put_msg(&log_key, &new_entry(20, RAFT_INIT_LOG_TERM))
.unwrap();
// applied_index > commit_index is invalid.
let mut apply_state = RaftApplyState::default();
apply_state.set_applied_index(13);
apply_state.mut_truncated_state().set_index(13);
apply_state
.mut_truncated_state()
.set_term(RAFT_INIT_LOG_TERM);
let apply_state_key = keys::apply_state_key(1);
engines
.kv
.c()
.put_msg_cf(CF_RAFT, &apply_state_key, &apply_state)
.unwrap();
assert!(build_storage().is_err());
// It should not recover if corresponding log doesn't exist.
apply_state.set_commit_index(14);
apply_state.set_commit_term(RAFT_INIT_LOG_TERM);
engines
.kv
.c()
.put_msg_cf(CF_RAFT, &apply_state_key, &apply_state)
.unwrap();
assert!(build_storage().is_err());
let log_key = keys::raft_log_key(1, 14);
engines
.raft
.c()
.put_msg(&log_key, &new_entry(14, RAFT_INIT_LOG_TERM))
.unwrap();
raft_state.mut_hard_state().set_commit(14);
s = build_storage().unwrap();
let initial_state = s.initial_state().unwrap();
assert_eq!(initial_state.hard_state, *raft_state.get_hard_state());
// log term miss match is invalid.
engines
.raft
.c()
.put_msg(&log_key, &new_entry(14, RAFT_INIT_LOG_TERM - 1))
.unwrap();
assert!(build_storage().is_err());
// hard state term miss match is invalid.
engines
.raft
.c()
.put_msg(&log_key, &new_entry(14, RAFT_INIT_LOG_TERM))
.unwrap();
raft_state.mut_hard_state().set_term(RAFT_INIT_LOG_TERM - 1);
engines
.raft
.c()
.put_msg(&raft_state_key, &raft_state)
.unwrap();
assert!(build_storage().is_err());
// last index < recorded_commit_index is invalid.
raft_state.mut_hard_state().set_term(RAFT_INIT_LOG_TERM);
raft_state.set_last_index(13);
let log_key = keys::raft_log_key(1, 13);
engines
.raft
.c()
.put_msg(&log_key, &new_entry(13, RAFT_INIT_LOG_TERM))
.unwrap();
engines
.raft
.c()
.put_msg(&raft_state_key, &raft_state)
.unwrap();
assert!(build_storage().is_err());
// last_commit_index > commit_index is invalid.
raft_state.set_last_index(20);
raft_state.mut_hard_state().set_commit(12);
engines
.raft
.c()
.put_msg(&raft_state_key, &raft_state)
.unwrap();
apply_state.set_last_commit_index(13);
engines
.kv
.c()
.put_msg_cf(CF_RAFT, &apply_state_key, &apply_state)
.unwrap();
assert!(build_storage().is_err());
}
}
| 35.100149 | 120 | 0.562974 |
d94b11fc194c4023b676cef139eb2ef3e564fde7
| 1,673 |
// An imaginary magical school has a new report card generation system written in Rust!
// Currently the system only supports creating report cards where the student's grade
// is represented numerically (e.g. 1.0 -> 5.5).
// However, the school also issues alphabetical grades (A+ -> F-) and needs
// to be able to print both types of report card!
// Make the necessary code changes in the struct ReportCard and the impl block
// to support alphabetical report cards. Change the Grade in the second test to "A+"
// to show that your changes allow alphabetical grades.
// Execute 'rustlings hint generics3' for hints!
use std::fmt::Display;
pub struct ReportCard<T> {
pub grade: T,
pub student_name: String,
pub student_age: u8,
}
impl<T> ReportCard<T> where T: Display {
pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generate_numeric_report_card() {
let report_card = ReportCard {
grade: 2.1,
student_name: "Tom Wriggle".to_string(),
student_age: 12,
};
assert_eq!(
report_card.print(),
"Tom Wriggle (12) - achieved a grade of 2.1"
);
}
#[test]
fn generate_alphabetic_report_card() {
let report_card = ReportCard {
grade: "A+",
student_name: "Gary Plotter".to_string(),
student_age: 11,
};
assert_eq!(
report_card.print(),
"Gary Plotter (11) - achieved a grade of A+"
);
}
}
| 28.355932 | 87 | 0.606695 |
b9fbf9f157b997d4b39c4fc867060616f481062d
| 6,017 |
// Copyright 2019 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::handler::base::Request,
crate::service_context::{ExternalServiceProxy, ServiceContextHandle},
crate::{call, call_async},
anyhow::{format_err, Error},
fidl::endpoints::{create_proxy, create_request_stream},
fidl_fuchsia_camera3::{
DeviceMarker, DeviceProxy as Camera3DeviceProxy, DeviceWatcherMarker,
DeviceWatcherProxy as Camera3DeviceWatcherProxy, WatchDevicesEvent,
},
fidl_fuchsia_ui_input::MediaButtonsEvent,
fidl_fuchsia_ui_policy::{
DeviceListenerRegistryMarker, MediaButtonsListenerMarker, MediaButtonsListenerRequest,
},
fuchsia_async as fasync,
fuchsia_syslog::fx_log_err,
futures::StreamExt,
serde::{Deserialize, Serialize},
};
/// Builder to simplify construction of fidl_fuchsia_ui_input::MediaButtonsEvent.
/// # Example usage:
/// ```
/// MediaButtonsEventBuilder::new().set_volume(1).set_mic_mute(true).build();
/// ```
pub struct MediaButtonsEventBuilder {
volume: i8,
mic_mute: bool,
pause: bool,
camera_disable: bool,
}
#[allow(dead_code)]
impl MediaButtonsEventBuilder {
pub fn new() -> Self {
// Create with defaults.
Self { volume: 0, mic_mute: false, pause: false, camera_disable: false }
}
pub fn build(self) -> MediaButtonsEvent {
MediaButtonsEvent {
volume: Some(self.volume),
mic_mute: Some(self.mic_mute),
pause: Some(self.pause),
camera_disable: Some(self.camera_disable),
..MediaButtonsEvent::EMPTY
}
}
pub fn set_volume(mut self, volume: i8) -> Self {
self.volume = volume;
self
}
pub fn set_mic_mute(mut self, mic_mute: bool) -> Self {
self.mic_mute = mic_mute;
self
}
pub fn set_pause(mut self, pause: bool) -> Self {
self.pause = pause;
self
}
pub fn set_camera_disable(mut self, camera_disable: bool) -> Self {
self.camera_disable = camera_disable;
self
}
}
/// The possible types of input to monitor.
#[derive(Eq, PartialEq, Debug, Clone, Copy, Hash, Serialize, Deserialize)]
pub enum InputType {
Camera,
Microphone,
VolumeButtons,
}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum ButtonType {
MicrophoneMute(bool),
CameraDisable(bool),
}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum VolumeGain {
/// This is neither up nor down. It is equivalent to no gain.
Neutral,
Up,
Down,
}
impl From<ButtonType> for Request {
fn from(button_type: ButtonType) -> Self {
Request::OnButton(button_type)
}
}
impl From<VolumeGain> for Request {
fn from(volume_gain: VolumeGain) -> Self {
Request::OnVolume(volume_gain)
}
}
/// Method for listening to media button changes. Changes will be reported back
/// on the supplied sender.
pub async fn monitor_media_buttons(
service_context_handle: ServiceContextHandle,
sender: futures::channel::mpsc::UnboundedSender<MediaButtonsEvent>,
) -> Result<(), Error> {
let presenter_service =
service_context_handle.lock().await.connect::<DeviceListenerRegistryMarker>().await?;
let (client_end, mut stream) = create_request_stream::<MediaButtonsListenerMarker>().unwrap();
if call!(presenter_service => register_media_buttons_listener(client_end)).is_err() {
fx_log_err!("Registering media button listener with presenter service failed.");
return Err(format_err!("presenter service not ready"));
}
fasync::Task::spawn(async move {
while let Some(Ok(media_request)) = stream.next().await {
// Support future expansion of FIDL
#[allow(unreachable_patterns)]
match media_request {
MediaButtonsListenerRequest::OnMediaButtonsEvent { event, control_handle: _ } => {
sender.unbounded_send(event).ok();
}
_ => {}
}
}
})
.detach();
Ok(())
}
/// Connects to the fuchsia.camera3.DeviceWatcher api.
async fn connect_to_camera_watcher(
service_context_handle: ServiceContextHandle,
) -> Result<ExternalServiceProxy<Camera3DeviceWatcherProxy>, Error> {
service_context_handle.lock().await.connect::<DeviceWatcherMarker>().await
}
/// Retrieves the id of a camera device given the camera device watcher proxy.
#[allow(dead_code)]
async fn get_camera_id(
camera_watcher_proxy: &ExternalServiceProxy<Camera3DeviceWatcherProxy>,
) -> Result<u64, Error> {
// Get a list of id structs containing existing, new, and removed ids.
let camera_ids = call_async!(camera_watcher_proxy => watch_devices()).await?;
// TODO(fxbug.dev/66881): support multiple camera devices.
let first_cam = camera_ids.first();
if let Some(WatchDevicesEvent::Existing(id)) | Some(WatchDevicesEvent::Added(id)) = first_cam {
Ok(*id)
} else {
Err(format_err!("Could not find a camera"))
}
}
/// Establishes a connection to the fuchsia.camera3.Device api by watching
/// the camera id and using it to connect to the device.
pub async fn connect_to_camera(
service_context_handle: ServiceContextHandle,
) -> Result<Camera3DeviceProxy, Error> {
// Connect to the camera device watcher to get camera ids. This will
// be used to connect to the camera.
let camera_watcher_proxy = connect_to_camera_watcher(service_context_handle.clone()).await?;
let camera_id = get_camera_id(&camera_watcher_proxy).await?;
// Connect to the camera device with the found id.
let (camera_proxy, device_server) = create_proxy::<DeviceMarker>().unwrap();
if call!(camera_watcher_proxy => connect_to_device(camera_id, device_server)).is_err() {
return Err(format_err!("Could not connect to fuchsia.camera3.DeviceWatcher device"));
}
Ok(camera_proxy)
}
| 33.427778 | 99 | 0.681403 |
d79c9bad523c3cb223076bcaba218a376d074bfa
| 1,174 |
extern crate svm_sdk_mock as svm_sdk;
use svm_sdk_mock::host::MockHost;
use svm_sdk_mock::storage::MockStorage;
use trybuild::TestCases;
fn pass(t: &TestCases, test: &'static str) {
MockHost::reset();
MockStorage::clear();
t.pass(test);
}
fn compile_fail(t: &TestCases, test: &'static str) {
MockHost::reset();
MockStorage::clear();
t.compile_fail(test);
}
#[test]
fn template_tests() {
let t = TestCases::new();
pass(&t, "tests/template/empty.rs");
compile_fail(&t, "tests/template/declaring_const_not_allowed.rs");
compile_fail(&t, "tests/template/declaring_static_not_allowed.rs");
compile_fail(&t, "tests/template/declaring_enum_not_allowed.rs");
compile_fail(&t, "tests/template/declaring_union_not_allowed.rs");
compile_fail(&t, "tests/template/declaring_traits_not_allowed.rs");
compile_fail(
&t,
"tests/template/template_with_two_default_fundable_hook_not_allowed.rs",
);
compile_fail(&t, "tests/template/using_extern_crate_not_allowed.rs");
compile_fail(&t, "tests/template/using_ffi_not_allowed.rs");
compile_fail(&t, "tests/template/using_impl_not_allowed.rs");
}
| 27.302326 | 80 | 0.711244 |
8725d7226fc300328a4958a12d768530fcf36bf8
| 1,474 |
use anchor_lang::prelude::*;
use borsh::{BorshDeserialize, BorshSerialize};
#[account(zero_copy)]
pub struct DepositHistory {
head: u64,
deposit_records: [DepositRecord; 1024],
}
impl Default for DepositHistory {
fn default() -> Self {
DepositHistory {
head: 0,
deposit_records: [DepositRecord::default(); 1024],
}
}
}
impl DepositHistory {
pub fn append(&mut self, pos: DepositRecord) {
self.deposit_records[DepositHistory::index_of(self.head)] = pos;
self.head = (self.head + 1) % 1024;
}
pub fn index_of(counter: u64) -> usize {
std::convert::TryInto::try_into(counter).unwrap()
}
pub fn next_record_id(&self) -> u128 {
let prev_trade_id = if self.head == 0 { 1023 } else { self.head - 1 };
let prev_trade = &self.deposit_records[DepositHistory::index_of(prev_trade_id)];
prev_trade.record_id + 1
}
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq)]
pub enum DepositDirection {
DEPOSIT,
WITHDRAW,
}
impl Default for DepositDirection {
// UpOnly
fn default() -> Self {
DepositDirection::DEPOSIT
}
}
#[zero_copy]
#[derive(Default)]
pub struct DepositRecord {
pub ts: i64,
pub record_id: u128,
pub user_authority: Pubkey,
pub user: Pubkey,
pub direction: DepositDirection,
pub collateral_before: u128,
pub cumulative_deposits_before: i128,
pub amount: u64,
}
| 24.163934 | 88 | 0.644505 |
f95194aaeb4e45a77f56d125444297fd476e9948
| 920 |
use clap::{crate_authors, crate_version, App, Arg};
pub fn app() -> App<'static> {
App::new(String::from(env!("CARGO_PKG_NAME")))
.bin_name(String::from(env!("CARGO_PKG_NAME")))
.version(crate_version!())
.author(crate_authors!())
.about(env!("CARGO_PKG_DESCRIPTION"))
.arg(
Arg::new("only-4")
.long("only-4")
.short('4')
.help("Only print IPv4 addresses")
.conflicts_with("only-6"),
)
.arg(
Arg::new("only-6")
.long("only-6")
.short('6')
.help("Only print IPv6 addresses")
.conflicts_with("only-4"),
)
.arg(
Arg::new("reverse")
.long("reverse")
.short('r')
.help("Print the reverse DNS entries for the IP addresses"),
)
}
| 30.666667 | 76 | 0.455435 |
db5cd3aedf638d6e8140817e7f2277ae1f78005b
| 1,208 |
// 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.
mod codegen;
mod ir;
mod obj_path;
use crate::{common::GenerateCode, utils::check_idents};
use proc_macro2::TokenStream as TokenStream2;
use std::convert::TryFrom;
use syn::Result;
pub fn generate(attr: TokenStream2, input: TokenStream2) -> TokenStream2 {
match generate_impl(attr, input) {
Ok(tokens) => tokens,
Err(err) => err.to_compile_error(),
}
}
fn generate_impl(_attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {
check_idents(input.clone())?;
let item_mod = syn::parse2::<syn::ItemMod>(input)?;
let liquid_ir = ir::Collaboration::try_from(item_mod)?;
Ok(liquid_ir.generate_code())
}
| 33.555556 | 84 | 0.721026 |
038f6b6570c26d77ee4c421732b3c067102ee946
| 1,786 |
use ckb_indexer::store::Error as StoreError;
use derive_more::Display;
#[allow(dead_code)]
#[derive(Debug, Display)]
pub enum MercuryError {
#[display(fmt = "DB error: {}", _0)]
DBError(String),
#[display(fmt = "Parse CKB address error {}", _0)]
ParseCKBAddressError(String),
#[display(fmt = "Already a short CKB address")]
AlreadyShortCKBAddress,
#[display(fmt = "UDT {} is inexistent", _0)]
UDTInexistence(String),
#[display(fmt = "The address {} has no acp cell", _0)]
NoACPInThisAddress(String),
#[display(fmt = "Lack of ACP to pay for udt capacity, address {}", _0)]
LackACPCells(String),
#[display(fmt = "Missing ACP cell with type_hash {}, address {}", _1, _0)]
MissingACPCell(String, String),
#[display(fmt = "Lack of sUDT cell of address{}", _0)]
LackSUDTCells(String),
#[display(fmt = "Ckb is not enough, address {}", _0)]
CkbIsNotEnough(String),
#[display(fmt = "UDT is not enough, address {}", _0)]
UDTIsNotEnough(String),
#[display(fmt = "UDT min is some when Ckb min is none")]
InvalidAccountUDTMin,
#[display(fmt = "Invalid create account info")]
InvalidAccountInfo,
#[display(fmt = "Ckb transfer can only pay by from")]
InvalidTransferPayload,
#[display(fmt = "Missing config of {:?} script", _0)]
MissingConfig(String),
#[display(
fmt = "Cannot get live cell by outpoint tx_hash {}, index {}",
tx_hash,
index
)]
CannotGetLiveCellByOutPoint { tx_hash: String, index: u32 },
}
impl std::error::Error for MercuryError {}
impl From<StoreError> for MercuryError {
fn from(error: StoreError) -> Self {
match error {
StoreError::DBError(s) => MercuryError::DBError(s),
}
}
}
| 27.060606 | 78 | 0.629899 |
5dfc546746494230aa4b47d4a51459d2324f0e0a
| 1,052 |
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None
}
}
}
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
if root.is_none() {
return vec![];
}
let mut ans = vec![];
Self::pre_order(0, &root, &mut ans);
ans
}
fn pre_order(dep: usize, r: &Option<Rc<RefCell<TreeNode>>>, ans: &mut Vec<i32>) {
if r.is_none() {
return;
}
let br = r.as_ref().unwrap().borrow();
if dep >= ans.len() {
ans.push(br.val);
} else {
ans[dep] = br.val;
}
Self::pre_order(dep+1, &br.left, ans);
Self::pre_order(dep+1, &br.right, ans);
}
}
struct Solution;
| 23.377778 | 85 | 0.526616 |
62bf467c2665420485dad83ef26943beb064e983
| 4,478 |
//! Definition of the `JoinAll` combinator, waiting for all of a list of futures
//! to finish.
use core::fmt;
use core::future::Future;
use core::iter::FromIterator;
use core::mem;
use core::pin::Pin;
use core::task::{Context, Poll};
use alloc::boxed::Box;
use alloc::vec::Vec;
#[derive(Debug)]
enum ElemState<F>
where
F: Future,
{
Pending(F),
Done(Option<F::Output>),
}
impl<F> ElemState<F>
where
F: Future,
{
fn pending_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut F>> {
// Safety: Basic enum pin projection, no drop + optionally Unpin based
// on the type of this variant
match unsafe { self.get_unchecked_mut() } {
ElemState::Pending(f) => Some(unsafe { Pin::new_unchecked(f) }),
ElemState::Done(_) => None,
}
}
fn take_done(self: Pin<&mut Self>) -> Option<F::Output> {
// Safety: Going from pin to a variant we never pin-project
match unsafe { self.get_unchecked_mut() } {
ElemState::Pending(_) => None,
ElemState::Done(output) => output.take(),
}
}
}
impl<F> Unpin for ElemState<F>
where
F: Future + Unpin,
{
}
fn iter_pin_mut<T>(slice: Pin<&mut [T]>) -> impl Iterator<Item = Pin<&mut T>> {
// Safety: `std` _could_ make this unsound if it were to decide Pin's
// invariants aren't required to transmit through slices. Otherwise this has
// the same safety as a normal field pin projection.
unsafe { slice.get_unchecked_mut() }
.iter_mut()
.map(|t| unsafe { Pin::new_unchecked(t) })
}
/// Future for the [`join_all`] function.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct JoinAll<F>
where
F: Future,
{
elems: Pin<Box<[ElemState<F>]>>,
}
impl<F> fmt::Debug for JoinAll<F>
where
F: Future + fmt::Debug,
F::Output: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("JoinAll")
.field("elems", &self.elems)
.finish()
}
}
/// Creates a future which represents a collection of the outputs of the futures
/// given.
///
/// The returned future will drive execution for all of its underlying futures,
/// collecting the results into a destination `Vec<T>` in the same order as they
/// were provided.
///
/// This function is only available when the `std` or `alloc` feature of this
/// library is activated, and it is activated by default.
///
/// # See Also
///
/// This is purposefully a very simple API for basic use-cases. In a lot of
/// cases you will want to use the more powerful
/// [`FuturesUnordered`][crate::stream::FuturesUnordered] APIs, some
/// examples of additional functionality that provides:
///
/// * Adding new futures to the set even after it has been started.
///
/// * Only polling the specific futures that have been woken. In cases where
/// you have a lot of futures this will result in much more efficient polling.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::future::{join_all};
///
/// async fn foo(i: u32) -> u32 { i }
///
/// let futures = vec![foo(1), foo(2), foo(3)];
///
/// assert_eq!(join_all(futures).await, [1, 2, 3]);
/// # });
/// ```
pub fn join_all<I>(i: I) -> JoinAll<I::Item>
where
I: IntoIterator,
I::Item: Future,
{
let elems: Box<[_]> = i.into_iter().map(ElemState::Pending).collect();
JoinAll { elems: elems.into() }
}
impl<F> Future for JoinAll<F>
where
F: Future,
{
type Output = Vec<F::Output>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut all_done = true;
for mut elem in iter_pin_mut(self.elems.as_mut()) {
if let Some(pending) = elem.as_mut().pending_pin_mut() {
if let Poll::Ready(output) = pending.poll(cx) {
elem.set(ElemState::Done(Some(output)));
} else {
all_done = false;
}
}
}
if all_done {
let mut elems = mem::replace(&mut self.elems, Box::pin([]));
let result = iter_pin_mut(elems.as_mut())
.map(|e| e.take_done().unwrap())
.collect();
Poll::Ready(result)
} else {
Poll::Pending
}
}
}
impl<F: Future> FromIterator<F> for JoinAll<F> {
fn from_iter<T: IntoIterator<Item = F>>(iter: T) -> Self {
join_all(iter)
}
}
| 27.9875 | 83 | 0.595578 |
6afbf673e6675f9a629b3852d3884e63df3cc3cc
| 10,427 |
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use std::{
collections::HashMap,
fmt::Display,
fs::{create_dir_all, read_to_string},
io::Write,
path::{Path, PathBuf},
time::Instant,
};
use anyhow::Result;
use codespan_reporting::term::termcolor::{ColorChoice, StandardStream};
use move_command_line_common::files::FileHash;
use move_lang::{
compiled_unit::CompiledUnit,
diagnostics::{self, codes::Severity},
unit_test::{plan_builder::construct_test_plan, TestPlan},
PASS_CFGIR,
};
use move_package::{
compilation::build_plan::BuildPlan, source_package::layout::SourcePackageLayout,
};
use move_prover::run_move_prover_with_model;
use move_unit_test::UnitTestingConfig;
use structopt::StructOpt;
#[derive(StructOpt)]
pub enum PackageCommand {
/// Create a new Move package with name `name` at `path`. If `path` is not provided the package
/// will be created in the directory `name`.
#[structopt(name = "new")]
New {
/// The name of the package to be created.
name: String,
},
/// Build the package at `path`. If no path is provided defaults to current directory.
#[structopt(name = "build")]
Build,
/// Generate error map for the package and its dependencies at `path` for use by the Move
/// explanation tool.
#[structopt(name = "errmap")]
ErrMapGen {
/// The prefix that all error reasons within modules will be prefixed with, e.g., "E" if
/// all error reasons are "E_CANNOT_PERFORM_OPERATION", "E_CANNOT_ACCESS", etc.
error_prefix: Option<String>,
/// The file to serialize the generated error map to.
#[structopt(default_value = "error_map", parse(from_os_str))]
output_file: PathBuf,
},
/// Run the Move Prover on the package at `path`. If no path is provided defaults to current
/// directory.
#[structopt(name = "prove")]
Prove {
#[structopt(subcommand)]
cmd: Option<ProverOptions>,
},
#[structopt(name = "test")]
UnitTest {
/// Bound the number of instructions that can be executed by any one test.
#[structopt(
name = "instructions",
default_value = "5000",
short = "i",
long = "instructions"
)]
instruction_execution_bound: u64,
/// A filter string to determine which unit tests to run
#[structopt(name = "filter", short = "f", long = "filter")]
filter: Option<String>,
/// List all tests
#[structopt(name = "list", short = "l", long = "list")]
list: bool,
/// Number of threads to use for running tests.
#[structopt(
name = "num_threads",
default_value = "8",
short = "t",
long = "threads"
)]
num_threads: usize,
/// Report test statistics at the end of testing
#[structopt(name = "report_statistics", short = "s", long = "statistics")]
report_statistics: bool,
/// Show the storage state at the end of execution of a failing test
#[structopt(name = "global_state_on_error", short = "g", long = "state_on_error")]
report_storage_on_error: bool,
/// Use the stackless bytecode interpreter to run the tests and cross check its results with
/// the execution result from Move VM.
#[structopt(long = "stackless")]
check_stackless_vm: bool,
/// Verbose mode
#[structopt(long = "verbose")]
verbose_mode: bool,
},
}
#[derive(StructOpt)]
pub enum ProverOptions {
// Pass through unknown commands to the prover Clap parser
#[structopt(external_subcommand)]
Options(Vec<String>),
}
pub fn handle_package_commands(
path: &Option<PathBuf>,
mut config: move_package::BuildConfig,
cmd: &PackageCommand,
) -> Result<()> {
let path = path
.as_ref()
.map(PathBuf::from)
.unwrap_or_else(|| std::env::current_dir().unwrap());
match cmd {
PackageCommand::Build => {
config.compile_package(&path, &mut std::io::stdout())?;
}
PackageCommand::New { name } => {
let creation_path = Path::new(&path).join(name);
create_move_package(name, &creation_path)?;
}
PackageCommand::Prove { cmd } => {
let options = match cmd {
None => move_prover::cli::Options::default(),
Some(ProverOptions::Options(options)) => {
move_prover::cli::Options::create_from_args(options)?
}
};
let mut error_writer = StandardStream::stderr(ColorChoice::Auto);
let now = Instant::now();
let model = config.move_model_for_package(&path)?;
run_move_prover_with_model(&model, &mut error_writer, options, Some(now))?;
}
PackageCommand::ErrMapGen {
error_prefix,
output_file,
} => {
let mut errmap_options = errmapgen::ErrmapOptions::default();
if let Some(err_prefix) = error_prefix {
errmap_options.error_prefix = err_prefix.to_string();
}
errmap_options.output_file = output_file
.with_extension(move_command_line_common::files::MOVE_ERROR_DESC_EXTENSION)
.to_string_lossy()
.to_string();
let model = config.move_model_for_package(&path)?;
let mut errmap_gen = errmapgen::ErrmapGen::new(&model, &errmap_options);
errmap_gen.gen();
errmap_gen.save_result();
}
PackageCommand::UnitTest {
instruction_execution_bound,
filter,
list,
num_threads,
report_statistics,
report_storage_on_error,
check_stackless_vm,
verbose_mode,
} => {
let unit_test_config = UnitTestingConfig {
instruction_execution_bound: *instruction_execution_bound,
filter: filter.clone(),
list: *list,
num_threads: *num_threads,
report_statistics: *report_statistics,
report_storage_on_error: *report_storage_on_error,
check_stackless_vm: *check_stackless_vm,
verbose: *verbose_mode,
..UnitTestingConfig::default_with_bound(None)
};
let mut test_plan = None;
config.test_mode = true;
config.dev_mode = true;
let resolution_graph = config.resolution_graph_for_package(&path)?;
let dep_file_map: HashMap<_, _> = resolution_graph
.package_table
.iter()
.flat_map(|(_, rpkg)| {
rpkg.get_sources(&resolution_graph.build_options)
.unwrap()
.iter()
.map(|fname| {
let contents = read_to_string(Path::new(fname.as_str())).unwrap();
let fhash = FileHash::new(&contents);
(fhash, (*fname, contents))
})
.collect::<HashMap<_, _>>()
})
.collect();
let build_plan = BuildPlan::create(resolution_graph)?;
let pkg =
build_plan.compile_with_driver(&mut std::io::stdout(), |compiler, is_root| {
if !is_root {
compiler.build_and_report()
} else {
let (files, comments_and_compiler_res) =
compiler.run::<PASS_CFGIR>().unwrap();
let (_, compiler) = diagnostics::unwrap_or_report_diagnostics(
&files,
comments_and_compiler_res,
);
let (mut compiler, cfgir) = compiler.into_ast();
let compilation_env = compiler.compilation_env();
let built_test_plan = construct_test_plan(compilation_env, &cfgir);
if let Err(diags) =
compilation_env.check_diags_at_or_above_severity(Severity::Warning)
{
diagnostics::report_diagnostics(&files, diags);
}
let compilation_result = compiler.at_cfgir(cfgir).build();
let (units, _) =
diagnostics::unwrap_or_report_diagnostics(&files, compilation_result);
test_plan = Some((built_test_plan, files.clone(), units.clone()));
Ok((files, units))
}
})?;
let (test_plan, mut files, units) = test_plan.unwrap();
files.extend(dep_file_map);
let mut test_plan = TestPlan::new(test_plan.unwrap(), files, units);
for pkg in pkg.transitive_dependencies() {
for module in &pkg.compiled_units {
match module {
CompiledUnit::Script(_) => (),
CompiledUnit::Module(module) => {
test_plan
.module_info
.insert(module.module.self_id(), module.clone());
}
}
}
}
// TODO: We only run with stdlib natives for now. Revisit once we have native support
// in packages.
if unit_test_config
.run_and_report_unit_tests(test_plan, None, std::io::stdout())
.unwrap()
.1
{
std::process::exit(0)
} else {
std::process::exit(1)
}
}
};
Ok(())
}
pub fn create_move_package<S: AsRef<str> + Display>(name: S, creation_path: &Path) -> Result<()> {
create_dir_all(creation_path.join(SourcePackageLayout::Sources.path()))?;
let mut w = std::fs::File::create(creation_path.join(SourcePackageLayout::Manifest.path()))?;
writeln!(
&mut w,
"[package]\nname = \"{}\"\nversion = \"0.0.0\"",
name
)?;
Ok(())
}
| 38.054745 | 100 | 0.543205 |
90771620f9adb662896dca49371447f7e35d3f43
| 1,969 |
use query_engine_tests::*;
/// Port note: The `findMany` portion of the old `WhereUniqueSpec` was omitted, didn't add any value.
#[test_suite(schema(schemas::user))]
mod where_unique {
#[connector_test]
async fn no_unique_fields(runner: &Runner) -> TestResult<()> {
assert_error!(
runner,
"query { findUniqueUser(where: {}){ id }}",
2009,
"Expected exactly one field to be present, got 0."
);
Ok(())
}
#[connector_test]
async fn one_unique_field(runner: &Runner) -> TestResult<()> {
test_users(runner).await?;
assert_query!(
runner,
"query { findUniqueUser(where: { id: 1 }){ id }}",
r#"{"data":{"findUniqueUser":{"id":1}}}"#
);
Ok(())
}
#[connector_test]
async fn more_than_one_unique_field(runner: &Runner) -> TestResult<()> {
test_users(runner).await?;
assert_error!(
runner,
r#"query { findUniqueUser(where: { id: 1, first_name: "Elongated" }){ id }}"#,
2009,
"Field does not exist on enclosing type."
);
Ok(())
}
#[connector_test]
async fn implicit_unique_and(runner: &Runner) -> TestResult<()> {
test_users(runner).await?;
assert_query!(
runner,
"query { findUniqueUser(where: { id: 1 }){ id }}",
r#"{"data":{"findUniqueUser":{"id":1}}}"#
);
Ok(())
}
async fn test_users(runner: &Runner) -> TestResult<()> {
runner
.query(r#"mutation { createOneUser(data: { id: 1, email: "[email protected]", first_name: "Elongated", last_name: "Muskrat" }) { id } }"#)
.await?.assert_success();
runner
.query(r#"mutation { createOneUser(data: { id: 2, email: "[email protected]", first_name: "John", last_name: "Cena" }) { id } }"#)
.await?.assert_success();
Ok(())
}
}
| 28.955882 | 140 | 0.523108 |
fcf641dc0231d3c0e7ed59edc338b2abd6d7565f
| 13,409 |
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
#[macro_use]
extern crate lazy_static;
extern crate tempfile;
mod util;
use util::*;
#[test]
fn benchmark_test() {
run_python_script("tools/benchmark_test.py")
}
#[test]
fn deno_dir_test() {
let g = http_server();
run_python_script("tools/deno_dir_test.py");
drop(g);
}
// TODO(#2933): Rewrite this test in rust.
#[test]
fn fetch_test() {
let g = http_server();
run_python_script("tools/fetch_test.py");
drop(g);
}
// TODO(#2933): Rewrite this test in rust.
#[test]
fn fmt_test() {
let g = http_server();
run_python_script("tools/fmt_test.py");
drop(g);
}
#[test]
fn js_unit_tests() {
let g = http_server();
let mut deno = deno_cmd()
.current_dir(root_path())
.arg("run")
.arg("--reload")
.arg("--allow-run")
.arg("--allow-env")
.arg("cli/js/unit_test_runner.ts")
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert_eq!(Some(0), status.code());
assert!(status.success());
drop(g);
}
// TODO(#2933): Rewrite this test in rust.
#[test]
fn repl_test() {
run_python_script("tools/repl_test.py")
}
#[test]
fn setup_test() {
run_python_script("tools/setup_test.py")
}
#[test]
fn target_test() {
run_python_script("tools/target_test.py")
}
#[test]
fn util_test() {
run_python_script("tools/util_test.py")
}
macro_rules! itest(
($name:ident {$( $key:ident: $value:expr,)*}) => {
#[test]
fn $name() {
(CheckOutputIntegrationTest {
$(
$key: $value,
)*
.. Default::default()
}).run()
}
}
);
itest!(_001_hello {
args: "run --reload 001_hello.js",
output: "001_hello.js.out",
});
itest!(_002_hello {
args: "run --reload 002_hello.ts",
output: "002_hello.ts.out",
});
itest!(_003_relative_import {
args: "run --reload 003_relative_import.ts",
output: "003_relative_import.ts.out",
});
itest!(_004_set_timeout {
args: "run --reload 004_set_timeout.ts",
output: "004_set_timeout.ts.out",
});
itest!(_005_more_imports {
args: "run --reload 005_more_imports.ts",
output: "005_more_imports.ts.out",
});
itest!(_006_url_imports {
args: "run --reload 006_url_imports.ts",
output: "006_url_imports.ts.out",
http_server: true,
});
itest!(_012_async {
args: "run --reload 012_async.ts",
output: "012_async.ts.out",
});
itest!(_013_dynamic_import {
args: "013_dynamic_import.ts --reload --allow-read",
output: "013_dynamic_import.ts.out",
});
itest!(_014_duplicate_import {
args: "014_duplicate_import.ts --reload --allow-read",
output: "014_duplicate_import.ts.out",
});
itest!(_015_duplicate_parallel_import {
args: "015_duplicate_parallel_import.js --reload --allow-read",
output: "015_duplicate_parallel_import.js.out",
});
itest!(_016_double_await {
args: "run --allow-read --reload 016_double_await.ts",
output: "016_double_await.ts.out",
});
itest!(_017_import_redirect {
args: "run --reload 017_import_redirect.ts",
output: "017_import_redirect.ts.out",
});
itest!(_018_async_catch {
args: "run --reload 018_async_catch.ts",
output: "018_async_catch.ts.out",
});
itest!(_019_media_types {
args: "run --reload 019_media_types.ts",
output: "019_media_types.ts.out",
http_server: true,
});
itest!(_020_json_modules {
args: "run --reload 020_json_modules.ts",
output: "020_json_modules.ts.out",
});
itest!(_021_mjs_modules {
args: "run --reload 021_mjs_modules.ts",
output: "021_mjs_modules.ts.out",
});
itest!(_022_info_flag_script {
args: "info http://127.0.0.1:4545/cli/tests/019_media_types.ts",
output: "022_info_flag_script.out",
http_server: true,
});
itest!(_023_no_ext_with_headers {
args: "run --reload 023_no_ext_with_headers",
output: "023_no_ext_with_headers.out",
});
// FIXME(bartlomieju): this test should use remote file
// itest!(_024_import_no_ext_with_headers {
// args: "run --reload 024_import_no_ext_with_headers.ts",
// output: "024_import_no_ext_with_headers.ts.out",
// });
itest!(_025_hrtime {
args: "run --allow-hrtime --reload 025_hrtime.ts",
output: "025_hrtime.ts.out",
});
itest!(_025_reload_js_type_error {
args: "run --reload 025_reload_js_type_error.js",
output: "025_reload_js_type_error.js.out",
});
itest!(_026_redirect_javascript {
args: "run --reload 026_redirect_javascript.js",
output: "026_redirect_javascript.js.out",
http_server: true,
});
itest!(_026_workers {
args: "run --reload 026_workers.ts",
output: "026_workers.ts.out",
});
itest!(_027_redirect_typescript {
args: "run --reload 027_redirect_typescript.ts",
output: "027_redirect_typescript.ts.out",
http_server: true,
});
itest!(_028_args {
args: "run --reload 028_args.ts --arg1 val1 --arg2=val2 -- arg3 arg4",
output: "028_args.ts.out",
});
itest!(_029_eval {
args: "eval console.log(\"hello\")",
output: "029_eval.out",
});
itest!(_030_xeval {
args: "xeval console.log($.toUpperCase())",
input: Some("a\nb\n\nc"),
output: "030_xeval.out",
});
itest!(_031_xeval_replvar {
args: "xeval -I val console.log(val.toUpperCase());",
input: Some("a\nb\n\nc"),
output: "031_xeval_replvar.out",
});
itest!(_032_xeval_delim {
args: "xeval -d DELIM console.log($.toUpperCase());",
input: Some("aDELIMbDELIMDELIMc"),
output: "032_xeval_delim.out",
});
itest!(_033_import_map {
args:
"run --reload --importmap=importmaps/import_map.json importmaps/test.ts",
output: "033_import_map.out",
});
itest!(_034_onload {
args: "run --reload 034_onload/main.ts",
output: "034_onload.out",
});
itest!(_035_no_fetch_flag {
args:
"--reload --no-fetch http://127.0.0.1:4545/cli/tests/019_media_types.ts",
output: "035_no_fetch_flag.out",
exit_code: 1,
check_stderr: true,
http_server: true,
});
itest!(_036_import_map_fetch {
args:
"fetch --reload --importmap=importmaps/import_map.json importmaps/test.ts",
output: "036_import_map_fetch.out",
});
itest!(_037_current_thread {
args: "run --current-thread --reload 034_onload/main.ts",
output: "034_onload.out",
});
itest!(_038_checkjs {
// checking if JS file is run through TS compiler
args: "run --reload --config 038_checkjs.tsconfig.json 038_checkjs.js",
check_stderr: true,
exit_code: 1,
output: "038_checkjs.js.out",
});
itest!(_039_worker_deno_ns {
args: "run --reload 039_worker_deno_ns.ts",
output: "039_worker_deno_ns.ts.out",
});
itest!(_040_worker_blob {
args: "run --reload 040_worker_blob.ts",
output: "040_worker_blob.ts.out",
});
itest!(_041_dyn_import_eval {
args: "eval import('./subdir/mod4.js').then(console.log)",
output: "041_dyn_import_eval.out",
});
itest!(_041_info_flag {
args: "info",
output: "041_info_flag.out",
});
itest!(_042_dyn_import_evalcontext {
args: "run --allow-read --reload 042_dyn_import_evalcontext.ts",
output: "042_dyn_import_evalcontext.ts.out",
});
itest!(_044_bad_resource {
args: "run --reload --allow-read 044_bad_resource.ts",
output: "044_bad_resource.ts.out",
check_stderr: true,
exit_code: 1,
});
itest!(_045_proxy {
args: "run --allow-net --allow-env --allow-run --reload 045_proxy_test.ts",
output: "045_proxy_test.ts.out",
});
itest!(_046_tsx {
args: "run --reload 046_jsx_test.tsx",
output: "046_jsx_test.tsx.out",
});
itest!(_047_jsx {
args: "run --reload 047_jsx_test.jsx",
output: "047_jsx_test.jsx.out",
});
itest!(_048_media_types_jsx {
args: "run --reload 048_media_types_jsx.ts",
output: "048_media_types_jsx.ts.out",
http_server: true,
});
itest!(_049_info_flag_script_jsx {
args: "info http://127.0.0.1:4545/cli/tests/048_media_types_jsx.ts",
output: "049_info_flag_script_jsx.out",
http_server: true,
});
itest!(async_error {
exit_code: 1,
args: "run --reload async_error.ts",
check_stderr: true,
output: "async_error.ts.out",
});
itest!(circular1 {
args: "run --reload circular1.js",
output: "circular1.js.out",
});
itest!(config {
args: "run --reload --config config.tsconfig.json config.ts",
check_stderr: true,
exit_code: 1,
output: "config.ts.out",
});
itest!(error_001 {
args: "run --reload error_001.ts",
check_stderr: true,
exit_code: 1,
output: "error_001.ts.out",
});
itest!(error_002 {
args: "run --reload error_002.ts",
check_stderr: true,
exit_code: 1,
output: "error_002.ts.out",
});
itest!(error_003_typescript {
args: "run --reload error_003_typescript.ts",
check_stderr: true,
exit_code: 1,
output: "error_003_typescript.ts.out",
});
// Supposing that we've already attempted to run error_003_typescript.ts
// we want to make sure that JS wasn't emitted. Running again without reload flag
// should result in the same output.
// https://github.com/denoland/deno/issues/2436
itest!(error_003_typescript2 {
args: "run error_003_typescript.ts",
check_stderr: true,
exit_code: 1,
output: "error_003_typescript.ts.out",
});
itest!(error_004_missing_module {
args: "run --reload error_004_missing_module.ts",
check_stderr: true,
exit_code: 1,
output: "error_004_missing_module.ts.out",
});
itest!(error_005_missing_dynamic_import {
args: "run --reload error_005_missing_dynamic_import.ts",
check_stderr: true,
exit_code: 1,
output: "error_005_missing_dynamic_import.ts.out",
});
itest!(error_006_import_ext_failure {
args: "run --reload error_006_import_ext_failure.ts",
check_stderr: true,
exit_code: 1,
output: "error_006_import_ext_failure.ts.out",
});
itest!(error_007_any {
args: "run --reload error_007_any.ts",
check_stderr: true,
exit_code: 1,
output: "error_007_any.ts.out",
});
itest!(error_008_checkjs {
args: "run --reload error_008_checkjs.js",
check_stderr: true,
exit_code: 1,
output: "error_008_checkjs.js.out",
});
itest!(error_011_bad_module_specifier {
args: "run --reload error_011_bad_module_specifier.ts",
check_stderr: true,
exit_code: 1,
output: "error_011_bad_module_specifier.ts.out",
});
itest!(error_012_bad_dynamic_import_specifier {
args: "run --reload error_012_bad_dynamic_import_specifier.ts",
check_stderr: true,
exit_code: 1,
output: "error_012_bad_dynamic_import_specifier.ts.out",
});
itest!(error_013_missing_script {
args: "run --reload missing_file_name",
check_stderr: true,
exit_code: 1,
output: "error_013_missing_script.out",
});
itest!(error_014_catch_dynamic_import_error {
args: "error_014_catch_dynamic_import_error.js --reload --allow-read",
output: "error_014_catch_dynamic_import_error.js.out",
exit_code: 1,
});
itest!(error_015_dynamic_import_permissions {
args: "--reload --no-prompt error_015_dynamic_import_permissions.js",
output: "error_015_dynamic_import_permissions.out",
check_stderr: true,
exit_code: 1,
http_server: true,
});
// We have an allow-net flag but not allow-read, it should still result in error.
itest!(error_016_dynamic_import_permissions2 {
args:
"--no-prompt --reload --allow-net error_016_dynamic_import_permissions2.js",
output: "error_016_dynamic_import_permissions2.out",
check_stderr: true,
exit_code: 1,
http_server: true,
});
itest!(error_stack {
args: "run --reload error_stack.ts",
check_stderr: true,
exit_code: 1,
output: "error_stack.ts.out",
});
itest!(error_syntax {
args: "run --reload error_syntax.js",
check_stderr: true,
exit_code: 1,
output: "error_syntax.js.out",
});
itest!(error_type_definitions {
args: "run --reload error_type_definitions.ts",
check_stderr: true,
exit_code: 1,
output: "error_type_definitions.ts.out",
});
itest!(error_worker_dynamic {
args: "run --reload error_worker_dynamic.ts",
check_stderr: true,
exit_code: 1,
output: "error_worker_dynamic.ts.out",
});
itest!(exit_error42 {
exit_code: 42,
args: "run --reload exit_error42.ts",
output: "exit_error42.ts.out",
});
itest!(https_import {
args: "run --reload https_import.ts",
output: "https_import.ts.out",
});
itest!(if_main {
args: "run --reload if_main.ts",
output: "if_main.ts.out",
});
itest!(import_meta {
args: "run --reload import_meta.ts",
output: "import_meta.ts.out",
});
itest!(seed_random {
args: "run --seed=100 seed_random.js",
output: "seed_random.js.out",
});
itest!(type_definitions {
args: "run --reload type_definitions.ts",
output: "type_definitions.ts.out",
});
itest!(types {
args: "types",
output: "types.out",
});
itest!(unbuffered_stderr {
args: "run --reload unbuffered_stderr.ts",
check_stderr: true,
output: "unbuffered_stderr.ts.out",
});
itest!(unbuffered_stdout {
args: "run --reload unbuffered_stdout.ts",
output: "unbuffered_stdout.ts.out",
});
itest!(v8_flags {
args: "run --v8-flags=--expose-gc v8_flags.js",
output: "v8_flags.js.out",
});
itest!(v8_help {
args: "--v8-options",
output: "v8_help.out",
});
itest!(version {
args: "version",
output: "version.out",
});
itest!(version_long_flag {
args: "--version",
output: "version.out",
});
itest!(version_short_flag {
args: "-v",
output: "version.out",
});
itest!(wasm {
args: "run wasm.ts",
output: "wasm.ts.out",
});
itest!(wasm_async {
args: "wasm_async.js",
output: "wasm_async.out",
});
itest!(top_level_await {
args: "--allow-read top_level_await.js",
output: "top_level_await.out",
});
itest!(top_level_await_ts {
args: "--allow-read top_level_await.ts",
output: "top_level_await.out",
});
| 22.688663 | 81 | 0.695652 |
db278d3fa21939b60af11f890a001d8511c4467c
| 8,018 |
// Copyright 2019 Parity Technologies (UK) Ltd.
// Copyright 2020 Netwarps Ltd.
//
// 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.
//! Ed25519 keys.
use super::error::DecodingError;
use ed25519_dalek as ed25519;
use ed25519_dalek::{Signature, Signer, Verifier};
use rand::RngCore;
use std::convert::TryFrom;
use std::fmt;
use zeroize::Zeroize;
/// An Ed25519 keypair.
pub struct Keypair(ed25519::Keypair);
impl Keypair {
/// Generate a fixed Ed25519 keypair, used for test puepose only.
pub fn generate_fixed() -> Keypair {
let bytes = [0u8; 32];
Keypair::from(SecretKey::from_bytes(bytes).unwrap())
}
/// Generate a fixed Ed25519 keypair, used for test puepose only.
pub fn generate_with_seed(bytes: [u8; 32]) -> Keypair {
Keypair::from(SecretKey::from_bytes(bytes).unwrap())
}
/// Generate a new Ed25519 keypair.
pub fn generate() -> Keypair {
Keypair::from(SecretKey::generate())
}
/// Encode the keypair into a byte array by concatenating the bytes
/// of the secret scalar and the compressed public point,
/// an informal standard for encoding Ed25519 keypairs.
pub fn encode(&self) -> [u8; 64] {
self.0.to_bytes()
}
/// Decode a keypair from the format produced by `encode`,
/// zeroing the input on success.
pub fn decode(kp: &mut [u8]) -> Result<Keypair, DecodingError> {
ed25519::Keypair::from_bytes(kp)
.map(|k| {
kp.zeroize();
Keypair(k)
})
.map_err(|e| DecodingError::new("Ed25519 keypair").source(e))
}
/// Sign a message using the private key of this keypair.
pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
self.0.sign(&msg).to_bytes().to_vec()
}
/// Get the public key of this keypair.
pub fn public(&self) -> PublicKey {
PublicKey(self.0.public)
}
/// Get the secret key of this keypair.
pub fn secret(&self) -> SecretKey {
SecretKey::from_bytes(&mut self.0.secret.to_bytes()).expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
}
}
impl fmt::Debug for Keypair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Keypair").field("public", &self.0.public).finish()
}
}
impl Clone for Keypair {
fn clone(&self) -> Keypair {
let mut sk_bytes = self.0.secret.to_bytes();
let secret = SecretKey::from_bytes(&mut sk_bytes)
.expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
.0;
let public =
ed25519::PublicKey::from_bytes(&self.0.public.to_bytes()).expect("ed25519::PublicKey::from_bytes(to_bytes(k)) != k");
Keypair(ed25519::Keypair { secret, public })
}
}
/// Demote an Ed25519 keypair to a secret key.
impl From<Keypair> for SecretKey {
fn from(kp: Keypair) -> SecretKey {
SecretKey(kp.0.secret)
}
}
/// Promote an Ed25519 secret key into a keypair.
impl From<SecretKey> for Keypair {
fn from(sk: SecretKey) -> Keypair {
let secret: ed25519::ExpandedSecretKey = (&sk.0).into();
let public = ed25519::PublicKey::from(&secret);
Keypair(ed25519::Keypair { secret: sk.0, public })
}
}
/// An Ed25519 public key.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct PublicKey(ed25519::PublicKey);
impl PublicKey {
/// Verify the Ed25519 signature on a message using the public key.
pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
Signature::try_from(&sig[..]).and_then(|s| self.0.verify(msg, &s)).is_ok()
}
/// Encode the public key into a byte array in compressed form, i.e.
/// where one coordinate is represented by a single bit.
pub fn encode(&self) -> [u8; 32] {
self.0.to_bytes()
}
/// Decode a public key from a byte array as produced by `encode`.
pub fn decode(k: &[u8]) -> Result<PublicKey, DecodingError> {
ed25519::PublicKey::from_bytes(k)
.map_err(|e| DecodingError::new("Ed25519 public key").source(e))
.map(PublicKey)
}
}
/// An Ed25519 secret key.
pub struct SecretKey(ed25519::SecretKey);
/// View the bytes of the secret key.
impl AsRef<[u8]> for SecretKey {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl Clone for SecretKey {
fn clone(&self) -> SecretKey {
let mut sk_bytes = self.0.to_bytes();
Self::from_bytes(&mut sk_bytes).expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
}
}
impl fmt::Debug for SecretKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SecretKey")
}
}
impl SecretKey {
/// Generate a new Ed25519 secret key.
pub fn generate() -> SecretKey {
let mut bytes = [0u8; 32];
rand::thread_rng().fill_bytes(&mut bytes);
SecretKey(
ed25519::SecretKey::from_bytes(&bytes)
.expect("this returns `Err` only if the length is wrong; the length is correct; qed"),
)
}
/// Create an Ed25519 secret key from a byte slice, zeroing the input on success.
/// If the bytes do not constitute a valid Ed25519 secret key, an error is
/// returned.
pub fn from_bytes(mut sk_bytes: impl AsMut<[u8]>) -> Result<SecretKey, DecodingError> {
let sk_bytes = sk_bytes.as_mut();
let secret = ed25519::SecretKey::from_bytes(&*sk_bytes).map_err(|e| DecodingError::new("Ed25519 secret key").source(e))?;
sk_bytes.zeroize();
Ok(SecretKey(secret))
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::*;
fn eq_keypairs(kp1: &Keypair, kp2: &Keypair) -> bool {
kp1.public() == kp2.public() && kp1.0.secret.as_bytes() == kp2.0.secret.as_bytes()
}
#[test]
fn ed25519_keypair_encode_decode() {
fn prop() -> bool {
let kp1 = Keypair::generate();
let mut kp1_enc = kp1.encode();
let kp2 = Keypair::decode(&mut kp1_enc).unwrap();
eq_keypairs(&kp1, &kp2) && kp1_enc.iter().all(|b| *b == 0)
}
QuickCheck::new().tests(10).quickcheck(prop as fn() -> _);
}
#[test]
fn ed25519_keypair_from_secret() {
fn prop() -> bool {
let kp1 = Keypair::generate();
let mut sk = kp1.0.secret.to_bytes();
let kp2 = Keypair::from(SecretKey::from_bytes(&mut sk).unwrap());
eq_keypairs(&kp1, &kp2) && sk == [0u8; 32]
}
QuickCheck::new().tests(10).quickcheck(prop as fn() -> _);
}
#[test]
fn ed25519_signature() {
let kp = Keypair::generate();
let pk = kp.public();
let msg = b"hello world";
let sig = kp.sign(msg);
assert!(pk.verify(msg, &sig));
let mut invalid_sig = sig.clone();
invalid_sig[3..6].copy_from_slice(&[10, 23, 42]);
assert!(!pk.verify(msg, &invalid_sig));
let invalid_msg = b"h3ll0 w0rld";
assert!(!pk.verify(invalid_msg, &sig[..]));
}
}
| 33.831224 | 129 | 0.621601 |
01fdd07cfe032ee9463b5127bb36270ca4537d54
| 5,769 |
use differential_datalog::record::FromRecord;
use differential_datalog::record::IntoRecord;
use differential_datalog::record::Mutator;
use differential_datalog::record::Record;
use serde::de::Deserialize;
use serde::de::Deserializer;
use serde::ser::Serialize;
use serde::ser::Serializer;
use std::net::Ipv6Addr;
use std::str::FromStr;
#[derive(Eq, Ord, Clone, Hash, PartialEq, PartialOrd)]
pub struct net_ipv6_Ipv6Addr(Ipv6Addr);
impl net_ipv6_Ipv6Addr {
pub fn new(addr: Ipv6Addr) -> Self {
net_ipv6_Ipv6Addr(addr)
}
}
impl Deref for net_ipv6_Ipv6Addr {
type Target = Ipv6Addr;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Default for net_ipv6_Ipv6Addr {
fn default() -> net_ipv6_Ipv6Addr {
net_ipv6_iPV6_UNSPECIFIED()
}
}
impl fmt::Display for net_ipv6_Ipv6Addr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", net_ipv6_ipv6_to_u128(self))
}
}
impl fmt::Debug for net_ipv6_Ipv6Addr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl Serialize for net_ipv6_Ipv6Addr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
net_ipv6_ipv6_to_u128(self).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for net_ipv6_Ipv6Addr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
u128::deserialize(deserializer).map(|x| net_ipv6_ipv6_from_u128(&x))
}
}
impl FromRecord for net_ipv6_Ipv6Addr {
fn from_record(val: &Record) -> Result<Self, String> {
u128::from_record(val).map(|x| net_ipv6_ipv6_from_u128(&x))
}
}
impl IntoRecord for net_ipv6_Ipv6Addr {
fn into_record(self) -> Record {
net_ipv6_ipv6_to_u128(&self).into_record()
}
}
impl Mutator<net_ipv6_Ipv6Addr> for Record {
fn mutate(&self, addr: &mut net_ipv6_Ipv6Addr) -> Result<(), String> {
net_ipv6_Ipv6Addr::from_record(self).map(|a| *addr = a)
}
}
pub fn net_ipv6_ipv6_new(
a: &u16,
b: &u16,
c: &u16,
d: &u16,
e: &u16,
f: &u16,
g: &u16,
h: &u16,
) -> net_ipv6_Ipv6Addr {
net_ipv6_Ipv6Addr::new(Ipv6Addr::new(*a, *b, *c, *d, *e, *f, *g, *h))
}
pub fn net_ipv6_ipv6_from_segment_vec(segments: &std_Vec<u16>) -> std_Option<net_ipv6_Ipv6Addr> {
if segments.len() != 8 {
return std_Option::std_None;
};
std_Option::std_Some {
x: net_ipv6_Ipv6Addr::new(Ipv6Addr::from([
segments[0],
segments[1],
segments[2],
segments[3],
segments[4],
segments[5],
segments[6],
segments[7],
])),
}
}
pub fn net_ipv6_ipv6_from_octets(
b0: &u8,
b1: &u8,
b2: &u8,
b3: &u8,
b4: &u8,
b5: &u8,
b6: &u8,
b7: &u8,
b8: &u8,
b9: &u8,
b10: &u8,
b11: &u8,
b12: &u8,
b13: &u8,
b14: &u8,
b15: &u8,
) -> net_ipv6_Ipv6Addr {
net_ipv6_Ipv6Addr::new(Ipv6Addr::from([
*b0, *b1, *b2, *b3, *b4, *b5, *b6, *b7, *b8, *b9, *b10, *b11, *b12, *b13, *b14, *b15,
]))
}
pub fn net_ipv6_ipv6_from_octet_vec(octets: &std_Vec<u8>) -> std_Option<net_ipv6_Ipv6Addr> {
if octets.len() != 16 {
return std_Option::std_None;
};
std_Option::std_Some {
x: net_ipv6_Ipv6Addr::new(Ipv6Addr::from([
octets[0], octets[1], octets[2], octets[3], octets[4], octets[5], octets[6], octets[7],
octets[8], octets[9], octets[10], octets[11], octets[12], octets[13], octets[14],
octets[15],
])),
}
}
pub fn net_ipv6_ipv6_from_u128(ip: &u128) -> net_ipv6_Ipv6Addr {
net_ipv6_Ipv6Addr::new(Ipv6Addr::from(*ip))
}
pub fn net_ipv6_ipv6_from_str(s: &String) -> std_Result<net_ipv6_Ipv6Addr, String> {
res2std(Ipv6Addr::from_str(&*s).map(net_ipv6_Ipv6Addr::new))
}
pub fn net_ipv6_ipv6Addr2string(addr: &net_ipv6_Ipv6Addr) -> String {
(**addr).to_string()
}
pub fn net_ipv6_ipv6_to_u128(addr: &net_ipv6_Ipv6Addr) -> u128 {
u128::from(**addr)
}
pub fn net_ipv6_iPV6_LOCALHOST() -> net_ipv6_Ipv6Addr {
net_ipv6_Ipv6Addr::new(Ipv6Addr::LOCALHOST)
}
pub fn net_ipv6_iPV6_UNSPECIFIED() -> net_ipv6_Ipv6Addr {
net_ipv6_Ipv6Addr::new(Ipv6Addr::UNSPECIFIED)
}
pub fn net_ipv6_ipv6_segments(
addr: &net_ipv6_Ipv6Addr,
) -> (u16, u16, u16, u16, u16, u16, u16, u16) {
let segments = addr.segments();
(
segments[0],
segments[1],
segments[2],
segments[3],
segments[4],
segments[5],
segments[6],
segments[7],
)
}
pub fn net_ipv6_ipv6_segment_vec(addr: &net_ipv6_Ipv6Addr) -> std_Vec<u16> {
std_Vec::from(addr.segments().as_ref())
}
pub fn net_ipv6_ipv6_octets(
addr: &net_ipv6_Ipv6Addr,
) -> tuple16<u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8> {
let octets = addr.octets();
tuple16(
octets[0], octets[1], octets[2], octets[3], octets[4], octets[5], octets[6], octets[7],
octets[8], octets[9], octets[10], octets[11], octets[12], octets[13], octets[14],
octets[15],
)
}
pub fn net_ipv6_ipv6_octet_vec(addr: &net_ipv6_Ipv6Addr) -> std_Vec<u8> {
std_Vec::from(addr.octets().as_ref())
}
pub fn net_ipv6_ipv6_is_unspecified(addr: &net_ipv6_Ipv6Addr) -> bool {
addr.is_unspecified()
}
pub fn net_ipv6_ipv6_is_loopback(addr: &net_ipv6_Ipv6Addr) -> bool {
addr.is_loopback()
}
pub fn net_ipv6_ipv6_is_multicast(addr: &net_ipv6_Ipv6Addr) -> bool {
addr.is_multicast()
}
pub fn net_ipv6_ipv6_to_ipv4(addr: &net_ipv6_Ipv6Addr) -> std_Option<net_ipv4_Ipv4Addr> {
option2std(addr.to_ipv4().map(net_ipv4_Ipv4Addr::new))
}
| 25.754464 | 99 | 0.623852 |
dd2f1a89e65d38adc89cba1cefd69ac77359d373
| 11,217 |
use crate::common::*;
use std::path::Component;
pub(crate) const FILENAME: &str = "justfile";
const PROJECT_ROOT_CHILDREN: &[&str] = &[".bzr", ".git", ".hg", ".svn", "_darcs"];
pub(crate) struct Search {
pub(crate) justfile: PathBuf,
pub(crate) working_directory: PathBuf,
}
impl Search {
pub(crate) fn find(
search_config: &SearchConfig,
invocation_directory: &Path,
) -> SearchResult<Self> {
match search_config {
SearchConfig::FromInvocationDirectory => {
let justfile = Self::justfile(&invocation_directory)?;
let working_directory = Self::working_directory_from_justfile(&justfile)?;
Ok(Self {
justfile,
working_directory,
})
}
SearchConfig::FromSearchDirectory { search_directory } => {
let search_directory = Self::clean(invocation_directory, search_directory);
let justfile = Self::justfile(&search_directory)?;
let working_directory = Self::working_directory_from_justfile(&justfile)?;
Ok(Self {
justfile,
working_directory,
})
}
SearchConfig::WithJustfile { justfile } => {
let justfile = Self::clean(invocation_directory, justfile);
let working_directory = Self::working_directory_from_justfile(&justfile)?;
Ok(Self {
justfile,
working_directory,
})
}
SearchConfig::WithJustfileAndWorkingDirectory {
justfile,
working_directory,
} => Ok(Self {
justfile: Self::clean(invocation_directory, justfile),
working_directory: Self::clean(invocation_directory, working_directory),
}),
}
}
pub(crate) fn init(
search_config: &SearchConfig,
invocation_directory: &Path,
) -> SearchResult<Self> {
match search_config {
SearchConfig::FromInvocationDirectory => {
let working_directory = Self::project_root(&invocation_directory)?;
let justfile = working_directory.join(FILENAME);
Ok(Self {
justfile,
working_directory,
})
}
SearchConfig::FromSearchDirectory { search_directory } => {
let search_directory = Self::clean(invocation_directory, search_directory);
let working_directory = Self::project_root(&search_directory)?;
let justfile = working_directory.join(FILENAME);
Ok(Self {
justfile,
working_directory,
})
}
SearchConfig::WithJustfile { justfile } => {
let justfile = Self::clean(invocation_directory, justfile);
let working_directory = Self::working_directory_from_justfile(&justfile)?;
Ok(Self {
justfile,
working_directory,
})
}
SearchConfig::WithJustfileAndWorkingDirectory {
justfile,
working_directory,
} => Ok(Self {
justfile: Self::clean(invocation_directory, justfile),
working_directory: Self::clean(invocation_directory, working_directory),
}),
}
}
fn justfile(directory: &Path) -> SearchResult<PathBuf> {
for directory in directory.ancestors() {
let mut candidates = Vec::new();
let entries = fs::read_dir(directory).map_err(|io_error| SearchError::Io {
io_error,
directory: directory.to_owned(),
})?;
for entry in entries {
let entry = entry.map_err(|io_error| SearchError::Io {
io_error,
directory: directory.to_owned(),
})?;
if let Some(name) = entry.file_name().to_str() {
if name.eq_ignore_ascii_case(FILENAME) {
candidates.push(entry.path());
}
}
}
if candidates.len() == 1 {
return Ok(candidates.pop().unwrap());
} else if candidates.len() > 1 {
return Err(SearchError::MultipleCandidates { candidates });
}
}
Err(SearchError::NotFound)
}
fn clean(invocation_directory: &Path, path: &Path) -> PathBuf {
let path = invocation_directory.join(path);
let mut clean = Vec::new();
for component in path.components() {
if component == Component::ParentDir {
if let Some(Component::Normal(_)) = clean.last() {
clean.pop();
}
} else {
clean.push(component);
}
}
clean.into_iter().collect()
}
fn project_root(directory: &Path) -> SearchResult<PathBuf> {
for directory in directory.ancestors() {
let entries = fs::read_dir(directory).map_err(|io_error| SearchError::Io {
io_error,
directory: directory.to_owned(),
})?;
for entry in entries {
let entry = entry.map_err(|io_error| SearchError::Io {
io_error,
directory: directory.to_owned(),
})?;
for project_root_child in PROJECT_ROOT_CHILDREN.iter().cloned() {
if entry.file_name() == project_root_child {
return Ok(directory.to_owned());
}
}
}
}
Ok(directory.to_owned())
}
fn working_directory_from_justfile(justfile: &Path) -> SearchResult<PathBuf> {
Ok(justfile
.parent()
.ok_or_else(|| SearchError::JustfileHadNoParent {
path: justfile.to_path_buf(),
})?
.to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
use test_utilities::tmptree;
#[test]
fn not_found() {
let tmp = testing::tempdir();
match Search::justfile(tmp.path()) {
Err(SearchError::NotFound) => {}
_ => panic!("No justfile found error was expected"),
}
}
#[test]
fn multiple_candidates() {
let tmp = testing::tempdir();
let mut path = tmp.path().to_path_buf();
path.push(FILENAME);
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
path.push(FILENAME.to_uppercase());
if fs::File::open(path.as_path()).is_ok() {
// We are in case-insensitive file system
return;
}
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
match Search::justfile(path.as_path()) {
Err(SearchError::MultipleCandidates { .. }) => {}
_ => panic!("Multiple candidates error was expected"),
}
}
#[test]
fn found() {
let tmp = testing::tempdir();
let mut path = tmp.path().to_path_buf();
path.push(FILENAME);
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
if let Err(err) = Search::justfile(path.as_path()) {
panic!("No errors were expected: {}", err);
}
}
#[test]
fn found_spongebob_case() {
let tmp = testing::tempdir();
let mut path = tmp.path().to_path_buf();
let spongebob_case = FILENAME
.chars()
.enumerate()
.map(|(i, c)| {
if i % 2 == 0 {
c.to_ascii_uppercase()
} else {
c
}
})
.collect::<String>();
path.push(spongebob_case);
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
if let Err(err) = Search::justfile(path.as_path()) {
panic!("No errors were expected: {}", err);
}
}
#[test]
fn found_from_inner_dir() {
let tmp = testing::tempdir();
let mut path = tmp.path().to_path_buf();
path.push(FILENAME);
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
path.push("a");
fs::create_dir(&path)
.expect("test justfile search: failed to create intermediary directory");
path.push("b");
fs::create_dir(&path)
.expect("test justfile search: failed to create intermediary directory");
if let Err(err) = Search::justfile(path.as_path()) {
panic!("No errors were expected: {}", err);
}
}
#[test]
fn found_and_stopped_at_first_justfile() {
let tmp = testing::tempdir();
let mut path = tmp.path().to_path_buf();
path.push(FILENAME);
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
path.push("a");
fs::create_dir(&path)
.expect("test justfile search: failed to create intermediary directory");
path.push(FILENAME);
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
path.push("b");
fs::create_dir(&path)
.expect("test justfile search: failed to create intermediary directory");
match Search::justfile(path.as_path()) {
Ok(found_path) => {
path.pop();
path.push(FILENAME);
assert_eq!(found_path, path);
}
Err(err) => panic!("No errors were expected: {}", err),
}
}
#[test]
fn justfile_symlink_parent() {
let tmp = tmptree! {
src: "",
sub: {},
};
let src = tmp.path().join("src");
let sub = tmp.path().join("sub");
let justfile = sub.join("justfile");
#[cfg(unix)]
std::os::unix::fs::symlink(&src, &justfile).unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_file(&src, &justfile).unwrap();
let search_config = SearchConfig::FromInvocationDirectory;
let search = Search::find(&search_config, &sub).unwrap();
assert_eq!(search.justfile, justfile);
assert_eq!(search.working_directory, sub);
}
#[test]
fn clean() {
let cases = &[
("/", "foo", "/foo"),
("/bar", "/foo", "/foo"),
("//foo", "bar//baz", "/foo/bar/baz"),
("/", "..", "/"),
("/", "/..", "/"),
("/..", "", "/"),
("/../../../..", "../../../", "/"),
("/.", "./", "/"),
("/foo/../", "bar", "/bar"),
("/foo/bar", "..", "/foo"),
("/foo/bar/", "..", "/foo"),
];
for (prefix, suffix, want) in cases {
let have = Search::clean(Path::new(prefix), Path::new(suffix));
assert_eq!(have, Path::new(want));
}
}
}
| 31.597183 | 91 | 0.497727 |
cc086877f57e6d81bd20cfc6fdbcd447994b3815
| 2,035 |
use async_trait::async_trait;
use crate::{
requests::api_manager::{ApiManager, API_TIMEOUT_MS},
RobberError,
};
use serde::Deserialize;
use super::users::{User, UserInteraction};
#[derive(Debug, Deserialize)]
pub struct GetMembersResponse {
count: i32,
items: Vec<i32>,
}
#[derive(Debug, Deserialize)]
pub struct GetMembers {
response: Option<GetMembersResponse>,
}
impl GetMembers {
fn validate(&self) -> bool {
self.response.is_some()
}
}
#[async_trait]
pub trait GroupInteraction {
async fn get_members_ids(&self, group_id: i32) -> Result<Vec<i32>, RobberError>;
async fn get_members(&self, group_id: i32, fields: &str) -> Result<Vec<User>, RobberError>;
}
#[async_trait]
impl GroupInteraction for ApiManager {
async fn get_members_ids(&self, group_id: i32) -> Result<Vec<i32>, RobberError> {
let spy_request = self
.request_json::<_, GetMembers>("groups.getMembers", &[("group_id", group_id)])
.await?;
if !spy_request.validate() {
return Err(RobberError::APIError);
}
let resp = spy_request.response.unwrap();
let mut result: Vec<i32> = Vec::with_capacity(resp.count as usize);
for i in 0..=(resp.count / 1000) {
let request = self
.request_json::<_, GetMembers>(
"groups.getMembers",
&[("group_id", group_id), ("offset", i * 1000)],
)
.await?;
if !request.validate() {
return Err(RobberError::APIError);
}
let mut resp = request.response.unwrap();
result.extend(resp.items.drain(..));
tokio::time::sleep(tokio::time::Duration::from_millis(API_TIMEOUT_MS)).await;
}
Ok(result)
}
async fn get_members(&self, group_id: i32, fields: &str) -> Result<Vec<User>, RobberError> {
let ids = self.get_members_ids(group_id).await?;
Ok(self.get_users(&ids, fields).await?)
}
}
| 28.263889 | 96 | 0.596069 |
11786b13eeaf029d30ba3dd29d6b6b82811cf94e
| 11,185 |
// -*- mode: rust; -*-
//
// This file is part of x25519-dalek.
// Copyright (c) 2017-2019 isis lovecruft
// Copyright (c) 2019 DebugSteven
// See LICENSE for licensing information.
//
// Authors:
// - isis agora lovecruft <[email protected]>
// - DebugSteven <[email protected]>
//! x25519 Diffie-Hellman key exchange
//!
//! This implements x25519 key exchange as specified by Mike Hamburg
//! and Adam Langley in [RFC7748](https://tools.ietf.org/html/rfc7748).
use clear_on_drop::clear::Clear;
use curve25519_dalek::constants::ED25519_BASEPOINT_TABLE;
use curve25519_dalek::montgomery::MontgomeryPoint;
use curve25519_dalek::scalar::Scalar;
use rand_core::RngCore;
use rand_core::CryptoRng;
/// A `PublicKey` is the corresponding public key converted from
/// an `EphemeralSecret` or a `StaticSecret` key.
#[derive(Copy, Clone, Debug)]
pub struct PublicKey(pub (crate) MontgomeryPoint);
impl From<[u8; 32]> for PublicKey {
/// Given a byte array, construct a x25519 `PublicKey`.
fn from(bytes: [u8; 32]) -> PublicKey {
PublicKey(MontgomeryPoint(bytes))
}
}
impl PublicKey {
/// View this public key as a byte array.
#[inline]
pub fn as_bytes(&self) -> &[u8; 32] {
self.0.as_bytes()
}
}
/// A `EphemeralSecret` is a short lived Diffie-Hellman secret key
/// used to create a `SharedSecret` when given their `PublicKey`.
pub struct EphemeralSecret(pub (crate) Scalar);
/// Overwrite ephemeral secret key material with null bytes when it goes out of scope.
impl Drop for EphemeralSecret {
fn drop(&mut self) {
self.0.clear();
}
}
impl EphemeralSecret {
/// Perform a Diffie-Hellman key agreement between `self` and
/// `their_public` key to produce a `SharedSecret`.
pub fn diffie_hellman(self, their_public: &PublicKey) -> SharedSecret {
SharedSecret(self.0 * their_public.0)
}
/// Generate an x25519 `EphemeralSecret` key.
pub fn new<T>(csprng: &mut T) -> Self
where T: RngCore + CryptoRng
{
let mut bytes = [0u8; 32];
csprng.fill_bytes(&mut bytes);
EphemeralSecret(clamp_scalar(bytes))
}
}
impl<'a> From<&'a EphemeralSecret> for PublicKey {
/// Given an x25519 `EphemeralSecret` key, compute its corresponding
/// `PublicKey` key.
fn from(secret: &'a EphemeralSecret) -> PublicKey {
PublicKey((&ED25519_BASEPOINT_TABLE * &secret.0).to_montgomery())
}
}
/// A `StaticSecret` is a static Diffie-Hellman secret key that
/// can be saved and loaded to create a `SharedSecret` when given
/// their `PublicKey`.
pub struct StaticSecret(pub (crate) Scalar);
/// Overwrite static secret key material with null bytes when it goes out of scope.
impl Drop for StaticSecret {
fn drop(&mut self) {
self.0.clear();
}
}
impl StaticSecret {
/// Perform a Diffie-Hellman key agreement between `self` and
/// `their_public` key to produce a `SharedSecret`.
pub fn diffie_hellman(&self, their_public: &PublicKey) -> SharedSecret {
SharedSecret(&self.0 * their_public.0)
}
/// Generate a x25519 `StaticSecret` key.
pub fn new<T>(csprng: &mut T) -> Self
where T: RngCore + CryptoRng
{
let mut bytes = [0u8; 32];
csprng.fill_bytes(&mut bytes);
StaticSecret(clamp_scalar(bytes))
}
/// Save a x25519 `StaticSecret` key's bytes.
pub fn to_bytes(&self) -> [u8; 32] {
self.0.to_bytes()
}
}
impl From<[u8; 32]> for StaticSecret {
/// Load a `StaticSecret` from a byte array.
fn from(bytes: [u8; 32]) -> StaticSecret {
StaticSecret(clamp_scalar(bytes))
}
}
impl<'a> From<&'a StaticSecret> for PublicKey {
/// Given an x25519 `StaticSecret` key, compute its corresponding
/// `PublicKey` key.
fn from(secret: &'a StaticSecret) -> PublicKey {
PublicKey((&ED25519_BASEPOINT_TABLE * &secret.0).to_montgomery())
}
}
/// A `SharedSecret` is a Diffie-Hellman shared secret that’s generated
/// from your `EphemeralSecret` or `StaticSecret` and their `PublicKey`.
pub struct SharedSecret(pub (crate) MontgomeryPoint);
/// Overwrite shared secret material with null bytes when it goes out of scope.
impl Drop for SharedSecret {
fn drop(&mut self) {
self.0.clear();
}
}
impl SharedSecret {
/// View this shared secret key as a byte array.
#[inline]
pub fn as_bytes(&self) -> &[u8; 32] {
self.0.as_bytes()
}
}
/// "Decode" a scalar from a 32-byte array.
///
/// By "decode" here, what is really meant is applying key clamping by twiddling
/// some bits.
///
/// # Returns
///
/// A `Scalar`.
fn clamp_scalar(scalar: [u8; 32]) -> Scalar {
let mut s: [u8; 32] = scalar.clone();
s[0] &= 248;
s[31] &= 127;
s[31] |= 64;
Scalar::from_bits(s)
}
/// The bare, byte-oriented x25519 function, exactly as specified in RFC7748.
///
/// This can be used with [`X25519_BASEPOINT_BYTES`] for people who
/// cannot use the better, safer, and faster DH API.
pub fn x25519(k: [u8; 32], u: [u8; 32]) -> [u8; 32] {
(clamp_scalar(k) * MontgomeryPoint(u)).to_bytes()
}
/// The X25519 basepoint, for use with the bare, byte-oriented x25519
/// function. This is provided for people who cannot use the typed
/// DH API for some reason.
pub const X25519_BASEPOINT_BYTES: [u8; 32] = [
9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
#[cfg(test)]
mod test {
use super::*;
use rand_os::OsRng;
// This was previously a doctest but it got moved to the README to
// avoid duplication where it then wasn't being run, so now it
// lives here.
#[test]
fn alice_and_bob() {
let mut csprng = OsRng::new().unwrap();
let alice_secret = EphemeralSecret::new(&mut csprng);
let alice_public = PublicKey::from(&alice_secret);
let bob_secret = EphemeralSecret::new(&mut csprng);
let bob_public = PublicKey::from(&bob_secret);
let alice_shared_secret = alice_secret.diffie_hellman(&bob_public);
let bob_shared_secret = bob_secret.diffie_hellman(&alice_public);
assert_eq!(alice_shared_secret.as_bytes(), bob_shared_secret.as_bytes());
}
#[test]
fn byte_basepoint_matches_edwards_scalar_mul() {
let mut scalar_bytes = [0x37; 32];
for i in 0..32 {
scalar_bytes[i] += 2;
let result = x25519(scalar_bytes, X25519_BASEPOINT_BYTES);
let expected = (&ED25519_BASEPOINT_TABLE * &clamp_scalar(scalar_bytes))
.to_montgomery()
.to_bytes();
assert_eq!(result, expected);
}
}
fn do_rfc7748_ladder_test1(input_scalar: [u8; 32], input_point: [u8; 32], expected: [u8; 32]) {
let result = x25519(input_scalar, input_point);
assert_eq!(result, expected);
}
#[test]
fn rfc7748_ladder_test1_vectorset1() {
let input_scalar: [u8; 32] = [
0xa5, 0x46, 0xe3, 0x6b, 0xf0, 0x52, 0x7c, 0x9d,
0x3b, 0x16, 0x15, 0x4b, 0x82, 0x46, 0x5e, 0xdd,
0x62, 0x14, 0x4c, 0x0a, 0xc1, 0xfc, 0x5a, 0x18,
0x50, 0x6a, 0x22, 0x44, 0xba, 0x44, 0x9a, 0xc4, ];
let input_point: [u8; 32] = [
0xe6, 0xdb, 0x68, 0x67, 0x58, 0x30, 0x30, 0xdb,
0x35, 0x94, 0xc1, 0xa4, 0x24, 0xb1, 0x5f, 0x7c,
0x72, 0x66, 0x24, 0xec, 0x26, 0xb3, 0x35, 0x3b,
0x10, 0xa9, 0x03, 0xa6, 0xd0, 0xab, 0x1c, 0x4c, ];
let expected: [u8; 32] = [
0xc3, 0xda, 0x55, 0x37, 0x9d, 0xe9, 0xc6, 0x90,
0x8e, 0x94, 0xea, 0x4d, 0xf2, 0x8d, 0x08, 0x4f,
0x32, 0xec, 0xcf, 0x03, 0x49, 0x1c, 0x71, 0xf7,
0x54, 0xb4, 0x07, 0x55, 0x77, 0xa2, 0x85, 0x52, ];
do_rfc7748_ladder_test1(input_scalar, input_point, expected);
}
#[test]
fn rfc7748_ladder_test1_vectorset2() {
let input_scalar: [u8; 32] = [
0x4b, 0x66, 0xe9, 0xd4, 0xd1, 0xb4, 0x67, 0x3c,
0x5a, 0xd2, 0x26, 0x91, 0x95, 0x7d, 0x6a, 0xf5,
0xc1, 0x1b, 0x64, 0x21, 0xe0, 0xea, 0x01, 0xd4,
0x2c, 0xa4, 0x16, 0x9e, 0x79, 0x18, 0xba, 0x0d, ];
let input_point: [u8; 32] = [
0xe5, 0x21, 0x0f, 0x12, 0x78, 0x68, 0x11, 0xd3,
0xf4, 0xb7, 0x95, 0x9d, 0x05, 0x38, 0xae, 0x2c,
0x31, 0xdb, 0xe7, 0x10, 0x6f, 0xc0, 0x3c, 0x3e,
0xfc, 0x4c, 0xd5, 0x49, 0xc7, 0x15, 0xa4, 0x93, ];
let expected: [u8; 32] = [
0x95, 0xcb, 0xde, 0x94, 0x76, 0xe8, 0x90, 0x7d,
0x7a, 0xad, 0xe4, 0x5c, 0xb4, 0xb8, 0x73, 0xf8,
0x8b, 0x59, 0x5a, 0x68, 0x79, 0x9f, 0xa1, 0x52,
0xe6, 0xf8, 0xf7, 0x64, 0x7a, 0xac, 0x79, 0x57, ];
do_rfc7748_ladder_test1(input_scalar, input_point, expected);
}
#[test]
#[ignore] // Run only if you want to burn a lot of CPU doing 1,000,000 DH operations
fn rfc7748_ladder_test2() {
use curve25519_dalek::constants::X25519_BASEPOINT;
let mut k: [u8; 32] = X25519_BASEPOINT.0;
let mut u: [u8; 32] = X25519_BASEPOINT.0;
let mut result: [u8; 32];
macro_rules! do_iterations {
($n:expr) => (
for _ in 0..$n {
result = x25519(k, u);
// OBVIOUS THING THAT I'M GOING TO NOTE ANYWAY BECAUSE I'VE
// SEEN PEOPLE DO THIS WITH GOLANG'S STDLIB AND YOU SURE AS
// HELL SHOULDN'T DO HORRIBLY STUPID THINGS LIKE THIS WITH
// MY LIBRARY:
//
// NEVER EVER TREAT SCALARS AS POINTS AND/OR VICE VERSA.
//
// ↓↓ DON'T DO THIS ↓↓
u = k.clone();
k = result;
}
)
}
// After one iteration:
// 422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079
// After 1,000 iterations:
// 684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51
// After 1,000,000 iterations:
// 7c3911e0ab2586fd864497297e575e6f3bc601c0883c30df5f4dd2d24f665424
do_iterations!(1);
assert_eq!(k, [ 0x42, 0x2c, 0x8e, 0x7a, 0x62, 0x27, 0xd7, 0xbc,
0xa1, 0x35, 0x0b, 0x3e, 0x2b, 0xb7, 0x27, 0x9f,
0x78, 0x97, 0xb8, 0x7b, 0xb6, 0x85, 0x4b, 0x78,
0x3c, 0x60, 0xe8, 0x03, 0x11, 0xae, 0x30, 0x79, ]);
do_iterations!(999);
assert_eq!(k, [ 0x68, 0x4c, 0xf5, 0x9b, 0xa8, 0x33, 0x09, 0x55,
0x28, 0x00, 0xef, 0x56, 0x6f, 0x2f, 0x4d, 0x3c,
0x1c, 0x38, 0x87, 0xc4, 0x93, 0x60, 0xe3, 0x87,
0x5f, 0x2e, 0xb9, 0x4d, 0x99, 0x53, 0x2c, 0x51, ]);
do_iterations!(999_000);
assert_eq!(k, [ 0x7c, 0x39, 0x11, 0xe0, 0xab, 0x25, 0x86, 0xfd,
0x86, 0x44, 0x97, 0x29, 0x7e, 0x57, 0x5e, 0x6f,
0x3b, 0xc6, 0x01, 0xc0, 0x88, 0x3c, 0x30, 0xdf,
0x5f, 0x4d, 0xd2, 0xd2, 0x4f, 0x66, 0x54, 0x24, ]);
}
}
| 33.99696 | 99 | 0.597944 |
7170c6f90d6c70460658a777e3a26cdd89a23b8a
| 2,324 |
type Hash = Vec<u8>;
type Address = String;
// Credit: https://stackoverflow.com/a/44378174/2773837
use std::time::{SystemTime, UNIX_EPOCH};
pub fn now() -> u128 {
let duration = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap();
println!("Old Milis: {}", duration.as_secs() as u128 * 1000 + duration.subsec_millis() as u128);
println!("Milis: {}", duration.as_millis());
duration.as_millis()
}
pub fn u32_bytes(u: &u32) -> [u8; 4] {
[
(u >> 8 * 0x0) as u8,
(u >> 8 * 0x1) as u8,
(u >> 8 * 0x2) as u8,
(u >> 8 * 0x3) as u8,
]
}
pub fn u64_bytes(u: &u64) -> [u8; 8] {
[
(u >> 8 * 0x0) as u8,
(u >> 8 * 0x1) as u8,
(u >> 8 * 0x2) as u8,
(u >> 8 * 0x3) as u8,
(u >> 8 * 0x4) as u8,
(u >> 8 * 0x5) as u8,
(u >> 8 * 0x6) as u8,
(u >> 8 * 0x7) as u8,
]
}
pub fn u128_bytes(u: &u128) -> [u8; 16] {
[
(u >> 8 * 0x0) as u8,
(u >> 8 * 0x1) as u8,
(u >> 8 * 0x2) as u8,
(u >> 8 * 0x3) as u8,
(u >> 8 * 0x4) as u8,
(u >> 8 * 0x5) as u8,
(u >> 8 * 0x6) as u8,
(u >> 8 * 0x7) as u8,
(u >> 8 * 0x8) as u8,
(u >> 8 * 0x9) as u8,
(u >> 8 * 0xa) as u8,
(u >> 8 * 0xb) as u8,
(u >> 8 * 0xc) as u8,
(u >> 8 * 0xd) as u8,
(u >> 8 * 0xe) as u8,
(u >> 8 * 0xf) as u8,
]
}
pub fn difficulty_bytes_as_u128(v: &Vec<u8>) -> u128 {
((v[31] as u128) << 0xf * 8) |
((v[30] as u128) << 0xe * 8) |
((v[29] as u128) << 0xd * 8) |
((v[28] as u128) << 0xc * 8) |
((v[27] as u128) << 0xb * 8) |
((v[26] as u128) << 0xa * 8) |
((v[25] as u128) << 0x9 * 8) |
((v[24] as u128) << 0x8 * 8) |
((v[23] as u128) << 0x7 * 8) |
((v[22] as u128) << 0x6 * 8) |
((v[21] as u128) << 0x5 * 8) |
((v[20] as u128) << 0x4 * 8) |
((v[19] as u128) << 0x3 * 8) |
((v[18] as u128) << 0x2 * 8) |
((v[17] as u128) << 0x1 * 8) |
((v[16] as u128) << 0x0 * 8)
}
mod block;
pub use crate::block::Block;
mod hashable;
pub use crate::hashable::Hashable;
mod blockchain;
pub use crate::blockchain::Blockchain;
pub mod transaction;
pub use crate::transaction::Transaction;
| 26.712644 | 100 | 0.433735 |
acd45a5521b0a3b3cfc5e97147c0ea04455d6c60
| 33,541 |
// Copyright 2020, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::{
collections::HashMap,
fmt,
sync::Arc,
time::{Duration, Instant},
};
use log::*;
use nom::lib::std::collections::hash_map::Entry;
use tari_shutdown::ShutdownSignal;
use tokio::{
sync::{mpsc, oneshot},
task::JoinHandle,
time,
time::MissedTickBehavior,
};
use tracing::{span, Instrument, Level};
use super::{
config::ConnectivityConfig,
connection_pool::{ConnectionPool, ConnectionStatus},
connection_stats::PeerConnectionStats,
error::ConnectivityError,
requester::{ConnectivityEvent, ConnectivityRequest},
selection::ConnectivitySelection,
ConnectivityEventTx,
};
use crate::{
connection_manager::{
ConnectionDirection,
ConnectionManagerError,
ConnectionManagerEvent,
ConnectionManagerRequester,
},
peer_manager::NodeId,
runtime::task,
utils::datetime::format_duration,
NodeIdentity,
PeerConnection,
PeerManager,
};
const LOG_TARGET: &str = "comms::connectivity::manager";
/// # Connectivity Manager
///
/// The ConnectivityManager actor is responsible for tracking the state of all peer
/// connections in the system and maintaining a _pool_ of peer connections.
///
/// It emits [ConnectivityEvent](crate::connectivity::ConnectivityEvent)s that can keep client components
/// in the loop with the state of the node's connectivity.
pub struct ConnectivityManager {
pub config: ConnectivityConfig,
pub request_rx: mpsc::Receiver<ConnectivityRequest>,
pub event_tx: ConnectivityEventTx,
pub connection_manager: ConnectionManagerRequester,
pub peer_manager: Arc<PeerManager>,
pub node_identity: Arc<NodeIdentity>,
pub shutdown_signal: ShutdownSignal,
}
impl ConnectivityManager {
pub fn spawn(self) -> JoinHandle<()> {
ConnectivityManagerActor {
config: self.config,
status: ConnectivityStatus::Initializing,
request_rx: self.request_rx,
connection_manager: self.connection_manager,
peer_manager: self.peer_manager.clone(),
event_tx: self.event_tx,
connection_stats: HashMap::new(),
node_identity: self.node_identity,
pool: ConnectionPool::new(),
shutdown_signal: self.shutdown_signal,
#[cfg(feature = "metrics")]
uptime: Some(Instant::now()),
allow_list: vec![],
}
.spawn()
}
}
/// Node connectivity status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectivityStatus {
/// Initial connectivity status before the Connectivity actor has initialized.
Initializing,
/// Connectivity is online.
Online(usize),
/// Connectivity is less than the required minimum, but some connections are still active.
Degraded(usize),
/// There are no active connections.
Offline,
}
impl ConnectivityStatus {
is_fn!(is_initializing, ConnectivityStatus::Initializing);
is_fn!(is_online, ConnectivityStatus::Online(_));
is_fn!(is_offline, ConnectivityStatus::Offline);
is_fn!(is_degraded, ConnectivityStatus::Degraded(_));
pub fn num_connected_nodes(&self) -> usize {
use ConnectivityStatus::{Degraded, Initializing, Offline, Online};
match self {
Initializing | Offline => 0,
Online(n) | Degraded(n) => *n,
}
}
}
impl Default for ConnectivityStatus {
fn default() -> Self {
ConnectivityStatus::Initializing
}
}
impl fmt::Display for ConnectivityStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
struct ConnectivityManagerActor {
config: ConnectivityConfig,
status: ConnectivityStatus,
request_rx: mpsc::Receiver<ConnectivityRequest>,
connection_manager: ConnectionManagerRequester,
node_identity: Arc<NodeIdentity>,
peer_manager: Arc<PeerManager>,
event_tx: ConnectivityEventTx,
connection_stats: HashMap<NodeId, PeerConnectionStats>,
pool: ConnectionPool,
shutdown_signal: ShutdownSignal,
#[cfg(feature = "metrics")]
uptime: Option<Instant>,
allow_list: Vec<NodeId>,
}
impl ConnectivityManagerActor {
pub fn spawn(self) -> JoinHandle<()> {
let mut mdc = vec![];
log_mdc::iter(|k, v| mdc.push((k.to_owned(), v.to_owned())));
task::spawn(async {
log_mdc::extend(mdc);
Self::run(self).await
})
}
#[tracing::instrument(level = "trace", name = "connectivity_manager_actor::run", skip(self))]
pub async fn run(mut self) {
debug!(target: LOG_TARGET, "ConnectivityManager started");
let mut connection_manager_events = self.connection_manager.get_event_subscription();
let interval = self.config.connection_pool_refresh_interval;
let mut ticker = time::interval_at(
Instant::now()
.checked_add(interval)
.expect("connection_pool_refresh_interval cause overflow")
.into(),
interval,
);
ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
self.publish_event(ConnectivityEvent::ConnectivityStateInitialized);
loop {
tokio::select! {
Some(req) = self.request_rx.recv() => {
self.handle_request(req).await;
},
event = connection_manager_events.recv() => {
if let Ok(event) = event {
if let Err(err) = self.handle_connection_manager_event(&event).await {
error!(target:LOG_TARGET, "Error handling connection manager event: {:?}", err);
}
}
},
_ = ticker.tick() => {
self.cleanup_connection_stats();
if let Err(err) = self.refresh_connection_pool().await {
error!(target: LOG_TARGET, "Error when refreshing connection pools: {:?}", err);
}
},
_ = self.shutdown_signal.wait() => {
info!(target: LOG_TARGET, "ConnectivityManager is shutting down because it received the shutdown signal");
self.disconnect_all().await;
break;
}
}
}
}
async fn handle_request(&mut self, req: ConnectivityRequest) {
#[allow(clippy::enum_glob_use)]
use ConnectivityRequest::*;
trace!(target: LOG_TARGET, "Request: {:?}", req);
match req {
WaitStarted(reply) => {
let _ = reply.send(());
},
GetConnectivityStatus(reply) => {
let _ = reply.send(self.status);
},
DialPeer { node_id, reply_tx } => {
let tracing_id = tracing::Span::current().id();
let span = span!(Level::TRACE, "handle_dial_peer");
span.follows_from(tracing_id);
self.handle_dial_peer(node_id, reply_tx).instrument(span).await;
},
SelectConnections(selection, reply) => {
let _result = reply.send(self.select_connections(selection).await);
},
GetConnection(node_id, reply) => {
let _result = reply.send(
self.pool
.get(&node_id)
.filter(|c| c.status() == ConnectionStatus::Connected)
.and_then(|c| c.connection())
.filter(|conn| conn.is_connected())
.cloned(),
);
},
GetAllConnectionStates(reply) => {
let states = self.pool.all().into_iter().cloned().collect();
let _result = reply.send(states);
},
BanPeer(node_id, duration, reason) => {
if self.allow_list.contains(&node_id) {
info!(
target: LOG_TARGET,
"Peer is excluded from being banned as it was found in the AllowList, NodeId: {:?}", node_id
);
} else if let Err(err) = self.ban_peer(&node_id, duration, reason).await {
error!(target: LOG_TARGET, "Error when banning peer: {:?}", err);
} else {
}
},
AddPeerToAllowList(node_id) => {
if !self.allow_list.contains(&node_id) {
self.allow_list.push(node_id)
}
},
RemovePeerFromAllowList(node_id) => {
if let Some(index) = self.allow_list.iter().position(|x| *x == node_id) {
self.allow_list.remove(index);
}
},
GetActiveConnections(reply) => {
let _result = reply.send(
self.pool
.filter_connection_states(|s| s.is_connected())
.into_iter()
.cloned()
.collect(),
);
},
}
}
async fn handle_dial_peer(
&mut self,
node_id: NodeId,
reply_tx: Option<oneshot::Sender<Result<PeerConnection, ConnectionManagerError>>>,
) {
match self.peer_manager.is_peer_banned(&node_id).await {
Ok(true) => {
if let Some(reply) = reply_tx {
let _result = reply.send(Err(ConnectionManagerError::PeerBanned));
}
return;
},
Ok(false) => {},
Err(err) => {
if let Some(reply) = reply_tx {
let _result = reply.send(Err(err.into()));
}
return;
},
}
match self.pool.get(&node_id) {
Some(state) if state.is_connected() => {
debug!(
target: LOG_TARGET,
"Found existing connection for peer `{}`",
node_id.short_str()
);
if let Some(reply_tx) = reply_tx {
let _result = reply_tx.send(Ok(state.connection().cloned().expect("Already checked")));
}
},
_ => {
debug!(
target: LOG_TARGET,
"No existing connection found for peer `{}`. Dialing...",
node_id.short_str()
);
if let Err(err) = self.connection_manager.send_dial_peer(node_id, reply_tx).await {
error!(
target: LOG_TARGET,
"Failed to send dial request to connection manager: {:?}", err
);
}
},
}
}
async fn disconnect_all(&mut self) {
let mut node_ids = Vec::with_capacity(self.pool.count_connected());
for mut state in self.pool.filter_drain(|_| true) {
if let Some(conn) = state.connection_mut() {
if !conn.is_connected() {
continue;
}
match conn.disconnect_silent().await {
Ok(_) => {
node_ids.push(conn.peer_node_id().clone());
},
Err(err) => {
debug!(
target: LOG_TARGET,
"In disconnect_all: Error when disconnecting peer '{}' because '{:?}'",
conn.peer_node_id().short_str(),
err
);
},
}
}
}
for node_id in node_ids {
self.publish_event(ConnectivityEvent::PeerDisconnected(node_id));
}
}
async fn refresh_connection_pool(&mut self) -> Result<(), ConnectivityError> {
debug!(
target: LOG_TARGET,
"Performing connection pool cleanup/refresh. (#Peers = {}, #Connected={}, #Failed={}, #Disconnected={}, \
#Clients={})",
self.pool.count_entries(),
self.pool.count_connected_nodes(),
self.pool.count_failed(),
self.pool.count_disconnected(),
self.pool.count_connected_clients()
);
self.clean_connection_pool();
if self.config.is_connection_reaping_enabled {
self.reap_inactive_connections().await;
}
self.update_connectivity_status();
self.update_connectivity_metrics();
Ok(())
}
async fn reap_inactive_connections(&mut self) {
let connections = self
.pool
.get_inactive_connections_mut(self.config.reaper_min_inactive_age);
for conn in connections {
if !conn.is_connected() {
continue;
}
debug!(
target: LOG_TARGET,
"Disconnecting '{}' because connection was inactive",
conn.peer_node_id().short_str()
);
if let Err(err) = conn.disconnect().await {
// Already disconnected
debug!(
target: LOG_TARGET,
"Peer '{}' already disconnected. Error: {:?}",
conn.peer_node_id().short_str(),
err
);
}
}
}
fn clean_connection_pool(&mut self) {
let cleared_states = self.pool.filter_drain(|state| {
state.status() == ConnectionStatus::Failed || state.status() == ConnectionStatus::Disconnected
});
if !cleared_states.is_empty() {
debug!(
target: LOG_TARGET,
"Cleared connection states: {}",
cleared_states
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",")
)
}
}
async fn select_connections(
&self,
selection: ConnectivitySelection,
) -> Result<Vec<PeerConnection>, ConnectivityError> {
trace!(target: LOG_TARGET, "Selection query: {:?}", selection);
debug!(
target: LOG_TARGET,
"Selecting from {} connected node peers",
self.pool.count_connected_nodes()
);
let conns = selection.select(&self.pool);
debug!(target: LOG_TARGET, "Selected {} connections(s)", conns.len());
Ok(conns.into_iter().cloned().collect())
}
fn get_connection_stat_mut(&mut self, node_id: NodeId) -> &mut PeerConnectionStats {
match self.connection_stats.entry(node_id) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(PeerConnectionStats::new()),
}
}
fn mark_peer_succeeded(&mut self, node_id: NodeId) {
let entry = self.get_connection_stat_mut(node_id);
entry.set_connection_success();
}
fn mark_peer_failed(&mut self, node_id: NodeId) -> usize {
let entry = self.get_connection_stat_mut(node_id);
entry.set_connection_failed();
entry.failed_attempts()
}
async fn handle_peer_connection_failure(&mut self, node_id: &NodeId) -> Result<(), ConnectivityError> {
if self.status.is_offline() {
debug!(
target: LOG_TARGET,
"Node is offline. Ignoring connection failure event for peer '{}'.", node_id
);
return Ok(());
}
let num_failed = self.mark_peer_failed(node_id.clone());
if num_failed >= self.config.max_failures_mark_offline {
debug!(
target: LOG_TARGET,
"Marking peer '{}' as offline because this node failed to connect to them {} times",
node_id.short_str(),
num_failed
);
if !self.peer_manager.set_offline(node_id, true).await? {
// Only publish the `PeerOffline` event if we change from online to offline
self.publish_event(ConnectivityEvent::PeerOffline(node_id.clone()));
}
if let Some(peer) = self.peer_manager.find_by_node_id(node_id).await? {
if !peer.is_banned() &&
peer.last_seen_since()
// Haven't seen them in expire_peer_last_seen_duration
.map(|t| t > self.config.expire_peer_last_seen_duration)
// Or don't delete if never seen
.unwrap_or(false)
{
debug!(
target: LOG_TARGET,
"Peer `{}` was marked as offline after {} attempts (last seen: {}). Removing peer from peer \
list",
node_id,
num_failed,
peer.last_seen_since()
.map(|d| format!("{}s ago", d.as_secs()))
.unwrap_or_else(|| "Never".to_string()),
);
self.peer_manager.delete_peer(node_id).await?;
}
}
}
Ok(())
}
async fn handle_connection_manager_event(
&mut self,
event: &ConnectionManagerEvent,
) -> Result<(), ConnectivityError> {
use ConnectionManagerEvent::{PeerConnectFailed, PeerConnected, PeerDisconnected};
debug!(target: LOG_TARGET, "Received event: {}", event);
match event {
PeerConnected(new_conn) => {
match self.handle_new_connection_tie_break(new_conn).await {
TieBreak::KeepExisting => {
// Ignore event, we discarded the new connection and keeping the current one
return Ok(());
},
TieBreak::UseNew | TieBreak::None => {},
}
},
PeerDisconnected(id, node_id) => {
if let Some(conn) = self.pool.get_connection(node_id) {
if conn.id() != *id {
debug!(
target: LOG_TARGET,
"Ignoring peer disconnected event for stale peer connection (id: {}) for peer '{}'",
id,
node_id
);
return Ok(());
}
}
},
_ => {},
}
let (node_id, mut new_status, connection) = match event {
PeerDisconnected(_, node_id) => (&*node_id, ConnectionStatus::Disconnected, None),
PeerConnected(conn) => (conn.peer_node_id(), ConnectionStatus::Connected, Some(conn.clone())),
PeerConnectFailed(node_id, ConnectionManagerError::DialCancelled) => {
debug!(
target: LOG_TARGET,
"Dial was cancelled before connection completed to peer '{}'", node_id
);
(&*node_id, ConnectionStatus::Failed, None)
},
PeerConnectFailed(node_id, err) => {
debug!(
target: LOG_TARGET,
"Connection to peer '{}' failed because '{:?}'", node_id, err
);
self.handle_peer_connection_failure(node_id).await?;
(&*node_id, ConnectionStatus::Failed, None)
},
_ => return Ok(()),
};
let old_status = self.pool.set_status(node_id, new_status);
if let Some(conn) = connection {
new_status = self.pool.insert_connection(conn);
}
if old_status != new_status {
debug!(
target: LOG_TARGET,
"Peer connection for node '{}' transitioned from {} to {}", node_id, old_status, new_status
);
}
let node_id = node_id.clone();
use ConnectionStatus::{Connected, Disconnected, Failed};
match (old_status, new_status) {
(_, Connected) => {
self.mark_peer_succeeded(node_id.clone());
match self.pool.get_connection(&node_id).cloned() {
Some(conn) => {
self.publish_event(ConnectivityEvent::PeerConnected(conn));
},
None => unreachable!(
"Connection transitioning to CONNECTED state must always have a connection set i.e. \
ConnectionPool::get_connection is Some"
),
}
},
(Connected, Disconnected) => {
self.publish_event(ConnectivityEvent::PeerDisconnected(node_id));
},
// Was not connected so don't broadcast event
(_, Disconnected) => {},
(_, Failed) => {
self.publish_event(ConnectivityEvent::PeerConnectFailed(node_id));
},
_ => {
error!(
target: LOG_TARGET,
"Unexpected connection status transition ({} to {}) for peer '{}'", old_status, new_status, node_id
);
},
}
self.update_connectivity_status();
self.update_connectivity_metrics();
Ok(())
}
async fn handle_new_connection_tie_break(&mut self, new_conn: &PeerConnection) -> TieBreak {
match self.pool.get_connection(new_conn.peer_node_id()).cloned() {
Some(existing_conn) if !existing_conn.is_connected() => {
debug!(
target: LOG_TARGET,
"Tie break: Existing connection (id: {}, peer: {}, direction: {}) was not connected, resolving \
tie break by using the new connection. (New: id: {}, peer: {}, direction: {})",
existing_conn.id(),
existing_conn.peer_node_id(),
existing_conn.direction(),
new_conn.id(),
new_conn.peer_node_id(),
new_conn.direction(),
);
self.pool.remove(existing_conn.peer_node_id());
TieBreak::UseNew
},
Some(mut existing_conn) => {
if self.tie_break_existing_connection(&existing_conn, new_conn) {
debug!(
target: LOG_TARGET,
"Tie break: Keep new connection (id: {}, peer: {}, direction: {}). Disconnect existing \
connection (id: {}, peer: {}, direction: {})",
new_conn.id(),
new_conn.peer_node_id(),
new_conn.direction(),
existing_conn.id(),
existing_conn.peer_node_id(),
existing_conn.direction(),
);
let _result = existing_conn.disconnect_silent().await;
self.pool.remove(existing_conn.peer_node_id());
TieBreak::UseNew
} else {
debug!(
target: LOG_TARGET,
"Tie break: Keeping existing connection (id: {}, peer: {}, direction: {}). Disconnecting new \
connection (id: {}, peer: {}, direction: {})",
new_conn.id(),
new_conn.peer_node_id(),
new_conn.direction(),
existing_conn.id(),
existing_conn.peer_node_id(),
existing_conn.direction(),
);
let _result = new_conn.clone().disconnect_silent().await;
TieBreak::KeepExisting
}
},
None => TieBreak::None,
}
}
/// Two connections to the same peer have been created. This function deterministically determines which peer
/// connection to close. It does this by comparing our NodeId to that of the peer. This rule enables both sides to
/// agree which connection to disconnect
///
/// Returns true if the existing connection should close, otherwise false if the new connection should be closed.
fn tie_break_existing_connection(&self, existing_conn: &PeerConnection, new_conn: &PeerConnection) -> bool {
debug_assert_eq!(existing_conn.peer_node_id(), new_conn.peer_node_id());
let peer_node_id = existing_conn.peer_node_id();
let our_node_id = self.node_identity.node_id();
debug!(
target: LOG_TARGET,
"Tie-break: (Existing = {}, New = {})",
existing_conn.direction(),
new_conn.direction()
);
use ConnectionDirection::{Inbound, Outbound};
match (existing_conn.direction(), new_conn.direction()) {
// They connected to us twice for some reason. Drop the older connection
(Inbound, Inbound) => true,
// They connected to us at the same time we connected to them
(Inbound, Outbound) => peer_node_id > our_node_id,
// We connected to them at the same time as they connected to us
(Outbound, Inbound) => our_node_id > peer_node_id,
// We connected to them twice for some reason. Drop the older connection.
(Outbound, Outbound) => true,
}
}
fn update_connectivity_status(&mut self) {
// The contract we are making with online/degraded status transitions is as follows:
// - If min_connectivity peers are connected we MUST transition to ONLINE
// - Clients SHOULD tolerate entering a DEGRADED/OFFLINE status
// - If a number of peers disconnect or the local system's network goes down, the status MAY transition to
// DEGRADED
let min_peers = self.config.min_connectivity;
let num_connected_nodes = self.pool.count_connected_nodes();
let num_connected_clients = self.pool.count_connected_clients();
debug!(
target: LOG_TARGET,
"#min_peers = {}, #nodes = {}, #clients = {}", min_peers, num_connected_nodes, num_connected_clients
);
match num_connected_nodes {
n if n >= min_peers => {
self.transition(ConnectivityStatus::Online(n), min_peers);
},
n if n > 0 && n < min_peers => {
self.transition(ConnectivityStatus::Degraded(n), min_peers);
},
n if n == 0 => {
if num_connected_clients == 0 {
self.transition(ConnectivityStatus::Offline, min_peers);
}
},
_ => unreachable!("num_connected is unsigned and only negative pattern covered on this branch"),
}
}
#[cfg(not(feature = "metrics"))]
fn update_connectivity_metrics(&mut self) {}
#[cfg(feature = "metrics")]
fn update_connectivity_metrics(&mut self) {
use std::convert::TryFrom;
use super::metrics;
let total = self.pool.count_connected() as i64;
let num_inbound = self.pool.count_filtered(|state| match state.connection() {
Some(conn) => conn.is_connected() && conn.direction().is_inbound(),
None => false,
}) as i64;
metrics::connections(ConnectionDirection::Inbound).set(num_inbound);
metrics::connections(ConnectionDirection::Outbound).set(total - num_inbound);
let uptime = self
.uptime
.map(|ts| i64::try_from(ts.elapsed().as_secs()).unwrap_or(i64::MAX))
.unwrap_or(0);
metrics::uptime().set(uptime);
}
fn transition(&mut self, next_status: ConnectivityStatus, required_num_peers: usize) {
use ConnectivityStatus::{Degraded, Offline, Online};
if self.status != next_status {
debug!(
target: LOG_TARGET,
"Connectivity status transitioning from {} to {}", self.status, next_status
);
}
match (self.status, next_status) {
(Online(_), Online(_)) => {},
(_, Online(n)) => {
info!(
target: LOG_TARGET,
"Connectivity is ONLINE ({}/{} connections)", n, required_num_peers
);
#[cfg(feature = "metrics")]
if self.uptime.is_none() {
self.uptime = Some(Instant::now());
}
self.publish_event(ConnectivityEvent::ConnectivityStateOnline(n));
},
(Degraded(m), Degraded(n)) => {
info!(
target: LOG_TARGET,
"Connectivity is DEGRADED ({}/{} connections)", n, required_num_peers
);
if m != n {
self.publish_event(ConnectivityEvent::ConnectivityStateDegraded(n));
}
},
(_, Degraded(n)) => {
info!(
target: LOG_TARGET,
"Connectivity is DEGRADED ({}/{} connections)", n, required_num_peers
);
self.publish_event(ConnectivityEvent::ConnectivityStateDegraded(n));
},
(Offline, Offline) => {},
(_, Offline) => {
warn!(
target: LOG_TARGET,
"Connectivity is OFFLINE (0/{} connections)", required_num_peers
);
#[cfg(feature = "metrics")]
{
self.uptime = None;
}
self.publish_event(ConnectivityEvent::ConnectivityStateOffline);
},
(status, next_status) => unreachable!("Unexpected status transition ({} to {})", status, next_status),
}
self.status = next_status;
}
fn publish_event(&mut self, event: ConnectivityEvent) {
// A send operation can only fail if there are no subscribers, so it is safe to ignore the error
let _result = self.event_tx.send(event);
}
async fn ban_peer(
&mut self,
node_id: &NodeId,
duration: Duration,
reason: String,
) -> Result<(), ConnectivityError> {
info!(
target: LOG_TARGET,
"Banning peer {} for {} because: {}",
node_id,
format_duration(duration),
reason
);
self.peer_manager.ban_peer_by_node_id(node_id, duration, reason).await?;
#[cfg(feature = "metrics")]
super::metrics::banned_peers_counter(node_id).inc();
self.publish_event(ConnectivityEvent::PeerBanned(node_id.clone()));
if let Some(conn) = self.pool.get_connection_mut(node_id) {
conn.disconnect().await?;
let status = self.pool.get_connection_status(node_id);
debug!(
target: LOG_TARGET,
"Disconnected banned peer {}. The peer connection status is {}", node_id, status
);
}
Ok(())
}
fn cleanup_connection_stats(&mut self) {
let mut to_remove = Vec::new();
for node_id in self.connection_stats.keys() {
let status = self.pool.get_connection_status(node_id);
if matches!(
status,
ConnectionStatus::NotConnected | ConnectionStatus::Failed | ConnectionStatus::Disconnected
) {
to_remove.push(node_id.clone());
}
}
for node_id in to_remove {
self.connection_stats.remove(&node_id);
}
}
}
enum TieBreak {
None,
UseNew,
KeepExisting,
}
| 38.597238 | 126 | 0.53779 |
72746afced7d32562de91d58e2b8fef8f94e8e0f
| 904 |
/**
* iter: just borrow ...
* into_iter: move it!
*/
fn iter_borrow() {
let names = vec!("Bob", "Frank", "Ferris");
for name in names.into_iter() {
match name {
"Ferris" => println!("There is a rustacean among us!"),
_ => println!("hello {}", name),
}
}
}
fn iter_move() {
let names = vec!("Bob", "Frank", "Ferris");
for name in names.into_iter() {
match name {
"Ferris" => println!("There is a rustacean among us!"),
_ => println!("hello {}", name),
}
}
}
fn iter_mutable() {
let mut names = vec!("Bob", "Frank", "Ferris");
for name in names.iter_mut(){
match name {
&mut "Ferris" => println!("There is a rustacean among us!"),
_ => println!("Hello {}", name),
}
}
}
fn main() {
iter_borrow();
iter_move();
iter_mutable();
}
| 20.545455 | 72 | 0.490044 |
e24b0fb77deca1e74484a1828889024d09fe0e6f
| 2,056 |
use std::{convert::TryFrom, mem, ptr};
use crate::{crypto::buffer::SecretBytes, kms::Encrypted};
#[no_mangle]
pub extern "C" fn askar_buffer_free(buffer: SecretBuffer) {
ffi_support::abort_on_panic::with_abort_on_panic(|| {
drop(buffer.destroy_into_secret());
})
}
// Structure consistent with ffi_support ByteBuffer, but zeroized on drop
#[derive(Debug)]
#[repr(C)]
pub struct SecretBuffer {
// must be >= 0, signed int was chosen for compatibility
len: i64,
// nullable
data: *mut u8,
}
impl Default for SecretBuffer {
fn default() -> Self {
Self {
len: 0,
data: ptr::null_mut(),
}
}
}
impl SecretBuffer {
pub fn from_secret(buffer: impl Into<SecretBytes>) -> Self {
let mut buf = buffer.into();
buf.shrink_to_fit();
debug_assert_eq!(buf.len(), buf.capacity());
let mut buf = mem::ManuallyDrop::new(buf.into_vec());
let len = i64::try_from(buf.len()).expect("secret length exceeds i64::MAX");
let data = buf.as_mut_ptr();
Self { len, data }
}
pub fn destroy_into_secret(self) -> SecretBytes {
if self.data.is_null() {
SecretBytes::default()
} else {
if self.len < 0 {
panic!("found negative length for secret buffer");
}
let len = self.len as usize;
SecretBytes::from(unsafe { Vec::from_raw_parts(self.data, len, len) })
}
}
}
// A combined ciphertext and tag value
#[derive(Debug)]
#[repr(C)]
pub struct EncryptedBuffer {
buffer: SecretBuffer,
tag_pos: i64,
nonce_pos: i64,
}
impl EncryptedBuffer {
pub fn from_encrypted(enc: Encrypted) -> Self {
let tag_pos = i64::try_from(enc.tag_pos).expect("ciphertext length exceeds i64::MAX");
let nonce_pos = i64::try_from(enc.nonce_pos).expect("ciphertext length exceeds i64::MAX");
Self {
buffer: SecretBuffer::from_secret(enc.buffer),
tag_pos,
nonce_pos,
}
}
}
| 27.413333 | 98 | 0.598249 |
035da005790d6242980c77d2be579eaf7c11b940
| 2,746 |
#![allow(clippy::module_inception)]
#![allow(clippy::upper_case_acronyms)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::wrong_self_convention)]
#![allow(clippy::should_implement_trait)]
#![allow(clippy::blacklisted_name)]
#![allow(clippy::vec_init_then_push)]
#![allow(rustdoc::bare_urls)]
#![warn(missing_docs)]
//! <fullname>Batch</fullname>
//! <p>Using Batch, you can run batch computing workloads on the Cloud. Batch computing is a common means for
//! developers, scientists, and engineers to access large amounts of compute resources. Batch uses the advantages of
//! this computing workload to remove the undifferentiated heavy lifting of configuring and managing required
//! infrastructure. At the same time, it also adopts a familiar batch computing software approach. Given these
//! advantages, Batch can help you to efficiently provision resources in response to jobs submitted, thus effectively
//! helping you to eliminate capacity constraints, reduce compute costs, and deliver your results more quickly.</p>
//! <p>As a fully managed service, Batch can run batch computing workloads of any scale. Batch automatically
//! provisions compute resources and optimizes workload distribution based on the quantity and scale of your specific
//! workloads. With Batch, there's no need to install or manage batch computing software. This means that you can focus
//! your time and energy on analyzing results and solving your specific problems. </p>
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub use error_meta::Error;
pub use config::Config;
mod aws_endpoint;
/// Client and fluent builders for calling the service.
#[cfg(feature = "client")]
pub mod client;
/// Configuration for the service.
pub mod config;
/// Errors that can occur when calling the service.
pub mod error;
mod error_meta;
/// Input structures for operations.
pub mod input;
mod json_deser;
mod json_errors;
mod json_ser;
/// Data structures used by operation inputs/outputs.
pub mod model;
mod no_credentials;
/// All operations that this crate can perform.
pub mod operation;
mod operation_deser;
mod operation_ser;
/// Output structures for operations.
pub mod output;
/// Crate version number.
pub static PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
pub use aws_smithy_http::byte_stream::ByteStream;
pub use aws_smithy_http::result::SdkError;
pub use aws_smithy_types::Blob;
static API_METADATA: aws_http::user_agent::ApiMetadata =
aws_http::user_agent::ApiMetadata::new("batch", PKG_VERSION);
pub use aws_smithy_http::endpoint::Endpoint;
pub use aws_smithy_types::retry::RetryConfig;
pub use aws_types::region::Region;
pub use aws_types::Credentials;
#[cfg(feature = "client")]
pub use client::Client;
| 43.587302 | 119 | 0.777495 |
230e04c7878a465115de50ca855f3cb98a4a582f
| 44,574 |
// Copyright Materialize, Inc. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
use std::collections::HashSet;
use std::fmt;
use std::mem;
use serde::{Deserialize, Serialize};
use ore::collections::CollectionExt;
use repr::adt::array::InvalidArrayError;
use repr::adt::datetime::DateTimeUnits;
use repr::adt::regex::Regex;
use repr::strconv::{ParseError, ParseHexError};
use repr::{ColumnType, Datum, RelationType, Row, RowArena, ScalarType};
use self::func::{BinaryFunc, NullaryFunc, UnaryFunc, VariadicFunc};
use crate::explain;
use crate::scalar::func::parse_timezone;
pub mod func;
pub mod like_pattern;
#[derive(Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum MirScalarExpr {
/// A column of the input row
Column(usize),
/// A literal value.
/// (Stored as a row, because we can't own a Datum)
Literal(Result<Row, EvalError>, ColumnType),
/// A function call that takes no arguments.
CallNullary(NullaryFunc),
/// A function call that takes one expression as an argument.
CallUnary {
func: UnaryFunc,
expr: Box<MirScalarExpr>,
},
/// A function call that takes two expressions as arguments.
CallBinary {
func: BinaryFunc,
expr1: Box<MirScalarExpr>,
expr2: Box<MirScalarExpr>,
},
/// A function call that takes an arbitrary number of arguments.
CallVariadic {
func: VariadicFunc,
exprs: Vec<MirScalarExpr>,
},
/// Conditionally evaluated expressions.
///
/// It is important that `then` and `els` only be evaluated if
/// `cond` is true or not, respectively. This is the only way
/// users can guard execution (other logical operator do not
/// short-circuit) and we need to preserve that.
If {
cond: Box<MirScalarExpr>,
then: Box<MirScalarExpr>,
els: Box<MirScalarExpr>,
},
}
impl MirScalarExpr {
pub fn columns(is: &[usize]) -> Vec<MirScalarExpr> {
is.iter().map(|i| MirScalarExpr::Column(*i)).collect()
}
pub fn column(column: usize) -> Self {
MirScalarExpr::Column(column)
}
pub fn literal(res: Result<Datum, EvalError>, typ: ScalarType) -> Self {
let typ = typ.nullable(matches!(res, Ok(Datum::Null)));
let row = res.map(|datum| Row::pack_slice(&[datum]));
MirScalarExpr::Literal(row, typ)
}
pub fn literal_ok(datum: Datum, typ: ScalarType) -> Self {
MirScalarExpr::literal(Ok(datum), typ)
}
pub fn literal_null(typ: ScalarType) -> Self {
MirScalarExpr::literal_ok(Datum::Null, typ)
}
pub fn call_unary(self, func: UnaryFunc) -> Self {
MirScalarExpr::CallUnary {
func,
expr: Box::new(self),
}
}
pub fn call_binary(self, other: Self, func: BinaryFunc) -> Self {
MirScalarExpr::CallBinary {
func,
expr1: Box::new(self),
expr2: Box::new(other),
}
}
pub fn if_then_else(self, t: Self, f: Self) -> Self {
MirScalarExpr::If {
cond: Box::new(self),
then: Box::new(t),
els: Box::new(f),
}
}
pub fn visit1<'a, F>(&'a self, mut f: F)
where
F: FnMut(&'a Self),
{
match self {
MirScalarExpr::Column(_) => (),
MirScalarExpr::Literal(_, _) => (),
MirScalarExpr::CallNullary(_) => (),
MirScalarExpr::CallUnary { expr, .. } => {
f(expr);
}
MirScalarExpr::CallBinary { expr1, expr2, .. } => {
f(expr1);
f(expr2);
}
MirScalarExpr::CallVariadic { exprs, .. } => {
for expr in exprs {
f(expr);
}
}
MirScalarExpr::If { cond, then, els } => {
f(cond);
f(then);
f(els);
}
}
}
pub fn visit<'a, F>(&'a self, f: &mut F)
where
F: FnMut(&'a Self),
{
self.visit1(|e| e.visit(f));
f(self);
}
pub fn visit1_mut<'a, F>(&'a mut self, mut f: F)
where
F: FnMut(&'a mut Self),
{
match self {
MirScalarExpr::Column(_) => (),
MirScalarExpr::Literal(_, _) => (),
MirScalarExpr::CallNullary(_) => (),
MirScalarExpr::CallUnary { expr, .. } => {
f(expr);
}
MirScalarExpr::CallBinary { expr1, expr2, .. } => {
f(expr1);
f(expr2);
}
MirScalarExpr::CallVariadic { exprs, .. } => {
for expr in exprs {
f(expr);
}
}
MirScalarExpr::If { cond, then, els } => {
f(cond);
f(then);
f(els);
}
}
}
pub fn visit_mut<F>(&mut self, f: &mut F)
where
F: FnMut(&mut Self),
{
self.visit1_mut(|e| e.visit_mut(f));
f(self);
}
/// Rewrites column indices with their value in `permutation`.
///
/// This method is applicable even when `permutation` is not a
/// strict permutation, and it only needs to have entries for
/// each column referenced in `self`.
pub fn permute(&mut self, permutation: &[usize]) {
self.visit_mut(&mut |e| {
if let MirScalarExpr::Column(old_i) = e {
*old_i = permutation[*old_i];
}
});
}
/// Rewrites column indices with their value in `permutation`.
///
/// This method is applicable even when `permutation` is not a
/// strict permutation, and it only needs to have entries for
/// each column referenced in `self`.
pub fn permute_map(&mut self, permutation: &std::collections::HashMap<usize, usize>) {
self.visit_mut(&mut |e| {
if let MirScalarExpr::Column(old_i) = e {
*old_i = permutation[old_i];
}
});
}
pub fn support(&self) -> HashSet<usize> {
let mut support = HashSet::new();
self.visit(&mut |e| {
if let MirScalarExpr::Column(i) = e {
support.insert(*i);
}
});
support
}
pub fn take(&mut self) -> Self {
mem::replace(self, MirScalarExpr::literal_null(ScalarType::String))
}
pub fn as_literal(&self) -> Option<Result<Datum, &EvalError>> {
if let MirScalarExpr::Literal(lit, _column_type) = self {
Some(lit.as_ref().map(|row| row.unpack_first()))
} else {
None
}
}
pub fn as_literal_str(&self) -> Option<&str> {
match self.as_literal() {
Some(Ok(Datum::String(s))) => Some(s),
_ => None,
}
}
pub fn as_literal_err(&self) -> Option<&EvalError> {
self.as_literal().and_then(|lit| lit.err())
}
pub fn is_literal(&self) -> bool {
matches!(self, MirScalarExpr::Literal(_, _))
}
pub fn is_literal_true(&self) -> bool {
Some(Ok(Datum::True)) == self.as_literal()
}
pub fn is_literal_false(&self) -> bool {
Some(Ok(Datum::False)) == self.as_literal()
}
pub fn is_literal_null(&self) -> bool {
Some(Ok(Datum::Null)) == self.as_literal()
}
pub fn is_literal_ok(&self) -> bool {
matches!(self, MirScalarExpr::Literal(Ok(_), _typ))
}
pub fn is_literal_err(&self) -> bool {
matches!(self, MirScalarExpr::Literal(Err(_), _typ))
}
/// Reduces a complex expression where possible.
///
/// Also canonicalizes the expression.
///
/// ```rust
/// use expr::{BinaryFunc, MirScalarExpr};
/// use repr::{ColumnType, Datum, RelationType, ScalarType};
///
/// let expr_0 = MirScalarExpr::Column(0);
/// let expr_t = MirScalarExpr::literal_ok(Datum::True, ScalarType::Bool);
/// let expr_f = MirScalarExpr::literal_ok(Datum::False, ScalarType::Bool);
///
/// let mut test =
/// expr_t
/// .clone()
/// .call_binary(expr_f.clone(), BinaryFunc::And)
/// .if_then_else(expr_0, expr_t.clone());
///
/// let input_type = RelationType::new(vec![ScalarType::Int32.nullable(false)]);
/// test.reduce(&input_type);
/// assert_eq!(test, expr_t);
/// ```
pub fn reduce(&mut self, relation_type: &RelationType) {
let temp_storage = &RowArena::new();
let eval = |e: &MirScalarExpr| {
MirScalarExpr::literal(e.eval(&[], temp_storage), e.typ(&relation_type).scalar_type)
};
// Canonicalize the structure of the expression
self.demorgans();
self.undistribute_and();
self.visit_mut(&mut |e| match e {
MirScalarExpr::Column(_)
| MirScalarExpr::Literal(_, _)
| MirScalarExpr::CallNullary(_) => (),
MirScalarExpr::CallUnary { func, expr } => {
if expr.is_literal() {
*e = eval(e);
} else if *func == UnaryFunc::IsNull {
// (<expr1> <op> <expr2>) IS NULL can often be simplified to
// (<expr1> IS NULL) OR (<expr2> IS NULL).
if let MirScalarExpr::CallBinary { func, expr1, expr2 } = &mut **expr {
if func.propagates_nulls() && !func.introduces_nulls() {
let expr1 = expr1.take().call_unary(UnaryFunc::IsNull);
let expr2 = expr2.take().call_unary(UnaryFunc::IsNull);
*e = expr1.call_binary(expr2, BinaryFunc::Or);
}
}
} else if *func == UnaryFunc::Not {
match &mut **expr {
MirScalarExpr::CallBinary { expr1, expr2, func } => {
// Transforms `NOT(a <op> b)` to `a negate(<op>) b`
// if a negation exists.
if let Some(negated_func) = func.negate() {
*e = MirScalarExpr::CallBinary {
expr1: Box::new(expr1.take()),
expr2: Box::new(expr2.take()),
func: negated_func,
}
}
}
// Two negates cancel each other out.
MirScalarExpr::CallUnary {
expr: inner_expr,
func: UnaryFunc::Not,
} => *e = inner_expr.take(),
_ => {}
}
}
}
MirScalarExpr::CallBinary { func, expr1, expr2 } => {
if expr1.is_literal() && expr2.is_literal() {
*e = eval(e);
} else if (expr1.is_literal_null() || expr2.is_literal_null())
&& func.propagates_nulls()
{
*e = MirScalarExpr::literal_null(e.typ(relation_type).scalar_type);
} else if let Some(err) = expr1.as_literal_err() {
*e =
MirScalarExpr::literal(Err(err.clone()), e.typ(&relation_type).scalar_type);
} else if let Some(err) = expr2.as_literal_err() {
*e =
MirScalarExpr::literal(Err(err.clone()), e.typ(&relation_type).scalar_type);
} else if let BinaryFunc::IsLikePatternMatch { case_insensitive } = func {
if expr2.is_literal() {
// We can at least precompile the regex.
let pattern = expr2.as_literal_str().unwrap();
let flags = if *case_insensitive { "i" } else { "" };
*e = match like_pattern::build_regex(&pattern, flags) {
Ok(regex) => expr1
.take()
.call_unary(UnaryFunc::IsRegexpMatch(Regex(regex))),
Err(err) => {
MirScalarExpr::literal(Err(err), e.typ(&relation_type).scalar_type)
}
};
}
} else if let BinaryFunc::IsRegexpMatch { case_insensitive } = func {
if let MirScalarExpr::Literal(Ok(row), _) = &**expr2 {
let flags = if *case_insensitive { "i" } else { "" };
*e = match func::build_regex(row.unpack_first().unwrap_str(), flags) {
Ok(regex) => expr1
.take()
.call_unary(UnaryFunc::IsRegexpMatch(Regex(regex))),
Err(err) => {
MirScalarExpr::literal(Err(err), e.typ(&relation_type).scalar_type)
}
};
}
} else if *func == BinaryFunc::DatePartInterval && expr1.is_literal() {
let units = expr1.as_literal_str().unwrap();
*e = match units.parse::<DateTimeUnits>() {
Ok(units) => MirScalarExpr::CallUnary {
func: UnaryFunc::DatePartInterval(units),
expr: Box::new(expr2.take()),
},
Err(_) => MirScalarExpr::literal(
Err(EvalError::UnknownUnits(units.to_owned())),
e.typ(&relation_type).scalar_type,
),
}
} else if *func == BinaryFunc::DatePartTimestamp && expr1.is_literal() {
let units = expr1.as_literal_str().unwrap();
*e = match units.parse::<DateTimeUnits>() {
Ok(units) => MirScalarExpr::CallUnary {
func: UnaryFunc::DatePartTimestamp(units),
expr: Box::new(expr2.take()),
},
Err(_) => MirScalarExpr::literal(
Err(EvalError::UnknownUnits(units.to_owned())),
e.typ(&relation_type).scalar_type,
),
}
} else if *func == BinaryFunc::DatePartTimestampTz && expr1.is_literal() {
let units = expr1.as_literal_str().unwrap();
*e = match units.parse::<DateTimeUnits>() {
Ok(units) => MirScalarExpr::CallUnary {
func: UnaryFunc::DatePartTimestampTz(units),
expr: Box::new(expr2.take()),
},
Err(_) => MirScalarExpr::literal(
Err(EvalError::UnknownUnits(units.to_owned())),
e.typ(&relation_type).scalar_type,
),
}
} else if *func == BinaryFunc::DateTruncTimestamp && expr1.is_literal() {
let units = expr1.as_literal_str().unwrap();
*e = match units.parse::<DateTimeUnits>() {
Ok(units) => MirScalarExpr::CallUnary {
func: UnaryFunc::DateTruncTimestamp(units),
expr: Box::new(expr2.take()),
},
Err(_) => MirScalarExpr::literal(
Err(EvalError::UnknownUnits(units.to_owned())),
e.typ(&relation_type).scalar_type,
),
}
} else if *func == BinaryFunc::DateTruncTimestampTz && expr1.is_literal() {
let units = expr1.as_literal_str().unwrap();
*e = match units.parse::<DateTimeUnits>() {
Ok(units) => MirScalarExpr::CallUnary {
func: UnaryFunc::DateTruncTimestampTz(units),
expr: Box::new(expr2.take()),
},
Err(_) => MirScalarExpr::literal(
Err(EvalError::UnknownUnits(units.to_owned())),
e.typ(&relation_type).scalar_type,
),
}
} else if *func == BinaryFunc::TimezoneTimestamp && expr1.is_literal() {
// If the timezone argument is a literal, and we're applying the function on many rows at the same
// time we really don't want to parse it again and again, so we parse it once and embed it into the
// UnaryFunc enum. The memory footprint of Timezone is small (8 bytes).
let tz = expr1.as_literal_str().unwrap();
*e = match parse_timezone(tz) {
Ok(tz) => MirScalarExpr::CallUnary {
func: UnaryFunc::TimezoneTimestamp(tz),
expr: Box::new(expr2.take()),
},
Err(err) => {
MirScalarExpr::literal(Err(err), e.typ(&relation_type).scalar_type)
}
}
} else if *func == BinaryFunc::TimezoneTimestampTz && expr1.is_literal() {
let tz = expr1.as_literal_str().unwrap();
*e = match parse_timezone(tz) {
Ok(tz) => MirScalarExpr::CallUnary {
func: UnaryFunc::TimezoneTimestampTz(tz),
expr: Box::new(expr2.take()),
},
Err(err) => {
MirScalarExpr::literal(Err(err), e.typ(&relation_type).scalar_type)
}
}
} else if *func == BinaryFunc::TimezoneTime && expr1.is_literal() {
let tz = expr1.as_literal_str().unwrap();
*e = match parse_timezone(tz) {
Ok(tz) => MirScalarExpr::CallUnary {
func: UnaryFunc::TimezoneTime(tz),
expr: Box::new(expr2.take()),
},
Err(err) => {
MirScalarExpr::literal(Err(err), e.typ(&relation_type).scalar_type)
}
}
} else if *func == BinaryFunc::And {
// If we are here, not both inputs are literals.
if expr1.is_literal_false() || expr2.is_literal_true() {
*e = expr1.take();
} else if expr2.is_literal_false() || expr1.is_literal_true() {
*e = expr2.take();
} else if expr1 == expr2 {
*e = expr1.take();
}
} else if *func == BinaryFunc::Or {
// If we are here, not both inputs are literals.
if expr1.is_literal_true() || expr2.is_literal_false() {
*e = expr1.take();
} else if expr2.is_literal_true() || expr1.is_literal_false() {
*e = expr2.take();
} else if expr1 == expr2 {
*e = expr1.take();
}
} else if *func == BinaryFunc::Eq {
// Canonically order elements so that deduplication works better.
if expr2 < expr1 {
::std::mem::swap(expr1, expr2);
}
}
}
MirScalarExpr::CallVariadic { func, exprs } => {
if *func == VariadicFunc::Coalesce {
// If all inputs are null, output is null. This check must
// be done before `exprs.retain...` because `e.typ` requires
// > 0 `exprs` remain.
if exprs.iter().all(|expr| expr.is_literal_null()) {
*e = MirScalarExpr::literal_null(e.typ(&relation_type).scalar_type);
return;
}
// Remove any null values if not all values are null.
exprs.retain(|e| !e.is_literal_null());
// Find the first argument that is a literal or non-nullable
// column. All arguments after it get ignored, so throw them
// away. This intentionally throws away errors that can
// never happen.
if let Some(i) = exprs
.iter()
.position(|e| e.is_literal() || !e.typ(&relation_type).nullable)
{
exprs.truncate(i + 1);
}
// Deduplicate arguments in cases like `coalesce(#0, #0)`.
let mut prior_exprs = HashSet::new();
exprs.retain(|e| prior_exprs.insert(e.clone()));
if let Some(expr) = exprs.iter_mut().find(|e| e.is_literal_err()) {
// One of the remaining arguments is an error, so
// just replace the entire coalesce with that error.
*e = expr.take();
} else if exprs.len() == 1 {
// Only one argument, so the coalesce is a no-op.
*e = exprs[0].take();
}
} else if exprs.iter().all(|e| e.is_literal()) {
*e = eval(e);
} else if func.propagates_nulls() && exprs.iter().any(|e| e.is_literal_null()) {
*e = MirScalarExpr::literal_null(e.typ(&relation_type).scalar_type);
} else if let Some(err) = exprs.iter().find_map(|e| e.as_literal_err()) {
*e =
MirScalarExpr::literal(Err(err.clone()), e.typ(&relation_type).scalar_type);
} else if *func == VariadicFunc::RegexpMatch {
if exprs[1].is_literal() && exprs.get(2).map_or(true, |e| e.is_literal()) {
let needle = exprs[1].as_literal_str().unwrap();
let flags = match exprs.len() {
3 => exprs[2].as_literal_str().unwrap(),
_ => "",
};
*e = match func::build_regex(needle, flags) {
Ok(regex) => mem::take(exprs)
.into_first()
.call_unary(UnaryFunc::RegexpMatch(Regex(regex))),
Err(err) => {
MirScalarExpr::literal(Err(err), e.typ(&relation_type).scalar_type)
}
};
}
}
}
MirScalarExpr::If { cond, then, els } => {
if let Some(literal) = cond.as_literal() {
match literal {
Ok(Datum::True) => *e = then.take(),
Ok(Datum::False) | Ok(Datum::Null) => *e = els.take(),
Err(_) => *e = cond.take(),
_ => unreachable!(),
}
} else if then == els {
*e = then.take();
} else if then.is_literal_ok() && els.is_literal_ok() {
match (then.as_literal(), els.as_literal()) {
(Some(Ok(Datum::True)), _) => {
*e = cond.take().call_binary(els.take(), BinaryFunc::Or);
}
(Some(Ok(Datum::False)), _) => {
*e = cond
.take()
.call_unary(UnaryFunc::Not)
.call_binary(els.take(), BinaryFunc::And);
}
(_, Some(Ok(Datum::True))) => {
*e = cond
.take()
.call_unary(UnaryFunc::Not)
.call_binary(then.take(), BinaryFunc::Or);
}
(_, Some(Ok(Datum::False))) => {
*e = cond.take().call_binary(then.take(), BinaryFunc::And);
}
_ => {}
}
}
}
});
}
/// Transforms !(a && b) into !a || !b and !(a || b) into !a && !b
/// TODO: Make this recursive?
fn demorgans(&mut self) {
if let MirScalarExpr::CallUnary {
expr: inner,
func: UnaryFunc::Not,
} = self
{
if let MirScalarExpr::CallBinary { expr1, expr2, func } = &mut **inner {
match func {
BinaryFunc::And => {
let inner0 = MirScalarExpr::CallUnary {
expr: Box::new(expr1.take()),
func: UnaryFunc::Not,
};
let inner1 = MirScalarExpr::CallUnary {
expr: Box::new(expr2.take()),
func: UnaryFunc::Not,
};
*self = MirScalarExpr::CallBinary {
expr1: Box::new(inner0),
expr2: Box::new(inner1),
func: BinaryFunc::Or,
}
}
BinaryFunc::Or => {
let inner0 = MirScalarExpr::CallUnary {
expr: Box::new(expr1.take()),
func: UnaryFunc::Not,
};
let inner1 = MirScalarExpr::CallUnary {
expr: Box::new(expr2.take()),
func: UnaryFunc::Not,
};
*self = MirScalarExpr::CallBinary {
expr1: Box::new(inner0),
expr2: Box::new(inner1),
func: BinaryFunc::And,
}
}
_ => {}
}
}
}
}
/* #region `undistribute_and` and helper functions */
/// Transforms (a && b) || (a && c) into a && (b || c)
fn undistribute_and(&mut self) {
self.visit_mut(&mut |x| x.undistribute_and_helper());
}
/// AND undistribution to apply at each `ScalarExpr`.
fn undistribute_and_helper(&mut self) {
if let MirScalarExpr::CallBinary {
expr1,
expr2,
func: BinaryFunc::Or,
} = self
{
let mut ands0 = Vec::new();
expr1.harvest_ands(&mut ands0);
let mut ands1 = Vec::new();
expr2.harvest_ands(&mut ands1);
let mut intersection = Vec::new();
for expr in ands0.into_iter() {
if ands1.contains(&expr) {
intersection.push(expr);
}
}
if !intersection.is_empty() {
expr1.suppress_ands(&intersection[..]);
expr2.suppress_ands(&intersection[..]);
}
for and_term in intersection.into_iter() {
*self = MirScalarExpr::CallBinary {
expr1: Box::new(self.take()),
expr2: Box::new(and_term),
func: BinaryFunc::And,
};
}
}
}
/// Collects undistributable terms from AND expressions.
fn harvest_ands(&mut self, ands: &mut Vec<MirScalarExpr>) {
if let MirScalarExpr::CallBinary {
expr1,
expr2,
func: BinaryFunc::And,
} = self
{
expr1.harvest_ands(ands);
expr2.harvest_ands(ands);
} else {
ands.push(self.clone())
}
}
/// Removes undistributed terms from AND expressions.
fn suppress_ands(&mut self, ands: &[MirScalarExpr]) {
if let MirScalarExpr::CallBinary {
expr1,
expr2,
func: BinaryFunc::And,
} = self
{
// Suppress the ands in children.
expr1.suppress_ands(ands);
expr2.suppress_ands(ands);
// If either argument is in our list, replace it by `true`.
let tru = MirScalarExpr::literal_ok(Datum::True, ScalarType::Bool);
if ands.contains(expr1) {
*self = std::mem::replace(expr2, tru);
} else if ands.contains(expr2) {
*self = std::mem::replace(expr1, tru);
}
}
}
/* #endregion */
/// Adds any columns that *must* be non-Null for `self` to be non-Null.
pub fn non_null_requirements(&self, columns: &mut HashSet<usize>) {
match self {
MirScalarExpr::Column(col) => {
columns.insert(*col);
}
MirScalarExpr::Literal(..) => {}
MirScalarExpr::CallNullary(_) => (),
MirScalarExpr::CallUnary { func, expr } => {
if func.propagates_nulls() {
expr.non_null_requirements(columns);
}
}
MirScalarExpr::CallBinary { func, expr1, expr2 } => {
if func.propagates_nulls() {
expr1.non_null_requirements(columns);
expr2.non_null_requirements(columns);
}
}
MirScalarExpr::CallVariadic { func, exprs } => {
if func.propagates_nulls() {
for expr in exprs {
expr.non_null_requirements(columns);
}
}
}
MirScalarExpr::If { .. } => (),
}
}
pub fn typ(&self, relation_type: &RelationType) -> ColumnType {
match self {
MirScalarExpr::Column(i) => relation_type.column_types[*i].clone(),
MirScalarExpr::Literal(_, typ) => typ.clone(),
MirScalarExpr::CallNullary(func) => func.output_type(),
MirScalarExpr::CallUnary { expr, func } => func.output_type(expr.typ(relation_type)),
MirScalarExpr::CallBinary { expr1, expr2, func } => {
func.output_type(expr1.typ(relation_type), expr2.typ(relation_type))
}
MirScalarExpr::CallVariadic { exprs, func } => {
func.output_type(exprs.iter().map(|e| e.typ(relation_type)).collect())
}
MirScalarExpr::If { cond: _, then, els } => {
let then_type = then.typ(relation_type);
let else_type = els.typ(relation_type);
debug_assert!(then_type.scalar_type == else_type.scalar_type);
ColumnType {
nullable: then_type.nullable || else_type.nullable,
scalar_type: then_type.scalar_type,
}
}
}
}
pub fn eval<'a>(
&'a self,
datums: &[Datum<'a>],
temp_storage: &'a RowArena,
) -> Result<Datum<'a>, EvalError> {
match self {
MirScalarExpr::Column(index) => Ok(datums[*index].clone()),
MirScalarExpr::Literal(res, _column_type) => match res {
Ok(row) => Ok(row.unpack_first()),
Err(e) => Err(e.clone()),
},
// Nullary functions must be transformed away before evaluation.
// Their purpose is as a placeholder for data that is not known at
// plan time but can be inlined before runtime.
MirScalarExpr::CallNullary(x) => Err(EvalError::Internal(format!(
"cannot evaluate nullary function: {:?}",
x
))),
MirScalarExpr::CallUnary { func, expr } => func.eval(datums, temp_storage, expr),
MirScalarExpr::CallBinary { func, expr1, expr2 } => {
func.eval(datums, temp_storage, expr1, expr2)
}
MirScalarExpr::CallVariadic { func, exprs } => func.eval(datums, temp_storage, exprs),
MirScalarExpr::If { cond, then, els } => match cond.eval(datums, temp_storage)? {
Datum::True => then.eval(datums, temp_storage),
Datum::False | Datum::Null => els.eval(datums, temp_storage),
d => Err(EvalError::Internal(format!(
"if condition evaluated to non-boolean datum: {:?}",
d
))),
},
}
}
/// True iff the expression contains `NullaryFunc::MzLogicalTimestamp`.
pub fn contains_temporal(&self) -> bool {
let mut contains = false;
self.visit(&mut |e| {
if let MirScalarExpr::CallNullary(NullaryFunc::MzLogicalTimestamp) = e {
contains = true;
}
});
contains
}
}
impl fmt::Display for MirScalarExpr {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
use MirScalarExpr::*;
match self {
Column(i) => write!(f, "#{}", i)?,
Literal(Ok(row), _) => write!(f, "{}", row.unpack_first())?,
Literal(Err(e), _) => write!(f, "(err: {})", e)?,
CallNullary(func) => write!(f, "{}()", func)?,
CallUnary { func, expr } => {
write!(f, "{}({})", func, expr)?;
}
CallBinary { func, expr1, expr2 } => {
if func.is_infix_op() {
write!(f, "({} {} {})", expr1, func, expr2)?;
} else {
write!(f, "{}({}, {})", func, expr1, expr2)?;
}
}
CallVariadic { func, exprs } => {
write!(f, "{}({})", func, explain::separated(", ", exprs.clone()))?;
}
If { cond, then, els } => {
write!(f, "if {} then {{{}}} else {{{}}}", cond, then, els)?;
}
}
Ok(())
}
}
#[derive(Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum EvalError {
DivisionByZero,
FloatOverflow,
FloatUnderflow,
NumericFieldOverflow,
Int32OutOfRange,
Int64OutOfRange,
IntervalOutOfRange,
TimestampOutOfRange,
InvalidBase64Equals,
InvalidBase64Symbol(char),
InvalidBase64EndSequence,
InvalidTimezone(String),
InvalidTimezoneInterval,
InvalidTimezoneConversion,
InvalidDimension {
max_dim: usize,
val: i64,
},
InvalidArray(InvalidArrayError),
InvalidEncodingName(String),
InvalidHashAlgorithm(String),
InvalidByteSequence {
byte_sequence: String,
encoding_name: String,
},
InvalidJsonbCast {
from: String,
to: String,
},
InvalidRegex(String),
InvalidRegexFlag(char),
InvalidParameterValue(String),
NegSqrt,
UnknownUnits(String),
UnsupportedDateTimeUnits(DateTimeUnits),
UnterminatedLikeEscapeSequence,
Parse(ParseError),
ParseHex(ParseHexError),
Internal(String),
InfinityOutOfDomain(String),
NegativeOutOfDomain(String),
ZeroOutOfDomain(String),
}
impl fmt::Display for EvalError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
EvalError::DivisionByZero => f.write_str("division by zero"),
EvalError::FloatOverflow => f.write_str("value out of range: overflow"),
EvalError::FloatUnderflow => f.write_str("value out of range: underflow"),
EvalError::NumericFieldOverflow => f.write_str("numeric field overflow"),
EvalError::Int32OutOfRange => f.write_str("integer out of range"),
EvalError::Int64OutOfRange => f.write_str("bigint out of range"),
EvalError::IntervalOutOfRange => f.write_str("interval out of range"),
EvalError::TimestampOutOfRange => f.write_str("timestamp out of range"),
EvalError::InvalidBase64Equals => {
f.write_str("unexpected \"=\" while decoding base64 sequence")
}
EvalError::InvalidBase64Symbol(c) => write!(
f,
"invalid symbol \"{}\" found while decoding base64 sequence",
c.escape_default()
),
EvalError::InvalidBase64EndSequence => f.write_str("invalid base64 end sequence"),
EvalError::InvalidJsonbCast { from, to } => {
write!(f, "cannot cast jsonb {} to type {}", from, to)
}
EvalError::InvalidTimezone(tz) => write!(f, "invalid time zone '{}'", tz),
EvalError::InvalidTimezoneInterval => {
f.write_str("timezone interval must not contain months or years")
}
EvalError::InvalidTimezoneConversion => f.write_str("invalid timezone conversion"),
EvalError::InvalidDimension { max_dim, val } => write!(
f,
"invalid dimension: {}; must use value within [1, {}]",
val, max_dim
),
EvalError::InvalidArray(e) => e.fmt(f),
EvalError::InvalidEncodingName(name) => write!(f, "invalid encoding name '{}'", name),
EvalError::InvalidHashAlgorithm(alg) => write!(f, "invalid hash algorithm '{}'", alg),
EvalError::InvalidByteSequence {
byte_sequence,
encoding_name,
} => write!(
f,
"invalid byte sequence '{}' for encoding '{}'",
byte_sequence, encoding_name
),
EvalError::NegSqrt => f.write_str("cannot take square root of a negative number"),
EvalError::InvalidRegex(e) => write!(f, "invalid regular expression: {}", e),
EvalError::InvalidRegexFlag(c) => write!(f, "invalid regular expression flag: {}", c),
EvalError::InvalidParameterValue(s) => f.write_str(s),
EvalError::UnknownUnits(units) => write!(f, "unknown units '{}'", units),
EvalError::UnsupportedDateTimeUnits(units) => {
write!(f, "unsupported timestamp units '{}'", units)
}
EvalError::UnterminatedLikeEscapeSequence => {
f.write_str("unterminated escape sequence in LIKE")
}
EvalError::Parse(e) => e.fmt(f),
EvalError::ParseHex(e) => e.fmt(f),
EvalError::Internal(s) => write!(f, "internal error: {}", s),
EvalError::InfinityOutOfDomain(s) => {
write!(f, "function {} is only defined for finite arguments", s)
}
EvalError::NegativeOutOfDomain(s) => {
write!(f, "function {} is not defined for negative numbers", s)
}
EvalError::ZeroOutOfDomain(s) => {
write!(f, "function {} is not defined for zero", s)
}
}
}
}
impl EvalError {
pub fn detail(&self) -> Option<String> {
None
}
pub fn hint(&self) -> Option<String> {
match self {
EvalError::InvalidBase64EndSequence => Some(
"Input data is missing padding, is truncated, or is otherwise corrupted.".into(),
),
_ => None,
}
}
}
impl std::error::Error for EvalError {}
impl From<ParseError> for EvalError {
fn from(e: ParseError) -> EvalError {
EvalError::Parse(e)
}
}
impl From<ParseHexError> for EvalError {
fn from(e: ParseHexError) -> EvalError {
EvalError::ParseHex(e)
}
}
impl From<InvalidArrayError> for EvalError {
fn from(e: InvalidArrayError) -> EvalError {
EvalError::InvalidArray(e)
}
}
impl From<regex::Error> for EvalError {
fn from(e: regex::Error) -> EvalError {
EvalError::InvalidRegex(e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reduce() {
let relation_type = RelationType::new(vec![
ScalarType::Int64.nullable(true),
ScalarType::Int64.nullable(true),
ScalarType::Int64.nullable(false),
]);
let col = |i| MirScalarExpr::Column(i);
let err = |e| MirScalarExpr::literal(Err(e), ScalarType::Int64);
let lit = |i| MirScalarExpr::literal_ok(Datum::Int64(i), ScalarType::Int64);
let null = || MirScalarExpr::literal_null(ScalarType::Int64);
struct TestCase {
input: MirScalarExpr,
output: MirScalarExpr,
}
let test_cases = vec![
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![lit(1)],
},
output: lit(1),
},
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![lit(1), lit(2)],
},
output: lit(1),
},
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![null(), lit(2), null()],
},
output: lit(2),
},
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![null(), col(0), null(), col(1), lit(2), lit(3)],
},
output: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![col(0), col(1), lit(2)],
},
},
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![col(0), col(2), col(1)],
},
output: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![col(0), col(2)],
},
},
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![lit(1), err(EvalError::DivisionByZero)],
},
output: lit(1),
},
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![col(0), err(EvalError::DivisionByZero)],
},
output: err(EvalError::DivisionByZero),
},
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![
null(),
err(EvalError::DivisionByZero),
err(EvalError::NumericFieldOverflow),
],
},
output: err(EvalError::DivisionByZero),
},
TestCase {
input: MirScalarExpr::CallVariadic {
func: VariadicFunc::Coalesce,
exprs: vec![col(0), err(EvalError::DivisionByZero)],
},
output: err(EvalError::DivisionByZero),
},
];
for tc in test_cases {
let mut actual = tc.input.clone();
actual.reduce(&relation_type);
assert!(
actual == tc.output,
"input: {}\nactual: {}\nexpected: {}",
tc.input,
actual,
tc.output
);
}
}
}
| 39.691897 | 119 | 0.472697 |
298c440a49f06bb0c5b2d31b23b39ef86ca92225
| 14,020 |
use assert_cmd::prelude::*;
use bookwerx_core_rust::constants as C;
use predicates::prelude::*;
use std::process::Command;
/*
These tests should be run one at a time so be sure to set RUST_TEST_THREADS=1 when executing the tests. For example:
RUST_BACKTRACE=1 RUST_TEST_THREADS=1 cargo test --test server_config
Test that we can provide the correct configuration via a mixture of command-line and the environment. Other configuration is frequently needed in order to enable the server to proceed to the behavior under test.
1.1 If neither --bind_ip nor BCR_BIND_IP are specified, the server will complain and exit. We _must have_ an IP address for the Rocket server to use or there's nothing else to do.
1.2 If either one of --bind_ip or BCR_BIND_IP are specified, the startup message will mention it. But the server will terminate with an error because other subsequent configuration is missing.
1.3 If both --bind_ip and BCR_BIND_IP are specified, the startup message mentions the value from --bind_ip. But the server will terminate with an error because other subsequent configuration is missing.
2.1 If neither --bind_port nor BCR_BIND_PORT are specified, the server will complain and exit. We _must have_ a port for the Rocket server to use or there's nothing else to do.
2.2 If either one of --bind_port or BCR_BIND_PORT are specified, the startup message will mention it. But the server will terminate with an error because other subsequent configuration is missing.
2.3 If both --bind_port and BCR_BIND_PORT are specified, the startup message mentions the value from --bind_port. But the server will terminate with an error because other subsequent configuration is missing.
3.1 If neither --conn nor BCR_CONN are specified, the server will complain and exit. We _must have_ a connection string or there's nothing else to do.
3.2 If either one of --conn or BCR_CONN are specified, the startup message will mention it. But the server will terminate with an error because other subsequent configuration is missing.
3.3 If both --conn and BCR_CONN are specified, the startup message mentions the value from --conn. But the server will terminate with an error because other subsequent configuration is missing.
4.1 If neither --dbname nor BCR_DBNAME are specified, the server will complain and exit. We _must have_ a db name or there's nothing else to do.
4.2 If either one of --dbname or BCR_DBNAME are specified, the startup message will mention it. But the server will terminate with an error because other subsequent configuration is missing.
4.3 If both --dbname and BCR_DBNAME are specified, the startup message mentions the value from --dbname. But the server will terminate with an error because other subsequent configuration is missing.
5.1 If neither --mode nor BCR_MODE are specified, the server will complain and exit. We _must have_ an operation mode or there's nothing else to do.
5.2 If either one of --mode or BCR_MODE are specified, the startup message will mention it. But the server will terminate with an error because other subsequent configuration is missing.
5.3 If both --mode and BCR_MODE are specified, the startup message mentions the value from --mode. But the server will terminate with an error because other subsequent configuration is missing.
*/
const CARGO_BIN: &str = "server";
const TEST_BIND_IP: &str = "0.0.0.0";
const TEST_BIND_PORT: &str = "8888";
const TEST_CONN_STR: &str = "mysql://root:[email protected]:3306";
const TEST_DBNAME: &str = "bookwerx-core-rust-test";
//const TEST_MODE: &str = "test";
#[test] // 1.1
fn bind_ip_no_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
cmd.assert()
.stdout(predicate::str::contains("Fatal error: No binding IP address is available."))
.failure();
Ok(())
}
#[test] // 1.2
fn bind_ip_no_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP);
cmd.assert()
.stdout(predicate::str::contains(format!("Rocket will bind to IP address [{}], as set from the environment.", TEST_BIND_IP)))
.failure();
Ok(())
}
#[test] // 1.2
fn bind_ip_with_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
cmd.arg(format!("--{}", C::BIND_IP_KEY_CLI))
.arg(TEST_BIND_IP);
cmd.assert()
.stdout(predicate::str::contains(format!("Rocket will bind to IP address [{}], as set from the command line.", TEST_BIND_IP)))
.failure();
Ok(())
}
#[test] // 1.3
// The value set in the command line should override whatever is in the environment.
fn bind_ip_with_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP);
cmd.arg(format!("--{}", C::BIND_IP_KEY_CLI))
.arg(TEST_BIND_IP);
cmd.assert()
.stdout(predicate::str::contains(format!("Rocket will bind to IP address [{}], as set from the command line.", TEST_BIND_IP)))
.failure();
Ok(())
}
#[test] // 2.1
fn bind_port_no_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP);
cmd.assert()
.stdout(predicate::str::contains("Fatal error: No binding port is available."))
.failure();
Ok(())
}
#[test] // 2.2
fn bind_port_no_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
// This is what we're really testing
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT);
cmd.assert()
.stdout(predicate::str::contains(format!("Rocket will bind to port [{}], as set from the environment.", TEST_BIND_PORT)))
.failure();
Ok(())
}
#[test] // 2.2
fn bind_port_with_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
// This is what we're really testing
.arg(format!("--{}", C::BIND_PORT_KEY_CLI))
.arg(TEST_BIND_PORT);
cmd.assert()
.stdout(predicate::str::contains(format!("Rocket will bind to port [{}], as set from the command line.", TEST_BIND_PORT)))
.failure();
Ok(())
}
#[test] // 2.3
// The value set in the command line should override whatever is in the environment.
fn bind_port_with_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
// This is what we're really testing
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
.arg(format!("--{}", C::BIND_PORT_KEY_CLI))
.arg(TEST_BIND_PORT);
cmd.assert()
.stdout(predicate::str::contains(format!("Rocket will bind to port [{}], as set from the command line.", TEST_BIND_PORT)))
.failure();
Ok(())
}
#[test] // 3.1
fn conn_no_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT);
cmd.assert()
.stdout(predicate::str::contains("Fatal error: No db connection string is available."))
.failure();
Ok(())
}
#[test] // 3.2
fn conn_no_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
// This is what we're really testing
.env(C::CONN_KEY_ENV,TEST_CONN_STR);
cmd.assert()
.stdout(predicate::str::contains(format!("Accessing the db via connection string [{}], as set from the environment.", TEST_CONN_STR)))
//.stdout(predicate::str::contains(format!("Fatal error: No database specified.")))
.failure();
Ok(())
}
#[test] // 3.2
fn conn_with_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
// This is what we're really testing
.arg(format!("--{}", C::CONN_KEY_CLI))
.arg(TEST_CONN_STR);
cmd.assert()
.stdout(predicate::str::contains(format!("Accessing the db via connection string [{}], as set from the command line.", TEST_CONN_STR)))
//.stdout(predicate::str::contains(format!("Fatal error: No database specified.")))
.failure();
Ok(())
}
#[test] // 3.3
// The value set in the command line should override whatever is in the environment.
fn conn_with_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
// This is what we're really testing
.env(C::CONN_KEY_ENV,TEST_CONN_STR)
.arg(format!("--{}", C::CONN_KEY_CLI))
.arg(TEST_CONN_STR);
cmd.assert()
.stdout(predicate::str::contains(format!("Accessing the db via connection string [{}], as set from the command line.", TEST_CONN_STR)))
.failure();
Ok(())
}
#[test] // 4.1
fn dbname_no_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
.env(C::CONN_KEY_ENV,TEST_CONN_STR);
cmd.assert()
.stdout(predicate::str::contains("Fatal error: No db name is available."))
.failure();
Ok(())
}
#[test] // 4.2
fn dbname_no_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
.env(C::CONN_KEY_ENV,TEST_CONN_STR)
// This is what we're really testing
.env(C::DBNAME_KEY_ENV,TEST_DBNAME);
cmd.assert()
.stdout(predicate::str::contains(format!("Using db [{}], as set from the environment.", TEST_DBNAME)))
.failure();
Ok(())
}
#[test] // 4.2
fn dbname_with_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
.env(C::CONN_KEY_ENV,TEST_CONN_STR)
// This is what we're really testing
.arg(format!("--{}", C::DBNAME_KEY_CLI))
.arg(TEST_DBNAME);
cmd.assert()
.stdout(predicate::str::contains(format!("Using db [{}], as set from the command line.", TEST_DBNAME)))
.failure();
Ok(())
}
#[test] // 4.3
// The value set in the command line should override whatever is in the environment.
fn dbname_with_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
.env(C::CONN_KEY_ENV,TEST_CONN_STR)
// This is what we're really testing
.env(C::DBNAME_KEY_ENV,"example-db-name-from-env")
.arg(format!("--{}", C::DBNAME_KEY_CLI))
.arg(TEST_DBNAME);
cmd.assert()
.stdout(predicate::str::contains(format!("Using db [{}], as set from the command line.", TEST_DBNAME)))
.failure();
Ok(())
}
#[test] // 5.1
fn mode_no_cli_no_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
.env(C::CONN_KEY_ENV,TEST_CONN_STR)
.env(C::DBNAME_KEY_ENV,TEST_DBNAME);
cmd.assert()
.stdout(predicate::str::contains("Fatal error: No operating mode is available."))
.failure();
Ok(())
}
//#[test] // 5.2 This test should enable the server to start up. But it starts blockingly, so it never returns to this test. How can we test this?
/*fn mode_no_cli_with_env() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(CARGO_BIN)?;
// This is necessary to make the test proceed far enough to test what we want.
cmd.env(C::BIND_IP_KEY_ENV,TEST_BIND_IP)
.env(C::BIND_PORT_KEY_ENV,TEST_BIND_PORT)
.env(C::CONN_KEY_ENV,TEST_CONN_STR)
.env(C::DBNAME_KEY_ENV,TEST_DBNAME)
// This is what we're really testing
.env(C::MODE_KEY_ENV,TEST_MODE);
cmd.assert()
.stdout(predicate::str::contains(format!("Operating in {} mode, as set from the environment.", TEST_MODE)))
.failure();
Ok(())
}*/
| 35.137845 | 212 | 0.676034 |
64925bbecde2337d4cb8778ed55118c18ca5236b
| 807 |
mod with_atom_left;
mod with_big_integer_left;
mod with_empty_list_left;
mod with_external_pid_left;
mod with_float_left;
mod with_function_left;
mod with_heap_binary_left;
mod with_list_left;
mod with_local_pid_left;
mod with_local_reference_left;
mod with_map_left;
mod with_small_integer_left;
mod with_subbinary_left;
mod with_tuple_left;
use std::convert::TryInto;
use std::sync::Arc;
use proptest::arbitrary::any;
use proptest::prop_assert_eq;
use proptest::strategy::Just;
use proptest::test_runner::{Config, TestRunner};
use liblumen_alloc::erts::process::alloc::TermAlloc;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::otp::erlang::are_not_equal_after_conversion_2::native;
use crate::scheduler::with_process_arc;
use crate::test::strategy;
| 26.032258 | 65 | 0.817844 |
626a7bd1e2ab7126a0221cb1b07326903db206df
| 1,737 |
#![feature(int_abs_diff)]
use std::env::args;
use std::time::Instant;
#[cfg(test)]
const SIZE: usize = 10;
#[cfg(not(test))]
const SIZE: usize = 1000;
static mut DATA: [u32; SIZE] = [0; SIZE];
fn main() {
let input = args().nth(1).expect("Please provide an input");
let input = input.as_bytes();
let now = Instant::now();
let output = run(input);
let elapsed = now.elapsed();
println!("_duration:{}", elapsed.as_secs_f64() * 1000.);
println!("{}", output);
}
macro_rules! commit {
($acc: expr, $idx: expr) => {{
unsafe {
*DATA.get_unchecked_mut($idx) = $acc;
}
$acc = 0;
$idx += 1;
}};
}
#[inline(always)]
fn dist(x: u32) -> u32 {
let mut i = 0;
let mut s = 0;
while i < SIZE {
let dist = unsafe { DATA.get_unchecked(i).abs_diff(x) };
s += (dist * (dist + 1)) / 2;
i += 1;
}
s
}
fn run(input: &[u8]) -> u32 {
let len = input.len();
let mut idx = 0;
let mut num_acc = 0;
let mut c = 0;
// Parsing
while c < len {
match unsafe { input.get_unchecked(c) } {
b',' => commit!(num_acc, idx),
c => num_acc = 10 * num_acc + (c - 48) as u32,
}
c += 1;
}
unsafe {
*DATA.get_unchecked_mut(idx) = num_acc;
}
let mut prev = 0;
let mut prev_dist = dist(0);
loop {
let next = prev + 1;
let next_dist = dist(next);
if next_dist >= prev_dist {
return prev_dist;
}
prev = next;
prev_dist = next_dist;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_test() {
assert_eq!(run("16,1,2,0,4,2,7,1,2,14".as_bytes()), 168)
}
}
| 20.435294 | 64 | 0.496834 |
bbb86c09c7aaf55a38c49efcab37d1b9a56f4a00
| 759 |
use clap::{App, Arg};
fn main() {
solana_logger::setup();
let matches = App::new("solana-ip-address")
.version(solana_clap_utils::version!())
.arg(
Arg::with_name("host_port")
.index(1)
.required(true)
.help("Host:port to connect to"),
)
.get_matches();
let host_port = matches.value_of("host_port").unwrap();
let addr = solana_net_utils::parse_host_port(host_port)
.unwrap_or_else(|_| panic!("failed to parse {}", host_port));
match solana_net_utils::get_public_ip_addr(&addr) {
Ok(ip) => println!("{}", ip),
Err(err) => {
eprintln!("{}: {}", addr, err);
std::process::exit(1)
}
}
}
| 28.111111 | 69 | 0.524374 |
acaa26c6ad2fc609b72adbc4c8f79761e3ab902e
| 18,772 |
use crate::snippet::Style;
use crate::Applicability;
use crate::CodeSuggestion;
use crate::Level;
use crate::Substitution;
use crate::SubstitutionPart;
use crate::SuggestionStyle;
use rustc_span::{MultiSpan, Span, DUMMY_SP};
use std::fmt;
#[must_use]
#[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
pub struct Diagnostic {
pub level: Level,
pub message: Vec<(String, Style)>,
pub code: Option<DiagnosticId>,
pub span: MultiSpan,
pub children: Vec<SubDiagnostic>,
pub suggestions: Vec<CodeSuggestion>,
/// This is not used for highlighting or rendering any error message. Rather, it can be used
/// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
/// `span` if there is one. Otherwise, it is `DUMMY_SP`.
pub sort_span: Span,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub enum DiagnosticId {
Error(String),
Lint(String),
}
/// For example a note attached to an error.
#[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
pub struct SubDiagnostic {
pub level: Level,
pub message: Vec<(String, Style)>,
pub span: MultiSpan,
pub render_span: Option<MultiSpan>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct DiagnosticStyledString(pub Vec<StringPart>);
impl DiagnosticStyledString {
pub fn new() -> DiagnosticStyledString {
DiagnosticStyledString(vec![])
}
pub fn push_normal<S: Into<String>>(&mut self, t: S) {
self.0.push(StringPart::Normal(t.into()));
}
pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
self.0.push(StringPart::Highlighted(t.into()));
}
pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
if highlight {
self.push_highlighted(t);
} else {
self.push_normal(t);
}
}
pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
DiagnosticStyledString(vec![StringPart::Normal(t.into())])
}
pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
}
pub fn content(&self) -> String {
self.0.iter().map(|x| x.content()).collect::<String>()
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum StringPart {
Normal(String),
Highlighted(String),
}
impl StringPart {
pub fn content(&self) -> &str {
match self {
&StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
}
}
}
impl Diagnostic {
pub fn new(level: Level, message: &str) -> Self {
Diagnostic::new_with_code(level, None, message)
}
pub fn new_with_code(level: Level, code: Option<DiagnosticId>, message: &str) -> Self {
Diagnostic {
level,
message: vec![(message.to_owned(), Style::NoStyle)],
code,
span: MultiSpan::new(),
children: vec![],
suggestions: vec![],
sort_span: DUMMY_SP,
}
}
pub fn is_error(&self) -> bool {
match self.level {
Level::Bug | Level::Fatal | Level::Error | Level::FailureNote => true,
Level::Warning | Level::Note | Level::Help | Level::Cancelled => false,
}
}
/// Cancel the diagnostic (a structured diagnostic must either be emitted or
/// canceled or it will panic when dropped).
pub fn cancel(&mut self) {
self.level = Level::Cancelled;
}
pub fn cancelled(&self) -> bool {
self.level == Level::Cancelled
}
/// Set the sorting span.
pub fn set_sort_span(&mut self, sp: Span) {
self.sort_span = sp;
}
/// Adds a span/label to be included in the resulting snippet.
/// This label will be shown together with the original span/label used when creating the
/// diagnostic, *not* a span added by one of the `span_*` methods.
///
/// This is pushed onto the `MultiSpan` that was created when the
/// diagnostic was first built. If you don't call this function at
/// all, and you just supplied a `Span` to create the diagnostic,
/// then the snippet will just include that `Span`, which is
/// called the primary span.
pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
self.span.push_span_label(span, label.into());
self
}
pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
let before = self.span.clone();
self.set_span(after);
for span_label in before.span_labels() {
if let Some(label) = span_label.label {
self.span_label(after, label);
}
}
self
}
pub fn note_expected_found(
&mut self,
expected_label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found_label: &dyn fmt::Display,
found: DiagnosticStyledString,
) -> &mut Self {
self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
}
pub fn note_unsuccessfull_coercion(
&mut self,
expected: DiagnosticStyledString,
found: DiagnosticStyledString,
) -> &mut Self {
let mut msg: Vec<_> =
vec![("required when trying to coerce from type `".to_string(), Style::NoStyle)];
msg.extend(expected.0.iter().map(|x| match *x {
StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
}));
msg.push(("` to type '".to_string(), Style::NoStyle));
msg.extend(found.0.iter().map(|x| match *x {
StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
}));
msg.push(("`".to_string(), Style::NoStyle));
// For now, just attach these as notes
self.highlighted_note(msg);
self
}
pub fn note_expected_found_extra(
&mut self,
expected_label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found_label: &dyn fmt::Display,
found: DiagnosticStyledString,
expected_extra: &dyn fmt::Display,
found_extra: &dyn fmt::Display,
) -> &mut Self {
let expected_label = expected_label.to_string();
let expected_label = if expected_label.is_empty() {
"expected".to_string()
} else {
format!("expected {}", expected_label)
};
let found_label = found_label.to_string();
let found_label = if found_label.is_empty() {
"found".to_string()
} else {
format!("found {}", found_label)
};
let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
(expected_label.len() - found_label.len(), 0)
} else {
(0, found_label.len() - expected_label.len())
};
let mut msg: Vec<_> =
vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
msg.extend(expected.0.iter().map(|x| match *x {
StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
}));
msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
msg.extend(found.0.iter().map(|x| match *x {
StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
}));
msg.push((format!("`{}", found_extra), Style::NoStyle));
// For now, just attach these as notes.
self.highlighted_note(msg);
self
}
pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
self.highlighted_note(vec![
(format!("`{}` from trait: `", name), Style::NoStyle),
(signature, Style::Highlight),
("`".to_string(), Style::NoStyle),
]);
self
}
pub fn note(&mut self, msg: &str) -> &mut Self {
self.sub(Level::Note, msg, MultiSpan::new(), None);
self
}
pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
self
}
/// Prints the span with a note above it.
pub fn span_note<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
self.sub(Level::Note, msg, sp.into(), None);
self
}
pub fn warn(&mut self, msg: &str) -> &mut Self {
self.sub(Level::Warning, msg, MultiSpan::new(), None);
self
}
/// Prints the span with a warn above it.
pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
self.sub(Level::Warning, msg, sp.into(), None);
self
}
pub fn help(&mut self, msg: &str) -> &mut Self {
self.sub(Level::Help, msg, MultiSpan::new(), None);
self
}
/// Prints the span with some help above it.
pub fn span_help<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
self.sub(Level::Help, msg, sp.into(), None);
self
}
pub fn multipart_suggestion(
&mut self,
msg: &str,
suggestion: Vec<(Span, String)>,
applicability: Applicability,
) -> &mut Self {
self.suggestions.push(CodeSuggestion {
substitutions: vec![Substitution {
parts: suggestion
.into_iter()
.map(|(span, snippet)| SubstitutionPart { snippet, span })
.collect(),
}],
msg: msg.to_owned(),
style: SuggestionStyle::ShowCode,
applicability,
});
self
}
pub fn multipart_suggestions(
&mut self,
msg: &str,
suggestions: Vec<Vec<(Span, String)>>,
applicability: Applicability,
) -> &mut Self {
self.suggestions.push(CodeSuggestion {
substitutions: suggestions
.into_iter()
.map(|suggestion| Substitution {
parts: suggestion
.into_iter()
.map(|(span, snippet)| SubstitutionPart { snippet, span })
.collect(),
})
.collect(),
msg: msg.to_owned(),
style: SuggestionStyle::ShowCode,
applicability,
});
self
}
/// Prints out a message with for a multipart suggestion without showing the suggested code.
///
/// This is intended to be used for suggestions that are obvious in what the changes need to
/// be from the message, showing the span label inline would be visually unpleasant
/// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
/// improve understandability.
pub fn tool_only_multipart_suggestion(
&mut self,
msg: &str,
suggestion: Vec<(Span, String)>,
applicability: Applicability,
) -> &mut Self {
self.suggestions.push(CodeSuggestion {
substitutions: vec![Substitution {
parts: suggestion
.into_iter()
.map(|(span, snippet)| SubstitutionPart { snippet, span })
.collect(),
}],
msg: msg.to_owned(),
style: SuggestionStyle::CompletelyHidden,
applicability,
});
self
}
/// Prints out a message with a suggested edit of the code.
///
/// In case of short messages and a simple suggestion, rustc displays it as a label:
///
/// ```text
/// try adding parentheses: `(tup.0).1`
/// ```
///
/// The message
///
/// * should not end in any punctuation (a `:` is added automatically)
/// * should not be a question (avoid language like "did you mean")
/// * should not contain any phrases like "the following", "as shown", etc.
/// * may look like "to do xyz, use" or "to do xyz, use abc"
/// * may contain a name of a function, variable, or type, but not whole expressions
///
/// See `CodeSuggestion` for more information.
pub fn span_suggestion(
&mut self,
sp: Span,
msg: &str,
suggestion: String,
applicability: Applicability,
) -> &mut Self {
self.span_suggestion_with_style(
sp,
msg,
suggestion,
applicability,
SuggestionStyle::ShowCode,
);
self
}
pub fn span_suggestion_with_style(
&mut self,
sp: Span,
msg: &str,
suggestion: String,
applicability: Applicability,
style: SuggestionStyle,
) -> &mut Self {
self.suggestions.push(CodeSuggestion {
substitutions: vec![Substitution {
parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
}],
msg: msg.to_owned(),
style,
applicability,
});
self
}
pub fn span_suggestion_verbose(
&mut self,
sp: Span,
msg: &str,
suggestion: String,
applicability: Applicability,
) -> &mut Self {
self.span_suggestion_with_style(
sp,
msg,
suggestion,
applicability,
SuggestionStyle::ShowAlways,
);
self
}
/// Prints out a message with multiple suggested edits of the code.
pub fn span_suggestions(
&mut self,
sp: Span,
msg: &str,
suggestions: impl Iterator<Item = String>,
applicability: Applicability,
) -> &mut Self {
self.suggestions.push(CodeSuggestion {
substitutions: suggestions
.map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
.collect(),
msg: msg.to_owned(),
style: SuggestionStyle::ShowCode,
applicability,
});
self
}
/// Prints out a message with a suggested edit of the code. If the suggestion is presented
/// inline, it will only show the message and not the suggestion.
///
/// See `CodeSuggestion` for more information.
pub fn span_suggestion_short(
&mut self,
sp: Span,
msg: &str,
suggestion: String,
applicability: Applicability,
) -> &mut Self {
self.span_suggestion_with_style(
sp,
msg,
suggestion,
applicability,
SuggestionStyle::HideCodeInline,
);
self
}
/// Prints out a message with for a suggestion without showing the suggested code.
///
/// This is intended to be used for suggestions that are obvious in what the changes need to
/// be from the message, showing the span label inline would be visually unpleasant
/// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
/// improve understandability.
pub fn span_suggestion_hidden(
&mut self,
sp: Span,
msg: &str,
suggestion: String,
applicability: Applicability,
) -> &mut Self {
self.span_suggestion_with_style(
sp,
msg,
suggestion,
applicability,
SuggestionStyle::HideCodeAlways,
);
self
}
/// Adds a suggestion to the json output, but otherwise remains silent/undisplayed in the cli.
///
/// This is intended to be used for suggestions that are *very* obvious in what the changes
/// need to be from the message, but we still want other tools to be able to apply them.
pub fn tool_only_span_suggestion(
&mut self,
sp: Span,
msg: &str,
suggestion: String,
applicability: Applicability,
) -> &mut Self {
self.span_suggestion_with_style(
sp,
msg,
suggestion,
applicability,
SuggestionStyle::CompletelyHidden,
);
self
}
pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
self.span = sp.into();
if let Some(span) = self.span.primary_span() {
self.sort_span = span;
}
self
}
pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
self.code = Some(s);
self
}
pub fn clear_code(&mut self) -> &mut Self {
self.code = None;
self
}
pub fn get_code(&self) -> Option<DiagnosticId> {
self.code.clone()
}
pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self {
self.message[0] = (msg.into(), Style::NoStyle);
self
}
pub fn message(&self) -> String {
self.message.iter().map(|i| i.0.as_str()).collect::<String>()
}
pub fn styled_message(&self) -> &Vec<(String, Style)> {
&self.message
}
/// Used by a lint. Copies over all details *but* the "main
/// message".
pub fn copy_details_not_message(&mut self, from: &Diagnostic) {
self.span = from.span.clone();
self.code = from.code.clone();
self.children.extend(from.children.iter().cloned())
}
/// Convenience function for internal use, clients should use one of the
/// public methods above.
pub fn sub(
&mut self,
level: Level,
message: &str,
span: MultiSpan,
render_span: Option<MultiSpan>,
) {
let sub = SubDiagnostic {
level,
message: vec![(message.to_owned(), Style::NoStyle)],
span,
render_span,
};
self.children.push(sub);
}
/// Convenience function for internal use, clients should use one of the
/// public methods above.
fn sub_with_highlights(
&mut self,
level: Level,
message: Vec<(String, Style)>,
span: MultiSpan,
render_span: Option<MultiSpan>,
) {
let sub = SubDiagnostic { level, message, span, render_span };
self.children.push(sub);
}
}
impl SubDiagnostic {
pub fn message(&self) -> String {
self.message.iter().map(|i| i.0.as_str()).collect::<String>()
}
pub fn styled_message(&self) -> &Vec<(String, Style)> {
&self.message
}
}
| 32.03413 | 100 | 0.569039 |
9ce9f3c30ccf6dbab654991057654ee7906112bc
| 6,187 |
use crate::RegulatoryGraph;
use crate::_aeon_parser::RegulationTemp;
use std::collections::HashSet;
use std::convert::TryFrom;
/// Methods for parsing `RegulatoryGraph`s from string representations.
impl RegulatoryGraph {
/// Create a `RegulatoryGraph` from a collection of regulation strings.
///
/// The variables of the `RegulatoryGraph` are determined from the regulations
/// and are ordered alphabetically. Otherwise, this is equivalent to iteratively
/// calling `add_string_regulation`.
pub fn try_from_string_regulations(
regulations: Vec<String>,
) -> Result<RegulatoryGraph, String> {
let mut templates = Vec::new();
let mut variables = HashSet::new();
for string in regulations {
let template = RegulationTemp::try_from(string.as_str())?;
variables.insert(template.regulator.clone());
variables.insert(template.target.clone());
templates.push(template);
}
let mut variables: Vec<String> = variables.into_iter().collect();
variables.sort();
let mut rg = RegulatoryGraph::new(variables);
for template in templates {
rg.add_temp_regulation(template)?;
}
Ok(rg)
}
/// Add a new `Regulation` to this `RegulatoryGraph` where the regulation is
/// given in its string representation (e.g. "v1 ->? v2").
///
/// The `regulation` parameter must be a valid string representation of a regulation,
/// plus all conditions of `add_regulation` must be satisfied as well.
pub fn add_string_regulation(&mut self, regulation: &str) -> Result<(), String> {
let template = RegulationTemp::try_from(regulation)?;
self.add_temp_regulation(template)
}
/// **(internal)** A utility method for adding regulations once they are parsed.
pub(crate) fn add_temp_regulation(&mut self, regulation: RegulationTemp) -> Result<(), String> {
self.add_regulation(
®ulation.regulator,
®ulation.target,
regulation.observable,
regulation.monotonicity,
)
}
}
impl TryFrom<&str> for RegulatoryGraph {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let lines: Vec<String> = value
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.collect();
RegulatoryGraph::try_from_string_regulations(lines)
}
}
#[cfg(test)]
mod tests {
use crate::Monotonicity::{Activation, Inhibition};
use crate::{Regulation, RegulatoryGraph, Variable, VariableId};
use std::collections::HashMap;
use std::convert::TryFrom;
fn make_rg() -> RegulatoryGraph {
let mut map = HashMap::new();
map.insert("abc".to_string(), VariableId(0));
map.insert("hello".to_string(), VariableId(1));
map.insert("numbers_123".to_string(), VariableId(2));
RegulatoryGraph {
variables: vec![
Variable {
name: "abc".to_string(),
},
Variable {
name: "hello".to_string(),
},
Variable {
name: "numbers_123".to_string(),
},
],
regulations: vec![
Regulation {
// abc -> hello
regulator: VariableId(0),
target: VariableId(1),
observable: true,
monotonicity: Some(Activation),
},
Regulation {
// hello -|? abc
regulator: VariableId(1),
target: VariableId(0),
observable: false,
monotonicity: Some(Inhibition),
},
Regulation {
// numbers_123 -?? abc
regulator: VariableId(2),
target: VariableId(0),
observable: false,
monotonicity: None,
},
Regulation {
// numbers_123 -? hello
regulator: VariableId(2),
target: VariableId(1),
observable: true,
monotonicity: None,
},
],
variable_to_index: map,
}
}
#[test]
fn test_regulatory_graph_from_string_with_comments() {
let rg = RegulatoryGraph::try_from(
"
# Some comment
abc -> hello
hello -|? abc
numbers_123 -?? abc
# Another comment
numbers_123 -? hello
",
)
.unwrap();
assert_eq!(make_rg(), rg);
}
#[test]
fn test_regulatory_graph_from_regulation_list() {
let rg = RegulatoryGraph::try_from_string_regulations(vec![
"abc -> hello".to_string(),
"hello -|? abc".to_string(),
"numbers_123 -?? abc".to_string(),
"numbers_123 -? hello".to_string(),
]);
assert_eq!(make_rg(), rg.unwrap());
}
#[test]
fn test_regulatory_graph_from_individual_regulations() {
let mut rg = RegulatoryGraph::new(vec![
"abc".to_string(),
"hello".to_string(),
"numbers_123".to_string(),
]);
rg.add_string_regulation("abc -> hello").unwrap();
rg.add_string_regulation("hello -|? abc").unwrap();
rg.add_string_regulation("numbers_123 -?? abc").unwrap();
rg.add_string_regulation("numbers_123 -? hello").unwrap();
assert_eq!(make_rg(), rg);
}
#[test]
fn test_regulatory_graph_invalid_regulations() {
let mut rg = RegulatoryGraph::new(vec!["a".to_string(), "b".to_string()]);
assert!(rg.add_string_regulation(" a -> bb ").is_err());
assert!(rg.add_string_regulation(" aa -> b ").is_err());
rg.add_string_regulation(" a -> b ").unwrap();
assert!(rg.add_string_regulation(" a -| b ").is_err());
}
}
| 33.994505 | 100 | 0.542751 |
db6314b87ebfe01b64cc86172c4e7d97cf7b8d22
| 6,446 |
use
{
crate :: { SpawnHandle, LocalSpawnHandle, JoinHandle, BlockingHandle } ,
std :: { rc::Rc, future::Future } ,
tokio :: { task::LocalSet, runtime::{ Runtime } } ,
futures_task :: { FutureObj, LocalFutureObj, Spawn, LocalSpawn, SpawnError } ,
};
/// An executor that uses a [`tokio::runtime::Runtime`] with the [current thread](tokio::runtime::Builder::new_current_thread)
/// and a [`tokio::task::LocalSet`]. Can spawn `!Send` futures.
///
/// ## Creation of the runtime
///
/// You must use [`TokioCtBuilder`](crate::TokioCtBuilder) to create the executor.
///
/// ```
/// // Make sure to set the `tokio_ct` feature on async_executors.
/// //
/// use
/// {
/// async_executors :: { TokioCt, TokioCtBuilder, LocalSpawnHandleExt } ,
/// tokio :: { runtime::Builder } ,
/// std :: { rc::Rc } ,
/// };
///
/// // You must use the builder. This guarantees that TokioCt is always backed by a single threaded runtime.
/// // You can set other configurations by calling `tokio_builder()` on TokioCtBuilder, so you get
/// // access to the `tokio::runtime::Builder`.
/// //
/// let exec = TokioCtBuilder::new().build().expect( "create tokio runtime" );
///
/// // block_on takes a &self, so if you need to `async move`,
/// // just clone it for use inside the async block.
/// //
/// exec.block_on( async
/// {
/// let not_send = async { let rc = Rc::new(()); };
///
/// // We can spawn !Send futures here.
/// //
/// let join_handle = exec.spawn_handle_local( not_send ).expect( "spawn" );
///
/// join_handle.await;
/// });
///```
///
/// ## Unwind Safety.
///
/// When a future spawned on this wrapper panics, the panic will be caught by tokio in the poll function.
///
/// You must only spawn futures to this API that are unwind safe. Tokio will wrap spawned tasks in
/// [`std::panic::AssertUnwindSafe`] and wrap the poll invocation with [`std::panic::catch_unwind`].
///
/// They reason that this is fine because they require `Send + 'static` on the task. As far
/// as I can tell this is wrong. Unwind safety can be circumvented in several ways even with
/// `Send + 'static` (eg. `parking_lot::Mutex` is `Send + 'static` but `!UnwindSafe`).
///
/// You should make sure that if your future panics, no code that lives on after the panic,
/// nor any destructors called during the unwind can observe data in an inconsistent state.
///
/// Note: the future running from within `block_on` as opposed to `spawn` does not exhibit this behavior and will panic
/// the current thread.
///
/// Note that these are logic errors, not related to the class of problems that cannot happen
/// in safe rust (memory safety, undefined behavior, unsoundness, data races, ...). See the relevant
/// [catch_unwind RFC](https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md)
/// and it's discussion threads for more info as well as the documentation of [std::panic::UnwindSafe]
/// for more information.
///
//
#[ derive( Debug, Clone ) ]
//
#[ cfg_attr( nightly, doc(cfg( feature = "tokio_ct" )) ) ]
//
pub struct TokioCt
{
pub(crate) exec : Rc< Runtime > ,
pub(crate) local: Rc< LocalSet > ,
}
impl TokioCt
{
/// This is the entry point for this executor. Once this call returns, no remaining tasks shall be polled anymore.
/// However the tasks stay in the executor, so if you make a second call to `block_on` with a new task, the older
/// tasks will start making progress again.
///
/// For simplicity, it's advised to just create top level task that you run through `block_on` and make sure your
/// program is done when it returns.
///
/// See: [tokio::runtime::Runtime::block_on]
///
/// ## Panics
///
/// This function will panic if it is called from an async context, including but not limited to making a nested
/// call. It will also panic if the provided future panics.
//
pub fn block_on<F: Future>( &self, f: F ) -> F::Output
{
self.exec.block_on( self.local.run_until( f ) )
}
}
impl Spawn for TokioCt
{
fn spawn_obj( &self, future: FutureObj<'static, ()> ) -> Result<(), SpawnError>
{
// We drop the tokio JoinHandle, so the task becomes detached.
//
let _ = self.local.spawn_local( future );
Ok(())
}
}
impl LocalSpawn for TokioCt
{
fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()> ) -> Result<(), SpawnError>
{
// We drop the tokio JoinHandle, so the task becomes detached.
//
let _ = self.local.spawn_local( future );
Ok(())
}
}
impl<Out: 'static + Send> SpawnHandle<Out> for TokioCt
{
fn spawn_handle_obj( &self, future: FutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError>
{
let handle = self.exec.spawn( future );
Ok( JoinHandle::tokio(handle) )
}
}
impl<Out: 'static> LocalSpawnHandle<Out> for TokioCt
{
fn spawn_handle_local_obj( &self, future: LocalFutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError>
{
let handle = self.local.spawn_local( future );
Ok( JoinHandle::tokio(handle) )
}
}
#[ cfg(all( feature = "timer", not(feature="tokio_timer" )) ) ]
//
#[ cfg_attr( nightly, doc(cfg(all( feature = "timer", feature = "tokio_ct" ))) ) ]
//
impl crate::Timer for TokioCt
{
fn sleep( &self, dur: std::time::Duration ) -> futures_core::future::BoxFuture<'static, ()>
{
Box::pin( futures_timer::Delay::new(dur) )
}
}
#[ cfg( feature = "tokio_timer" ) ]
//
#[ cfg_attr( nightly, doc(cfg(all( feature = "tokio_timer", feature = "tokio_ct" ))) ) ]
//
impl crate::Timer for TokioCt
{
fn sleep( &self, dur: std::time::Duration ) -> futures_core::future::BoxFuture<'static, ()>
{
Box::pin( tokio::time::sleep(dur) )
}
}
#[ cfg( feature = "tokio_io" ) ]
//
#[ cfg_attr( nightly, doc(cfg( feature = "tokio_io" )) ) ]
//
impl crate::TokioIo for TokioCt {}
impl crate::YieldNow for TokioCt {}
impl crate::SpawnBlocking for TokioCt
{
fn spawn_blocking<F, R>( &self, f: F ) -> BlockingHandle<R>
where F: FnOnce() -> R + Send + 'static ,
R: Send + 'static ,
{
let handle = self.exec.as_ref().spawn_blocking( f );
BlockingHandle::tokio( handle )
}
}
#[ cfg(test) ]
//
mod tests
{
use super::*;
// It's important that this is not Send, as we allow spawning !Send futures on it.
//
static_assertions::assert_not_impl_any!( TokioCt: Send, Sync );
}
| 28.776786 | 126 | 0.640397 |
26c88d756de914821a366b777ca1348a127b23b7
| 26,654 |
// Copyright 2017 Dmitry Tantsur <[email protected]>
//
// 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.
//! Server management via Compute API.
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::rc::Rc;
use std::time::Duration;
use chrono::{DateTime, FixedOffset};
use fallible_iterator::{FallibleIterator, IntoFallibleIterator};
use osproto::common::IdAndName;
use waiter::{Waiter, WaiterCurrentState};
use super::super::common::{
DeletionWaiter, FlavorRef, ImageRef, IntoVerified, KeyPairRef, NetworkRef, PortRef, ProjectRef,
Refresh, ResourceIterator, ResourceQuery, UserRef, VolumeRef,
};
#[cfg(feature = "image")]
use super::super::image::Image;
use super::super::session::Session;
use super::super::utils::Query;
use super::super::{Error, ErrorKind, Result, Sort};
use super::{api, protocol, BlockDevice, KeyPair};
/// A query to server list.
#[derive(Clone, Debug)]
pub struct ServerQuery {
session: Rc<Session>,
query: Query,
can_paginate: bool,
}
/// A detailed query to server list.
///
/// Is constructed from a `ServerQuery`.
#[derive(Clone, Debug)]
pub struct DetailedServerQuery {
inner: ServerQuery,
}
/// Structure representing a single server.
#[derive(Clone, Debug)]
pub struct Server {
session: Rc<Session>,
inner: protocol::Server,
flavor: protocol::ServerFlavor,
}
/// Structure representing a summary of a single server.
#[derive(Clone, Debug)]
pub struct ServerSummary {
session: Rc<Session>,
inner: IdAndName,
}
/// Waiter for server status to change.
#[derive(Debug)]
pub struct ServerStatusWaiter<'server> {
server: &'server mut Server,
target: protocol::ServerStatus,
}
/// A virtual NIC of a new server.
#[derive(Clone, Debug)]
pub enum ServerNIC {
/// A NIC from the given network.
FromNetwork(NetworkRef),
/// A NIC with the given port.
WithPort(PortRef),
/// A NIC with the given fixed IP.
WithFixedIp(Ipv4Addr),
}
/// A request to create a server.
#[derive(Debug)]
pub struct NewServer {
session: Rc<Session>,
flavor: FlavorRef,
image: Option<ImageRef>,
keypair: Option<KeyPairRef>,
metadata: HashMap<String, String>,
name: String,
nics: Vec<ServerNIC>,
block_devices: Vec<BlockDevice>,
user_data: Option<String>,
config_drive: Option<bool>,
availability_zone: Option<String>,
}
/// Waiter for server to be created.
#[derive(Debug)]
pub struct ServerCreationWaiter {
server: Server,
}
impl Refresh for Server {
/// Refresh the server.
fn refresh(&mut self) -> Result<()> {
self.inner = api::get_server_by_id(&self.session, &self.inner.id)?;
Ok(())
}
}
impl Server {
/// Create a new Server object.
pub(crate) fn new(session: Rc<Session>, inner: protocol::Server) -> Result<Server> {
let flavor = api::get_flavor(&session, &inner.flavor.id)?;
Ok(Server {
session,
inner,
flavor: protocol::ServerFlavor {
ephemeral_size: flavor.ephemeral,
extra_specs: flavor.extra_specs,
original_name: flavor.name,
ram_size: flavor.ram,
root_size: flavor.disk,
swap_size: flavor.swap,
vcpu_count: flavor.vcpus,
},
})
}
/// Load a Server object.
pub(crate) fn load<Id: AsRef<str>>(session: Rc<Session>, id: Id) -> Result<Server> {
let inner = api::get_server(&session, id)?;
Server::new(session, inner)
}
transparent_property! {
#[doc = "IPv4 address to access the server (if provided)."]
access_ipv4: Option<Ipv4Addr>
}
transparent_property! {
#[doc = "IPv6 address to access the server (if provided)."]
access_ipv6: Option<Ipv6Addr>
}
transparent_property! {
#[doc = "Addresses (floating and fixed) associated with the server."]
addresses: ref HashMap<String, Vec<protocol::ServerAddress>>
}
transparent_property! {
#[doc = "Availability zone."]
availability_zone: ref String
}
transparent_property! {
#[doc = "Creation date and time."]
created_at: DateTime<FixedOffset>
}
transparent_property! {
#[doc = "Server description."]
description: ref Option<String>
}
/// Flavor information used to create this server.
#[inline]
pub fn flavor(&self) -> &protocol::ServerFlavor {
&self.flavor
}
/// Find a floating IP, if it exists.
///
/// If multiple floating IPs exist, the first is returned.
pub fn floating_ip(&self) -> Option<IpAddr> {
self.inner
.addresses
.values()
.flat_map(|l| l.iter())
.filter(|a| a.addr_type == Some(protocol::AddressType::Floating))
.map(|a| a.addr)
.next()
}
transparent_property! {
#[doc = "Whether the server was created with a config drive."]
has_config_drive: bool
}
/// Whether the server has an image.
///
/// May return `false` if the server was created from a volume.
#[inline]
pub fn has_image(&self) -> bool {
self.inner.image.is_some()
}
transparent_property! {
#[doc = "Server unique ID."]
id: ref String
}
/// Fetch the associated image.
///
/// Fails with `ResourceNotFound` if the server does not have an image.
#[cfg(feature = "image")]
pub fn image(&self) -> Result<Image> {
match self.inner.image {
Some(ref image) => Image::new(self.session.clone(), &image.id),
None => Err(Error::new(
ErrorKind::ResourceNotFound,
"No image associated with server",
)),
}
}
/// Get a reference to the image.
///
/// May be None if the server was created from a volume.
pub fn image_id(&self) -> Option<&String> {
match self.inner.image {
Some(ref image) => Some(&image.id),
None => None,
}
}
transparent_property! {
#[doc = "Instance name."]
instance_name: ref Option<String>
}
/// Fetch the key pair used for the server.
pub fn key_pair(&self) -> Result<KeyPair> {
match self.inner.key_pair_name {
Some(ref key_pair) => KeyPair::new(self.session.clone(), key_pair),
None => Err(Error::new(
ErrorKind::ResourceNotFound,
"No key pair associated with server",
)),
}
}
transparent_property! {
#[doc = "Name of a key pair used with this server (if any)."]
key_pair_name: ref Option<String>
}
transparent_property! {
#[doc = "Server name."]
name: ref String
}
transparent_property! {
#[doc = "Metadata associated with the server."]
metadata: ref HashMap<String, String>
}
transparent_property! {
#[doc = "Server power state."]
power_state: protocol::ServerPowerState
}
transparent_property! {
#[doc = "Server status."]
status: protocol::ServerStatus
}
transparent_property! {
#[doc = "Last update date and time."]
updated_at: DateTime<FixedOffset>
}
/// Delete the server.
pub fn delete(self) -> Result<DeletionWaiter<Server>> {
api::delete_server(&self.session, &self.inner.id)?;
Ok(DeletionWaiter::new(
self,
Duration::new(120, 0),
Duration::new(1, 0),
))
}
/// Reboot the server.
pub fn reboot<'server>(
&'server mut self,
reboot_type: protocol::RebootType,
) -> Result<ServerStatusWaiter<'server>> {
let mut args = HashMap::new();
let _ = args.insert("type", reboot_type);
api::server_action_with_args(&self.session, &self.inner.id, "reboot", args)?;
Ok(ServerStatusWaiter {
server: self,
target: protocol::ServerStatus::Active,
})
}
/// Start the server, optionally wait for it to be active.
pub fn start<'server>(&'server mut self) -> Result<ServerStatusWaiter<'server>> {
api::server_simple_action(&self.session, &self.inner.id, "os-start")?;
Ok(ServerStatusWaiter {
server: self,
target: protocol::ServerStatus::Active,
})
}
/// Stop the server, optionally wait for it to be powered off.
pub fn stop<'server>(&'server mut self) -> Result<ServerStatusWaiter<'server>> {
api::server_simple_action(&self.session, &self.inner.id, "os-stop")?;
Ok(ServerStatusWaiter {
server: self,
target: protocol::ServerStatus::ShutOff,
})
}
}
impl<'server> Waiter<(), Error> for ServerStatusWaiter<'server> {
fn default_wait_timeout(&self) -> Option<Duration> {
// TODO(dtantsur): vary depending on target?
Some(Duration::new(600, 0))
}
fn default_delay(&self) -> Duration {
Duration::new(1, 0)
}
fn timeout_error(&self) -> Error {
Error::new(
ErrorKind::OperationTimedOut,
format!(
"Timeout waiting for server {} to reach state {}",
self.server.id(),
self.target
),
)
}
fn poll(&mut self) -> Result<Option<()>> {
self.server.refresh()?;
if self.server.status() == self.target {
debug!("Server {} reached state {}", self.server.id(), self.target);
Ok(Some(()))
} else if self.server.status() == protocol::ServerStatus::Error {
debug!(
"Failed to move server {} to {} - status is ERROR",
self.server.id(),
self.target
);
Err(Error::new(
ErrorKind::OperationFailed,
format!("Server {} got into ERROR state", self.server.id()),
))
} else {
trace!(
"Still waiting for server {} to get to state {}, current is {}",
self.server.id(),
self.target,
self.server.status()
);
Ok(None)
}
}
}
impl<'server> WaiterCurrentState<Server> for ServerStatusWaiter<'server> {
fn waiter_current_state(&self) -> &Server {
&self.server
}
}
impl ServerSummary {
transparent_property! {
#[doc = "Server unique ID."]
id: ref String
}
transparent_property! {
#[doc = "Server name."]
name: ref String
}
/// Get details.
pub fn details(&self) -> Result<Server> {
Server::load(self.session.clone(), &self.inner.id)
}
/// Delete the server.
pub fn delete(self) -> Result<()> {
// TODO(dtantsur): implement wait
api::delete_server(&self.session, &self.inner.id)
}
}
impl ServerQuery {
pub(crate) fn new(session: Rc<Session>) -> ServerQuery {
ServerQuery {
session,
query: Query::new(),
can_paginate: true,
}
}
/// Add marker to the request.
///
/// Using this disables automatic pagination.
pub fn with_marker<T: Into<String>>(mut self, marker: T) -> Self {
self.can_paginate = false;
self.query.push_str("marker", marker);
self
}
/// Add limit to the request.
///
/// Using this disables automatic pagination.
pub fn with_limit(mut self, limit: usize) -> Self {
self.can_paginate = false;
self.query.push("limit", limit);
self
}
/// Add sorting to the request.
pub fn sort_by(mut self, sort: Sort<protocol::ServerSortKey>) -> Self {
let (field, direction) = sort.into();
self.query.push_str("sort_key", field);
self.query.push("sort_dir", direction);
self
}
query_filter! {
#[doc = "Filter by IPv4 address that should be used to access the server."]
set_access_ip_v4, with_access_ip_v4 -> access_ip_v4: Ipv4Addr
}
query_filter! {
#[doc = "Filter by IPv6 address that should be used to access the server."]
set_access_ip_v6, with_access_ip_v6 -> access_ip_v6: Ipv6Addr
}
query_filter! {
#[doc = "Filter by availability zone."]
set_availability_zone, with_availability_zone -> availability_zone: String
}
query_filter! {
#[doc = "Filter by flavor."]
set_flavor, with_flavor -> flavor: FlavorRef
}
query_filter! {
#[doc = "Filter by host name."]
set_hostname, with_hostname -> hostname: String
}
query_filter! {
#[doc = "Filter by image used to build the server."]
set_image, with_image -> image: ImageRef
}
query_filter! {
#[doc = "Filter by an IPv4 address."]
set_ip_v4, with_ip_v4 -> ip: Ipv4Addr
}
query_filter! {
#[doc = "Filter by an IPv6 address."]
set_ip_v6, with_ip_v6 -> ip6: Ipv6Addr
}
query_filter! {
#[doc = "Filter by name."]
set_name, with_name -> name: String
}
query_filter! {
#[doc = "Filter by project (also commonly known as tenant)."]
set_project, with_project -> project_id: ProjectRef
}
query_filter! {
#[doc = "Filter by server status."]
set_status, with_status -> status: protocol::ServerStatus
}
query_filter! {
#[doc = "Filter by user."]
set_user, with_user -> user_id: UserRef
}
/// Convert this query into a detailed query.
#[inline]
pub fn detailed(self) -> DetailedServerQuery {
DetailedServerQuery { inner: self }
}
/// Convert this query into an iterator executing the request.
///
/// This iterator yields only `ServerSummary` objects, containing
/// IDs and names. Use `into_iter_detailed` for full `Server` objects.
///
/// Returns a `FallibleIterator`, which is an iterator with each `next`
/// call returning a `Result`.
///
/// Note that no requests are done until you start iterating.
#[inline]
pub fn into_iter(self) -> ResourceIterator<ServerQuery> {
debug!("Fetching servers with {:?}", self.query);
ResourceIterator::new(self)
}
/// Execute this request and return all results.
///
/// A convenience shortcut for `self.into_iter().collect()`.
#[inline]
pub fn all(self) -> Result<Vec<ServerSummary>> {
self.into_iter().collect()
}
/// Return one and exactly one result.
///
/// Fails with `ResourceNotFound` if the query produces no results and
/// with `TooManyItems` if the query produces more than one result.
pub fn one(mut self) -> Result<ServerSummary> {
debug!("Fetching one server with {:?}", self.query);
if self.can_paginate {
// We need only one result. We fetch maximum two to be able
// to check if the query yieled more than one result.
self.query.push("limit", 2);
}
self.into_iter().one()
}
}
impl ResourceQuery for ServerQuery {
type Item = ServerSummary;
const DEFAULT_LIMIT: usize = 100;
fn can_paginate(&self) -> Result<bool> {
Ok(self.can_paginate)
}
fn extract_marker(&self, resource: &Self::Item) -> String {
resource.id().clone()
}
fn fetch_chunk(&self, limit: Option<usize>, marker: Option<String>) -> Result<Vec<Self::Item>> {
let query = self.query.with_marker_and_limit(limit, marker);
Ok(api::list_servers(&self.session, &query)?
.into_iter()
.map(|srv| ServerSummary {
session: self.session.clone(),
inner: srv,
})
.collect())
}
}
impl DetailedServerQuery {
/// Convert this query into an iterator executing the request.
///
/// This iterator yields full `Server` objects.
///
/// Returns a `FallibleIterator`, which is an iterator with each `next`
/// call returning a `Result`.
///
/// Note that no requests are done until you start iterating.
pub fn into_iter(self) -> ResourceIterator<DetailedServerQuery> {
debug!("Fetching server details with {:?}", self.inner.query);
ResourceIterator::new(self)
}
}
impl ResourceQuery for DetailedServerQuery {
type Item = Server;
const DEFAULT_LIMIT: usize = 50;
fn can_paginate(&self) -> Result<bool> {
Ok(self.inner.can_paginate)
}
fn extract_marker(&self, resource: &Self::Item) -> String {
resource.id().clone()
}
fn fetch_chunk(&self, limit: Option<usize>, marker: Option<String>) -> Result<Vec<Self::Item>> {
let query = self.inner.query.with_marker_and_limit(limit, marker);
let servers = api::list_servers_detail(&self.inner.session, &query)?;
let mut result = Vec::with_capacity(servers.len());
for srv in servers {
result.push(Server::new(self.inner.session.clone(), srv)?);
}
Ok(result)
}
}
impl From<DetailedServerQuery> for ServerQuery {
fn from(value: DetailedServerQuery) -> ServerQuery {
value.inner
}
}
impl From<ServerQuery> for DetailedServerQuery {
fn from(value: ServerQuery) -> DetailedServerQuery {
value.detailed()
}
}
fn convert_networks(
session: &Session,
networks: Vec<ServerNIC>,
) -> Result<Vec<protocol::ServerNetwork>> {
let mut result = Vec::with_capacity(networks.len());
for item in networks {
result.push(match item {
ServerNIC::FromNetwork(n) => protocol::ServerNetwork::Network {
uuid: n.into_verified(session)?.into(),
},
ServerNIC::WithPort(p) => protocol::ServerNetwork::Port {
port: p.into_verified(session)?.into(),
},
ServerNIC::WithFixedIp(ip) => protocol::ServerNetwork::FixedIp { fixed_ip: ip },
});
}
Ok(result)
}
impl NewServer {
/// Start creating a server.
pub(crate) fn new(session: Rc<Session>, name: String, flavor: FlavorRef) -> NewServer {
NewServer {
session,
flavor,
image: None,
keypair: None,
metadata: HashMap::new(),
name,
nics: Vec::new(),
block_devices: Vec::new(),
user_data: None,
config_drive: None,
availability_zone: None,
}
}
/// Request creation of the server.
pub fn create(self) -> Result<ServerCreationWaiter> {
let request = protocol::ServerCreate {
block_devices: self.block_devices.into_verified(&self.session)?,
flavorRef: self.flavor.into_verified(&self.session)?.into(),
imageRef: match self.image {
Some(img) => Some(img.into_verified(&self.session)?.into()),
None => None,
},
key_name: match self.keypair {
Some(item) => Some(item.into_verified(&self.session)?.into()),
None => None,
},
metadata: self.metadata,
name: self.name,
networks: convert_networks(&self.session, self.nics)?,
user_data: self.user_data,
config_drive: self.config_drive,
availability_zone: self.availability_zone,
};
let server_ref = api::create_server(&self.session, request)?;
Ok(ServerCreationWaiter {
server: Server::load(self.session, server_ref.id)?,
})
}
/// Add a virtual NIC with given fixed IP to the new server.
#[inline]
pub fn add_fixed_ip(&mut self, fixed_ip: Ipv4Addr) {
self.nics.push(ServerNIC::WithFixedIp(fixed_ip));
}
/// Add a virtual NIC from this network to the new server.
#[inline]
pub fn add_network<N>(&mut self, network: N)
where
N: Into<NetworkRef>,
{
self.nics.push(ServerNIC::FromNetwork(network.into()));
}
/// Add a virtual NIC with this port to the new server.
#[inline]
pub fn add_port<P>(&mut self, port: P)
where
P: Into<PortRef>,
{
self.nics.push(ServerNIC::WithPort(port.into()));
}
/// Metadata assigned to this server.
#[inline]
pub fn metadata(&mut self) -> &mut HashMap<String, String> {
&mut self.metadata
}
/// NICs to attach to this server.
#[inline]
pub fn nics(&mut self) -> &mut Vec<ServerNIC> {
&mut self.nics
}
/// Block devices attached to the server.
#[inline]
pub fn block_devices(&mut self) -> &mut Vec<BlockDevice> {
&mut self.block_devices
}
/// Use this image as a source for the new server.
pub fn set_image<I>(&mut self, image: I)
where
I: Into<ImageRef>,
{
self.image = Some(image.into());
}
/// Use this key pair for the new server.
pub fn set_keypair<K>(&mut self, keypair: K)
where
K: Into<KeyPairRef>,
{
self.keypair = Some(keypair.into());
}
/// Use this availability_zone for the new server.
pub fn set_availability_zone<A>(&mut self, availability_zone: A)
where
A: Into<String>,
{
self.availability_zone = Some(availability_zone.into());
}
/// Add a block device to attach to the server.
#[inline]
pub fn with_block_device(mut self, block_device: BlockDevice) -> Self {
self.block_devices.push(block_device);
self
}
/// Add a volume to boot from.
#[inline]
pub fn with_boot_volume<V>(self, volume: V) -> Self
where
V: Into<VolumeRef>,
{
self.with_block_device(BlockDevice::from_volume(volume, true))
}
/// Add a virtual NIC with given fixed IP to the new server.
#[inline]
pub fn with_fixed_ip(mut self, fixed_ip: Ipv4Addr) -> NewServer {
self.add_fixed_ip(fixed_ip);
self
}
/// Use this image as a source for the new server.
#[inline]
pub fn with_image<I>(mut self, image: I) -> NewServer
where
I: Into<ImageRef>,
{
self.set_image(image);
self
}
/// Use this key pair for the new server.
#[inline]
pub fn with_keypair<K>(mut self, keypair: K) -> NewServer
where
K: Into<KeyPairRef>,
{
self.set_keypair(keypair);
self
}
/// Use this availability zone for the new server.
#[inline]
pub fn with_availability_zone<K>(mut self, availability_zone: K) -> NewServer
where
K: Into<String>,
{
self.set_availability_zone(availability_zone);
self
}
/// Add an arbitrary key/value metadata pair.
pub fn with_metadata<S1, S2>(mut self, key: S1, value: S2) -> NewServer
where
S1: Into<String>,
S2: Into<String>,
{
let _ = self.metadata.insert(key.into(), value.into());
self
}
/// Add a virtual NIC from this network to the new server.
#[inline]
pub fn with_network<N>(mut self, network: N) -> NewServer
where
N: Into<NetworkRef>,
{
self.add_network(network);
self
}
/// Create a volume to boot from from an image.
#[inline]
pub fn with_new_boot_volume<I>(self, image: I, size_gib: u32) -> Self
where
I: Into<ImageRef>,
{
self.with_block_device(BlockDevice::from_new_volume(image, size_gib, true))
}
/// Add a virtual NIC with this port to the new server.
#[inline]
pub fn with_port<P>(mut self, port: P) -> NewServer
where
P: Into<PortRef>,
{
self.add_port(port);
self
}
creation_field! {
#[doc = "Use this user-data for the new server."]
set_user_data, with_user_data -> user_data: optional String
}
creation_field! {
#[doc = "Enable/disable config-drive for the new server."]
set_config_drive, with_config_drive -> config_drive: optional bool
}
}
impl Waiter<Server, Error> for ServerCreationWaiter {
fn default_wait_timeout(&self) -> Option<Duration> {
Some(Duration::new(1800, 0))
}
fn default_delay(&self) -> Duration {
Duration::new(5, 0)
}
fn timeout_error(&self) -> Error {
Error::new(
ErrorKind::OperationTimedOut,
format!(
"Timeout waiting for server {} to become ACTIVE",
self.server.id()
),
)
}
fn poll(&mut self) -> Result<Option<Server>> {
self.server.refresh()?;
if self.server.status() == protocol::ServerStatus::Active {
debug!("Server {} successfully created", self.server.id());
// TODO(dtantsur): get rid of clone?
Ok(Some(self.server.clone()))
} else if self.server.status() == protocol::ServerStatus::Error {
debug!(
"Failed create server {} - status is ERROR",
self.server.id()
);
Err(Error::new(
ErrorKind::OperationFailed,
format!("Server {} got into ERROR state", self.server.id()),
))
} else {
trace!(
"Still waiting for server {} to become ACTIVE, current is {}",
self.server.id(),
self.server.status()
);
Ok(None)
}
}
}
impl WaiterCurrentState<Server> for ServerCreationWaiter {
fn waiter_current_state(&self) -> &Server {
&self.server
}
}
impl IntoFallibleIterator for ServerQuery {
type Item = ServerSummary;
type Error = Error;
type IntoFallibleIter = ResourceIterator<ServerQuery>;
fn into_fallible_iter(self) -> Self::IntoFallibleIter {
self.into_iter()
}
}
impl IntoFallibleIterator for DetailedServerQuery {
type Item = Server;
type Error = Error;
type IntoFallibleIter = ResourceIterator<DetailedServerQuery>;
fn into_fallible_iter(self) -> Self::IntoFallibleIter {
self.into_iter()
}
}
| 28.908894 | 100 | 0.588054 |
d58dcdc37c7978eb92433c7b30a0fcfd6d2e24d5
| 1,322 |
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! cargo run --example account_config
use identity::account::Account;
use identity::account::AccountStorage;
use identity::account::AutoSave;
use identity::account::Result;
use identity::iota::Network;
#[tokio::main]
async fn main() -> Result<()> {
pretty_env_logger::init();
// Create a new Account with explicit configuration
let account: Account = Account::builder()
.autosave(AutoSave::Never) // never auto-save. rely on the drop save
.autosave(AutoSave::Every) // save immediately after every action
.autosave(AutoSave::Batch(10)) // save after every 10 actions
.dropsave(false) // save the account state on drop
.milestone(4) // save a snapshot every 4 actions
.storage(AccountStorage::Memory) // use the default in-memory storage adapter
// configure the mainnet Tangle client
.client(Network::Mainnet, |builder| {
builder
.node("https://chrysalis-nodes.iota.org")
.unwrap() // unwrap is safe, we provided a valid node URL
.permanode("https://chrysalis-chronicle.iota.org/api/mainnet/", None, None)
.unwrap() // unwrap is safe, we provided a valid permanode URL
})
.build()
.await?;
println!("[Example] Account = {:#?}", account);
Ok(())
}
| 33.897436 | 83 | 0.680787 |
2120c6305dd48ab68ae23e9a0374b7fe88e4f027
| 7,253 |
//! tendermint-proto library gives the developer access to the Tendermint proto-defined structs.
#![deny(warnings, trivial_casts, trivial_numeric_casts, unused_import_braces)]
#![allow(clippy::large_enum_variant)]
#![forbid(unsafe_code)]
#![doc(html_root_url = "https://docs.rs/tendermint-proto/0.21.0")]
/// Built-in prost_types with slight customization to enable JSON-encoding
#[allow(warnings)]
pub mod google {
pub mod protobuf {
include!("prost/google.protobuf.rs");
// custom Timeout and Duration types that have valid doctest documentation texts
include!("protobuf.rs");
}
}
mod error;
#[allow(warnings)]
mod tendermint;
pub use error::Error;
pub use tendermint::*;
use bytes::{Buf, BufMut};
use prost::encoding::encoded_len_varint;
use prost::Message;
use std::convert::{TryFrom, TryInto};
use std::fmt::Display;
pub mod serializers;
/// Allows for easy Google Protocol Buffers encoding and decoding of domain
/// types with validation.
///
/// ## Examples
///
/// ```rust
/// use bytes::BufMut;
/// use prost::Message;
/// use std::convert::TryFrom;
/// use tendermint_proto::Protobuf;
///
/// // This struct would ordinarily be automatically generated by prost.
/// #[derive(Clone, PartialEq, Message)]
/// pub struct MyRawType {
/// #[prost(uint64, tag="1")]
/// pub a: u64,
/// #[prost(string, tag="2")]
/// pub b: String,
/// }
///
/// #[derive(Clone)]
/// pub struct MyDomainType {
/// a: u64,
/// b: String,
/// }
///
/// impl MyDomainType {
/// /// Trivial constructor with basic validation logic.
/// pub fn new(a: u64, b: String) -> Result<Self, String> {
/// if a < 1 {
/// return Err("a must be greater than 0".to_owned());
/// }
/// Ok(Self { a, b })
/// }
/// }
///
/// impl TryFrom<MyRawType> for MyDomainType {
/// type Error = String;
///
/// fn try_from(value: MyRawType) -> Result<Self, Self::Error> {
/// Self::new(value.a, value.b)
/// }
/// }
///
/// impl From<MyDomainType> for MyRawType {
/// fn from(value: MyDomainType) -> Self {
/// Self { a: value.a, b: value.b }
/// }
/// }
///
/// impl Protobuf<MyRawType> for MyDomainType {}
///
///
/// // Simulate an incoming valid raw message
/// let valid_raw = MyRawType { a: 1, b: "Hello!".to_owned() };
/// let mut valid_raw_bytes: Vec<u8> = Vec::new();
/// valid_raw.encode(&mut valid_raw_bytes).unwrap();
/// assert!(!valid_raw_bytes.is_empty());
///
/// // Try to decode the simulated incoming message
/// let valid_domain = MyDomainType::decode(valid_raw_bytes.clone().as_ref()).unwrap();
/// assert_eq!(1, valid_domain.a);
/// assert_eq!("Hello!".to_owned(), valid_domain.b);
///
/// // Encode it to compare the serialized form to what we received
/// let mut valid_domain_bytes: Vec<u8> = Vec::new();
/// valid_domain.encode(&mut valid_domain_bytes).unwrap();
/// assert_eq!(valid_raw_bytes, valid_domain_bytes);
///
/// // Simulate an incoming invalid raw message
/// let invalid_raw = MyRawType { a: 0, b: "Hello!".to_owned() };
/// let mut invalid_raw_bytes: Vec<u8> = Vec::new();
/// invalid_raw.encode(&mut invalid_raw_bytes).unwrap();
///
/// // We expect a validation error here
/// assert!(MyDomainType::decode(invalid_raw_bytes.as_ref()).is_err());
/// ```
pub trait Protobuf<T: Message + From<Self> + Default>
where
Self: Sized + Clone + TryFrom<T>,
<Self as TryFrom<T>>::Error: Display,
{
/// Encode into a buffer in Protobuf format.
///
/// Uses [`prost::Message::encode`] after converting into its counterpart
/// Protobuf data structure.
///
/// [`prost::Message::encode`]: https://docs.rs/prost/*/prost/trait.Message.html#method.encode
fn encode<B: BufMut>(&self, buf: &mut B) -> Result<(), Error> {
T::from(self.clone())
.encode(buf)
.map_err(Error::encode_message)
}
/// Encode with a length-delimiter to a buffer in Protobuf format.
///
/// An error will be returned if the buffer does not have sufficient capacity.
///
/// Uses [`prost::Message::encode_length_delimited`] after converting into
/// its counterpart Protobuf data structure.
///
/// [`prost::Message::encode_length_delimited`]: https://docs.rs/prost/*/prost/trait.Message.html#method.encode_length_delimited
fn encode_length_delimited<B: BufMut>(&self, buf: &mut B) -> Result<(), Error> {
T::from(self.clone())
.encode_length_delimited(buf)
.map_err(Error::encode_message)
}
/// Constructor that attempts to decode an instance from a buffer.
///
/// The entire buffer will be consumed.
///
/// Similar to [`prost::Message::decode`] but with additional validation
/// prior to constructing the destination type.
///
/// [`prost::Message::decode`]: https://docs.rs/prost/*/prost/trait.Message.html#method.decode
fn decode<B: Buf>(buf: B) -> Result<Self, Error> {
let raw = T::decode(buf).map_err(Error::decode_message)?;
Self::try_from(raw).map_err(Error::try_from::<T, Self, _>)
}
/// Constructor that attempts to decode a length-delimited instance from
/// the buffer.
///
/// The entire buffer will be consumed.
///
/// Similar to [`prost::Message::decode_length_delimited`] but with
/// additional validation prior to constructing the destination type.
///
/// [`prost::Message::decode_length_delimited`]: https://docs.rs/prost/*/prost/trait.Message.html#method.decode_length_delimited
fn decode_length_delimited<B: Buf>(buf: B) -> Result<Self, Error> {
let raw = T::decode_length_delimited(buf).map_err(Error::decode_message)?;
Self::try_from(raw).map_err(Error::try_from::<T, Self, _>)
}
/// Returns the encoded length of the message without a length delimiter.
///
/// Uses [`prost::Message::encoded_len`] after converting to its
/// counterpart Protobuf data structure.
///
/// [`prost::Message::encoded_len`]: https://docs.rs/prost/*/prost/trait.Message.html#method.encoded_len
fn encoded_len(&self) -> usize {
T::from(self.clone()).encoded_len()
}
/// Encodes into a Protobuf-encoded `Vec<u8>`.
fn encode_vec(&self) -> Result<Vec<u8>, Error> {
let mut wire = Vec::with_capacity(self.encoded_len());
self.encode(&mut wire).map(|_| wire)
}
/// Constructor that attempts to decode a Protobuf-encoded instance from a
/// `Vec<u8>` (or equivalent).
fn decode_vec(v: &[u8]) -> Result<Self, Error> {
Self::decode(v)
}
/// Encode with a length-delimiter to a `Vec<u8>` Protobuf-encoded message.
fn encode_length_delimited_vec(&self) -> Result<Vec<u8>, Error> {
let len = self.encoded_len();
let lenu64 = len.try_into().map_err(Error::parse_length)?;
let mut wire = Vec::with_capacity(len + encoded_len_varint(lenu64));
self.encode_length_delimited(&mut wire).map(|_| wire)
}
/// Constructor that attempts to decode a Protobuf-encoded instance with a
/// length-delimiter from a `Vec<u8>` or equivalent.
fn decode_length_delimited_vec(v: &[u8]) -> Result<Self, Error> {
Self::decode_length_delimited(v)
}
}
| 35.208738 | 132 | 0.638908 |
c18ea23a1f4903d7350598731736b79ffcd7f768
| 23,394 |
//! A platform agnostic Rust driver for Edinburgh gas sensor, based
//! on the [`embedded-hal`](https://github.com/japaric/embedded-hal) traits.
//! [Homepage]: https://edinburghsensors.com/
//! [Edinburgh]: https://edinburghsensors.com/products/oem-co2-sensor/gascard-ng
//! KEY FEATURES
//! On-board barometric pressure correction in the range 800mbar to 1150mbar.
//! Extensive temperature compensation.
//! Minimum operating voltage 7V and wide operating voltage range (7V to 30V).
//! True RS232 communications for control and data logging. Optional on-board LAN support.
//! # References
//! # GAS MEASUREMENT RANGE
//! Model CO2 CH4 CO
//! GasCard NG - 0-5% 0-10%
//! GasCard NG - 0-10% 0-30%
//! GasCard NG 0-2000 ppm 0-30% 0-100%
//! GasCard NG 0-3000 ppm 0-100% -
//! CardCard NG 0-5000 ppm - -
//! GasCard NG 0-1% - -
//! GasCard NG 0-3% - -
//! GasCard NG 0-5% - -
//! GasCard NG 0-10% - -
//! GasCard NG 0-30% - -
//! GasCard NG 0-100% - -
//! Biogas 100% 100% -
//! Accuracy ±2% of range ±<0.015% of range per mbar
//! Zero stability ±2% of range (over 12 months)
//! Response time T90 = 10 seconds or programmable RC
//! Operating temperature 0-45ºC
//! Power requirements 24 V DC (7V-30V)
//! Warm-up time 1 minute (initial) 30 minutes (full specification)
//! Humidity Measurements are unaffected by 0-95% relative humidity, non condensing
//! Output Linear 4-20 mA, 0-20 mA (bit switch selectable) maximum load dependant on supply voltage
//! Please Note Equipment is configured for one gas type at a time.
//!
//!
//! ## The Device
//!
//! The Sensirion SGP30 is a low-power gas sensor for indoor air quality
//! applications with good long-term stability. It has an I²C interface with TVOC
//! (*Total Volatile Organic Compounds*) and CO₂ equivalent signals.
//!
//! - [Datasheet](https://www.sensirion.com/file/datasheet_sgp30)
//! - [Product Page](https://www.sensirion.com/sgp)
//!
//! ## Usage
//!
//! ### Instantiating
//!
//! Import this crate and an `embedded_hal` implementation, then instantiate
//! the device:
//!
//! ```no_run
//! extern crate linux_embedded_hal as hal;
//! extern crate edinburgh;
//!
//! use hal::{Delay, I2cdev};
//! use edinburgh::Edinburgh;
//!
//! # fn main() {
//! let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! let address = 0x58;
//! let mut sgp = Edinburgh::new(dev, address, Delay);
//! # }
//! ```
//!
//! ### Fetching Device Information
//!
//! You can fetch the serial number of your sensor as well as the [feature
//! set](struct.FeatureSet.html):
//!
//! ```no_run
//! # extern crate linux_embedded_hal as hal;
//! # extern crate edinburgh;
//! # use hal::{Delay, I2cdev};
//! # use edinburgh::Edinburgh;
//! use edinburgh::FeatureSet;
//!
//! # fn main() {
//! # let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! # let mut sgp = Edinburgh::new(dev, 0x58, Delay);
//! let serial_number: [u8; 6] = sgp.serial().unwrap();
//! let feature_set: FeatureSet = sgp.get_feature_set().unwrap();
//! # }
//! ```
//!
//! ### Doing Measurements
//!
//! Before you do any measurements, you need to initialize the sensor.
//!
//! ```no_run
//! # extern crate linux_embedded_hal as hal;
//! # extern crate edinburgh;
//! # use hal::{Delay, I2cdev};
//! # use edinburgh::Edinburgh;
//! # fn main() {
//! # let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! # let mut sgp = Edinburgh::new(dev, 0x58, Delay);
//! sgp.init().unwrap();
//! # }
//! ```
//!
//! The SGP30 uses a dynamic baseline compensation algorithm and on-chip
//! calibration parameters to provide two complementary air quality signals.
//! Calling this method starts the air quality measurement. **After
//! initializing the measurement, the `measure()` method must be called in
//! regular intervals of 1 second** to ensure proper operation of the dynamic
//! baseline compensation algorithm. It is the responsibility of the user of
//! this driver to ensure that these periodic measurements are being done!
//!
//! ```no_run
//! # extern crate embedded_hal;
//! # extern crate linux_embedded_hal as hal;
//! # extern crate edinburgh;
//! # use hal::I2cdev;
//! # use edinburgh::Edinburgh;
//! use embedded_hal::blocking::delay::DelayMs;
//! use hal::Delay;
//! use edinburgh::Measurement;
//!
//! # fn main() {
//! # let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! # let mut sgp = Edinburgh::new(dev, 0x58, Delay);
//! # sgp.init().unwrap();
//! loop {
//! let measurement: Measurement = sgp.measure().unwrap();
//! println!("CO₂eq parts per million: {}", measurement.co2eq_ppm);
//! println!("TVOC parts per billion: {}", measurement.tvoc_ppb);
//! Delay.delay_ms(1000u16 - 12);
//! }
//! # }
//! ```
//!
//! *(Note: In the example we're using a delay of 988 ms because the
//! measurement takes up to 12 ms according to the datasheet. In reality, it
//! would be better to use a timer-based approach instead.)*
//!
//! For the first 15 s after initializing the air quality measurement, the
//! sensor is in an initialization phase during which it returns fixed
//! values of 400 ppm CO₂eq and 0 ppb TVOC. After 15 s (15 measurements)
//! the values should start to change.
//!
//! A new init command has to be sent after every power-up or soft reset.
//!
//! ### Restoring Baseline Values
//!
//! The SGP30 provides the possibility to read and write the values of the
//! baseline correction algorithm. This feature is used to save the baseline in
//! regular intervals on an external non-volatile memory and restore it after a
//! new power-up or soft reset of the sensor.
//!
//! The [`get_baseline()`](struct.Edinburgh.html#method.get_baseline) method
//! returns the baseline values for the two air quality signals. After a
//! power-up or soft reset, the baseline of the baseline correction algorithm
//! can be restored by calling [`init()`](struct.Edinburgh.html#method.init)
//! followed by [`set_baseline()`](struct.Edinburgh.html#method.set_baseline).
//!
//! ```no_run
//! # extern crate linux_embedded_hal as hal;
//! # extern crate edinburgh;
//! # use hal::{I2cdev, Delay};
//! # use edinburgh::Edinburgh;
//! use edinburgh::Baseline;
//!
//! # fn main() {
//! # let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! # let mut sgp = Edinburgh::new(dev, 0x58, Delay);
//! # sgp.init().unwrap();
//! let baseline: Baseline = sgp.get_baseline().unwrap();
//! // …
//! sgp.init().unwrap();
//! sgp.set_baseline(&baseline).unwrap();
//! # }
//! ```
//!
//! ### Humidity Compensation
//!
//! The SGP30 features an on-chip humidity compensation for the air quality
//! signals (CO₂eq and TVOC) and sensor raw signals (H2 and Ethanol). To use
//! the on-chip humidity compensation, an absolute humidity value from an
//! external humidity sensor is required.
//!
//! ```no_run
//! # extern crate linux_embedded_hal as hal;
//! # extern crate edinburgh;
//! # use hal::{I2cdev, Delay};
//! # use edinburgh::Edinburgh;
//! use edinburgh::Humidity;
//!
//! # fn main() {
//! # let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! # let mut sgp = Edinburgh::new(dev, 0x58, Delay);
//! // This value must be obtained from a separate humidity sensor
//! let humidity = Humidity::from_f32(23.42).unwrap();
//!
//! sgp.init().unwrap();
//! sgp.set_humidity(Some(&humidity)).unwrap();
//! # }
//! ```
//!
//! After setting a new humidity value, this value will be used by the
//! on-chip humidity compensation algorithm until a new humidity value is
//! set. Restarting the sensor (power-on or soft reset) or calling the
//! function with a `None` value sets the humidity value used for
//! compensation to its default value (11.57 g/m³) until a new humidity
//! value is sent.
// Testdate edinburgh
// const TEST_DATA: &'static str = "N 0.0414 0.0000 0.0000 0.00 0.0000 22942 992.6";
// Regex::new(r"N (?P<fsr>\d{1}.\d{4}) \d{1}.\d{4} \d{1}.\d{4} \d{1}.\d{2} \d{1}.\d{4} (?P<dig>\d{5}) (?P<ppm>\d{1}.\d{4}) \d{1}").unwrap()*
// -- Listenmakros für Aufzählungen
// #define BAUD_RATES(g,f,d) \
// g(9600, d) \
// f(1200, d) \
// f(2400, d) \
// f(4800, d) \
// f(9600, d) \
// f(19200, d) \
// f(38400, d) \
// f(57600, d) \
// f(115200, no)
// #[derive(Serialize,Deserialize, Clone, Debug)]
// pub struct Signal{
// fsr: f32,
// ppm: f32,
// dig: u32,
// }
// fn decode(input: &str) -> Option<Signal> {
// lazy_static! {
// // N 0.0384 0.0000 0.0000 0.00 0.0000 25764 997.2 0
// static ref RE: Regex = Regex::new(r"N (?P<fsr>\d{1}.\d{4}) \d{1}.\d{4} \d{1}.\d{4} \d{1}.\d{2} \d{1}.\d{4} (?P<dig>\d{5}) (?P<ppm>\d{1,5}.\d{1}) \d{1}").unwrap();
// }
// RE.captures(input).and_then(|cap| {
// let fsr = cap.name("fsr").map(|fsr| fsr.as_str().parse::<f32>().unwrap_or(0.0)).unwrap();
// let dig = cap.name("dig").map(|dig| dig.as_str().parse::<u32>().unwrap_or(0)).unwrap();
// let ppm = cap.name("ppm").map(|ppm| ppm.as_str().parse::<f32>().unwrap_or(0.0)).unwrap();
// Some(Signal{fsr,ppm,dig})
// })
// }
// impl std::fmt::Display for Signal {
// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
// write!(f, "fsr:{} dig:{} ppm:{}", self.fsr, self.ppm, self.dig)
// }
// }
#![deny(unsafe_code)]
// #![deny(missing_docs)]
#![cfg_attr(not(test), no_std)]
// extern crate byteorder;
use embedded_hal as hal;
// extern crate num_traits;
use byteorder::{BigEndian, ByteOrder};
use hal::blocking::delay::{DelayMs, DelayUs};
// use hal::blocking::serial::{Read, Write, WriteRead};
// use hal::serial;
use hal::serial::{Read,Write};
// pub use nb::Error;
use regex::Regex;
// use lazy_static::lazy_static;
// use std::time::Duration;
// use std::str::FromStr;
// use std::time::SystemTime;
// use super::*;
use lazy_static::lazy_static;
// const CRC8_POLYNOMIAL: u8 = 0x31;
fn extract_fsr(input: &str) -> Option<f32> {
lazy_static! {
// N 0.0384 0.0000 0.0000 0.00 0.0000 25764 997.2 0
static ref RE: Regex = Regex::new(r"N (?P<fsr>\d{1}.\d{4}) \d{1}.\d{4} \d{1}.\d{4} \d{1}.\d{2} \d{1}.\d{4} (?P<dig>\d{5}) (?P<ppm>\d{1,5}.\d{1}) \d{1}").unwrap();
}
RE.captures(input).and_then(|cap| {
cap.name("fsr").map(|fsr| fsr.as_str().parse::<f32>().unwrap_or(0.0))
})
}
/// All possible errors in this crate
#[derive(Debug)]
pub enum Error<E> {
/// Serial communication error
Serial(E),
/// CRC checksum validation failed
Crc,
/// User tried to measure the air quality without starting the
/// initialization phase.
NotInitialized,
}
/// Serial commands sent to the sensor.
#[derive(Debug, Copy, Clone)]
pub enum Command {
/// Run an on-chip self-test.
SelfTest,
/// Initialize air quality measurements.
InitAirQuality,
/// Get a current air quality measurement.
MeasureAirQuality,
/// Measure raw signals.
MeasureRawSignals,
// Return the baseline value.
// GetBaseline,
// Set the baseline value.
// SetBaseline,
/// Set the feature set.
GetFeatureSet,
}
impl Command {
fn as_bytes(self) -> [u8; 2] {
match self {
Command::SelfTest => [0x20, 0x32],
Command::InitAirQuality => [0x20, 0x03],
Command::MeasureAirQuality => [0x20, 0x08],
Command::MeasureRawSignals => [0x20, 0x50],
// Command::GetBaseline => [0x20, 0x15],
// Command::SetBaseline => [0x20, 0x1E],
Command::GetFeatureSet => [0x20, 0x2F],
}
}
}
/// A measurement result from the sensor.
#[derive(Debug, PartialEq, Clone)]
pub struct Measurement {
/// CO₂ equivalent (parts per million, ppm)
pub co2eq_ppm: u16,
/// Total Volatile Organic Compounds (parts per billion, ppb)
pub tvoc_ppb: u16,
pub fsr: f32
}
/// A raw signals result from the sensor.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RawSignals {
/// H2 signal
pub h2: u16,
/// Ethanol signal
pub ethanol: u16,
}
/// The baseline values.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Baseline {
/// CO₂eq baseline
pub co2eq: u16,
/// TVOC baseline
pub tvoc: u16,
}
/// The product types compatible with this driver.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum ProductType {
/// Edinburgh500
Edinburgh500,
/// Edinburgh1%
Edinburgh1ppm,
/// Edinburgh3%
Edinburgh3ppm,
/// Unknown product type
Unknown(u8),
}
impl ProductType {
/// Parse the product type.
pub fn parse(val: u8) -> Self {
match val {
0 => ProductType::Edinburgh500,
1 => ProductType::Edinburgh500,
2 => ProductType::Edinburgh500,
_ => ProductType::Unknown(val),
}
}
}
/// The feature set returned by the sensor.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct FeatureSet {
/// The product type (see [`ProductType`](enum.ProductType.html))
pub product_type: ProductType,
/// The product version
pub product_version: u8,
}
impl FeatureSet {
/// Parse the two bytes returned by the device.
pub fn parse(msb: u8, lsb: u8) -> Self {
FeatureSet {
product_type: ProductType::parse(msb >> 4),
product_version: lsb,
}
}
}
/// Driver for the SGP30
#[derive(Debug, Default)]
pub struct Edinburgh<S, D> {
/// The concrete I²C device implementation.
s: S,
/// The concrete Delay implementation.
delay: D,
/// Whether the air quality measurement was initialized.
initialized: bool,
}
impl<S, D, E> Edinburgh<S, D>
where
S: Read<String, Error = E> + Write<String, Error = E>,
D: DelayUs<u16> + DelayMs<u16>,
{
/// Create a new instance of the Edinburgh driver.
pub fn new(s: S, address: u8, delay: D) -> Self {
Edinburgh {
s,
delay,
initialized: false,
}
}
/// Destroy driver instance, return I²C bus instance.
pub fn destroy(self) -> S{
self.s
}
/// Run an on-chip self-test. Return a boolean indicating whether the test succeeded.
pub fn selftest(&mut self) -> nb::Result<bool, Error<E>> {
// Start self test
// Max duration according to datasheet (Table 10)
self.delay.delay_ms(220);
// Read result
let mut buf = [0; 3];
// Compare with self-test success pattern
Ok(buf[0..2] == [0xd4, 0x00])
}
/// Initialize the air quality measurement.
///
/// The Edinburgh uses a dynamic baseline compensation algorithm and on-chip
/// calibration parameters to provide two complementary air quality
/// signals.
///
/// Calling this method starts the air quality measurement. After
/// initializing the measurement, the `measure()` method must be called in
/// regular intervals of 1 s to ensure proper operation of the dynamic
/// baseline compensation algorithm. It is the responsibility of the user
/// of this driver to ensure that these periodic measurements are being
/// done.
///
/// For the first 15 s after initializing the air quality measurement, the
/// sensor is in an initialization phase during which it returns fixed
/// values of 400 ppm CO₂eq and 0 ppb TVOC. After 15 s (15 measurements)
/// the values should start to change.
///
/// A new init command has to be sent after every power-up or soft reset.
pub fn init(&mut self) -> nb::Result<(), Error<E>> {
if self.initialized {
// Already initialized
return Ok(());
}
self.force_init()
}
/// Like [`init()`](struct.Edinburgh.html#method.init), but without checking
/// whether the sensor is already initialized.
///
/// This might be necessary after a sensor soft or hard reset.
pub fn force_init(&mut self) -> nb::Result<(), Error<E>> {
// Send command to sensor
// Max duration according to datasheet (Table 10)
self.delay.delay_ms(10);
self.initialized = true;
Ok(())
}
/// Get measurement.
///
/// Before calling this method, the air quality measurements must have been
/// initialized using the [`init()`](struct.Edinburgh.html#method.init) method.
/// Otherwise an [`Error::NotInitialized`](enum.Error.html#variant.NotInitialized)
/// will be returned.
///
/// Once the measurements have been initialized, the
/// [`measure()`](struct.Edinburgh.html#method.measure) method must be called
/// in regular intervals of 1 s to ensure proper operation of the dynamic
/// baseline compensation algorithm. It is the responsibility of the user
/// of this driver to ensure that these periodic measurements are being
/// done.
///
/// For the first 15 s after initializing the air quality measurement, the
/// sensor is in an initialization phase during which it returns fixed
/// values of 400 ppm CO₂eq and 0 ppb TVOC. After 15 s (15 measurements)
/// the values should start to change.
pub fn measure(&mut self) -> nb::Result<Measurement, Error<E>> {
if !self.initialized {
// Measurements weren't initialized
return Err(nb::Error::Other(Error::NotInitialized))
}
// Send command to sensor
// Max duration according to datasheet (Table 10)
self.delay.delay_ms(12);
// Read result
let mut buf = [0; 6];
let co2eq_ppm = 0 as u16;// (u16::from(buf[0]) << 8) | u16::from(buf[1]);
let tvoc_ppb = 0 as u16;// (u16::from(buf[3]) << 8) | u16::from(buf[4]);
let fsr = 0.0;
Ok(Measurement {
co2eq_ppm,
tvoc_ppb,
fsr,
})
}
/// Return sensor raw signals.
///
/// This command is intended for part verification and testing purposes. It
/// returns the raw signals which are used as inputs for the on-chip
/// calibration and baseline compensation algorithm. The command performs a
/// measurement to which the sensor responds with the two signals for H2
/// and Ethanol.
pub fn measure_raw_signals(&mut self) -> nb::Result<RawSignals, Error<E>> {
if !self.initialized {
// Measurements weren't initialized
return Err(nb::Error::Other(Error::NotInitialized));
}
// Max duration according to datasheet (Table 10)
self.delay.delay_ms(25);
// Read result
let mut buf = [0; 6];
let h2_signal = 0 as u16; //(u16::from(buf[0]) << 8) | u16::from(buf[1]);
let ethanol_signal = 0 as u16;// (u16::from(buf[3]) << 8) | u16::from(buf[4]);
Ok(RawSignals {
h2: h2_signal,
ethanol: ethanol_signal,
})
}
/// Return the baseline values of the baseline correction algorithm.
///
/// The Edinburgh provides the possibility to read and write the baseline
/// values of the baseline correction algorithm. This feature is used to
/// save the baseline in regular intervals on an external non-volatile
/// memory and restore it after a new power-up or soft reset of the sensor.
///
/// This function returns the baseline values for the two air quality
/// signals. These two values should be stored on an external memory. After
/// a power-up or soft reset, the baseline of the baseline correction
/// algorithm can be restored by calling
/// [`init()`](struct.Edinburgh.html#method.init) followed by
/// [`set_baseline()`](struct.Edinburgh.html#method.set_baseline).
pub fn get_baseline(&mut self) -> nb::Result<Baseline, Error<E>> {
// Send command to sensor
// self.send_command(Command::GetBaseline)?;
// Max duration according to datasheet (Table 10)
self.delay.delay_ms(10);
// Read result
// let mut buf = [0; 6];
// self.read_with_crc(&mut buf)?;
let co2eq_baseline = 0;//(u16::from(buf[0]) << 8) | u16::from(buf[1]);
let tvoc_baseline = 0;//(u16::from(buf[3]) << 8) | u16::from(buf[4]);
Ok(Baseline {
co2eq: co2eq_baseline,
tvoc: tvoc_baseline,
})
}
/// Set the baseline values for the baseline correction algorithm.
///
/// Before calling this method, the air quality measurements must have been
/// initialized using the [`init()`](struct.Edinburgh.html#method.init) method.
/// Otherwise an [`Error::NotInitialized`](enum.Error.html#variant.NotInitialized)
/// will be returned.
///
/// The Edinburgh provides the possibilty to read and write the baseline
/// values of the baseline correction algorithm. This feature is used to
/// save the baseline in regular intervals on an external non-volatile
/// memory and restore it after a new power-up or soft reset of the sensor.
///
/// This function sets the baseline values for the two air quality
/// signals.
pub fn set_baseline(&mut self, baseline: &Baseline) -> nb::Result<(), Error<E>> {
if !self.initialized {
// Measurements weren't initialized
return Err(nb::Error::Other(Error::NotInitialized));
}
// Send command and data to sensor
// Note that the order of the two parameters is inverted when writing
// compared to when reading.
let mut buf = [0; 4];
BigEndian::write_u16(&mut buf[0..2], baseline.tvoc);
BigEndian::write_u16(&mut buf[2..4], baseline.co2eq);
// self.send_command_and_data(Command::SetBaseline, &buf)?;
// Max duration according to datasheet (Table 10)
self.delay.delay_ms(10);
Ok(())
}
/// Get the feature set.
///
/// The Edinburgh features a versioning system for the available set of
/// measurement commands and on-chip algorithms. This so called feature set
/// version number can be read out with this method.
pub fn get_feature_set(&mut self) -> nb::Result<FeatureSet, Error<E>> {
// Send command to sensor
// Max duration according to datasheet (Table 10)
self.delay.delay_ms(2);
// Read result
let mut buf = [0; 3];
Ok(FeatureSet::parse(buf[0], buf[1]))
}
}
#[cfg(test)]
mod tests {
extern crate embedded_hal_mock as hal;
// use super::*;
use embedded_hal::serial::{Read, Write};
use embedded_hal_mock::serial::{
Mock as SerialMock,Transaction as SerialTransaction,
};
// use self::hal::delay::MockNoop as DelayMock;
/// Test the crc8 function against the test value provided in the
/// datasheet (section 6.6).
#[test]
fn crc8_test_value() {
// assert_eq!(crc8(&[0xbe, 0xef]), 0x92);
}
/// Test the `validate_crc` function.
#[test]
fn measure_test() {
let expectations = [
SerialTransaction::read(0x0A),
SerialTransaction::read_many(b"xy"),
SerialTransaction::write_many([1, 2]), // (1)
SerialTransaction::flush(),
];
let mut serial = SerialMock::new(&expectations);
// Expect three reads
assert_eq!(serial.read().unwrap(), 0x0A);
assert_eq!(serial.read().unwrap(), b'x');
assert_eq!(serial.read().unwrap(), b'y');
}
}
| 34.453608 | 173 | 0.618193 |
eb9f68ccbc74b3567d0bbd35a7ff9d676aa95a84
| 6,437 |
use crate::Error;
#[cfg(unix)]
use notify::{raw_watcher, Op, RawEvent, RecommendedWatcher, RecursiveMode, Watcher};
use std::{path::PathBuf, time::Duration};
#[cfg(unix)]
use std::{
sync::mpsc::{channel, Receiver},
thread,
};
/// Per notify own documentation, it's advised to have delay of more than 30 sec,
/// so to avoid receiving repetitions of previous events on macOS.
///
/// But, config and topology reload logic can handle:
/// - Invalid config, caused either by user or by data race.
/// - Frequent changes, caused by user/editor modifying/saving file in small chunks.
/// so we can use smaller, more responsive delay.
pub const CONFIG_WATCH_DELAY: std::time::Duration = std::time::Duration::from_secs(1);
#[cfg(unix)]
const RETRY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// Triggers SIGHUP when file on config_path changes.
/// Accumulates file changes until no change for given duration has occured.
/// Has best effort guarante of detecting all file changes from the end of
/// this function until the main thread stops.
#[cfg(unix)]
pub fn config_watcher(config_paths: Vec<PathBuf>, delay: Duration) -> Result<(), Error> {
// Create watcher now so not to miss any changes happening between
// returning from this function and the thread starting.
let mut watcher = Some(create_watcher(&config_paths)?);
info!("Watching configuration files.");
thread::spawn(move || loop {
if let Some((mut watcher, receiver)) = watcher.take() {
while let Ok(RawEvent { op: Ok(event), .. }) = receiver.recv() {
if event.intersects(Op::CREATE | Op::REMOVE | Op::WRITE | Op::CLOSE_WRITE) {
debug!(message = "Configuration file change detected.", ?event);
// Consume events until delay amount of time has passed since the latest event.
while let Ok(..) = receiver.recv_timeout(delay) {}
// We need to readd paths to resolve any inode changes that may have happened.
// And we need to do it before raising sighup to avoid missing any change.
if let Err(error) = add_paths(&mut watcher, &config_paths) {
error!(message = "Failed to readd files to watch.", ?error);
break;
}
info!("Configuration file changed.");
raise_sighup();
} else {
debug!(message = "Ignoring event.", ?event)
}
}
}
thread::sleep(RETRY_TIMEOUT);
watcher = create_watcher(&config_paths)
.map_err(|error| error!(message = "Failed to create file watcher.", ?error))
.ok();
if watcher.is_some() {
// Config files could have changed while we weren't watching,
// so for a good measure raise SIGHUP and let reload logic
// determine if anything changed.
info!("Speculating that configuration files have changed.");
raise_sighup();
}
});
Ok(())
}
#[cfg(windows)]
/// Errors on Windows.
pub fn config_watcher(_config_paths: Vec<PathBuf>, _delay: Duration) -> Result<(), Error> {
Err("Reloading config on Windows isn't currently supported. Related issue https://github.com/timberio/vector/issues/938 .".into())
}
#[cfg(unix)]
fn raise_sighup() {
use nix::sys::signal;
let _ = signal::raise(signal::Signal::SIGHUP).map_err(|error| {
error!(message = "Unable to reload configuration file. Restart Vector to reload it.", cause = ?error)
});
}
#[cfg(unix)]
fn create_watcher(
config_paths: &Vec<PathBuf>,
) -> Result<(RecommendedWatcher, Receiver<RawEvent>), Error> {
info!("Creating configuration file watcher.");
let (sender, receiver) = channel();
let mut watcher = raw_watcher(sender)?;
add_paths(&mut watcher, config_paths)?;
Ok((watcher, receiver))
}
#[cfg(unix)]
fn add_paths(watcher: &mut RecommendedWatcher, config_paths: &Vec<PathBuf>) -> Result<(), Error> {
for path in config_paths {
watcher.watch(path, RecursiveMode::NonRecursive)?;
}
Ok(())
}
#[cfg(unix)]
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::{runtime, temp_file};
use futures01::future;
use futures01::{Future, Stream};
use std::time::{Duration, Instant};
use std::{fs::File, io::Write};
use tokio::timer::Delay;
#[cfg(unix)]
use tokio_signal::unix::{Signal, SIGHUP};
fn test(file: &mut File, timeout: Duration) -> bool {
file.write_all(&[0]).unwrap();
std::mem::drop(file);
let mut rt = runtime();
let signal = Signal::new(SIGHUP).flatten_stream();
let result = rt
.block_on(
signal
.into_future()
.select2(Delay::new(Instant::now() + timeout)),
)
.ok()
.unwrap();
match result {
future::Either::A(_) => true, //OK
future::Either::B(_) => false,
}
}
#[test]
fn file_update() {
crate::test_util::trace_init();
let delay = Duration::from_secs(1);
let file_path = temp_file();
let mut file = File::create(&file_path).unwrap();
let _ = config_watcher(vec![file_path], delay).unwrap();
if !test(&mut file, delay * 5) {
panic!("Test timed out");
}
}
#[test]
fn multi_file_update() {
crate::test_util::trace_init();
let delay = Duration::from_secs(1);
let file_path = temp_file();
let mut file = File::create(&file_path).unwrap();
let _ = config_watcher(vec![file_path], delay).unwrap();
for i in 0..3 {
if !test(&mut file, delay * 5) {
panic!("Test timed out on {}. update", i + 1);
}
}
}
#[test]
fn sym_file_update() {
crate::test_util::trace_init();
let delay = Duration::from_secs(1);
let file_path = temp_file();
let sym_file = temp_file();
let mut file = File::create(&file_path).unwrap();
std::os::unix::fs::symlink(&file_path, &sym_file).unwrap();
let _ = config_watcher(vec![sym_file], delay).unwrap();
if !test(&mut file, delay * 5) {
panic!("Test timed out");
}
}
}
| 33.701571 | 134 | 0.587075 |
3aaad130e0c987850af5d18dcaf59a5a9a800a6f
| 5,779 |
//! Useful comparison functions.
/// Compare two slices for equality in fixed time. Panics if the slices are of non-equal length.
///
/// This works by XOR'ing each byte of the two inputs together and keeping an OR counter of the
/// results.
///
/// Instead of doing fancy bit twiddling to try to outsmart the compiler and prevent early exits,
/// which is not guaranteed to remain stable as compilers get ever smarter, we take the hit of
/// writing each intermediate value to memory with a volatile write and then re-reading it with a
/// volatile read. This should remain stable across compiler upgrades, but is much slower.
///
/// As of rust 1.31.0 disassembly looks completely within reason for this, see
/// <https://godbolt.org/z/mMbGQv>.
pub fn fixed_time_eq(a: &[u8], b: &[u8]) -> bool {
assert!(a.len() == b.len());
let count = a.len();
let lhs = &a[..count];
let rhs = &b[..count];
let mut r: u8 = 0;
for i in 0..count {
let mut rs = unsafe { ::core::ptr::read_volatile(&r) };
rs |= lhs[i] ^ rhs[i];
unsafe { ::core::ptr::write_volatile(&mut r, rs); }
}
{
let mut t = unsafe { ::core::ptr::read_volatile(&r) };
t |= t >> 4;
unsafe { ::core::ptr::write_volatile(&mut r, t); }
}
{
let mut t = unsafe { ::core::ptr::read_volatile(&r) };
t |= t >> 2;
unsafe { ::core::ptr::write_volatile(&mut r, t); }
}
{
let mut t = unsafe { ::core::ptr::read_volatile(&r) };
t |= t >> 1;
unsafe { ::core::ptr::write_volatile(&mut r, t); }
}
unsafe { (::core::ptr::read_volatile(&r) & 1) == 0 }
}
#[test]
fn eq_test() {
assert!(fixed_time_eq(&[0b00000000], &[0b00000000]));
assert!(fixed_time_eq(&[0b00000001], &[0b00000001]));
assert!(fixed_time_eq(&[0b00000010], &[0b00000010]));
assert!(fixed_time_eq(&[0b00000100], &[0b00000100]));
assert!(fixed_time_eq(&[0b00001000], &[0b00001000]));
assert!(fixed_time_eq(&[0b00010000], &[0b00010000]));
assert!(fixed_time_eq(&[0b00100000], &[0b00100000]));
assert!(fixed_time_eq(&[0b01000000], &[0b01000000]));
assert!(fixed_time_eq(&[0b10000000], &[0b10000000]));
assert!(fixed_time_eq(&[0b11111111], &[0b11111111]));
assert!(!fixed_time_eq(&[0b00000001], &[0b00000000]));
assert!(!fixed_time_eq(&[0b00000001], &[0b11111111]));
assert!(!fixed_time_eq(&[0b00000010], &[0b00000000]));
assert!(!fixed_time_eq(&[0b00000010], &[0b11111111]));
assert!(!fixed_time_eq(&[0b00000100], &[0b00000000]));
assert!(!fixed_time_eq(&[0b00000100], &[0b11111111]));
assert!(!fixed_time_eq(&[0b00001000], &[0b00000000]));
assert!(!fixed_time_eq(&[0b00001000], &[0b11111111]));
assert!(!fixed_time_eq(&[0b00010000], &[0b00000000]));
assert!(!fixed_time_eq(&[0b00010000], &[0b11111111]));
assert!(!fixed_time_eq(&[0b00100000], &[0b00000000]));
assert!(!fixed_time_eq(&[0b00100000], &[0b11111111]));
assert!(!fixed_time_eq(&[0b01000000], &[0b00000000]));
assert!(!fixed_time_eq(&[0b01000000], &[0b11111111]));
assert!(!fixed_time_eq(&[0b10000000], &[0b00000000]));
assert!(!fixed_time_eq(&[0b10000000], &[0b11111111]));
assert!( fixed_time_eq(&[0b00000000, 0b00000000], &[0b00000000, 0b00000000]));
assert!(!fixed_time_eq(&[0b00000001, 0b00000000], &[0b00000000, 0b00000000]));
assert!(!fixed_time_eq(&[0b00000000, 0b00000001], &[0b00000000, 0b00000000]));
assert!(!fixed_time_eq(&[0b00000000, 0b00000000], &[0b00000001, 0b00000000]));
assert!(!fixed_time_eq(&[0b00000000, 0b00000000], &[0b00000001, 0b00000001]));
}
#[cfg(all(test, feature = "unstable"))]
mod benches {
use test::Bencher;
use sha256;
use sha512;
use Hash;
use cmp::fixed_time_eq;
#[bench]
fn bench_32b_constant_time_cmp_ne(bh: &mut Bencher) {
let hash_a = sha256::Hash::hash(&[0; 1]);
let hash_b = sha256::Hash::hash(&[1; 1]);
bh.iter(|| {
fixed_time_eq(&hash_a[..], &hash_b[..])
})
}
#[bench]
fn bench_32b_slice_cmp_ne(bh: &mut Bencher) {
let hash_a = sha256::Hash::hash(&[0; 1]);
let hash_b = sha256::Hash::hash(&[1; 1]);
bh.iter(|| {
&hash_a[..] == &hash_b[..]
})
}
#[bench]
fn bench_32b_constant_time_cmp_eq(bh: &mut Bencher) {
let hash_a = sha256::Hash::hash(&[0; 1]);
let hash_b = sha256::Hash::hash(&[0; 1]);
bh.iter(|| {
fixed_time_eq(&hash_a[..], &hash_b[..])
})
}
#[bench]
fn bench_32b_slice_cmp_eq(bh: &mut Bencher) {
let hash_a = sha256::Hash::hash(&[0; 1]);
let hash_b = sha256::Hash::hash(&[0; 1]);
bh.iter(|| {
&hash_a[..] == &hash_b[..]
})
}
#[bench]
fn bench_64b_constant_time_cmp_ne(bh: &mut Bencher) {
let hash_a = sha512::Hash::hash(&[0; 1]);
let hash_b = sha512::Hash::hash(&[1; 1]);
bh.iter(|| {
fixed_time_eq(&hash_a[..], &hash_b[..])
})
}
#[bench]
fn bench_64b_slice_cmp_ne(bh: &mut Bencher) {
let hash_a = sha512::Hash::hash(&[0; 1]);
let hash_b = sha512::Hash::hash(&[1; 1]);
bh.iter(|| {
&hash_a[..] == &hash_b[..]
})
}
#[bench]
fn bench_64b_constant_time_cmp_eq(bh: &mut Bencher) {
let hash_a = sha512::Hash::hash(&[0; 1]);
let hash_b = sha512::Hash::hash(&[0; 1]);
bh.iter(|| {
fixed_time_eq(&hash_a[..], &hash_b[..])
})
}
#[bench]
fn bench_64b_slice_cmp_eq(bh: &mut Bencher) {
let hash_a = sha512::Hash::hash(&[0; 1]);
let hash_b = sha512::Hash::hash(&[0; 1]);
bh.iter(|| {
&hash_a[..] == &hash_b[..]
})
}
}
| 35.453988 | 97 | 0.578647 |
091857e13bdf181b84ec80b8c7aef26cae2a19f2
| 455 |
use criterion::{criterion_group, criterion_main, Criterion};
use std::path::PathBuf;
use treefmt::config;
pub fn bench_group(c: &mut Criterion) {
c.bench_function("parse config", |b| {
b.iter(|| {
let treefmt_toml = PathBuf::from("./treefmt.toml");
let root = config::from_path(&treefmt_toml);
assert!(root.is_ok());
})
});
}
criterion_group!(benches, bench_group);
criterion_main!(benches);
| 25.277778 | 63 | 0.624176 |
8f70d3d8d44947f57e5f11b31326126254d40457
| 1,285 |
use bio::io::fasta;
use bio::io::fasta::Record;
use std::collections::HashMap;
use std::path::PathBuf;
use std::str;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
pub struct Opts {
/// Path to input fasta file.
#[structopt(short, long, parse(from_os_str))]
infile: PathBuf,
}
fn format_header(rec: &Record) -> String {
match rec.desc() {
Some(desc) => format!(">{} {}", rec.id(), desc),
None => rec.id().to_string(),
}
}
/// We start with the simplest possible way to do this. Just hash the record and store it.
pub fn run(opts: Opts) {
let mut records = HashMap::new();
let reader = fasta::Reader::from_file(opts.infile).expect("couldn't read input file");
let mut total_duplicates = 0;
for item in reader.records() {
let record = item.unwrap();
// Doing it this way will keep the headers further down in the file.
match records.insert(
str::from_utf8(record.seq()).unwrap().to_ascii_uppercase(),
format_header(&record),
) {
None => (),
Some(_) => total_duplicates += 1,
}
}
eprintln!("Total duplicates: {}", total_duplicates);
for (seq, header) in records.iter() {
println!("{}\n{}", header, seq);
}
}
| 26.770833 | 91 | 0.593774 |
716afee33e7520d2eb9e39d0a8dc6dbaf4447296
| 31,487 |
/*
* Copyright (C) 2015 Benjamin Fry <[email protected]>
*
* 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.
*/
//! Basic protocol message for DNS
use std::iter;
use std::mem;
use std::ops::Deref;
use std::sync::Arc;
use super::{Edns, Header, MessageType, OpCode, Query, ResponseCode};
use crate::error::*;
use crate::rr::{Record, RecordType};
use crate::serialize::binary::{BinDecodable, BinDecoder, BinEncodable, BinEncoder, EncodeMode};
#[cfg(feature = "dnssec")]
use crate::rr::dnssec::rdata::DNSSECRecordType;
/// The basic request and response datastructure, used for all DNS protocols.
///
/// [RFC 1035, DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION, November 1987](https://tools.ietf.org/html/rfc1035)
///
/// ```text
/// 4.1. Format
///
/// All communications inside of the domain protocol are carried in a single
/// format called a message. The top level format of message is divided
/// into 5 sections (some of which are empty in certain cases) shown below:
///
/// +--------------------------+
/// | Header |
/// +--------------------------+
/// | Question / Zone | the question for the name server
/// +--------------------------+
/// | Answer / Prerequisite | RRs answering the question
/// +--------------------------+
/// | Authority / Update | RRs pointing toward an authority
/// +--------------------------+
/// | Additional | RRs holding additional information
/// +--------------------------+
///
/// The header section is always present. The header includes fields that
/// specify which of the remaining sections are present, and also specify
/// whether the message is a query or a response, a standard query or some
/// other opcode, etc.
///
/// The names of the sections after the header are derived from their use in
/// standard queries. The question section contains fields that describe a
/// question to a name server. These fields are a query type (QTYPE), a
/// query class (QCLASS), and a query domain name (QNAME). The last three
/// sections have the same format: a possibly empty list of concatenated
/// resource records (RRs). The answer section contains RRs that answer the
/// question; the authority section contains RRs that point toward an
/// authoritative name server; the additional records section contains RRs
/// which relate to the query, but are not strictly answers for the
/// question.
/// ```
///
/// By default Message is a Query. Use the Message::as_update() to create and update, or
/// Message::new_update()
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Message {
header: Header,
queries: Vec<Query>,
answers: Vec<Record>,
name_servers: Vec<Record>,
additionals: Vec<Record>,
sig0: Vec<Record>,
edns: Option<Edns>,
}
/// Returns a new Header with accurate counts for each Message section
pub fn update_header_counts(
current_header: &Header,
is_truncated: bool,
counts: HeaderCounts,
) -> Header {
assert!(counts.query_count <= u16::max_value() as usize);
assert!(counts.answer_count <= u16::max_value() as usize);
assert!(counts.nameserver_count <= u16::max_value() as usize);
assert!(counts.additional_count <= u16::max_value() as usize);
let mut header = current_header.clone();
header.set_query_count(counts.query_count as u16);
header.set_answer_count(counts.answer_count as u16);
header.set_name_server_count(counts.nameserver_count as u16);
header.set_additional_count(counts.additional_count as u16);
header.set_truncated(is_truncated);
header
}
/// Tracks the counts of the records in the Message.
///
/// This is only used internally during serialization.
pub struct HeaderCounts {
/// The number of queries in the Message
pub query_count: usize,
/// The number of answers in the Message
pub answer_count: usize,
/// The number of nameservers or authorities in the Message
pub nameserver_count: usize,
/// The number of additional records in the Message
pub additional_count: usize,
}
impl Message {
/// Returns a new "empty" Message
pub fn new() -> Self {
Message {
header: Header::new(),
queries: Vec::new(),
answers: Vec::new(),
name_servers: Vec::new(),
additionals: Vec::new(),
sig0: Vec::new(),
edns: None,
}
}
/// Returns a Message constructed with error details to return to a client
///
/// # Arguments
///
/// * `id` - message id should match the request message id
/// * `op_code` - operation of the request
/// * `response_code` - the error code for the response
pub fn error_msg(id: u16, op_code: OpCode, response_code: ResponseCode) -> Message {
let mut message: Message = Message::new();
message.set_message_type(MessageType::Response);
message.set_id(id);
message.set_response_code(response_code);
message.set_op_code(op_code);
message
}
/// Truncates a Message, this blindly removes all response fields and sets truncated to `true`
pub fn truncate(&self) -> Self {
let mut truncated: Message = Message::new();
truncated.set_id(self.id());
truncated.set_message_type(self.message_type());
truncated.set_op_code(self.op_code());
truncated.set_authoritative(self.authoritative());
truncated.set_truncated(true);
truncated.set_recursion_desired(self.recursion_desired());
truncated.set_recursion_available(self.recursion_available());
truncated.set_response_code(self.response_code());
if self.edns().is_some() {
truncated.set_edns(self.edns().unwrap().clone());
}
// TODO, perhaps just quickly add a few response records here? that we know would fit?
truncated
}
/// see `Header::set_id`
pub fn set_id(&mut self, id: u16) -> &mut Self {
self.header.set_id(id);
self
}
/// see `Header::set_message_type`
pub fn set_message_type(&mut self, message_type: MessageType) -> &mut Self {
self.header.set_message_type(message_type);
self
}
/// see `Header::set_op_code`
pub fn set_op_code(&mut self, op_code: OpCode) -> &mut Self {
self.header.set_op_code(op_code);
self
}
/// see `Header::set_authoritative`
pub fn set_authoritative(&mut self, authoritative: bool) -> &mut Self {
self.header.set_authoritative(authoritative);
self
}
/// see `Header::set_truncated`
pub fn set_truncated(&mut self, truncated: bool) -> &mut Self {
self.header.set_truncated(truncated);
self
}
/// see `Header::set_recursion_desired`
pub fn set_recursion_desired(&mut self, recursion_desired: bool) -> &mut Self {
self.header.set_recursion_desired(recursion_desired);
self
}
/// see `Header::set_recursion_available`
pub fn set_recursion_available(&mut self, recursion_available: bool) -> &mut Self {
self.header.set_recursion_available(recursion_available);
self
}
/// see `Header::set_authentic_data`
pub fn set_authentic_data(&mut self, authentic_data: bool) -> &mut Self {
self.header.set_authentic_data(authentic_data);
self
}
/// see `Header::set_checking_disabled`
pub fn set_checking_disabled(&mut self, checking_disabled: bool) -> &mut Self {
self.header.set_checking_disabled(checking_disabled);
self
}
/// see `Header::set_response_code`
pub fn set_response_code(&mut self, response_code: ResponseCode) -> &mut Self {
self.header.set_response_code(response_code);
self
}
/// Add a query to the Message, either the query response from the server, or the request Query.
pub fn add_query(&mut self, query: Query) -> &mut Self {
self.queries.push(query);
self
}
/// Adds an iterator over a set of Queries to be added to the message
pub fn add_queries<Q, I>(&mut self, queries: Q) -> &mut Self
where
Q: IntoIterator<Item = Query, IntoIter = I>,
I: Iterator<Item = Query>,
{
for query in queries {
self.add_query(query);
}
self
}
/// Add an answer to the Message
pub fn add_answer(&mut self, record: Record) -> &mut Self {
self.answers.push(record);
self
}
/// Add all the records from the iterator to the answers section of the Message
pub fn add_answers<R, I>(&mut self, records: R) -> &mut Self
where
R: IntoIterator<Item = Record, IntoIter = I>,
I: Iterator<Item = Record>,
{
for record in records {
self.add_answer(record);
}
self
}
/// Sets the answers to the specified set of Records.
///
/// # Panics
///
/// Will panic if answer records are already associated to the message.
pub fn insert_answers(&mut self, records: Vec<Record>) {
assert!(self.answers.is_empty());
self.answers = records;
}
/// Add a name server record to the Message
pub fn add_name_server(&mut self, record: Record) -> &mut Self {
self.name_servers.push(record);
self
}
/// Add all the records in the Iterator to the name server section of the message
pub fn add_name_servers<R, I>(&mut self, records: R) -> &mut Self
where
R: IntoIterator<Item = Record, IntoIter = I>,
I: Iterator<Item = Record>,
{
for record in records {
self.add_name_server(record);
}
self
}
/// Sets the name_servers to the specified set of Records.
///
/// # Panics
///
/// Will panic if name_servers records are already associated to the message.
pub fn insert_name_servers(&mut self, records: Vec<Record>) {
assert!(self.name_servers.is_empty());
self.name_servers = records;
}
/// Add an additional Record to the message
pub fn add_additional(&mut self, record: Record) -> &mut Self {
self.additionals.push(record);
self
}
/// Sets the additional to the specified set of Records.
///
/// # Panics
///
/// Will panic if additional records are already associated to the message.
pub fn insert_additionals(&mut self, records: Vec<Record>) {
assert!(self.additionals.is_empty());
self.additionals = records;
}
/// Add the EDNS section to the Message
pub fn set_edns(&mut self, edns: Edns) -> &mut Self {
self.edns = Some(edns);
self
}
/// Add a SIG0 record, i.e. sign this message
///
/// This must be don't only after all records have been associated. Generally this will be handled by the client and not need to be used directly
#[cfg(feature = "dnssec")]
pub fn add_sig0(&mut self, record: Record) -> &mut Self {
assert_eq!(RecordType::DNSSEC(DNSSECRecordType::SIG), record.rr_type());
self.sig0.push(record);
self
}
/// Gets the header of the Message
pub fn header(&self) -> &Header {
&self.header
}
/// see `Header::id()`
pub fn id(&self) -> u16 {
self.header.id()
}
/// see `Header::message_type()`
pub fn message_type(&self) -> MessageType {
self.header.message_type()
}
/// see `Header::op_code()`
pub fn op_code(&self) -> OpCode {
self.header.op_code()
}
/// see `Header::authoritative()`
pub fn authoritative(&self) -> bool {
self.header.authoritative()
}
/// see `Header::truncated()`
pub fn truncated(&self) -> bool {
self.header.truncated()
}
/// see `Header::recursion_desired()`
pub fn recursion_desired(&self) -> bool {
self.header.recursion_desired()
}
/// see `Header::recursion_available()`
pub fn recursion_available(&self) -> bool {
self.header.recursion_available()
}
/// see `Header::authentic_data()`
pub fn authentic_data(&self) -> bool {
self.header.authentic_data()
}
/// see `Header::checking_disabled()`
pub fn checking_disabled(&self) -> bool {
self.header.checking_disabled()
}
/// # Return value
///
/// The `ResponseCode`, if this is an EDNS message then this will join the section from the OPT
/// record to create the EDNS `ResponseCode`
pub fn response_code(&self) -> ResponseCode {
ResponseCode::from(
self.edns.as_ref().map_or(0, Edns::rcode_high),
self.header.response_code(),
)
}
/// ```text
/// Question Carries the query name and other query parameters.
/// ```
pub fn queries(&self) -> &[Query] {
&self.queries
}
/// ```text
/// Answer Carries RRs which directly answer the query.
/// ```
pub fn answers(&self) -> &[Record] {
&self.answers
}
/// Removes all the answers from the Message
pub fn take_answers(&mut self) -> Vec<Record> {
mem::replace(&mut self.answers, vec![])
}
/// ```text
/// Authority Carries RRs which describe other authoritative servers.
/// May optionally carry the SOA RR for the authoritative
/// data in the answer section.
/// ```
pub fn name_servers(&self) -> &[Record] {
&self.name_servers
}
/// Remove the name servers from the Message
pub fn take_name_servers(&mut self) -> Vec<Record> {
mem::replace(&mut self.name_servers, vec![])
}
/// ```text
/// Additional Carries RRs which may be helpful in using the RRs in the
/// other sections.
/// ```
pub fn additionals(&self) -> &[Record] {
&self.additionals
}
/// Remove the additional Records from the Message
pub fn take_additionals(&mut self) -> Vec<Record> {
mem::replace(&mut self.additionals, vec![])
}
/// [RFC 6891, EDNS(0) Extensions, April 2013](https://tools.ietf.org/html/rfc6891#section-6.1.1)
///
/// ```text
/// 6.1.1. Basic Elements
///
/// An OPT pseudo-RR (sometimes called a meta-RR) MAY be added to the
/// additional data section of a request.
///
/// The OPT RR has RR type 41.
///
/// If an OPT record is present in a received request, compliant
/// responders MUST include an OPT record in their respective responses.
///
/// An OPT record does not carry any DNS data. It is used only to
/// contain control information pertaining to the question-and-answer
/// sequence of a specific transaction. OPT RRs MUST NOT be cached,
/// forwarded, or stored in or loaded from master files.
///
/// The OPT RR MAY be placed anywhere within the additional data section.
/// When an OPT RR is included within any DNS message, it MUST be the
/// only OPT RR in that message. If a query message with more than one
/// OPT RR is received, a FORMERR (RCODE=1) MUST be returned. The
/// placement flexibility for the OPT RR does not override the need for
/// the TSIG or SIG(0) RRs to be the last in the additional section
/// whenever they are present.
/// ```
/// # Return value
///
/// Returns the EDNS record if it was found in the additional section.
pub fn edns(&self) -> Option<&Edns> {
self.edns.as_ref()
}
/// If edns is_none, this will create a new default Edns.
pub fn edns_mut(&mut self) -> &mut Edns {
if self.edns.is_none() {
self.edns = Some(Edns::new());
}
self.edns.as_mut().unwrap()
}
/// # Return value
///
/// the max payload value as it's defined in the EDNS section.
pub fn max_payload(&self) -> u16 {
let max_size = self.edns.as_ref().map_or(512, Edns::max_payload);
if max_size < 512 {
512
} else {
max_size
}
}
/// # Return value
///
/// the version as defined in the EDNS record
pub fn version(&self) -> u8 {
self.edns.as_ref().map_or(0, Edns::version)
}
/// [RFC 2535, Domain Name System Security Extensions, March 1999](https://tools.ietf.org/html/rfc2535#section-4)
///
/// ```text
/// A DNS request may be optionally signed by including one or more SIGs
/// at the end of the query. Such SIGs are identified by having a "type
/// covered" field of zero. They sign the preceding DNS request message
/// including DNS header but not including the IP header or any request
/// SIGs at the end and before the request RR counts have been adjusted
/// for the inclusions of any request SIG(s).
/// ```
///
/// # Return value
///
/// The sig0, i.e. signed record, for verifying the sending and package integrity
pub fn sig0(&self) -> &[Record] {
&self.sig0
}
// TODO: only necessary in tests, should it be removed?
/// this is necessary to match the counts in the header from the record sections
/// this happens implicitly on write_to, so no need to call before write_to
#[cfg(test)]
pub fn update_counts(&mut self) -> &mut Self {
self.header = update_header_counts(
&self.header,
false,
HeaderCounts {
query_count: self.queries.len(),
answer_count: self.answers.len(),
nameserver_count: self.name_servers.len(),
additional_count: self.additionals.len(),
},
);
self
}
/// Attempts to read the specified number of `Query`s
pub fn read_queries(decoder: &mut BinDecoder, count: usize) -> ProtoResult<Vec<Query>> {
let mut queries = Vec::with_capacity(count);
for _ in 0..count {
queries.push(Query::read(decoder)?);
}
Ok(queries)
}
/// Attempts to read the specified number of records
///
/// # Returns
///
/// This returns a tuple of first standard Records, then a possibly associated Edns, and then finally any optionally associated SIG0 records.
#[cfg_attr(not(feature = "dnssec"), allow(unused_mut))]
pub fn read_records(
decoder: &mut BinDecoder,
count: usize,
is_additional: bool,
) -> ProtoResult<(Vec<Record>, Option<Edns>, Vec<Record>)> {
let mut records: Vec<Record> = Vec::with_capacity(count);
let mut edns: Option<Edns> = None;
let mut sig0s: Vec<Record> = Vec::with_capacity(if is_additional { 1 } else { 0 });
// sig0 must be last, once this is set, disable.
let mut saw_sig0 = false;
for _ in 0..count {
let record = Record::read(decoder)?;
if !is_additional {
if saw_sig0 {
return Err("sig0 must be final resource record".into());
} // SIG0 must be last
records.push(record)
} else {
match record.rr_type() {
#[cfg(feature = "dnssec")]
RecordType::DNSSEC(DNSSECRecordType::SIG) => {
saw_sig0 = true;
sig0s.push(record);
}
RecordType::OPT => {
if saw_sig0 {
return Err("sig0 must be final resource record".into());
} // SIG0 must be last
if edns.is_some() {
return Err("more than one edns record present".into());
}
edns = Some((&record).into());
}
_ => {
if saw_sig0 {
return Err("sig0 must be final resource record".into());
} // SIG0 must be last
records.push(record);
}
}
}
}
Ok((records, edns, sig0s))
}
/// Decodes a message from the buffer.
pub fn from_vec(buffer: &[u8]) -> ProtoResult<Message> {
let mut decoder = BinDecoder::new(buffer);
Message::read(&mut decoder)
}
/// Encodes the Message into a buffer
pub fn to_vec(&self) -> Result<Vec<u8>, ProtoError> {
// TODO: this feels like the right place to verify the max packet size of the message,
// will need to update the header for truncation and the lengths if we send less than the
// full response. This needs to conform with the EDNS settings of the server...
let mut buffer = Vec::with_capacity(512);
{
let mut encoder = BinEncoder::new(&mut buffer);
self.emit(&mut encoder)?;
}
Ok(buffer)
}
/// Finalize the message prior to sending.
///
/// Subsequent to calling this, the Message should not change.
pub fn finalize<MF: MessageFinalizer>(
&mut self,
finalizer: &MF,
inception_time: u32,
) -> ProtoResult<()> {
debug!("finalizing message: {:?}", self);
let finals: Vec<Record> = finalizer.finalize_message(self, inception_time)?;
// append all records to message
for fin in finals {
match fin.rr_type() {
// SIG0's are special, and come at the very end of the message
#[cfg(feature = "dnssec")]
RecordType::DNSSEC(DNSSECRecordType::SIG) => self.add_sig0(fin),
_ => self.add_additional(fin),
};
}
Ok(())
}
}
impl Deref for Message {
type Target = Header;
fn deref(&self) -> &Self::Target {
&self.header
}
}
/// A trait for performing final amendments to a Message before it is sent.
///
/// An example of this is a SIG0 signer, which needs the final form of the message,
/// but then needs to attach additional data to the body of the message.
pub trait MessageFinalizer: Send + Sync + 'static {
/// The message taken in should be processed and then return [`Record`]s which should be
/// appended to the additional section of the message.
///
/// # Arguments
///
/// * `message` - message to process
/// * `current_time` - the current time as specified by the system, it's not recommended to read the current time as that makes testing complicated.
///
/// # Return
///
/// A vector to append to the additionals section of the message, sorted in the order as they should appear in the message.
fn finalize_message(&self, message: &Message, current_time: u32) -> ProtoResult<Vec<Record>>;
}
/// A MessageFinalizer which does nothing
///
/// *WARNING* This should only be used in None context, it will panic in all cases where finalize is called.
pub struct NoopMessageFinalizer;
impl NoopMessageFinalizer {
/// Always returns None
pub fn new() -> Option<Arc<Self>> {
None
}
}
impl MessageFinalizer for NoopMessageFinalizer {
fn finalize_message(&self, _: &Message, _: u32) -> ProtoResult<Vec<Record>> {
panic!("Misused NoopMessageFinalizer, None should be used instead")
}
}
/// Returns the count written and a boolean if it was truncated
pub fn count_was_truncated(result: ProtoResult<usize>) -> ProtoResult<(usize, bool)> {
result.map(|count| (count, false)).or_else(|e| {
if let ProtoErrorKind::NotAllRecordsWritten { count } = e.kind() {
return Ok((*count, true));
}
Err(e)
})
}
/// A trait that defines types which can be emitted as a set, with the associated count returned.
pub trait EmitAndCount {
/// Emit self to the encoder and return the count of items
fn emit(&mut self, encoder: &mut BinEncoder) -> ProtoResult<usize>;
}
impl<'e, I: Iterator<Item = &'e E>, E: 'e + BinEncodable> EmitAndCount for I {
fn emit(&mut self, encoder: &mut BinEncoder) -> ProtoResult<usize> {
encoder.emit_all(self)
}
}
/// Emits the different sections of a message properly
#[allow(clippy::too_many_arguments)]
pub fn emit_message_parts<Q, A, N, D>(
header: &Header,
queries: &mut Q,
answers: &mut A,
name_servers: &mut N,
additionals: &mut D,
edns: Option<&Edns>,
sig0: &[Record],
encoder: &mut BinEncoder,
) -> ProtoResult<()>
where
Q: EmitAndCount,
A: EmitAndCount,
N: EmitAndCount,
D: EmitAndCount,
{
let include_sig0: bool = encoder.mode() != EncodeMode::Signing;
let place = encoder.place::<Header>()?;
let query_count = queries.emit(encoder)?;
// TODO: need to do something on max records
// return offset of last emitted record.
let answer_count = count_was_truncated(answers.emit(encoder))?;
let nameserver_count = count_was_truncated(name_servers.emit(encoder))?;
let mut additional_count = count_was_truncated(additionals.emit(encoder))?;
if let Some(edns) = edns {
// need to commit the error code
let count = count_was_truncated(encoder.emit_all(iter::once(&Record::from(edns))))?;
additional_count.0 += count.0;
additional_count.1 |= count.1;
}
// this is a little hacky, but if we are Verifying a signature, i.e. the original Message
// then the SIG0 records should not be encoded and the edns record (if it exists) is already
// part of the additionals section.
if include_sig0 {
let count = count_was_truncated(encoder.emit_all(sig0.iter()))?;
additional_count.0 += count.0;
additional_count.1 |= count.1;
}
let counts = HeaderCounts {
query_count,
answer_count: answer_count.0,
nameserver_count: nameserver_count.0,
additional_count: additional_count.0,
};
let was_truncated = answer_count.1 || nameserver_count.1 || additional_count.1;
place.replace(encoder, update_header_counts(header, was_truncated, counts))?;
Ok(())
}
impl BinEncodable for Message {
fn emit(&self, encoder: &mut BinEncoder) -> ProtoResult<()> {
emit_message_parts(
&self.header,
&mut self.queries.iter(),
&mut self.answers.iter(),
&mut self.name_servers.iter(),
&mut self.additionals.iter(),
self.edns.as_ref(),
&self.sig0,
encoder,
)
}
}
impl<'r> BinDecodable<'r> for Message {
fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self> {
let header = Header::read(decoder)?;
// TODO/FIXME: return just header, and in the case of the rest of message getting an error.
// this could improve error detection while decoding.
// get the questions
let count = header.query_count() as usize;
let mut queries = Vec::with_capacity(count);
for _ in 0..count {
queries.push(Query::read(decoder)?);
}
// get all counts before header moves
let answer_count = header.answer_count() as usize;
let name_server_count = header.name_server_count() as usize;
let additional_count = header.additional_count() as usize;
let (answers, _, _) = Self::read_records(decoder, answer_count, false)?;
let (name_servers, _, _) = Self::read_records(decoder, name_server_count, false)?;
let (additionals, edns, sig0) = Self::read_records(decoder, additional_count, true)?;
Ok(Message {
header,
queries,
answers,
name_servers,
additionals,
sig0,
edns,
})
}
}
#[test]
fn test_emit_and_read_header() {
let mut message = Message::new();
message
.set_id(10)
.set_message_type(MessageType::Response)
.set_op_code(OpCode::Update)
.set_authoritative(true)
.set_truncated(false)
.set_recursion_desired(true)
.set_recursion_available(true)
.set_response_code(ResponseCode::ServFail);
test_emit_and_read(message);
}
#[test]
fn test_emit_and_read_query() {
let mut message = Message::new();
message
.set_id(10)
.set_message_type(MessageType::Response)
.set_op_code(OpCode::Update)
.set_authoritative(true)
.set_truncated(true)
.set_recursion_desired(true)
.set_recursion_available(true)
.set_response_code(ResponseCode::ServFail)
.add_query(Query::new())
.update_counts(); // we're not testing the query parsing, just message
test_emit_and_read(message);
}
#[test]
fn test_emit_and_read_records() {
let mut message = Message::new();
message
.set_id(10)
.set_message_type(MessageType::Response)
.set_op_code(OpCode::Update)
.set_authoritative(true)
.set_truncated(true)
.set_recursion_desired(true)
.set_recursion_available(true)
.set_authentic_data(true)
.set_checking_disabled(true)
.set_response_code(ResponseCode::ServFail);
message.add_answer(Record::new());
message.add_name_server(Record::new());
message.add_additional(Record::new());
message.update_counts(); // needed for the comparison...
test_emit_and_read(message);
}
#[cfg(test)]
fn test_emit_and_read(message: Message) {
let mut byte_vec: Vec<u8> = Vec::with_capacity(512);
{
let mut encoder = BinEncoder::new(&mut byte_vec);
message.emit(&mut encoder).unwrap();
}
let mut decoder = BinDecoder::new(&byte_vec);
let got = Message::read(&mut decoder).unwrap();
assert_eq!(got, message);
}
#[test]
#[rustfmt::skip]
fn test_legit_message() {
let buf: Vec<u8> = vec![
0x10,0x00,0x81,0x80, // id = 4096, response, op=query, recursion_desired, recursion_available, no_error
0x00,0x01,0x00,0x01, // 1 query, 1 answer,
0x00,0x00,0x00,0x00, // 0 namesservers, 0 additional record
0x03,b'w',b'w',b'w', // query --- www.example.com
0x07,b'e',b'x',b'a', //
b'm',b'p',b'l',b'e', //
0x03,b'c',b'o',b'm', //
0x00, // 0 = endname
0x00,0x01,0x00,0x01, // ReordType = A, Class = IN
0xC0,0x0C, // name pointer to www.example.com
0x00,0x01,0x00,0x01, // RecordType = A, Class = IN
0x00,0x00,0x00,0x02, // TTL = 2 seconds
0x00,0x04, // record length = 4 (ipv4 address)
0x5D,0xB8,0xD8,0x22, // address = 93.184.216.34
];
let mut decoder = BinDecoder::new(&buf);
let message = Message::read(&mut decoder).unwrap();
assert_eq!(message.id(), 4096);
let mut buf: Vec<u8> = Vec::with_capacity(512);
{
let mut encoder = BinEncoder::new(&mut buf);
message.emit(&mut encoder).unwrap();
}
let mut decoder = BinDecoder::new(&buf);
let message = Message::read(&mut decoder).unwrap();
assert_eq!(message.id(), 4096);
}
| 33.748124 | 152 | 0.610506 |
ffb87f8dbdffa1026e6bd0e6490e682cb4e6b7fc
| 291,922 |
use super::Tab;
use crate::zellij_tile::data::{ModeInfo, Palette};
use crate::{
os_input_output::{AsyncReader, Pid, ServerOsApi},
panes::PaneId,
thread_bus::ThreadSenders,
ClientId,
};
use std::convert::TryInto;
use std::path::PathBuf;
use zellij_utils::input::layout::LayoutTemplate;
use zellij_utils::ipc::IpcReceiverWithContext;
use zellij_utils::pane_size::Size;
use std::os::unix::io::RawFd;
use zellij_utils::nix;
use zellij_utils::{
input::command::TerminalAction,
interprocess::local_socket::LocalSocketStream,
ipc::{ClientToServerMsg, ServerToClientMsg},
};
#[derive(Clone)]
struct FakeInputOutput {}
impl ServerOsApi for FakeInputOutput {
fn set_terminal_size_using_fd(&self, _fd: RawFd, _cols: u16, _rows: u16) {
// noop
}
fn spawn_terminal(
&self,
_file_to_open: TerminalAction,
_quit_cb: Box<dyn Fn(PaneId) + Send>,
) -> (RawFd, RawFd) {
unimplemented!()
}
fn read_from_tty_stdout(&self, _fd: RawFd, _buf: &mut [u8]) -> Result<usize, nix::Error> {
unimplemented!()
}
fn async_file_reader(&self, _fd: RawFd) -> Box<dyn AsyncReader> {
unimplemented!()
}
fn write_to_tty_stdin(&self, _fd: RawFd, _buf: &[u8]) -> Result<usize, nix::Error> {
unimplemented!()
}
fn tcdrain(&self, _fd: RawFd) -> Result<(), nix::Error> {
unimplemented!()
}
fn kill(&self, _pid: Pid) -> Result<(), nix::Error> {
unimplemented!()
}
fn force_kill(&self, _pid: Pid) -> Result<(), nix::Error> {
unimplemented!()
}
fn box_clone(&self) -> Box<dyn ServerOsApi> {
Box::new((*self).clone())
}
fn send_to_client(&self, _client_id: ClientId, _msg: ServerToClientMsg) {
unimplemented!()
}
fn new_client(
&mut self,
_client_id: ClientId,
_stream: LocalSocketStream,
) -> IpcReceiverWithContext<ClientToServerMsg> {
unimplemented!()
}
fn remove_client(&mut self, _client_id: ClientId) {
unimplemented!()
}
fn load_palette(&self) -> Palette {
unimplemented!()
}
fn get_cwd(&self, _pid: Pid) -> Option<PathBuf> {
unimplemented!()
}
}
fn create_new_tab(size: Size) -> Tab {
let index = 0;
let position = 0;
let name = String::new();
let os_api = Box::new(FakeInputOutput {});
let senders = ThreadSenders::default().silently_fail_on_send();
let max_panes = None;
let mode_info = ModeInfo::default();
let colors = Palette::default();
let draw_pane_frames = true;
let client_id = 1;
let mut tab = Tab::new(
index,
position,
name,
size,
os_api,
senders,
max_panes,
mode_info,
colors,
draw_pane_frames,
client_id,
);
tab.apply_layout(
LayoutTemplate::default().try_into().unwrap(),
vec![1],
index,
);
tab
}
#[test]
fn split_panes_vertically() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.vertical_split(new_pane_id);
assert_eq!(tab.panes.len(), 2, "The tab has two panes");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"first pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"first pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
61,
"second pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"second pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"second pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"second pane row count"
);
}
#[test]
fn split_panes_horizontally() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
assert_eq!(tab.panes.len(), 2, "The tab has two panes");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"first pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"first pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"second pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
10,
"second pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"second pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"second pane row count"
);
}
#[test]
fn split_largest_pane() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
for i in 2..5 {
let new_pane_id = PaneId::Terminal(i);
tab.new_pane(new_pane_id);
}
assert_eq!(tab.panes.len(), 4, "The tab has four panes");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"first pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"first pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
61,
"second pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"second pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"second pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"second pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"third pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"third pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"third pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"third pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"fourth pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
10,
"fourth pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"fourth pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"fourth pane row count"
);
}
#[test]
pub fn cannot_split_panes_vertically_when_active_pane_is_too_small() {
let size = Size { cols: 8, rows: 20 };
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
assert_eq!(tab.panes.len(), 1, "Tab still has only one pane");
}
#[test]
pub fn cannot_split_panes_horizontally_when_active_pane_is_too_small() {
let size = Size { cols: 121, rows: 4 };
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
assert_eq!(tab.panes.len(), 1, "Tab still has only one pane");
}
#[test]
pub fn cannot_split_largest_pane_when_there_is_no_room() {
let size = Size { cols: 8, rows: 4 };
let mut tab = create_new_tab(size);
tab.new_pane(PaneId::Terminal(2));
assert_eq!(tab.panes.len(), 1, "Tab still has only one pane");
}
#[test]
pub fn toggle_focused_pane_fullscreen() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
for i in 2..5 {
let new_pane_id = PaneId::Terminal(i);
tab.new_pane(new_pane_id);
}
tab.toggle_active_pane_fullscreen();
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().x(),
0,
"Pane x is on screen edge"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().y(),
0,
"Pane y is on screen edge"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().cols(),
121,
"Pane cols match fullscreen cols"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().rows(),
20,
"Pane rows match fullscreen rows"
);
tab.toggle_active_pane_fullscreen();
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().x(),
61,
"Pane x is on screen edge"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().y(),
10,
"Pane y is on screen edge"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().cols(),
60,
"Pane cols match fullscreen cols"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().rows(),
10,
"Pane rows match fullscreen rows"
);
// we don't test if all other panes are hidden because this logic is done in the render
// function and we already test that in the e2e tests
}
#[test]
pub fn move_focus_is_disabled_in_fullscreen() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
for i in 2..5 {
let new_pane_id = PaneId::Terminal(i);
tab.new_pane(new_pane_id);
}
tab.toggle_active_pane_fullscreen();
tab.move_focus_left();
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().x(),
0,
"Pane x is on screen edge"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().y(),
0,
"Pane y is on screen edge"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().cols(),
121,
"Pane cols match fullscreen cols"
);
assert_eq!(
tab.panes.get(&PaneId::Terminal(4)).unwrap().rows(),
20,
"Pane rows match fullscreen rows"
);
}
#[test]
pub fn close_pane_with_another_pane_above_it() {
// ┌───────────┐ ┌───────────┐
// │xxxxxxxxxxx│ │xxxxxxxxxxx│
// │xxxxxxxxxxx│ │xxxxxxxxxxx│
// ├───────────┤ ==close==> │xxxxxxxxxxx│
// │███████████│ │xxxxxxxxxxx│
// │███████████│ │xxxxxxxxxxx│
// └───────────┘ └───────────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 1, "One pane left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"remaining pane row count"
);
}
#[test]
pub fn close_pane_with_another_pane_below_it() {
// ┌───────────┐ ┌───────────┐
// │███████████│ │xxxxxxxxxxx│
// │███████████│ │xxxxxxxxxxx│
// ├───────────┤ ==close==> │xxxxxxxxxxx│
// │xxxxxxxxxxx│ │xxxxxxxxxxx│
// │xxxxxxxxxxx│ │xxxxxxxxxxx│
// └───────────┘ └───────────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
tab.move_focus_up();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 1, "One pane left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"remaining pane row count"
);
}
#[test]
pub fn close_pane_with_another_pane_to_the_left() {
// ┌─────┬─────┐ ┌──────────┐
// │xxxxx│█████│ │xxxxxxxxxx│
// │xxxxx│█████│ ==close==> │xxxxxxxxxx│
// │xxxxx│█████│ │xxxxxxxxxx│
// └─────┴─────┘ └──────────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.vertical_split(new_pane_id);
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 1, "One pane left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"remaining pane row count"
);
}
#[test]
pub fn close_pane_with_another_pane_to_the_right() {
// ┌─────┬─────┐ ┌──────────┐
// │█████│xxxxx│ │xxxxxxxxxx│
// │█████│xxxxx│ ==close==> │xxxxxxxxxx│
// │█████│xxxxx│ │xxxxxxxxxx│
// └─────┴─────┘ └──────────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.vertical_split(new_pane_id);
tab.move_focus_left();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 1, "One pane left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"remaining pane row count"
);
}
#[test]
pub fn close_pane_with_multiple_panes_above_it() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │xxxxx│xxxxx│ │xxxxx│xxxxx│
// │xxxxx│xxxxx│ │xxxxx│xxxxx│
// ├─────┴─────┤ ==close==> │xxxxx│xxxxx│
// │███████████│ │xxxxx│xxxxx│
// │███████████│ │xxxxx│xxxxx│
// └───────────┘ └─────┴─────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
tab.horizontal_split(new_pane_id_1);
tab.move_focus_up();
tab.vertical_split(new_pane_id_2);
tab.move_focus_down();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 2, "Two panes left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"first remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"first remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"second remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"second remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"second remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"second remaining pane row count"
);
}
#[test]
pub fn close_pane_with_multiple_panes_below_it() {
// ┌───────────┐ ┌─────┬─────┐
// │███████████│ │xxxxx│xxxxx│
// │███████████│ │xxxxx│xxxxx│
// ├─────┬─────┤ ==close==> │xxxxx│xxxxx│
// │xxxxx│xxxxx│ │xxxxx│xxxxx│
// │xxxxx│xxxxx│ │xxxxx│xxxxx│
// └─────┴─────┘ └─────┴─────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
tab.horizontal_split(new_pane_id_1);
tab.vertical_split(new_pane_id_2);
tab.move_focus_up();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 2, "Two panes left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"first remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"first remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"first remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"first remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"second remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"second remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"second remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"second remaining pane row count"
);
}
#[test]
pub fn close_pane_with_multiple_panes_to_the_left() {
// ┌─────┬─────┐ ┌──────────┐
// │xxxxx│█████│ │xxxxxxxxxx│
// │xxxxx│█████│ │xxxxxxxxxx│
// ├─────┤█████│ ==close==> ├──────────┤
// │xxxxx│█████│ │xxxxxxxxxx│
// │xxxxx│█████│ │xxxxxxxxxx│
// └─────┴─────┘ └──────────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
tab.vertical_split(new_pane_id_1);
tab.move_focus_left();
tab.horizontal_split(new_pane_id_2);
tab.move_focus_right();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 2, "Two panes left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"first remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"first remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"second remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"second remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"second remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"second remaining pane row count"
);
}
#[test]
pub fn close_pane_with_multiple_panes_to_the_right() {
// ┌─────┬─────┐ ┌──────────┐
// │█████│xxxxx│ │xxxxxxxxxx│
// │█████│xxxxx│ │xxxxxxxxxx│
// │█████├─────┤ ==close==> ├──────────┤
// │█████│xxxxx│ │xxxxxxxxxx│
// │█████│xxxxx│ │xxxxxxxxxx│
// └─────┴─────┘ └──────────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
tab.vertical_split(new_pane_id_1);
tab.horizontal_split(new_pane_id_2);
tab.move_focus_left();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 2, "Two panes left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"first remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"first remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"first remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"first remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"second remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"second remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"second remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"second remaining pane row count"
);
}
#[test]
pub fn close_pane_with_multiple_panes_above_it_away_from_screen_edges() {
// ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐
// │xxx│xxx│xxx│xxx│ │xxx│xxx│xxx│xxx│
// ├───┤xxx│xxx├───┤ ├───┤xxx│xxx├───┤
// │xxx├───┴───┤xxx│ ==close==> │xxx│xxx│xxx│xxx│
// │xxx│███████│xxx│ │xxx│xxx│xxx│xxx│
// │xxx│███████│xxx│ │xxx│xxx│xxx│xxx│
// └───┴───────┴───┘ └───┴───┴───┴───┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
let new_pane_id_4 = PaneId::Terminal(5);
let new_pane_id_5 = PaneId::Terminal(6);
let new_pane_id_6 = PaneId::Terminal(7);
tab.vertical_split(new_pane_id_1);
tab.vertical_split(new_pane_id_2);
tab.move_focus_left();
tab.move_focus_left();
tab.horizontal_split(new_pane_id_3);
tab.move_focus_right();
tab.horizontal_split(new_pane_id_4);
tab.move_focus_right();
tab.horizontal_split(new_pane_id_5);
tab.move_focus_left();
tab.move_focus_up();
tab.resize_down();
tab.vertical_split(new_pane_id_6);
tab.move_focus_down();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 6, "Six panes left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"first remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"first remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
61,
"second remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"second remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
15,
"second remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"second remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
91,
"third remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"third remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"third remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"third remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
0,
"fourth remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
10,
"fourth remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"fourth remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"fourth remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"sixths remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
10,
"sixths remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"sixths remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"sixths remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
76,
"seventh remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
0,
"seventh remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
15,
"seventh remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"seventh remaining pane row count"
);
}
#[test]
pub fn close_pane_with_multiple_panes_below_it_away_from_screen_edges() {
// ┌───┬───────┬───┐ ┌───┬───┬───┬───┐
// │xxx│███████│xxx│ │xxx│xxx│xxx│xxx│
// │xxx│███████│xxx│ │xxx│xxx│xxx│xxx│
// │xxx├───┬───┤xxx│ ==close==> │xxx│xxx│xxx│xxx│
// ├───┤xxx│xxx├───┤ ├───┤xxx│xxx├───┤
// │xxx│xxx│xxx│xxx│ │xxx│xxx│xxx│xxx│
// └───┴───┴───┴───┘ └───┴───┴───┴───┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
let new_pane_id_4 = PaneId::Terminal(5);
let new_pane_id_5 = PaneId::Terminal(6);
let new_pane_id_6 = PaneId::Terminal(7);
tab.vertical_split(new_pane_id_1);
tab.vertical_split(new_pane_id_2);
tab.move_focus_left();
tab.move_focus_left();
tab.horizontal_split(new_pane_id_3);
tab.move_focus_right();
tab.horizontal_split(new_pane_id_4);
tab.move_focus_right();
tab.horizontal_split(new_pane_id_5);
tab.move_focus_left();
tab.resize_up();
tab.vertical_split(new_pane_id_6);
tab.move_focus_up();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 6, "Six panes left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"first remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"first remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
91,
"third remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"third remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"third remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"third remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
0,
"fourth remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
10,
"fourth remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"fourth remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"fourth remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"second remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"second remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
15,
"second remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"second remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"sixths remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
10,
"sixths remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"sixths remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"sixths remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
76,
"seventh remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
0,
"seventh remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
15,
"seventh remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"seventh remaining pane row count"
);
}
#[test]
pub fn close_pane_with_multiple_panes_to_the_left_away_from_screen_edges() {
// ┌────┬──────┐ ┌────┬──────┐
// │xxxx│xxxxxx│ │xxxx│xxxxxx│
// ├────┴┬─────┤ ├────┴──────┤
// │xxxxx│█████│ │xxxxxxxxxxx│
// ├─────┤█████│ ==close==> ├───────────┤
// │xxxxx│█████│ │xxxxxxxxxxx│
// ├────┬┴─────┤ ├────┬──────┤
// │xxxx│xxxxxx│ │xxxx│xxxxxx│
// └────┴──────┘ └────┴──────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
let new_pane_id_4 = PaneId::Terminal(5);
let new_pane_id_5 = PaneId::Terminal(6);
let new_pane_id_6 = PaneId::Terminal(7);
tab.horizontal_split(new_pane_id_1);
tab.horizontal_split(new_pane_id_2);
tab.move_focus_up();
tab.move_focus_up();
tab.vertical_split(new_pane_id_3);
tab.move_focus_down();
tab.vertical_split(new_pane_id_4);
tab.move_focus_down();
tab.vertical_split(new_pane_id_5);
tab.move_focus_up();
tab.move_focus_left();
tab.resize_right();
tab.resize_up();
tab.resize_up();
tab.horizontal_split(new_pane_id_6);
tab.move_focus_right();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 6, "Six panes left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"first remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
12,
"first remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"third remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
12,
"third remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"third remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"third remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"fourth remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
22,
"fourth remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"fourth remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"fourth remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"second remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"second remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"second remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
12,
"second remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
61,
"sixths remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
22,
"sixths remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"sixths remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"sixths remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
0,
"seventh remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
17,
"seventh remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"seventh remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"seventh remaining pane row count"
);
}
#[test]
pub fn close_pane_with_multiple_panes_to_the_right_away_from_screen_edges() {
// ┌────┬──────┐ ┌────┬──────┐
// │xxxx│xxxxxx│ │xxxx│xxxxxx│
// ├────┴┬─────┤ ├────┴──────┤
// │█████│xxxxx│ │xxxxxxxxxxx│
// │█████├─────┤ ==close==> ├───────────┤
// │█████│xxxxx│ │xxxxxxxxxxx│
// ├────┬┴─────┤ ├────┬──────┤
// │xxxx│xxxxxx│ │xxxx│xxxxxx│
// └────┴──────┘ └────┴──────┘
// █ == pane being closed
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
let new_pane_id_4 = PaneId::Terminal(5);
let new_pane_id_5 = PaneId::Terminal(6);
let new_pane_id_6 = PaneId::Terminal(7);
tab.horizontal_split(new_pane_id_1);
tab.horizontal_split(new_pane_id_2);
tab.move_focus_up();
tab.move_focus_up();
tab.vertical_split(new_pane_id_3);
tab.move_focus_down();
tab.vertical_split(new_pane_id_4);
tab.move_focus_down();
tab.vertical_split(new_pane_id_5);
tab.move_focus_up();
tab.resize_left();
tab.resize_up();
tab.resize_up();
tab.horizontal_split(new_pane_id_6);
tab.move_focus_left();
tab.close_focused_pane();
assert_eq!(tab.panes.len(), 6, "Six panes left in tab");
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"first remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"first remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"first remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"first remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"fourth remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
22,
"fourth remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"fourth remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"fourth remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"second remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"second remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"second remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"second remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
0,
"third remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
11,
"third remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"third remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
6,
"third remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
61,
"sixths remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
22,
"sixths remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"sixths remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"sixths remaining pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
0,
"seventh remaining pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
17,
"seventh remaining pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"seventh remaining pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"seventh remaining pane row count"
);
}
#[test]
pub fn move_focus_down() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
tab.move_focus_up();
tab.move_focus_down();
assert_eq!(
tab.get_active_pane().unwrap().y(),
10,
"Active pane is the bottom one"
);
}
#[test]
pub fn move_focus_down_to_the_most_recently_used_pane() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
tab.horizontal_split(new_pane_id_1);
tab.vertical_split(new_pane_id_2);
tab.vertical_split(new_pane_id_3);
tab.move_focus_up();
tab.move_focus_down();
assert_eq!(
tab.get_active_pane().unwrap().y(),
10,
"Active pane y position"
);
assert_eq!(
tab.get_active_pane().unwrap().x(),
91,
"Active pane x position"
);
}
#[test]
pub fn move_focus_up() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
tab.move_focus_up();
assert_eq!(
tab.get_active_pane().unwrap().y(),
0,
"Active pane is the top one"
);
}
#[test]
pub fn move_focus_up_to_the_most_recently_used_pane() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
tab.horizontal_split(new_pane_id_1);
tab.move_focus_up();
tab.vertical_split(new_pane_id_2);
tab.vertical_split(new_pane_id_3);
tab.move_focus_down();
tab.move_focus_up();
assert_eq!(
tab.get_active_pane().unwrap().y(),
0,
"Active pane y position"
);
assert_eq!(
tab.get_active_pane().unwrap().x(),
91,
"Active pane x position"
);
}
#[test]
pub fn move_focus_left() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.vertical_split(new_pane_id);
tab.move_focus_left();
assert_eq!(
tab.get_active_pane().unwrap().x(),
0,
"Active pane is the left one"
);
}
#[test]
pub fn move_focus_left_to_the_most_recently_used_pane() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
tab.vertical_split(new_pane_id_1);
tab.move_focus_left();
tab.horizontal_split(new_pane_id_2);
tab.horizontal_split(new_pane_id_3);
tab.move_focus_right();
tab.move_focus_left();
assert_eq!(
tab.get_active_pane().unwrap().y(),
15,
"Active pane y position"
);
assert_eq!(
tab.get_active_pane().unwrap().x(),
0,
"Active pane x position"
);
}
#[test]
pub fn move_focus_right() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.vertical_split(new_pane_id);
tab.move_focus_left();
tab.move_focus_right();
assert_eq!(
tab.get_active_pane().unwrap().x(),
61,
"Active pane is the right one"
);
}
#[test]
pub fn move_focus_right_to_the_most_recently_used_pane() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
tab.vertical_split(new_pane_id_1);
tab.horizontal_split(new_pane_id_2);
tab.horizontal_split(new_pane_id_3);
tab.move_focus_left();
tab.move_focus_right();
assert_eq!(
tab.get_active_pane().unwrap().y(),
15,
"Active pane y position"
);
assert_eq!(
tab.get_active_pane().unwrap().x(),
61,
"Active pane x position"
);
}
#[test]
pub fn move_active_pane_down() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
tab.move_focus_up();
tab.move_active_pane_down();
assert_eq!(
tab.get_active_pane().unwrap().y(),
10,
"Active pane is the bottom one"
);
assert_eq!(
tab.get_active_pane().unwrap().pid(),
PaneId::Terminal(1),
"Active pane is the bottom one"
);
}
#[test]
pub fn move_active_pane_down_to_the_most_recently_used_position() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
tab.horizontal_split(new_pane_id_1);
tab.vertical_split(new_pane_id_2);
tab.vertical_split(new_pane_id_3);
tab.move_focus_up();
tab.move_active_pane_down();
assert_eq!(
tab.get_active_pane().unwrap().y(),
10,
"Active pane y position"
);
assert_eq!(
tab.get_active_pane().unwrap().x(),
91,
"Active pane x position"
);
assert_eq!(
tab.get_active_pane().unwrap().pid(),
PaneId::Terminal(1),
"Active pane PaneId"
);
}
#[test]
pub fn move_active_pane_up() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
tab.move_active_pane_up();
assert_eq!(
tab.get_active_pane().unwrap().y(),
0,
"Active pane is the top one"
);
assert_eq!(
tab.get_active_pane().unwrap().pid(),
PaneId::Terminal(2),
"Active pane is the top one"
);
}
#[test]
pub fn move_active_pane_up_to_the_most_recently_used_position() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
tab.horizontal_split(new_pane_id_1);
tab.move_focus_up();
tab.vertical_split(new_pane_id_2);
tab.vertical_split(new_pane_id_3);
tab.move_focus_down();
tab.move_active_pane_up();
assert_eq!(
tab.get_active_pane().unwrap().y(),
0,
"Active pane y position"
);
assert_eq!(
tab.get_active_pane().unwrap().x(),
91,
"Active pane x position"
);
assert_eq!(
tab.get_active_pane().unwrap().pid(),
PaneId::Terminal(2),
"Active pane PaneId"
);
}
#[test]
pub fn move_active_pane_left() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.vertical_split(new_pane_id);
tab.move_active_pane_left();
assert_eq!(
tab.get_active_pane().unwrap().x(),
0,
"Active pane is the left one"
);
assert_eq!(
tab.get_active_pane().unwrap().pid(),
PaneId::Terminal(2),
"Active pane is the left one"
);
}
#[test]
pub fn move_active_pane_left_to_the_most_recently_used_position() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
tab.vertical_split(new_pane_id_1);
tab.move_focus_left();
tab.horizontal_split(new_pane_id_2);
tab.horizontal_split(new_pane_id_3);
tab.move_focus_right();
tab.move_active_pane_left();
assert_eq!(
tab.get_active_pane().unwrap().y(),
15,
"Active pane y position"
);
assert_eq!(
tab.get_active_pane().unwrap().x(),
0,
"Active pane x position"
);
assert_eq!(
tab.get_active_pane().unwrap().pid(),
PaneId::Terminal(2),
"Active pane PaneId"
);
}
#[test]
pub fn move_active_pane_right() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.vertical_split(new_pane_id);
tab.move_focus_left();
tab.move_active_pane_right();
assert_eq!(
tab.get_active_pane().unwrap().x(),
61,
"Active pane is the right one"
);
assert_eq!(
tab.get_active_pane().unwrap().pid(),
PaneId::Terminal(1),
"Active pane is the right one"
);
}
#[test]
pub fn move_active_pane_right_to_the_most_recently_used_position() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
let new_pane_id_3 = PaneId::Terminal(4);
tab.vertical_split(new_pane_id_1);
tab.horizontal_split(new_pane_id_2);
tab.horizontal_split(new_pane_id_3);
tab.move_focus_left();
tab.move_active_pane_right();
assert_eq!(
tab.get_active_pane().unwrap().y(),
15,
"Active pane y position"
);
assert_eq!(
tab.get_active_pane().unwrap().x(),
61,
"Active pane x position"
);
assert_eq!(
tab.get_active_pane().unwrap().pid(),
PaneId::Terminal(1),
"Active pane Paneid"
);
}
#[test]
pub fn resize_down_with_pane_above() {
// ┌───────────┐ ┌───────────┐
// │ │ │ │
// │ │ │ │
// ├───────────┤ ==resize=down==> │ │
// │███████████│ ├───────────┤
// │███████████│ │███████████│
// │███████████│ │███████████│
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
tab.resize_down();
assert_eq!(
tab.panes.get(&new_pane_id).unwrap().position_and_size().x,
0,
"focused pane x position"
);
assert_eq!(
tab.panes.get(&new_pane_id).unwrap().position_and_size().y,
11,
"focused pane y position"
);
assert_eq!(
tab.panes
.get(&new_pane_id)
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"focused pane column count"
);
assert_eq!(
tab.panes
.get(&new_pane_id)
.unwrap()
.position_and_size()
.rows
.as_usize(),
9,
"focused pane row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane above x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane above y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane above column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"pane above row count"
);
}
#[test]
pub fn resize_down_with_pane_below() {
// ┌───────────┐ ┌───────────┐
// │███████████│ │███████████│
// │███████████│ │███████████│
// ├───────────┤ ==resize=down==> │███████████│
// │ │ ├───────────┤
// │ │ │ │
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
let new_pane_id = PaneId::Terminal(2);
tab.horizontal_split(new_pane_id);
tab.move_focus_up();
tab.resize_down();
assert_eq!(
tab.panes.get(&new_pane_id).unwrap().position_and_size().x,
0,
"pane below x position"
);
assert_eq!(
tab.panes.get(&new_pane_id).unwrap().position_and_size().y,
11,
"pane below y position"
);
assert_eq!(
tab.panes
.get(&new_pane_id)
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane below column count"
);
assert_eq!(
tab.panes
.get(&new_pane_id)
.unwrap()
.position_and_size()
.rows
.as_usize(),
9,
"pane below row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"focused pane x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"focused pane y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"focused pane column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"focused pane row count"
);
}
#[test]
pub fn resize_down_with_panes_above_and_below() {
// ┌───────────┐ ┌───────────┐
// │ │ │ │
// │ │ │ │
// ├───────────┤ ├───────────┤
// │███████████│ ==resize=down==> │███████████│
// │███████████│ │███████████│
// │███████████│ │███████████│
// ├───────────┤ │███████████│
// │ │ ├───────────┤
// │ │ │ │
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
let first_pane_id = PaneId::Terminal(1);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
tab.horizontal_split(new_pane_id_1);
tab.horizontal_split(new_pane_id_2);
tab.move_focus_up();
tab.resize_down();
assert_eq!(
tab.panes.get(&new_pane_id_1).unwrap().position_and_size().x,
0,
"focused pane x position"
);
assert_eq!(
tab.panes.get(&new_pane_id_1).unwrap().position_and_size().y,
15,
"focused pane y position"
);
assert_eq!(
tab.panes
.get(&new_pane_id_1)
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"focused pane column count"
);
assert_eq!(
tab.panes
.get(&new_pane_id_1)
.unwrap()
.position_and_size()
.rows
.as_usize(),
9,
"focused pane row count"
);
assert_eq!(
tab.panes.get(&new_pane_id_2).unwrap().position_and_size().x,
0,
"pane below x position"
);
assert_eq!(
tab.panes.get(&new_pane_id_2).unwrap().position_and_size().y,
24,
"pane below y position"
);
assert_eq!(
tab.panes
.get(&new_pane_id_2)
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane below column count"
);
assert_eq!(
tab.panes
.get(&new_pane_id_2)
.unwrap()
.position_and_size()
.rows
.as_usize(),
6,
"pane below row count"
);
assert_eq!(
tab.panes.get(&first_pane_id).unwrap().position_and_size().x,
0,
"pane above x position"
);
assert_eq!(
tab.panes.get(&first_pane_id).unwrap().position_and_size().y,
0,
"pane above y position"
);
assert_eq!(
tab.panes
.get(&first_pane_id)
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane above column count"
);
assert_eq!(
tab.panes
.get(&first_pane_id)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane above row count"
);
}
#[test]
pub fn resize_down_with_multiple_panes_above() {
//
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┴─────┤ ==resize=down==> │ │ │
// │███████████│ ├─────┴─────┤
// │███████████│ │███████████│
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
let first_pane_id = PaneId::Terminal(1);
let new_pane_id_1 = PaneId::Terminal(2);
let new_pane_id_2 = PaneId::Terminal(3);
tab.horizontal_split(new_pane_id_1);
tab.move_focus_up();
tab.vertical_split(new_pane_id_2);
tab.move_focus_down();
tab.resize_down();
assert_eq!(
tab.panes.get(&new_pane_id_1).unwrap().position_and_size().x,
0,
"focused pane x position"
);
assert_eq!(
tab.panes.get(&new_pane_id_1).unwrap().position_and_size().y,
16,
"focused pane y position"
);
assert_eq!(
tab.panes
.get(&new_pane_id_1)
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"focused pane column count"
);
assert_eq!(
tab.panes
.get(&new_pane_id_1)
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"focused pane row count"
);
assert_eq!(
tab.panes.get(&new_pane_id_2).unwrap().position_and_size().x,
61,
"first pane above x position"
);
assert_eq!(
tab.panes.get(&new_pane_id_2).unwrap().position_and_size().y,
0,
"first pane above y position"
);
assert_eq!(
tab.panes
.get(&new_pane_id_2)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"first pane above column count"
);
assert_eq!(
tab.panes
.get(&new_pane_id_2)
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"first pane above row count"
);
assert_eq!(
tab.panes.get(&first_pane_id).unwrap().position_and_size().x,
0,
"second pane above x position"
);
assert_eq!(
tab.panes.get(&first_pane_id).unwrap().position_and_size().y,
0,
"second pane above y position"
);
assert_eq!(
tab.panes
.get(&first_pane_id)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"second pane above column count"
);
assert_eq!(
tab.panes
.get(&first_pane_id)
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"second pane above row count"
);
}
#[test]
pub fn resize_down_with_panes_above_aligned_left_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// │ │ │ │ │ │
// ├─────┼─────┤ ==resize=down==> ├─────┤ │
// │ │█████│ │ ├─────┤
// │ │█████│ │ │█████│
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
let pane_above_and_left = PaneId::Terminal(1);
let pane_to_the_left = PaneId::Terminal(2);
let focused_pane = PaneId::Terminal(3);
let pane_above = PaneId::Terminal(4);
tab.horizontal_split(pane_to_the_left);
tab.vertical_split(focused_pane);
tab.move_focus_up();
tab.vertical_split(pane_above);
tab.move_focus_down();
tab.resize_down();
assert_eq!(
tab.panes.get(&focused_pane).unwrap().position_and_size().x,
61,
"focused pane x position"
);
assert_eq!(
tab.panes.get(&focused_pane).unwrap().position_and_size().y,
16,
"focused pane y position"
);
assert_eq!(
tab.panes
.get(&focused_pane)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"focused pane column count"
);
assert_eq!(
tab.panes
.get(&focused_pane)
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"focused pane row count"
);
assert_eq!(
tab.panes
.get(&pane_above_and_left)
.unwrap()
.position_and_size()
.x,
0,
"pane above and to the left x position"
);
assert_eq!(
tab.panes
.get(&pane_above_and_left)
.unwrap()
.position_and_size()
.y,
0,
"pane above and to the left y position"
);
assert_eq!(
tab.panes
.get(&pane_above_and_left)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane above and to the left column count"
);
assert_eq!(
tab.panes
.get(&pane_above_and_left)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane above and to the left row count"
);
assert_eq!(
tab.panes.get(&pane_above).unwrap().position_and_size().x,
61,
"pane above x position"
);
assert_eq!(
tab.panes.get(&pane_above).unwrap().position_and_size().y,
0,
"pane above y position"
);
assert_eq!(
tab.panes
.get(&pane_above)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane above column count"
);
assert_eq!(
tab.panes
.get(&pane_above)
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane above row count"
);
assert_eq!(
tab.panes
.get(&pane_to_the_left)
.unwrap()
.position_and_size()
.x,
0,
"pane to the left x position"
);
assert_eq!(
tab.panes
.get(&pane_to_the_left)
.unwrap()
.position_and_size()
.y,
15,
"pane to the left y position"
);
assert_eq!(
tab.panes
.get(&pane_to_the_left)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane to the left column count"
);
assert_eq!(
tab.panes
.get(&pane_to_the_left)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane to the left row count"
);
}
#[test]
pub fn resize_down_with_panes_below_aligned_left_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │█████│ │ │█████│
// │ │█████│ │ │█████│
// ├─────┼─────┤ ==resize=down==> ├─────┤█████│
// │ │ │ │ ├─────┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
let pane_to_the_left = PaneId::Terminal(1);
let pane_below_and_left = PaneId::Terminal(2);
let pane_below = PaneId::Terminal(3);
let focused_pane = PaneId::Terminal(4);
tab.horizontal_split(pane_below_and_left);
tab.vertical_split(pane_below);
tab.move_focus_up();
tab.vertical_split(focused_pane);
tab.resize_down();
assert_eq!(
tab.panes.get(&focused_pane).unwrap().position_and_size().x,
61,
"focused pane x position"
);
assert_eq!(
tab.panes.get(&focused_pane).unwrap().position_and_size().y,
0,
"focused pane y position"
);
assert_eq!(
tab.panes
.get(&focused_pane)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"focused pane column count"
);
assert_eq!(
tab.panes
.get(&focused_pane)
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"focused pane row count"
);
assert_eq!(
tab.panes
.get(&pane_to_the_left)
.unwrap()
.position_and_size()
.x,
0,
"pane above and to the left x position"
);
assert_eq!(
tab.panes
.get(&pane_to_the_left)
.unwrap()
.position_and_size()
.y,
0,
"pane above and to the left y position"
);
assert_eq!(
tab.panes
.get(&pane_to_the_left)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane above and to the left column count"
);
assert_eq!(
tab.panes
.get(&pane_to_the_left)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane above and to the left row count"
);
assert_eq!(
tab.panes.get(&pane_below).unwrap().position_and_size().x,
61,
"pane above x position"
);
assert_eq!(
tab.panes.get(&pane_below).unwrap().position_and_size().y,
16,
"pane above y position"
);
assert_eq!(
tab.panes
.get(&pane_below)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane above column count"
);
assert_eq!(
tab.panes
.get(&pane_below)
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane above row count"
);
assert_eq!(
tab.panes
.get(&pane_below_and_left)
.unwrap()
.position_and_size()
.x,
0,
"pane to the left x position"
);
assert_eq!(
tab.panes
.get(&pane_below_and_left)
.unwrap()
.position_and_size()
.y,
15,
"pane to the left y position"
);
assert_eq!(
tab.panes
.get(&pane_below_and_left)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane to the left column count"
);
assert_eq!(
tab.panes
.get(&pane_below_and_left)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane to the left row count"
);
}
#[test]
pub fn resize_down_with_panes_above_aligned_right_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// │ │ │ │ │ │
// ├─────┼─────┤ ==resize=down==> │ ├─────┤
// │█████│ │ ├─────┤ │
// │█████│ │ │█████│ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
let pane_above = PaneId::Terminal(1);
let focused_pane = PaneId::Terminal(2);
let pane_to_the_right = PaneId::Terminal(3);
let pane_above_and_right = PaneId::Terminal(4);
tab.horizontal_split(focused_pane);
tab.vertical_split(pane_to_the_right);
tab.move_focus_up();
tab.vertical_split(pane_above_and_right);
tab.move_focus_down();
tab.move_focus_left();
tab.resize_down();
assert_eq!(
tab.panes.get(&focused_pane).unwrap().position_and_size().x,
0,
"focused pane x position"
);
assert_eq!(
tab.panes.get(&focused_pane).unwrap().position_and_size().y,
16,
"focused pane y position"
);
assert_eq!(
tab.panes
.get(&focused_pane)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"focused pane column count"
);
assert_eq!(
tab.panes
.get(&focused_pane)
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"focused pane row count"
);
assert_eq!(
tab.panes.get(&pane_above).unwrap().position_and_size().x,
0,
"pane above x position"
);
assert_eq!(
tab.panes.get(&pane_above).unwrap().position_and_size().y,
0,
"pane above y position"
);
assert_eq!(
tab.panes
.get(&pane_above)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane above column count"
);
assert_eq!(
tab.panes
.get(&pane_above)
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane above row count"
);
assert_eq!(
tab.panes
.get(&pane_to_the_right)
.unwrap()
.position_and_size()
.x,
61,
"pane to the right x position"
);
assert_eq!(
tab.panes
.get(&pane_to_the_right)
.unwrap()
.position_and_size()
.y,
15,
"pane to the right y position"
);
assert_eq!(
tab.panes
.get(&pane_to_the_right)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane to the right column count"
);
assert_eq!(
tab.panes
.get(&pane_to_the_right)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane to the right row count"
);
assert_eq!(
tab.panes
.get(&pane_above_and_right)
.unwrap()
.position_and_size()
.x,
61,
"pane above and to the right x position"
);
assert_eq!(
tab.panes
.get(&pane_above_and_right)
.unwrap()
.position_and_size()
.y,
0,
"pane above and to the right y position"
);
assert_eq!(
tab.panes
.get(&pane_above_and_right)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane above and to the right column count"
);
assert_eq!(
tab.panes
.get(&pane_above_and_right)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane above and to the right row count"
);
}
#[test]
pub fn resize_down_with_panes_below_aligned_right_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │█████│ │ │█████│ │
// │█████│ │ │█████│ │
// ├─────┼─────┤ ==resize=down==> │█████├─────┤
// │ │ │ ├─────┤ │
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
let focused_pane = PaneId::Terminal(1);
let pane_below = PaneId::Terminal(2);
let pane_below_and_right = PaneId::Terminal(3);
let pane_to_the_right = PaneId::Terminal(4);
tab.horizontal_split(pane_below);
tab.vertical_split(pane_below_and_right);
tab.move_focus_up();
tab.vertical_split(pane_to_the_right);
tab.move_focus_left();
tab.resize_down();
assert_eq!(
tab.panes.get(&focused_pane).unwrap().position_and_size().x,
0,
"focused pane x position"
);
assert_eq!(
tab.panes.get(&focused_pane).unwrap().position_and_size().y,
0,
"focused pane y position"
);
assert_eq!(
tab.panes
.get(&focused_pane)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"focused pane column count"
);
assert_eq!(
tab.panes
.get(&focused_pane)
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"focused pane row count"
);
assert_eq!(
tab.panes.get(&pane_below).unwrap().position_and_size().x,
0,
"pane below x position"
);
assert_eq!(
tab.panes.get(&pane_below).unwrap().position_and_size().y,
16,
"pane below y position"
);
assert_eq!(
tab.panes
.get(&pane_below)
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane below column count"
);
assert_eq!(
tab.panes
.get(&pane_below)
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane below row count"
);
assert_eq!(
tab.panes
.get(&pane_below_and_right)
.unwrap()
.position_and_size()
.x,
61,
"pane below and to the right x position"
);
assert_eq!(
tab.panes
.get(&pane_below_and_right)
.unwrap()
.position_and_size()
.y,
15,
"pane below and to the right y position"
);
assert_eq!(
tab.panes
.get(&pane_below_and_right)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane below and to the right column count"
);
assert_eq!(
tab.panes
.get(&pane_below_and_right)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane below and to the right row count"
);
assert_eq!(
tab.panes
.get(&pane_to_the_right)
.unwrap()
.position_and_size()
.x,
61,
"pane to the right x position"
);
assert_eq!(
tab.panes
.get(&pane_to_the_right)
.unwrap()
.position_and_size()
.y,
0,
"pane to the right y position"
);
assert_eq!(
tab.panes
.get(&pane_to_the_right)
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane to the right column count"
);
assert_eq!(
tab.panes
.get(&pane_to_the_right)
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane to the right row count"
);
}
#[test]
pub fn resize_down_with_panes_above_aligned_left_and_right_with_current_pane() {
// ┌───┬───┬───┐ ┌───┬───┬───┐
// │ │ │ │ │ │ │ │
// │ │ │ │ │ │ │ │
// ├───┼───┼───┤ ==resize=down==> ├───┤ ├───┤
// │ │███│ │ │ ├───┤ │
// │ │███│ │ │ │███│ │
// └───┴───┴───┘ └───┴───┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_left();
tab.move_focus_down();
tab.resize_down();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
16,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
91,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
15,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 6 row count"
);
}
#[test]
pub fn resize_down_with_panes_below_aligned_left_and_right_with_current_pane() {
// ┌───┬───┬───┐ ┌───┬───┬───┐
// │ │███│ │ │ │███│ │
// │ │███│ │ │ │███│ │
// ├───┼───┼───┤ ==resize=down==> ├───┤███├───┤
// │ │ │ │ │ ├───┤ │
// │ │ │ │ │ │ │ │
// └───┴───┴───┘ └───┴───┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_left();
tab.resize_down();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
16,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
91,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
15,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 6 row count"
);
}
#[test]
pub fn resize_down_with_panes_above_aligned_left_and_right_with_panes_to_the_left_and_right() {
// ┌─┬───────┬─┐ ┌─┬───────┬─┐
// │ │ │ │ │ │ │ │
// │ │ │ │ │ │ │ │
// ├─┼─┬───┬─┼─┤ ==resize=down==> ├─┤ ├─┤
// │ │ │███│ │ │ │ ├─┬───┬─┤ │
// │ │ │███│ │ │ │ │ │███│ │ │
// └─┴─┴───┴─┴─┘ └─┴─┴───┴─┴─┘
// █ == focused pane
let size = Size {
cols: 122,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_down();
tab.vertical_split(PaneId::Terminal(5));
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_left();
tab.vertical_split(PaneId::Terminal(7));
tab.vertical_split(PaneId::Terminal(8));
tab.move_focus_left();
tab.resize_down();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
60,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
91,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
60,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
16,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
15,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
15,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 6 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
75,
"pane 7 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
16,
"pane 7 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
8,
"pane 7 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 7 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.x,
83,
"pane 8 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.y,
16,
"pane 8 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.cols
.as_usize(),
8,
"pane 8 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 8 row count"
);
}
#[test]
pub fn resize_down_with_panes_below_aligned_left_and_right_with_to_the_left_and_right() {
// ┌─┬─┬───┬─┬─┐ ┌─┬─┬───┬─┬─┐
// │ │ │███│ │ │ │ │ │███│ │ │
// │ │ │███│ │ │ │ │ │███│ │ │
// ├─┼─┴───┴─┼─┤ ==resize=down==> ├─┤ │███│ ├─┤
// │ │ │ │ │ ├─┴───┴─┤ │
// │ │ │ │ │ │ │ │
// └─┴───────┴─┘ └─┴───────┴─┘
// █ == focused pane
let size = Size {
cols: 122,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_left();
tab.vertical_split(PaneId::Terminal(5));
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_down();
tab.vertical_split(PaneId::Terminal(7));
tab.vertical_split(PaneId::Terminal(8));
tab.move_focus_left();
tab.move_focus_up();
tab.move_focus_left();
tab.resize_down();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
60,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
15,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
91,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
75,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
8,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
83,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
8,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 6 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
60,
"pane 7 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
16,
"pane 7 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 7 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 7 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.x,
91,
"pane 8 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.y,
15,
"pane 8 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 8 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 8 row count"
);
}
#[test]
pub fn cannot_resize_down_when_pane_below_is_at_minimum_height() {
// ┌───────────┐ ┌───────────┐
// │███████████│ │███████████│
// ├───────────┤ ==resize=down==> ├───────────┤
// │ │ │ │
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 10,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.resize_down();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 1 height stayed the same"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 2 height stayed the same"
);
}
#[test]
pub fn resize_left_with_pane_to_the_left() {
// ┌─────┬─────┐ ┌───┬───────┐
// │ │█████│ │ │███████│
// │ │█████│ ==resize=left==> │ │███████│
// │ │█████│ │ │███████│
// └─────┴─────┘ └───┴───────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
54,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
}
#[test]
pub fn resize_left_with_pane_to_the_right() {
// ┌─────┬─────┐ ┌───┬───────┐
// │█████│ │ │███│ │
// │█████│ │ ==resize=left==> │███│ │
// │█████│ │ │███│ │
// └─────┴─────┘ └───┴───────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
54,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_left_and_right() {
// ┌─────┬─────┬─────┐ ┌─────┬───┬───────┐
// │ │█████│ │ │ │███│ │
// │ │█████│ │ ==resize=left==> │ │███│ │
// │ │█████│ │ │ │███│ │
// └─────┴─────┴─────┘ └─────┴───┴───────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_left();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
54,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
36,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
90,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
}
#[test]
pub fn resize_left_with_multiple_panes_to_the_left() {
// ┌─────┬─────┐ ┌───┬───────┐
// │ │█████│ │ │███████│
// ├─────┤█████│ ==resize=left==> ├───┤███████│
// │ │█████│ │ │███████│
// └─────┴─────┘ └───┴───────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(3));
tab.move_focus_right();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
54,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 2 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_left_aligned_top_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┼─────┤ ==resize=left==> ├───┬─┴─────┤
// │ │█████│ │ │███████│
// └─────┴─────┘ └───┴───────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_down();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
54,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
15,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_right_aligned_top_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┼─────┤ ==resize=left==> ├───┬─┴─────┤
// │█████│ │ │███│ │
// └─────┴─────┘ └───┴───────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_down();
tab.move_focus_left();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
54,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
15,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_left_aligned_bottom_with_current_pane() {
// ┌─────┬─────┐ ┌───┬───────┐
// │ │█████│ │ │███████│
// ├─────┼─────┤ ==resize=left==> ├───┴─┬─────┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(4));
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
15,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
54,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_right_aligned_bottom_with_current_pane() {
// ┌─────┬─────┐ ┌───┬───────┐
// │█████│ │ │███│ │
// ├─────┼─────┤ ==resize=left==> ├───┴─┬─────┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_left();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
15,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
54,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_left_aligned_top_and_bottom_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┼─────┤ ├───┬─┴─────┤
// │ │█████│ ==resize=left==> │ │███████│
// ├─────┼─────┤ ├───┴─┬─────┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_down();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
14,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
22,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
22,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
54,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
14,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
61,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 6 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_right_aligned_top_and_bottom_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┼─────┤ ├───┬─┴─────┤
// │█████│ │ ==resize=left==> │███│ │
// ├─────┼─────┤ ├───┴─┬─────┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_down();
tab.move_focus_left();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
14,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
22,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
22,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
54,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
14,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
61,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 6 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_left_aligned_top_and_bottom_with_panes_above_and_below() {
// ┌─────┬─────┐ ┌─────┬─────┐
// ├─────┼─────┤ ├───┬─┴─────┤
// │ ├─────┤ │ ├───────┤
// │ │█████│ ==resize=left==> │ │███████│
// │ ├─────┤ │ ├───────┤
// ├─────┼─────┤ ├───┴─┬─────┤
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 70,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.move_focus_down();
tab.resize_down();
tab.vertical_split(PaneId::Terminal(6));
tab.horizontal_split(PaneId::Terminal(7));
tab.horizontal_split(PaneId::Terminal(8));
tab.move_focus_up();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
35,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
35,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
21,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
56,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
56,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
35,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
54,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
35,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"pane 6 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
54,
"pane 7 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
46,
"pane 7 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 7 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 7 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.x,
54,
"pane 8 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.y,
51,
"pane 8 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 8 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 8 row count"
);
}
#[test]
pub fn resize_left_with_panes_to_the_right_aligned_top_and_bottom_with_panes_above_and_below() {
// ┌─────┬─────┐ ┌─────┬─────┐
// ├─────┼─────┤ ├───┬─┴─────┤
// ├─────┤ │ ├───┤ │
// │█████│ │ ==resize=left==> │███│ │
// ├─────┤ │ ├───┤ │
// ├─────┼─────┤ ├───┴─┬─────┤
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 70,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.move_focus_down();
tab.resize_down();
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(7));
tab.horizontal_split(PaneId::Terminal(8));
tab.move_focus_up();
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
35,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
35,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
56,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
56,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
35,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
54,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
35,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
21,
"pane 6 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
0,
"pane 7 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
46,
"pane 7 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 7 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 7 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.x,
0,
"pane 8 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.y,
51,
"pane 8 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 8 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 8 row count"
);
}
#[test]
pub fn cannot_resize_left_when_pane_to_the_left_is_at_minimum_width() {
// ┌─┬─┐ ┌─┬─┐
// │ │█│ │ │█│
// │ │█│ ==resize=left==> │ │█│
// │ │█│ │ │█│
// └─┴─┘ └─┴─┘
// █ == focused pane
let size = Size { cols: 10, rows: 20 };
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.resize_left();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
5,
"pane 1 columns stayed the same"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
5,
"pane 2 columns stayed the same"
);
}
#[test]
pub fn resize_right_with_pane_to_the_left() {
// ┌─────┬─────┐ ┌───────┬───┐
// │ │█████│ │ │███│
// │ │█████│ ==resize=right==> │ │███│
// │ │█████│ │ │███│
// └─────┴─────┘ └───────┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
67,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
}
#[test]
pub fn resize_right_with_pane_to_the_right() {
// ┌─────┬─────┐ ┌───────┬───┐
// │█████│ │ │███████│ │
// │█████│ │ ==resize=right==> │███████│ │
// │█████│ │ │███████│ │
// └─────┴─────┘ └───────┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
67,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_left_and_right() {
// ┌─────┬─────┬─────┐ ┌─────┬───────┬───┐
// │ │█████│ │ │ │███████│ │
// │ │█████│ │ ==resize=right==> │ │███████│ │
// │ │█████│ │ │ │███████│ │
// └─────┴─────┴─────┘ └─────┴───────┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_left();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
61,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
36,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
97,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
24,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
}
#[test]
pub fn resize_right_with_multiple_panes_to_the_left() {
// ┌─────┬─────┐ ┌───────┬───┐
// │ │█████│ │ │███│
// ├─────┤█████│ ==resize=right==> ├───────┤███│
// │ │█████│ │ │███│
// └─────┴─────┘ └───────┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(3));
tab.move_focus_right();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
67,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 3 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_left_aligned_top_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┼─────┤ ==resize=right==> ├─────┴─┬───┤
// │ │█████│ │ │███│
// └─────┴─────┘ └───────┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(3));
tab.move_focus_right();
tab.horizontal_split(PaneId::Terminal(4));
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
61,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
67,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
10,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 4 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_right_aligned_top_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┼─────┤ ==resize=right==> ├─────┴─┬───┤
// │█████│ │ │███████│ │
// └─────┴─────┘ └───────┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(3));
tab.move_focus_right();
tab.horizontal_split(PaneId::Terminal(4));
tab.move_focus_left();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
61,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
67,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
10,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 4 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_left_aligned_bottom_with_current_pane() {
// ┌─────┬─────┐ ┌───────┬───┐
// │ │█████│ │ │███│
// ├─────┼─────┤ ==resize=right==> ├─────┬─┴───┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(3));
tab.move_focus_right();
tab.horizontal_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
67,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
10,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 4 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_right_aligned_bottom_with_current_pane() {
// ┌─────┬─────┐ ┌───────┬───┐
// │█████│ │ │███████│ │
// ├─────┼─────┤ ==resize=right==> ├─────┬─┴───┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(3));
tab.move_focus_right();
tab.horizontal_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.move_focus_left();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
67,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
10,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
10,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 4 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_left_aligned_top_and_bottom_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┼─────┤ ├─────┴─┬───┤
// │ │█████│ ==resize=right==> │ │███│
// ├─────┼─────┤ ├─────┬─┴───┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_down();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
10,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
15,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
15,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
67,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
10,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
61,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 6 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_right_aligned_top_and_bottom_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// ├─────┼─────┤ ├─────┴─┬───┤
// │█████│ │ ==resize=right==> │███████│ │
// ├─────┼─────┤ ├─────┬─┴───┤
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_down();
tab.move_focus_left();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
10,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
15,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
15,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
67,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
10,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
61,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
10,
"pane 6 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_left_aligned_top_and_bottom_with_panes_above_and_below() {
// ┌─────┬─────┐ ┌─────┬─────┐
// ├─────┼─────┤ ├─────┴─┬───┤
// │ ├─────┤ │ ├───┤
// │ │█████│ ==resize=right==> │ │███│
// │ ├─────┤ │ ├───┤
// ├─────┼─────┤ ├─────┬─┴───┤
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 70,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.move_focus_down();
tab.resize_up();
tab.vertical_split(PaneId::Terminal(6));
tab.horizontal_split(PaneId::Terminal(7));
tab.horizontal_split(PaneId::Terminal(8));
tab.move_focus_up();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
31,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
31,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
21,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
52,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
18,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
52,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
18,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
31,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
67,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
31,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"pane 6 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
67,
"pane 7 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
42,
"pane 7 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 7 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 7 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.x,
67,
"pane 8 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.y,
47,
"pane 8 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 8 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 8 row count"
);
}
#[test]
pub fn resize_right_with_panes_to_the_right_aligned_top_and_bottom_with_panes_above_and_below() {
// ┌─────┬─────┐ ┌─────┬─────┐
// ├─────┼─────┤ ├─────┴─┬───┤
// ├─────┤ │ ├───────┤ │
// │█████│ │ ==resize=right==> │███████│ │
// ├─────┤ │ ├───────┤ │
// ├─────┼─────┤ ├─────┬─┴───┤
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 70,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.move_focus_down();
tab.resize_up();
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(7));
tab.horizontal_split(PaneId::Terminal(8));
tab.move_focus_up();
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
31,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
31,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
52,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
18,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
52,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
18,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
31,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
67,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
31,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
54,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
21,
"pane 6 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
0,
"pane 7 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
42,
"pane 7 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 7 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 7 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.x,
0,
"pane 8 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.y,
47,
"pane 8 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 8 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 8 row count"
);
}
#[test]
pub fn cannot_resize_right_when_pane_to_the_left_is_at_minimum_width() {
// ┌─┬─┐ ┌─┬─┐
// │ │█│ │ │█│
// │ │█│ ==resize=right==> │ │█│
// │ │█│ │ │█│
// └─┴─┘ └─┴─┘
// █ == focused pane
let size = Size { cols: 10, rows: 20 };
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.resize_right();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
5,
"pane 1 columns stayed the same"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
5,
"pane 2 columns stayed the same"
);
}
#[test]
pub fn resize_up_with_pane_above() {
// ┌───────────┐ ┌───────────┐
// │ │ │ │
// │ │ ├───────────┤
// ├───────────┤ ==resize=up==> │███████████│
// │███████████│ │███████████│
// │███████████│ │███████████│
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
9,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
9,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"pane 2 row count"
);
}
#[test]
pub fn resize_up_with_pane_below() {
// ┌───────────┐ ┌───────────┐
// │███████████│ │███████████│
// │███████████│ ├───────────┤
// ├───────────┤ ==resize=up==> │ │
// │ │ │ │
// │ │ │ │
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
9,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
9,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"pane 2 row count"
);
}
#[test]
pub fn resize_up_with_panes_above_and_below() {
// ┌───────────┐ ┌───────────┐
// │ │ │ │
// │ │ ├───────────┤
// ├───────────┤ │███████████│
// │███████████│ ==resize=up==> │███████████│
// │███████████│ │███████████│
// ├───────────┤ ├───────────┤
// │ │ │ │
// │ │ │ │
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.horizontal_split(PaneId::Terminal(3));
tab.move_focus_up();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
13,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
13,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
9,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
22,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
8,
"pane 3 row count"
);
}
#[test]
pub fn resize_up_with_multiple_panes_above() {
//
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ ├─────┴─────┤
// ├─────┴─────┤ ==resize=up==> │███████████│
// │███████████│ │███████████│
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_down();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
14,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
121,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
}
#[test]
pub fn resize_up_with_panes_above_aligned_left_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ ├─────┤
// ├─────┼─────┤ ==resize=up==> ├─────┤█████│
// │ │█████│ │ │█████│
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_down();
tab.vertical_split(PaneId::Terminal(4));
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
14,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 4 row count"
);
}
#[test]
pub fn resize_up_with_panes_below_aligned_left_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │█████│ │ │█████│
// │ │█████│ │ ├─────┤
// ├─────┼─────┤ ==resize=up==> ├─────┤ │
// │ │ │ │ │ │
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_down();
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
14,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 4 row count"
);
}
#[test]
pub fn resize_up_with_panes_above_aligned_right_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │ │ │ │ │ │
// │ │ │ ├─────┤ │
// ├─────┼─────┤ ==resize=up==> │█████├─────┤
// │█████│ │ │█████│ │
// │█████│ │ │█████│ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_down();
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_left();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
14,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
15,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
}
#[test]
pub fn resize_up_with_panes_below_aligned_right_with_current_pane() {
// ┌─────┬─────┐ ┌─────┬─────┐
// │█████│ │ │█████│ │
// │█████│ │ ├─────┤ │
// ├─────┼─────┤ ==resize=up==> │ ├─────┤
// │ │ │ │ │ │
// │ │ │ │ │ │
// └─────┴─────┘ └─────┴─────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_down();
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_left();
tab.move_focus_up();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
14,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
61,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
15,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
}
#[test]
pub fn resize_up_with_panes_above_aligned_left_and_right_with_current_pane() {
// ┌───┬───┬───┐ ┌───┬───┬───┐
// │ │ │ │ │ │ │ │
// │ │ │ │ │ ├───┤ │
// ├───┼───┼───┤ ==resize=up==> ├───┤███├───┤
// │ │███│ │ │ │███│ │
// │ │███│ │ │ │███│ │
// └───┴───┴───┘ └───┴───┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_left();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
14,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
91,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
15,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 6 row count"
);
}
#[test]
pub fn resize_up_with_panes_below_aligned_left_and_right_with_current_pane() {
// ┌───┬───┬───┐ ┌───┬───┬───┐
// │ │███│ │ │ │███│ │
// │ │███│ │ │ ├───┤ │
// ├───┼───┼───┤ ==resize=up==> ├───┤ ├───┤
// │ │ │ │ │ │ │ │
// │ │ │ │ │ │ │ │
// └───┴───┴───┘ └───┴───┴───┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(5));
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_left();
tab.move_focus_up();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
61,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
61,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
14,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
91,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
15,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
61,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
0,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
0,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
30,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 6 row count"
);
}
#[test]
pub fn resize_up_with_panes_above_aligned_left_and_right_with_panes_to_the_left_and_right() {
// ┌─┬───────┬─┐ ┌─┬───────┬─┐
// │ │ │ │ │ │ │ │
// │ │ │ │ │ ├─┬───┬─┤ │
// ├─┼─┬───┬─┼─┤ ==resize=up==> ├─┤ │███│ ├─┤
// │ │ │███│ │ │ │ │ │███│ │ │
// │ │ │███│ │ │ │ │ │███│ │ │
// └─┴─┴───┴─┴─┘ └─┴─┴───┴─┴─┘
// █ == focused pane
let size = Size {
cols: 122,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_down();
tab.vertical_split(PaneId::Terminal(5));
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_left();
tab.vertical_split(PaneId::Terminal(7));
tab.vertical_split(PaneId::Terminal(8));
tab.move_focus_left();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
60,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
91,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
60,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
14,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
15,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
15,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 6 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
75,
"pane 7 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
14,
"pane 7 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
8,
"pane 7 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 7 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.x,
83,
"pane 8 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.y,
14,
"pane 8 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.cols
.as_usize(),
8,
"pane 8 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 8 row count"
);
}
#[test]
pub fn resize_up_with_panes_below_aligned_left_and_right_with_to_the_left_and_right() {
// ┌─┬─┬───┬─┬─┐ ┌─┬─┬───┬─┬─┐
// │ │ │███│ │ │ │ │ │███│ │ │
// │ │ │███│ │ │ │ ├─┴───┴─┤ │
// ├─┼─┴───┴─┼─┤ ==resize=up==> ├─┤ ├─┤
// │ │ │ │ │ │ │ │
// │ │ │ │ │ │ │ │
// └─┴───────┴─┘ └─┴───────┴─┘
// █ == focused pane
let size = Size {
cols: 122,
rows: 30,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.move_focus_up();
tab.vertical_split(PaneId::Terminal(3));
tab.vertical_split(PaneId::Terminal(4));
tab.move_focus_down();
tab.vertical_split(PaneId::Terminal(5));
tab.vertical_split(PaneId::Terminal(6));
tab.move_focus_up();
tab.move_focus_left();
tab.vertical_split(PaneId::Terminal(7));
tab.vertical_split(PaneId::Terminal(8));
tab.move_focus_left();
tab.resize_up();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.x,
0,
"pane 1 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.y,
0,
"pane 1 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 1 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 1 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
0,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
15,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
60,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 2 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
60,
"pane 3 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
0,
"pane 3 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
15,
"pane 3 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.x,
91,
"pane 4 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.y,
0,
"pane 4 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 4 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(4))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 4 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.x,
60,
"pane 5 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.y,
14,
"pane 5 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 5 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(5))
.unwrap()
.position_and_size()
.rows
.as_usize(),
16,
"pane 5 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.x,
91,
"pane 6 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.y,
15,
"pane 6 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.cols
.as_usize(),
31,
"pane 6 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(6))
.unwrap()
.position_and_size()
.rows
.as_usize(),
15,
"pane 6 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.x,
75,
"pane 7 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.y,
0,
"pane 7 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.cols
.as_usize(),
8,
"pane 7 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(7))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 7 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.x,
83,
"pane 8 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.y,
0,
"pane 8 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.cols
.as_usize(),
8,
"pane 8 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(8))
.unwrap()
.position_and_size()
.rows
.as_usize(),
14,
"pane 8 row count"
);
}
#[test]
pub fn cannot_resize_up_when_pane_above_is_at_minimum_height() {
// ┌───────────┐ ┌───────────┐
// │ │ │ │
// ├───────────┤ ==resize=up==> ├───────────┤
// │███████████│ │███████████│
// └───────────┘ └───────────┘
// █ == focused pane
let size = Size {
cols: 121,
rows: 10,
};
let mut tab = create_new_tab(size);
tab.horizontal_split(PaneId::Terminal(2));
tab.resize_down();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(1))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 1 height stayed the same"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
5,
"pane 2 height stayed the same"
);
}
#[test]
pub fn nondirectional_resize_increase_with_1_pane() {
let size = Size {
cols: 121,
rows: 10,
};
let mut tab = create_new_tab(size);
tab.resize_increase();
assert_eq!(
tab.get_active_pane().unwrap().position_and_size().y,
0,
"There is only 1 pane so both coordinates should be 0"
);
assert_eq!(
tab.get_active_pane().unwrap().position_and_size().x,
0,
"There is only 1 pane so both coordinates should be 0"
);
}
#[test]
pub fn nondirectional_resize_increase_with_1_pane_to_left() {
let size = Size {
cols: 121,
rows: 10,
};
let mut tab = create_new_tab(size);
let new_pane_id_1 = PaneId::Terminal(2);
tab.vertical_split(new_pane_id_1);
tab.resize_increase();
// should behave like `resize_left_with_pane_to_the_left`
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
54,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
}
#[test]
pub fn nondirectional_resize_increase_with_2_panes_to_left() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(3));
tab.move_focus_right();
tab.resize_increase();
// should behave like `resize_left_with_multiple_panes_to_the_left`
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
54,
"pane 2 x position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"pane 2 y position"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"pane 2 column count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"pane 2 row count"
);
}
#[test]
pub fn nondirectional_resize_increase_with_1_pane_to_right_1_pane_above() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.move_focus_left();
tab.horizontal_split(PaneId::Terminal(3));
tab.resize_increase();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.y,
9,
"Pane 3 y coordinate"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.x,
0,
"Pane 3 x coordinate"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.rows
.as_usize(),
11,
"Pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(3))
.unwrap()
.position_and_size()
.cols
.as_usize(),
67,
"Pane 3 col count"
);
}
#[test]
pub fn nondirectional_resize_increase_with_1_pane_to_right_1_pane_to_left() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_left();
tab.resize_increase();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"Pane 3 y coordinate"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
61,
"Pane 3 x coordinate"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"Pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
36,
"Pane 3 col count"
);
}
#[test]
pub fn nondirectional_resize_increase_with_pane_above_aligned_right_with_current_pane() {
let size = Size {
cols: 121,
rows: 20,
};
let mut tab = create_new_tab(size);
tab.vertical_split(PaneId::Terminal(2));
tab.vertical_split(PaneId::Terminal(3));
tab.move_focus_left();
tab.resize_increase();
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.y,
0,
"Pane 3 y coordinate"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.x,
61,
"Pane 3 x coordinate"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.rows
.as_usize(),
20,
"Pane 3 row count"
);
assert_eq!(
tab.panes
.get(&PaneId::Terminal(2))
.unwrap()
.position_and_size()
.cols
.as_usize(),
36,
"Pane 3 col count"
);
}
| 23.069543 | 97 | 0.420345 |
210055de114cc439c1b4a6816e7132887166c813
| 6,171 |
use capstone_sys::cs_arch::*;
use capstone_sys::cs_opt_value::*;
use capstone_sys::*;
use std::convert::From;
use std::fmt::{self, Display};
use std::str::FromStr;
/// A C-like enum can list its variants
pub trait EnumList where Self: Sized {
/// Slice of available variants
fn variants() -> &'static [Self];
}
/// Define an `enum` that corresponds to a capstone enum
///
/// The different `From` implementations can be disabled by using the cfg attribute
macro_rules! define_cs_enum_wrapper {
( [
$( #[$enum_attr:meta] )*
=> $rust_enum:ident = $cs_enum:ty
]
$( $( #[$attr:meta] )*
=> $rust_variant:ident = $cs_variant:tt; )* ) => {
$( #[$enum_attr] )*
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum $rust_enum {
$(
$( #[$attr] )*
$rust_variant,
)*
}
impl ::std::convert::From<$rust_enum> for $cs_enum {
fn from(other: $rust_enum) -> Self {
match other {
$(
$rust_enum::$rust_variant => $cs_variant,
)*
}
}
}
impl EnumList for $rust_enum {
fn variants() -> &'static [Self] {
&[
$(
$rust_enum::$rust_variant,
)*
]
}
}
impl FromStr for $rust_enum {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.to_lowercase();
$(
if s == stringify!($rust_variant).to_lowercase() {
return Ok($rust_enum::$rust_variant);
}
)*
Err(concat!("Failed to parse ", stringify!($rust_enum)))
}
}
impl Display for $rust_enum {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
$(
$rust_enum::$rust_variant => write!(f, "{}", stringify!($rust_variant)),
)*
}
}
}
}
}
define_cs_enum_wrapper!(
[
/// Architectures for the disassembler
=> Arch = cs_arch
]
/// ARM (Advanced RISC Machine)
=> ARM = CS_ARCH_ARM;
/// ARM 64-bit (also known as AArch64)
=> ARM64 = CS_ARCH_ARM64;
/// MIPS
=> MIPS = CS_ARCH_MIPS;
/// x86 family (includes 16, 32, and 64 bit modes)
=> X86 = CS_ARCH_X86;
/// PowerPC
=> PPC = CS_ARCH_PPC;
/// SPARC
=> SPARC = CS_ARCH_SPARC;
/// System z
=> SYSZ = CS_ARCH_SYSZ;
/// XCore
=> XCORE = CS_ARCH_XCORE;
);
define_cs_enum_wrapper!(
[
/// Disassembler modes
=> Mode = cs_mode
]
/// 32-bit ARM
=> Arm = CS_MODE_ARM;
/// 16-bit mode (X86)
=> Mode16 = CS_MODE_16;
/// 32-bit mode (X86)
=> Mode32 = CS_MODE_32;
/// 64-bit mode (X86, PPC)
=> Mode64 = CS_MODE_64;
/// ARM's Thumb mode, including Thumb-2
=> Thumb = CS_MODE_THUMB;
/// Mips II ISA
=> Mips2 = CS_MODE_MIPS2;
/// Mips III ISA
=> Mips3 = CS_MODE_MIPS3;
/// Mips32r6 ISA
=> Mips32R6 = CS_MODE_MIPS32R6;
/// Mips32 ISA (Mips)
=> Mips32 = CS_MODE_MIPS32;
/// Mips64 ISA (Mips)
=> Mips64 = CS_MODE_MIPS64;
/// SparcV9 mode (Sparc)
=> V9 = CS_MODE_V9;
/// Quad Processing eXtensions mode (PPC)
=> Qpx = CS_MODE_QPX;
/// M68K 68000 mode
=> M68k000 = CS_MODE_M68K_000;
/// M68K 68010 mode
=> M68k010 = CS_MODE_M68K_010;
/// M68K 68020 mode
=> M68k020 = CS_MODE_M68K_020;
/// M68K 68030 mode
=> M68k030 = CS_MODE_M68K_030;
/// M68K 68040 mode
=> M68k040 = CS_MODE_M68K_040;
/// M680X Hitachi 6301,6303 mode
=> M680x6301 = CS_MODE_M680X_6301;
/// M680X Hitachi 6309 mode
=> M680x6309 = CS_MODE_M680X_6309;
/// M680X Motorola 6800,6802 mode
=> M680x6800 = CS_MODE_M680X_6800;
/// M680X Motorola 6801,6803 mode
=> M680x6801 = CS_MODE_M680X_6801;
/// M680X Motorola/Freescale 6805 mode
=> M680x6805 = CS_MODE_M680X_6805;
/// M680X Motorola/Freescale/NXP 68HC08 mode
=> M680x6808 = CS_MODE_M680X_6808;
/// M680X Motorola 6809 mode
=> M680x6809 = CS_MODE_M680X_6809;
/// M680X Motorola/Freescale/NXP 68HC11 mode
=> M680x6811 = CS_MODE_M680X_6811;
/// M680X Motorola/Freescale/NXP CPU12
=> M680xCpu12 = CS_MODE_M680X_CPU12;
/// M680X Freescale/NXP HCS08 mode
=> M680xHcs08 = CS_MODE_M680X_HCS08;
/// Default mode for little-endian
=> Default = CS_MODE_LITTLE_ENDIAN;
);
define_cs_enum_wrapper!(
[
/// Extra modes or features that can be enabled with some modes
=> ExtraMode = cs_mode
]
/// ARM's Cortex-M series. Works with `Arm` mode.
=> MClass = CS_MODE_MCLASS;
/// ARMv8 A32 encodings for ARM. Works with `Arm` and `Thumb` modes.
=> V8 = CS_MODE_V8;
/// MicroMips mode. Works in `MIPS` mode.
=> Micro = CS_MODE_MICRO;
);
define_cs_enum_wrapper!(
[
/// Disassembler endianness
=> Endian = cs_mode
]
/// Little-endian mode
=> Little = CS_MODE_LITTLE_ENDIAN;
/// Big-endian mode
=> Big = CS_MODE_BIG_ENDIAN;
);
define_cs_enum_wrapper!(
[
/// Disassembly syntax
=> Syntax = cs_opt_value::Type
]
/// Intel syntax
=> Intel = CS_OPT_SYNTAX_INTEL;
/// AT&T syntax (also known as GNU assembler/GAS syntax)
=> Att = CS_OPT_SYNTAX_ATT;
/// No register name
=> NoRegName = CS_OPT_SYNTAX_NOREGNAME;
);
pub(crate) struct OptValue(pub cs_opt_value::Type);
impl From<bool> for OptValue {
fn from(value: bool) -> Self {
if value {
OptValue(cs_opt_value::CS_OPT_ON)
} else {
OptValue(cs_opt_value::CS_OPT_OFF)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse_arch() {
assert_eq!(Arch::from_str("x86"), Ok(Arch::X86));
assert_eq!(Arch::from_str("X86"), Ok(Arch::X86));
}
}
| 27.185022 | 96 | 0.540755 |
e2592d7ec6235a075a7c8cb67de13a4b5ab0aba7
| 462 |
pub fn all() {
day_6_a();
day_6_b();
}
pub fn day_6_a() {
println!("6a: {}", solve(80));
}
pub fn day_6_b() {
println!("6b: {}", solve(256));
}
fn solve(days: u16) -> u64 {
let mut map = [0; 9];
include_str!("../../input/day_6.txt")
.split(',')
.for_each(|fish| map[fish.parse::<usize>().unwrap()] += 1);
(0..days).for_each(|_| {
map[7] += map[0];
map.rotate_left(1);
});
map.iter().sum()
}
| 18.48 | 67 | 0.474026 |
8f202e752b4b7ec4fc495cfd40ed5d0fc43657f2
| 10,543 |
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{net, rc::Rc};
use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::net::TcpStream;
use actix_service::{
fn_factory, fn_service, pipeline_factory, IntoServiceFactory, Service,
ServiceFactory,
};
use actix_utils::future::ready;
use bytes::Bytes;
use futures_core::{future::LocalBoxFuture, ready};
use h2::server::{handshake, Handshake};
use log::error;
use crate::body::MessageBody;
use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error};
use crate::request::Request;
use crate::response::Response;
use crate::service::HttpFlow;
use crate::{ConnectCallback, OnConnectData};
use super::dispatcher::Dispatcher;
/// `ServiceFactory` implementation for HTTP/2 transport
pub struct H2Service<T, S, B> {
srv: S,
cfg: ServiceConfig,
on_connect_ext: Option<Rc<ConnectCallback<T>>>,
_phantom: PhantomData<(T, B)>,
}
impl<T, S, B> H2Service<T, S, B>
where
S: ServiceFactory<Request, Config = ()>,
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
{
/// Create new `H2Service` instance with config.
pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>(
cfg: ServiceConfig,
service: F,
) -> Self {
H2Service {
cfg,
on_connect_ext: None,
srv: service.into_factory(),
_phantom: PhantomData,
}
}
/// Set on connect callback.
pub(crate) fn on_connect_ext(mut self, f: Option<Rc<ConnectCallback<T>>>) -> Self {
self.on_connect_ext = f;
self
}
}
impl<S, B> H2Service<TcpStream, S, B>
where
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
{
/// Create plain TCP based service
pub fn tcp(
self,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = DispatchError,
InitError = S::InitError,
> {
pipeline_factory(fn_factory(|| {
ready(Ok::<_, S::InitError>(fn_service(|io: TcpStream| {
let peer_addr = io.peer_addr().ok();
ready(Ok::<_, DispatchError>((io, peer_addr)))
})))
}))
.and_then(self)
}
}
#[cfg(feature = "openssl")]
mod openssl {
use actix_service::{fn_factory, fn_service, ServiceFactoryExt};
use actix_tls::accept::openssl::{Acceptor, SslAcceptor, SslError, TlsStream};
use actix_tls::accept::TlsError;
use super::*;
impl<S, B> H2Service<TlsStream<TcpStream>, S, B>
where
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
{
/// Create OpenSSL based service
pub fn openssl(
self,
acceptor: SslAcceptor,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<SslError, DispatchError>,
InitError = S::InitError,
> {
pipeline_factory(
Acceptor::new(acceptor)
.map_err(TlsError::Tls)
.map_init_err(|_| panic!()),
)
.and_then(fn_factory(|| {
ready(Ok::<_, S::InitError>(fn_service(
|io: TlsStream<TcpStream>| {
let peer_addr = io.get_ref().peer_addr().ok();
ready(Ok((io, peer_addr)))
},
)))
}))
.and_then(self.map_err(TlsError::Service))
}
}
}
#[cfg(feature = "rustls")]
mod rustls {
use super::*;
use actix_service::ServiceFactoryExt;
use actix_tls::accept::rustls::{Acceptor, ServerConfig, TlsStream};
use actix_tls::accept::TlsError;
use std::io;
impl<S, B> H2Service<TlsStream<TcpStream>, S, B>
where
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
{
/// Create Rustls based service
pub fn rustls(
self,
mut config: ServerConfig,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<io::Error, DispatchError>,
InitError = S::InitError,
> {
let protos = vec!["h2".to_string().into()];
config.set_protocols(&protos);
pipeline_factory(
Acceptor::new(config)
.map_err(TlsError::Tls)
.map_init_err(|_| panic!()),
)
.and_then(fn_factory(|| {
ready(Ok::<_, S::InitError>(fn_service(
|io: TlsStream<TcpStream>| {
let peer_addr = io.get_ref().0.peer_addr().ok();
ready(Ok((io, peer_addr)))
},
)))
}))
.and_then(self.map_err(TlsError::Service))
}
}
}
impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B>
where
T: AsyncRead + AsyncWrite + Unpin + 'static,
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
{
type Response = ();
type Error = DispatchError;
type Config = ();
type Service = H2ServiceHandler<T, S::Service, B>;
type InitError = S::InitError;
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future {
let service = self.srv.new_service(());
let cfg = self.cfg.clone();
let on_connect_ext = self.on_connect_ext.clone();
Box::pin(async move {
let service = service.await?;
Ok(H2ServiceHandler::new(cfg, on_connect_ext, service))
})
}
}
/// `Service` implementation for HTTP/2 transport
pub struct H2ServiceHandler<T, S, B>
where
S: Service<Request>,
{
flow: Rc<HttpFlow<S, (), ()>>,
cfg: ServiceConfig,
on_connect_ext: Option<Rc<ConnectCallback<T>>>,
_phantom: PhantomData<B>,
}
impl<T, S, B> H2ServiceHandler<T, S, B>
where
S: Service<Request>,
S::Error: Into<Error> + 'static,
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
{
fn new(
cfg: ServiceConfig,
on_connect_ext: Option<Rc<ConnectCallback<T>>>,
service: S,
) -> H2ServiceHandler<T, S, B> {
H2ServiceHandler {
flow: HttpFlow::new(service, (), None),
cfg,
on_connect_ext,
_phantom: PhantomData,
}
}
}
impl<T, S, B> Service<(T, Option<net::SocketAddr>)> for H2ServiceHandler<T, S, B>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error> + 'static,
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
{
type Response = ();
type Error = DispatchError;
type Future = H2ServiceHandlerResponse<T, S, B>;
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.flow.service.poll_ready(cx).map_err(|e| {
let e = e.into();
error!("Service readiness error: {:?}", e);
DispatchError::Service(e)
})
}
fn call(&self, (io, addr): (T, Option<net::SocketAddr>)) -> Self::Future {
let on_connect_data =
OnConnectData::from_io(&io, self.on_connect_ext.as_deref());
H2ServiceHandlerResponse {
state: State::Handshake(
Some(self.flow.clone()),
Some(self.cfg.clone()),
addr,
on_connect_data,
handshake(io),
),
}
}
}
enum State<T, S: Service<Request>, B: MessageBody>
where
T: AsyncRead + AsyncWrite + Unpin,
S::Future: 'static,
{
Incoming(Dispatcher<T, S, B, (), ()>),
Handshake(
Option<Rc<HttpFlow<S, (), ()>>>,
Option<ServiceConfig>,
Option<net::SocketAddr>,
OnConnectData,
Handshake<T, Bytes>,
),
}
pub struct H2ServiceHandlerResponse<T, S, B>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error> + 'static,
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
{
state: State<T, S, B>,
}
impl<T, S, B> Future for H2ServiceHandlerResponse<T, S, B>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error> + 'static,
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody,
{
type Output = Result<(), DispatchError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.state {
State::Incoming(ref mut disp) => Pin::new(disp).poll(cx),
State::Handshake(
ref mut srv,
ref mut config,
ref peer_addr,
ref mut on_connect_data,
ref mut handshake,
) => match ready!(Pin::new(handshake).poll(cx)) {
Ok(conn) => {
let on_connect_data = std::mem::take(on_connect_data);
self.state = State::Incoming(Dispatcher::new(
srv.take().unwrap(),
conn,
on_connect_data,
config.take().unwrap(),
*peer_addr,
));
self.poll(cx)
}
Err(err) => {
trace!("H2 handshake error: {}", err);
Poll::Ready(Err(err.into()))
}
},
}
}
}
| 29.698592 | 87 | 0.542445 |
c1f0c31aaf8613b891758c1c12dc5edb540ac73f
| 1,177 |
// * This file is part of the uutils coreutils package.
// *
// * (c) Benoit Benedetti <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
/* last synced with: logname (GNU coreutils) 8.22 */
// spell-checker:ignore (ToDO) getlogin userlogin
#[macro_use]
extern crate uucore;
use std::ffi::CStr;
extern "C" {
// POSIX requires using getlogin (or equivalent code)
pub fn getlogin() -> *const libc::c_char;
}
fn get_userlogin() -> Option<String> {
unsafe {
let login: *const libc::c_char = getlogin();
if login.is_null() {
None
} else {
Some(String::from_utf8_lossy(CStr::from_ptr(login).to_bytes()).to_string())
}
}
}
static SYNTAX: &str = "";
static SUMMARY: &str = "Print user's login name";
static LONG_HELP: &str = "";
pub fn uumain(args: impl uucore::Args) -> i32 {
app!(SYNTAX, SUMMARY, LONG_HELP).parse(args.collect_str());
match get_userlogin() {
Some(userlogin) => println!("{}", userlogin),
None => show_error!("no login name"),
}
0
}
| 25.042553 | 87 | 0.623619 |
fe0c7a07d1c84df63f7d386d3e9939007cb7f426
| 653 |
//! Implements the static ecdh algorithm required by discv5 in terms of the `k256` library.
use k256::{
ecdsa::{SigningKey, VerifyingKey},
elliptic_curve::sec1::ToEncodedPoint,
};
pub fn ecdh(public_key: &VerifyingKey, secret_key: &SigningKey) -> Vec<u8> {
k256::PublicKey::from_affine(
(&k256::PublicKey::from_sec1_bytes(public_key.to_bytes().as_ref())
.unwrap()
.to_projective()
* k256::SecretKey::from_bytes(secret_key.to_bytes())
.unwrap()
.secret_scalar())
.to_affine(),
)
.unwrap()
.to_encoded_point(true)
.as_bytes()
.to_vec()
}
| 29.681818 | 91 | 0.607963 |
cc2a0ad209ae4499d513dfcd15c2820125061713
| 18,671 |
//! The shared module contains all common structs and enums used in the API
// use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fmt::Formatter;
/// An error response returned from the API
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ErrorMessage {
/// The data about the error
pub error: ErrorMessageData,
}
impl fmt::Display for ErrorMessage {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"Error Code: {} Error Message: {} Error Data: {:#?}",
self.error.code, self.error.message, self.error.data
)
}
}
impl Error for ErrorMessage {}
/// A representation of an error message
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ErrorMessageData {
/// The API sent error code
pub code: i32,
/// The message sent from the API about the error
pub message: String,
/// The data sent from the API server about the error in detail
pub data: Option<HashMap<String, Vec<String>>>,
}
/// The representation of agent information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct AgentInformation {
#[serde(rename = "accountId")]
/// The unique account id of the agent
pub account_id: String,
/// The given agent symbol/name
pub symbol: String,
/// The agent's headquarters location
pub headquarters: String,
/// The agent's current credit balance
pub credits: i64,
}
/// The representation of faction information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct FactionInformation {
/// The faction's symbol
pub symbol: String,
/// The faction's name
pub name: String,
/// A short description of the faction
pub description: String,
/// The faction's headquarters location
pub headquarters: String,
/// A list of faction traits
pub traits: Vec<String>,
}
/// The representation of a contract
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct Contract {
/// The unique contract id
pub id: String,
/// The faction giving the contract
pub faction: String,
/// The type of contract
#[serde(rename = "type")]
pub contract_type: String,
/// The contract's terms
pub terms: ContractTerms,
/// Whether the contract has been accepted
pub accepted: bool,
/// Whether the contract has been fulfilled
pub fulfilled: bool,
/// The expiry timestamp for the contract (must accept before)
#[serde(rename = "expiresAt")]
pub expires_at: String,
}
/// The representation of contract terms
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ContractTerms {
/// The deadline for the contract (must fulfill before)
pub deadline: String,
/// The payment terms for the contract
pub payment: ContractPaymentTerms,
/// The delivery terms for the contract
pub deliver: Vec<ContractDeliveryTerms>,
}
/// The representation of contract payment terms
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ContractPaymentTerms {
/// The payment upon contract acceptance
#[serde(rename = "onAccepted")]
pub on_accepted: i64,
/// The payment upon contract fulfillment
#[serde(rename = "onFulfilled")]
pub on_fulfilled: i64,
}
/// The representation of contract delivery terms
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ContractDeliveryTerms {
/// The trade symbol of the good requested by the contract
#[serde(rename = "tradeSymbol")]
pub trade_symbol: String,
/// The delivery destination for the contract
pub destination: String,
/// The number of units required by the contract
pub units: i64,
/// The number of already delivered units for this contract
pub fulfilled: i64,
}
/// The representation of a ship
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct Ship {
/// The ship's unique symbol
pub symbol: String,
/// Appears to be unimplemented 3/11/22
pub crew: Option<String>,
/// Appears to be unimplemented 3/11/22
pub officers: Option<String>,
/// The fuel remaining
pub fuel: i64,
/// The installed frame
pub frame: String,
/// The installed reactor
pub reactor: String,
/// The installed engine
pub engine: String,
/// A list of the installed modules
pub modules: Vec<String>,
/// A list of the installed mounts
pub mounts: Vec<String>,
/// The ship's stats like fuelTank, jumpRange, and cargoLimit
pub stats: ShipStats,
/// The ship's registration information
pub registration: ShipRegistration,
/// The ship's integrity information
pub integrity: ShipIntegrity,
/// The ship's status/activity
pub status: String,
/// The ship's current location
pub location: Option<String>,
/// The ship's stored cargo
pub cargo: Vec<Cargo>,
}
/// The representation of ship registration
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ShipRegistration {
/// The faction symbol that issued the registration
#[serde(rename = "factionSymbol")]
pub faction_symbol: String,
/// The agent symbol whom the ship is registered to
#[serde(rename = "agentSymbol")]
pub agent_symbol: String,
/// The registration fee
pub fee: i64,
/// The registered role
pub role: String,
}
/// The representation of ship integrity
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ShipIntegrity {
/// The ship frame integrity
pub frame: u16,
/// The ship reactor integrity
pub reactor: u16,
/// The ship engine integrity
pub engine: u16,
}
/// The representation of ship stats
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ShipStats {
/// The ship fuel tank size
#[serde(rename = "fuelTank")]
pub fuel_tank: u16,
/// The ship cargo limit
#[serde(rename = "cargoLimit")]
pub cargo_limit: u16,
/// The ship jump range
#[serde(rename = "jumpRange")]
pub jump_range: u16,
}
/// The representation of cargo
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct Cargo {
/// The good's trade symbol
#[serde(rename = "tradeSymbol")]
pub trade_symbol: String,
/// The number of units
pub units: i64,
}
/// The representation of response meta info
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct Meta {
/// The total
pub total: u16,
/// The page
pub page: u16,
/// The limit
pub limit: u16,
}
/// The representation of navigation information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct NavigationInformation {
/// The symbol of the ship navigating
pub navigation: Navigation,
/// The fuel cost of this flight
#[serde(rename = "fuelCost")]
pub fuel_cost: i64,
}
/// The representation of navigation summary
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct NavigationSummary {
/// The symbol of the ship navigating
pub navigation: Navigation,
}
/// The representation of a navigation object
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct Navigation {
/// The symbol of the ship navigating
#[serde(rename = "shipSymbol")]
pub ship_symbol: String,
/// The departure location
pub departure: String,
/// The destination location
pub destination: String,
/// Duration remaining as of call
#[serde(rename = "durationRemaining")]
pub duration_remaining: Option<u64>,
/// Timestamp of arrival
#[serde(rename = "arrivedAt")]
pub arrived_at: Option<String>,
}
/// The representation of cooldown data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct CooldownData {
/// The cooldown object
pub cooldown: Cooldown,
}
/// The representation of a cooldown object
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct Cooldown {
/// The duration remaining
pub duration: u64,
/// The timestamp for the end of the cooldown
pub expiration: String,
}
/// The representation of survey data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct SurveyData {
/// The cooldown data
pub cooldown: Cooldown,
/// List of surveys (extraction locations) available
pub surveys: Vec<Survey>,
}
/// The representation of a survey
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct Survey {
/// The signature of the survey
pub signature: String,
/// The list of deposits that the survey found
pub deposits: Vec<String>,
/// The expiration timestamp for the survey
pub expiration: String,
}
/// The representation of system information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct SystemInformation {
/// The symbol for the system
pub symbol: String,
/// The sector that contains this system
pub sector: String,
/// The type of system
#[serde(rename = "type")]
pub system_type: String,
/// The system x coordinate
pub x: i64,
/// The system y coordinate
pub y: i64,
/// A list of waypoints in the system
pub waypoints: Vec<String>,
/// A list of factions in the system
pub factions: Vec<String>,
/// Whether the system has been charted
pub charted: bool,
/// Who charted the system
#[serde(rename = "chartedBy")]
pub charted_by: Option<String>,
}
/// The representation of extract data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ExtractData {
/// The extraction information
pub extraction: Extraction,
/// The cooldown till next extraction
pub cooldown: Cooldown,
}
/// The representation of extraction information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct Extraction {
/// The symbol of the ship that completed extraction
#[serde(rename = "shipSymbol")]
pub ship_symbol: String,
/// The materials yielded from the extraction
#[serde(rename = "yield")]
pub extract_yield: Cargo,
}
/// The representation of status data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct StatusData {
/// The cooldown remaining in seconds
pub status: String,
}
/// The representation of delivery data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct DeliveryData {
/// The trade symbol delivered
#[serde(rename = "tradeSymbol")]
pub trade_symbol: String,
/// The destination delivered to
pub destination: String,
/// The number of units needed to fulfill the contract
pub units: i64,
/// The number of units fulfilled, after delivery
pub fulfilled: i64,
}
/// The representation of refuel data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct RefuelData {
/// The amount of credits spent on fuel
pub credits: i64,
/// The amount of fuel bought
pub fuel: i64,
}
/// The various scan modes
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub enum ScanMode {
/// Approaching ships scan mode
#[serde(rename = "APPROACHING_SHIPS")]
ApproachingShips,
}
/// The representation of scan data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ScanData {
/// Cooldown till next scan available
pub cooldown: Cooldown,
/// List of ship scan data
pub ships: Vec<ShipScan>,
}
/// The representation of a ship scan
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ShipScan {
/// Scanned ship symbol
pub symbol: String,
/// Scanned ship registration
pub registration: ShipScanRegistration,
/// Scanned ship frame symbol
#[serde(rename = "frameSymbol")]
pub frame_symbol: String,
/// Scanned ship reactor symbol
#[serde(rename = "reactorSymbol")]
pub reactor_symbol: String,
/// Scanned ship engine symbol
#[serde(rename = "engineSymbol")]
pub engine_symbol: String,
/// Scan expiration
pub expiration: String,
}
/// The representation of a ship scan registration
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ShipScanRegistration {
/// Faction symbol of scanned ship
#[serde(rename = "factionSymbol")]
pub faction_symbol: String,
/// Role of scanned ship
pub role: String,
}
/// The representation of waypoint information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct WaypointInformation {
/// The symbol for the system
pub system: String,
/// The symbol for the waypoint
pub symbol: String,
/// The type of waypoint
#[serde(rename = "type")]
pub system_type: String,
/// The waypoint x coordinate
pub x: i64,
/// The waypoint y coordinate
pub y: i64,
/// A list of celestial bodies orbiting the waypoint
pub orbitals: Vec<String>,
/// The faction that controls the waypoint
pub faction: String,
/// Waypoint features
pub features: Vec<String>,
/// Waypoint traits
pub traits: Vec<String>,
/// Whether the waypoint has been charted
pub charted: bool,
/// Who charted the system
#[serde(rename = "chartedBy")]
pub charted_by: Option<String>,
}
/// The representation of shipyard information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ShipyardInformation {
/// The symbol for the shipyard
pub symbol: String,
/// The symbol for the system
pub system: String,
/// The faction that controls the shipyard
pub faction: String,
/// Ship types available
pub ships: i64,
}
/// The representation of a ship listing
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ShipListing {
/// The ship listing's id
pub id: String,
/// The waypoint the listing corresponds to
pub waypoint: String,
/// The price of the listing
pub price: i64,
/// The role of the ship
pub role: String,
/// The installed frame
pub frame: String,
/// The installed reactor
pub reactor: String,
/// The installed engine
pub engine: String,
/// A list of the installed modules
pub modules: Vec<String>,
/// A list of the installed mounts
pub mounts: Vec<String>,
}
/// The representation of market information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct MarketInformation {
/// The list of imported goods
pub imports: Vec<MarketGood>,
/// The list of exported goods
pub exports: Vec<MarketGood>,
/// The list of exchange goods
pub exchange: Vec<MarketGood>,
}
/// The representation of market goods
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct MarketGood {
#[serde(rename = "waypointSymbol")]
/// The waypoint symbol
pub waypoint_symbol: String,
#[serde(rename = "tradeSymbol")]
/// The trade symbol
pub trade_symbol: String,
/// The credit delta per unit
pub price: i64,
/// The tariff delta per unit
pub tariff: i64,
}
/// The representation of jettison data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct JettisonData {
#[serde(rename = "tradeSymbol")]
/// The trade symbol of the good jettisoned
pub trade_symbol: String,
/// The number of units jettisoned
pub units: i64,
}
/// The representation of transaction data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct TransactionData {
#[serde(rename = "waypointSymbol")]
/// The waypoint symbol of the market
pub waypoint_symbol: String,
#[serde(rename = "tradeSymbol")]
/// The trade symbol of the good traded
pub trade_symbol: String,
/// The delta of credits after TX
pub credits: i64,
/// The delta units in cargo after TX
pub units: i64,
}
/// The representation of jump data with cooldown
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct JumpDataWithCooldown {
/// The jump data
pub jump: JumpData,
/// The cooldown data
pub cooldown: CooldownData,
}
/// The representation of jump data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct JumpData {
#[serde(rename = "shipSymbol")]
/// The ship symbol
pub ship_symbol: String,
/// The destination of the jump
pub destination: String,
}
/// The representation of chart data
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(debug_assertions, serde(deny_unknown_fields))]
pub struct ChartData {
/// The submitted symbols
pub submitted: Option<Vec<String>>,
}
| 31.327181 | 75 | 0.696535 |
297da7e38f2b905514f7c5fb3d385020afe8b7bb
| 322 |
use super::state::*;
impl TracesShow {
pub fn select_index(&self, index: usize) {
if let Some(on_select) = self.on_select.as_ref() {
(on_select)(index);
self.selected_index.set(Some(index));
}
}
pub fn deselect(&self) {
self.selected_index.set(None);
}
}
| 20.125 | 58 | 0.562112 |
330776fc8c5980f8fdaee02cac5cfdb3a4c365e7
| 83,263 |
use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
use rustc_ast::attr;
use rustc_ast::ptr::P as AstP;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::thin_vec::ThinVec;
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_session::parse::feature_err;
use rustc_span::hygiene::ForLoopLoc;
use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_target::asm;
use std::collections::hash_map::Entry;
use std::fmt::Write;
impl<'hir> LoweringContext<'_, 'hir> {
fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
}
pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
self.arena.alloc(self.lower_expr_mut(e))
}
pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
ensure_sufficient_stack(|| {
let kind = match e.kind {
ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
ExprKind::ConstBlock(ref anon_const) => {
let anon_const = self.lower_anon_const(anon_const);
hir::ExprKind::ConstBlock(anon_const)
}
ExprKind::Repeat(ref expr, ref count) => {
let expr = self.lower_expr(expr);
let count = self.lower_anon_const(count);
hir::ExprKind::Repeat(expr, count)
}
ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
ExprKind::Call(ref f, ref args) => {
let f = self.lower_expr(f);
hir::ExprKind::Call(f, self.lower_exprs(args))
}
ExprKind::MethodCall(ref seg, ref args, span) => {
let hir_seg = self.arena.alloc(self.lower_path_segment(
e.span,
seg,
ParamMode::Optional,
0,
ParenthesizedGenericArgs::Err,
ImplTraitContext::disallowed(),
None,
));
let args = self.lower_exprs(args);
hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args, span)
}
ExprKind::Binary(binop, ref lhs, ref rhs) => {
let binop = self.lower_binop(binop);
let lhs = self.lower_expr(lhs);
let rhs = self.lower_expr(rhs);
hir::ExprKind::Binary(binop, lhs, rhs)
}
ExprKind::Unary(op, ref ohs) => {
let op = self.lower_unop(op);
let ohs = self.lower_expr(ohs);
hir::ExprKind::Unary(op, ohs)
}
ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.kind.clone())),
ExprKind::Cast(ref expr, ref ty) => {
let expr = self.lower_expr(expr);
let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
hir::ExprKind::Cast(expr, ty)
}
ExprKind::Type(ref expr, ref ty) => {
let expr = self.lower_expr(expr);
let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
hir::ExprKind::Type(expr, ty)
}
ExprKind::AddrOf(k, m, ref ohs) => {
let ohs = self.lower_expr(ohs);
hir::ExprKind::AddrOf(k, m, ohs)
}
ExprKind::Let(ref pat, ref scrutinee) => {
self.lower_expr_let(e.span, pat, scrutinee)
}
ExprKind::If(ref cond, ref then, ref else_opt) => {
self.lower_expr_if(e.span, cond, then, else_opt.as_deref())
}
ExprKind::While(ref cond, ref body, opt_label) => self
.with_loop_scope(e.id, |this| {
this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label)
}),
ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
hir::ExprKind::Loop(
this.lower_block(body, false),
opt_label,
hir::LoopSource::Loop,
)
}),
ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
self.lower_expr(expr),
self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
hir::MatchSource::Normal,
),
ExprKind::Async(capture_clause, closure_node_id, ref block) => self
.make_async_expr(
capture_clause,
closure_node_id,
None,
block.span,
hir::AsyncGeneratorKind::Block,
|this| this.with_new_scopes(|this| this.lower_block_expr(block)),
),
ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
ExprKind::Closure(
capture_clause,
asyncness,
movability,
ref decl,
ref body,
fn_decl_span,
) => {
if let Async::Yes { closure_id, .. } = asyncness {
self.lower_expr_async_closure(
capture_clause,
closure_id,
decl,
body,
fn_decl_span,
)
} else {
self.lower_expr_closure(
capture_clause,
movability,
decl,
body,
fn_decl_span,
)
}
}
ExprKind::Block(ref blk, opt_label) => {
hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
}
ExprKind::Assign(ref el, ref er, span) => {
self.lower_expr_assign(el, er, span, e.span)
}
ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
self.lower_binop(op),
self.lower_expr(el),
self.lower_expr(er),
),
ExprKind::Field(ref el, ident) => hir::ExprKind::Field(self.lower_expr(el), ident),
ExprKind::Index(ref el, ref er) => {
hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
}
ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
self.lower_expr_range_closed(e.span, e1, e2)
}
ExprKind::Range(ref e1, ref e2, lims) => {
self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
}
ExprKind::Path(ref qself, ref path) => {
let qpath = self.lower_qpath(
e.id,
qself,
path,
ParamMode::Optional,
ImplTraitContext::disallowed(),
);
hir::ExprKind::Path(qpath)
}
ExprKind::Break(opt_label, ref opt_expr) => {
let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
}
ExprKind::Continue(opt_label) => {
hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
}
ExprKind::Ret(ref e) => {
let e = e.as_ref().map(|x| self.lower_expr(x));
hir::ExprKind::Ret(e)
}
ExprKind::InlineAsm(ref asm) => self.lower_expr_asm(e.span, asm),
ExprKind::LlvmInlineAsm(ref asm) => self.lower_expr_llvm_asm(asm),
ExprKind::Struct(ref path, ref fields, ref rest) => {
let rest = match rest {
StructRest::Base(e) => Some(self.lower_expr(e)),
StructRest::Rest(sp) => {
self.sess
.struct_span_err(*sp, "base expression required after `..`")
.span_label(*sp, "add a base expression here")
.emit();
Some(&*self.arena.alloc(self.expr_err(*sp)))
}
StructRest::None => None,
};
hir::ExprKind::Struct(
self.arena.alloc(self.lower_qpath(
e.id,
&None,
path,
ParamMode::Optional,
ImplTraitContext::disallowed(),
)),
self.arena.alloc_from_iter(fields.iter().map(|x| self.lower_field(x))),
rest,
)
}
ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
ExprKind::Err => hir::ExprKind::Err,
ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
ExprKind::Paren(ref ex) => {
let mut ex = self.lower_expr_mut(ex);
// Include parens in span, but only if it is a super-span.
if e.span.contains(ex.span) {
ex.span = e.span;
}
// Merge attributes into the inner expression.
let mut attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
attrs.extend::<Vec<_>>(ex.attrs.into());
ex.attrs = attrs.into();
return ex;
}
// Desugar `ExprForLoop`
// from: `[opt_ident]: for <pat> in <head> <body>`
ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
return self.lower_expr_for(e, pat, head, body, opt_label);
}
ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
};
hir::Expr {
hir_id: self.lower_node_id(e.id),
kind,
span: e.span,
attrs: e.attrs.iter().map(|a| self.lower_attr(a)).collect::<Vec<_>>().into(),
}
})
}
fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
match u {
UnOp::Deref => hir::UnOp::UnDeref,
UnOp::Not => hir::UnOp::UnNot,
UnOp::Neg => hir::UnOp::UnNeg,
}
}
fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
Spanned {
node: match b.node {
BinOpKind::Add => hir::BinOpKind::Add,
BinOpKind::Sub => hir::BinOpKind::Sub,
BinOpKind::Mul => hir::BinOpKind::Mul,
BinOpKind::Div => hir::BinOpKind::Div,
BinOpKind::Rem => hir::BinOpKind::Rem,
BinOpKind::And => hir::BinOpKind::And,
BinOpKind::Or => hir::BinOpKind::Or,
BinOpKind::BitXor => hir::BinOpKind::BitXor,
BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
BinOpKind::BitOr => hir::BinOpKind::BitOr,
BinOpKind::Shl => hir::BinOpKind::Shl,
BinOpKind::Shr => hir::BinOpKind::Shr,
BinOpKind::Eq => hir::BinOpKind::Eq,
BinOpKind::Lt => hir::BinOpKind::Lt,
BinOpKind::Le => hir::BinOpKind::Le,
BinOpKind::Ne => hir::BinOpKind::Ne,
BinOpKind::Ge => hir::BinOpKind::Ge,
BinOpKind::Gt => hir::BinOpKind::Gt,
},
span: b.span,
}
}
/// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
/// ```rust
/// match scrutinee { pats => true, _ => false }
/// ```
fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind<'hir> {
// If we got here, the `let` expression is not allowed.
if self.sess.opts.unstable_features.is_nightly_build() {
self.sess
.struct_span_err(span, "`let` expressions are not supported here")
.note("only supported directly in conditions of `if`- and `while`-expressions")
.note("as well as when nested within `&&` and parenthesis in those conditions")
.emit();
} else {
self.sess
.struct_span_err(span, "expected expression, found statement (`let`)")
.note("variable declaration using `let` is a statement")
.emit();
}
// For better recovery, we emit:
// ```
// match scrutinee { pat => true, _ => false }
// ```
// While this doesn't fully match the user's intent, it has key advantages:
// 1. We can avoid using `abort_if_errors`.
// 2. We can typeck both `pat` and `scrutinee`.
// 3. `pat` is allowed to be refutable.
// 4. The return type of the block is `bool` which seems like what the user wanted.
let scrutinee = self.lower_expr(scrutinee);
let then_arm = {
let pat = self.lower_pat(pat);
let expr = self.expr_bool(span, true);
self.arm(pat, expr)
};
let else_arm = {
let pat = self.pat_wild(span);
let expr = self.expr_bool(span, false);
self.arm(pat, expr)
};
hir::ExprKind::Match(
scrutinee,
arena_vec![self; then_arm, else_arm],
hir::MatchSource::Normal,
)
}
fn lower_expr_if(
&mut self,
span: Span,
cond: &Expr,
then: &Block,
else_opt: Option<&Expr>,
) -> hir::ExprKind<'hir> {
// FIXME(#53667): handle lowering of && and parens.
// `_ => else_block` where `else_block` is `{}` if there's `None`:
let else_pat = self.pat_wild(span);
let (else_expr, contains_else_clause) = match else_opt {
None => (self.expr_block_empty(span), false),
Some(els) => (self.lower_expr(els), true),
};
let else_arm = self.arm(else_pat, else_expr);
// Handle then + scrutinee:
let then_expr = self.lower_block_expr(then);
let (then_pat, scrutinee, desugar) = match cond.kind {
// `<pat> => <then>`:
ExprKind::Let(ref pat, ref scrutinee) => {
let scrutinee = self.lower_expr(scrutinee);
let pat = self.lower_pat(pat);
(pat, scrutinee, hir::MatchSource::IfLetDesugar { contains_else_clause })
}
// `true => <then>`:
_ => {
// Lower condition:
let cond = self.lower_expr(cond);
let span_block =
self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
// Wrap in a construct equivalent to `{ let _t = $cond; _t }`
// to preserve drop semantics since `if cond { ... }` does not
// let temporaries live outside of `cond`.
let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
let pat = self.pat_bool(span, true);
(pat, cond, hir::MatchSource::IfDesugar { contains_else_clause })
}
};
let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar)
}
fn lower_expr_while_in_loop_scope(
&mut self,
span: Span,
cond: &Expr,
body: &Block,
opt_label: Option<Label>,
) -> hir::ExprKind<'hir> {
// FIXME(#53667): handle lowering of && and parens.
// Note that the block AND the condition are evaluated in the loop scope.
// This is done to allow `break` from inside the condition of the loop.
// `_ => break`:
let else_arm = {
let else_pat = self.pat_wild(span);
let else_expr = self.expr_break(span, ThinVec::new());
self.arm(else_pat, else_expr)
};
// Handle then + scrutinee:
let then_expr = self.lower_block_expr(body);
let (then_pat, scrutinee, desugar, source) = match cond.kind {
ExprKind::Let(ref pat, ref scrutinee) => {
// to:
//
// [opt_ident]: loop {
// match <sub_expr> {
// <pat> => <body>,
// _ => break
// }
// }
let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
let pat = self.lower_pat(pat);
(pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
}
_ => {
// We desugar: `'label: while $cond $body` into:
//
// ```
// 'label: loop {
// match drop-temps { $cond } {
// true => $body,
// _ => break,
// }
// }
// ```
// Lower condition:
let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
let span_block =
self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
// Wrap in a construct equivalent to `{ let _t = $cond; _t }`
// to preserve drop semantics since `while cond { ... }` does not
// let temporaries live outside of `cond`.
let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
// `true => <then>`:
let pat = self.pat_bool(span, true);
(pat, cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
}
};
let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
// `match <scrutinee> { ... }`
let match_expr =
self.expr_match(span, scrutinee, arena_vec![self; then_arm, else_arm], desugar);
// `[opt_ident]: loop { ... }`
hir::ExprKind::Loop(self.block_expr(self.arena.alloc(match_expr)), opt_label, source)
}
/// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_ok(<expr>) }`,
/// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_ok(()) }`
/// and save the block id to use it as a break target for desugaring of the `?` operator.
fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
self.with_catch_scope(body.id, |this| {
let mut block = this.lower_block_noalloc(body, true);
// Final expression of the block (if present) or `()` with span at the end of block
let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
(
this.mark_span_with_reason(
DesugaringKind::TryBlock,
expr.span,
this.allow_try_trait.clone(),
),
expr,
)
} else {
let try_span = this.mark_span_with_reason(
DesugaringKind::TryBlock,
this.sess.source_map().end_point(body.span),
this.allow_try_trait.clone(),
);
(try_span, this.expr_unit(try_span))
};
let ok_wrapped_span =
this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
// `::std::ops::Try::from_ok($tail_expr)`
block.expr = Some(this.wrap_in_try_constructor(
hir::LangItem::TryFromOk,
try_span,
tail_expr,
ok_wrapped_span,
));
hir::ExprKind::Block(this.arena.alloc(block), None)
})
}
fn wrap_in_try_constructor(
&mut self,
lang_item: hir::LangItem,
method_span: Span,
expr: &'hir hir::Expr<'hir>,
overall_span: Span,
) -> &'hir hir::Expr<'hir> {
let constructor =
self.arena.alloc(self.expr_lang_item_path(method_span, lang_item, ThinVec::new()));
self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
}
fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
hir::Arm {
hir_id: self.next_id(),
attrs: self.lower_attrs(&arm.attrs),
pat: self.lower_pat(&arm.pat),
guard: match arm.guard {
Some(ref x) => Some(hir::Guard::If(self.lower_expr(x))),
_ => None,
},
body: self.lower_expr(&arm.body),
span: arm.span,
}
}
/// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
///
/// This results in:
///
/// ```text
/// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
/// <body>
/// })
/// ```
pub(super) fn make_async_expr(
&mut self,
capture_clause: CaptureBy,
closure_node_id: NodeId,
ret_ty: Option<AstP<Ty>>,
span: Span,
async_gen_kind: hir::AsyncGeneratorKind,
body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
) -> hir::ExprKind<'hir> {
let output = match ret_ty {
Some(ty) => hir::FnRetTy::Return(self.lower_ty(&ty, ImplTraitContext::disallowed())),
None => hir::FnRetTy::DefaultReturn(span),
};
// Resume argument type. We let the compiler infer this to simplify the lowering. It is
// fully constrained by `future::from_generator`.
let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Infer, span };
// The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
let decl = self.arena.alloc(hir::FnDecl {
inputs: arena_vec![self; input_ty],
output,
c_variadic: false,
implicit_self: hir::ImplicitSelfKind::None,
});
// Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
let (pat, task_context_hid) = self.pat_ident_binding_mode(
span,
Ident::with_dummy_span(sym::_task_context),
hir::BindingAnnotation::Mutable,
);
let param = hir::Param { attrs: &[], hir_id: self.next_id(), pat, ty_span: span, span };
let params = arena_vec![self; param];
let body_id = self.lower_body(move |this| {
this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
let old_ctx = this.task_context;
this.task_context = Some(task_context_hid);
let res = body(this);
this.task_context = old_ctx;
(params, res)
});
// `static |_task_context| -> <ret_ty> { body }`:
let generator_kind = hir::ExprKind::Closure(
capture_clause,
decl,
body_id,
span,
Some(hir::Movability::Static),
);
let generator = hir::Expr {
hir_id: self.lower_node_id(closure_node_id),
kind: generator_kind,
span,
attrs: ThinVec::new(),
};
// `future::from_generator`:
let unstable_span =
self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
let gen_future =
self.expr_lang_item_path(unstable_span, hir::LangItem::FromGenerator, ThinVec::new());
// `future::from_generator(generator)`:
hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
}
/// Desugar `<expr>.await` into:
/// ```rust
/// match <expr> {
/// mut pinned => loop {
/// match unsafe { ::std::future::Future::poll(
/// <::std::pin::Pin>::new_unchecked(&mut pinned),
/// ::std::future::get_context(task_context),
/// ) } {
/// ::std::task::Poll::Ready(result) => break result,
/// ::std::task::Poll::Pending => {}
/// }
/// task_context = yield ();
/// }
/// }
/// ```
fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
match self.generator_kind {
Some(hir::GeneratorKind::Async(_)) => {}
Some(hir::GeneratorKind::Gen) | None => {
let mut err = struct_span_err!(
self.sess,
await_span,
E0728,
"`await` is only allowed inside `async` functions and blocks"
);
err.span_label(await_span, "only allowed inside `async` functions and blocks");
if let Some(item_sp) = self.current_item {
err.span_label(item_sp, "this is not `async`");
}
err.emit();
}
}
let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None);
let gen_future_span = self.mark_span_with_reason(
DesugaringKind::Await,
await_span,
self.allow_gen_future.clone(),
);
let expr = self.lower_expr(expr);
let pinned_ident = Ident::with_dummy_span(sym::pinned);
let (pinned_pat, pinned_pat_hid) =
self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
let task_context_ident = Ident::with_dummy_span(sym::_task_context);
// unsafe {
// ::std::future::Future::poll(
// ::std::pin::Pin::new_unchecked(&mut pinned),
// ::std::future::get_context(task_context),
// )
// }
let poll_expr = {
let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
let task_context = if let Some(task_context_hid) = self.task_context {
self.expr_ident_mut(span, task_context_ident, task_context_hid)
} else {
// Use of `await` outside of an async context, we cannot use `task_context` here.
self.expr_err(span)
};
let new_unchecked = self.expr_call_lang_item_fn_mut(
span,
hir::LangItem::PinNewUnchecked,
arena_vec![self; ref_mut_pinned],
);
let get_context = self.expr_call_lang_item_fn_mut(
gen_future_span,
hir::LangItem::GetContext,
arena_vec![self; task_context],
);
let call = self.expr_call_lang_item_fn(
span,
hir::LangItem::FuturePoll,
arena_vec![self; new_unchecked, get_context],
);
self.arena.alloc(self.expr_unsafe(call))
};
// `::std::task::Poll::Ready(result) => break result`
let loop_node_id = self.resolver.next_node_id();
let loop_hir_id = self.lower_node_id(loop_node_id);
let ready_arm = {
let x_ident = Ident::with_dummy_span(sym::result);
let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
let x_expr = self.expr_ident(span, x_ident, x_pat_hid);
let ready_field = self.single_pat_field(span, x_pat);
let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
let break_x = self.with_loop_scope(loop_node_id, move |this| {
let expr_break =
hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new()))
});
self.arm(ready_pat, break_x)
};
// `::std::task::Poll::Pending => {}`
let pending_arm = {
let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]);
let empty_block = self.expr_block_empty(span);
self.arm(pending_pat, empty_block)
};
let inner_match_stmt = {
let match_expr = self.expr_match(
span,
poll_expr,
arena_vec![self; ready_arm, pending_arm],
hir::MatchSource::AwaitDesugar,
);
self.stmt_expr(span, match_expr)
};
// task_context = yield ();
let yield_stmt = {
let unit = self.expr_unit(span);
let yield_expr = self.expr(
span,
hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr.hir_id) }),
ThinVec::new(),
);
let yield_expr = self.arena.alloc(yield_expr);
if let Some(task_context_hid) = self.task_context {
let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
let assign =
self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, span), AttrVec::new());
self.stmt_expr(span, assign)
} else {
// Use of `await` outside of an async context. Return `yield_expr` so that we can
// proceed with type checking.
self.stmt(span, hir::StmtKind::Semi(yield_expr))
}
};
let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
// loop { .. }
let loop_expr = self.arena.alloc(hir::Expr {
hir_id: loop_hir_id,
kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop),
span,
attrs: ThinVec::new(),
});
// mut pinned => loop { ... }
let pinned_arm = self.arm(pinned_pat, loop_expr);
// match <expr> {
// mut pinned => loop { .. }
// }
hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar)
}
fn lower_expr_closure(
&mut self,
capture_clause: CaptureBy,
movability: Movability,
decl: &FnDecl,
body: &Expr,
fn_decl_span: Span,
) -> hir::ExprKind<'hir> {
// Lower outside new scope to preserve `is_in_loop_condition`.
let fn_decl = self.lower_fn_decl(decl, None, false, None);
self.with_new_scopes(move |this| {
let prev = this.current_item;
this.current_item = Some(fn_decl_span);
let mut generator_kind = None;
let body_id = this.lower_fn_body(decl, |this| {
let e = this.lower_expr_mut(body);
generator_kind = this.generator_kind;
e
});
let generator_option =
this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
this.current_item = prev;
hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, generator_option)
})
}
fn generator_movability_for_fn(
&mut self,
decl: &FnDecl,
fn_decl_span: Span,
generator_kind: Option<hir::GeneratorKind>,
movability: Movability,
) -> Option<hir::Movability> {
match generator_kind {
Some(hir::GeneratorKind::Gen) => {
if decl.inputs.len() > 1 {
struct_span_err!(
self.sess,
fn_decl_span,
E0628,
"too many parameters for a generator (expected 0 or 1 parameters)"
)
.emit();
}
Some(movability)
}
Some(hir::GeneratorKind::Async(_)) => {
panic!("non-`async` closure body turned `async` during lowering");
}
None => {
if movability == Movability::Static {
struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
.emit();
}
None
}
}
}
fn lower_expr_async_closure(
&mut self,
capture_clause: CaptureBy,
closure_id: NodeId,
decl: &FnDecl,
body: &Expr,
fn_decl_span: Span,
) -> hir::ExprKind<'hir> {
let outer_decl =
FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
// We need to lower the declaration outside the new scope, because we
// have to conserve the state of being inside a loop condition for the
// closure argument types.
let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
self.with_new_scopes(move |this| {
// FIXME(cramertj): allow `async` non-`move` closures with arguments.
if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
struct_span_err!(
this.sess,
fn_decl_span,
E0708,
"`async` non-`move` closures with parameters are not currently supported",
)
.help(
"consider using `let` statements to manually capture \
variables by reference before entering an `async move` closure",
)
.emit();
}
// Transform `async |x: u8| -> X { ... }` into
// `|x: u8| future_from_generator(|| -> X { ... })`.
let body_id = this.lower_fn_body(&outer_decl, |this| {
let async_ret_ty =
if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
let async_body = this.make_async_expr(
capture_clause,
closure_id,
async_ret_ty,
body.span,
hir::AsyncGeneratorKind::Closure,
|this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
);
this.expr(fn_decl_span, async_body, ThinVec::new())
});
hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, None)
})
}
/// Destructure the LHS of complex assignments.
/// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
fn lower_expr_assign(
&mut self,
lhs: &Expr,
rhs: &Expr,
eq_sign_span: Span,
whole_span: Span,
) -> hir::ExprKind<'hir> {
// Return early in case of an ordinary assignment.
fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
match &lhs.kind {
ExprKind::Array(..) | ExprKind::Struct(..) | ExprKind::Tup(..) => false,
// Check for tuple struct constructor.
ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
ExprKind::Paren(e) => {
match e.kind {
// We special-case `(..)` for consistency with patterns.
ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
_ => is_ordinary(lower_ctx, e),
}
}
_ => true,
}
}
if is_ordinary(self, lhs) {
return hir::ExprKind::Assign(self.lower_expr(lhs), self.lower_expr(rhs), eq_sign_span);
}
if !self.sess.features_untracked().destructuring_assignment {
feature_err(
&self.sess.parse_sess,
sym::destructuring_assignment,
eq_sign_span,
"destructuring assignments are unstable",
)
.span_label(lhs.span, "cannot assign to this expression")
.emit();
}
let mut assignments = vec![];
// The LHS becomes a pattern: `(lhs1, lhs2)`.
let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
let rhs = self.lower_expr(rhs);
// Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
let destructure_let = self.stmt_let_pat(
ThinVec::new(),
whole_span,
Some(rhs),
pat,
hir::LocalSource::AssignDesugar(eq_sign_span),
);
// `a = lhs1; b = lhs2;`.
let stmts = self
.arena
.alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
// Wrap everything in a block.
hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
}
/// If the given expression is a path to a tuple struct, returns that path.
/// It is not a complete check, but just tries to reject most paths early
/// if they are not tuple structs.
/// Type checking will take care of the full validation later.
fn extract_tuple_struct_path<'a>(&mut self, expr: &'a Expr) -> Option<&'a Path> {
// For tuple struct destructuring, it must be a non-qualified path (like in patterns).
if let ExprKind::Path(None, path) = &expr.kind {
// Does the path resolves to something disallowed in a tuple struct/variant pattern?
if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
if partial_res.unresolved_segments() == 0
&& !partial_res.base_res().expected_in_tuple_struct_pat()
{
return None;
}
}
return Some(path);
}
None
}
/// Convert the LHS of a destructuring assignment to a pattern.
/// Each sub-assignment is recorded in `assignments`.
fn destructure_assign(
&mut self,
lhs: &Expr,
eq_sign_span: Span,
assignments: &mut Vec<hir::Stmt<'hir>>,
) -> &'hir hir::Pat<'hir> {
match &lhs.kind {
// Slice patterns.
ExprKind::Array(elements) => {
let (pats, rest) =
self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
let slice_pat = if let Some((i, span)) = rest {
let (before, after) = pats.split_at(i);
hir::PatKind::Slice(
before,
Some(self.pat_without_dbm(span, hir::PatKind::Wild)),
after,
)
} else {
hir::PatKind::Slice(pats, None, &[])
};
return self.pat_without_dbm(lhs.span, slice_pat);
}
// Tuple structs.
ExprKind::Call(callee, args) => {
if let Some(path) = self.extract_tuple_struct_path(callee) {
let (pats, rest) = self.destructure_sequence(
args,
"tuple struct or variant",
eq_sign_span,
assignments,
);
let qpath = self.lower_qpath(
callee.id,
&None,
path,
ParamMode::Optional,
ImplTraitContext::disallowed(),
);
// Destructure like a tuple struct.
let tuple_struct_pat =
hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
return self.pat_without_dbm(lhs.span, tuple_struct_pat);
}
}
// Structs.
ExprKind::Struct(path, fields, rest) => {
let field_pats = self.arena.alloc_from_iter(fields.iter().map(|f| {
let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
hir::FieldPat {
hir_id: self.next_id(),
ident: f.ident,
pat,
is_shorthand: f.is_shorthand,
span: f.span,
}
}));
let qpath = self.lower_qpath(
lhs.id,
&None,
path,
ParamMode::Optional,
ImplTraitContext::disallowed(),
);
let fields_omitted = match rest {
StructRest::Base(e) => {
self.sess
.struct_span_err(
e.span,
"functional record updates are not allowed in destructuring \
assignments",
)
.span_suggestion(
e.span,
"consider removing the trailing pattern",
String::new(),
rustc_errors::Applicability::MachineApplicable,
)
.emit();
true
}
StructRest::Rest(_) => true,
StructRest::None => false,
};
let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
return self.pat_without_dbm(lhs.span, struct_pat);
}
// Tuples.
ExprKind::Tup(elements) => {
let (pats, rest) =
self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
return self.pat_without_dbm(lhs.span, tuple_pat);
}
ExprKind::Paren(e) => {
// We special-case `(..)` for consistency with patterns.
if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
return self.pat_without_dbm(lhs.span, tuple_pat);
} else {
return self.destructure_assign(e, eq_sign_span, assignments);
}
}
_ => {}
}
// Treat all other cases as normal lvalue.
let ident = Ident::new(sym::lhs, lhs.span);
let (pat, binding) = self.pat_ident(lhs.span, ident);
let ident = self.expr_ident(lhs.span, ident, binding);
let assign = hir::ExprKind::Assign(self.lower_expr(lhs), ident, eq_sign_span);
let expr = self.expr(lhs.span, assign, ThinVec::new());
assignments.push(self.stmt_expr(lhs.span, expr));
pat
}
/// Destructure a sequence of expressions occurring on the LHS of an assignment.
/// Such a sequence occurs in a tuple (struct)/slice.
/// Return a sequence of corresponding patterns, and the index and the span of `..` if it
/// exists.
/// Each sub-assignment is recorded in `assignments`.
fn destructure_sequence(
&mut self,
elements: &[AstP<Expr>],
ctx: &str,
eq_sign_span: Span,
assignments: &mut Vec<hir::Stmt<'hir>>,
) -> (&'hir [&'hir hir::Pat<'hir>], Option<(usize, Span)>) {
let mut rest = None;
let elements =
self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
// Check for `..` pattern.
if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
if let Some((_, prev_span)) = rest {
self.ban_extra_rest_pat(e.span, prev_span, ctx);
} else {
rest = Some((i, e.span));
}
None
} else {
Some(self.destructure_assign(e, eq_sign_span, assignments))
}
}));
(elements, rest)
}
/// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
let e1 = self.lower_expr_mut(e1);
let e2 = self.lower_expr_mut(e2);
let fn_path = hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, span);
let fn_expr =
self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
}
fn lower_expr_range(
&mut self,
span: Span,
e1: Option<&Expr>,
e2: Option<&Expr>,
lims: RangeLimits,
) -> hir::ExprKind<'hir> {
use rustc_ast::RangeLimits::*;
let lang_item = match (e1, e2, lims) {
(None, None, HalfOpen) => hir::LangItem::RangeFull,
(Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
(None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
(Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
(None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
(Some(..), Some(..), Closed) => unreachable!(),
(_, None, Closed) => {
self.diagnostic().span_fatal(span, "inclusive range with no end").raise()
}
};
let fields = self.arena.alloc_from_iter(
e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| {
let expr = self.lower_expr(&e);
let ident = Ident::new(Symbol::intern(s), e.span);
self.field(ident, expr, e.span)
}),
);
hir::ExprKind::Struct(self.arena.alloc(hir::QPath::LangItem(lang_item, span)), fields, None)
}
fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
let target_id = match destination {
Some((id, _)) => {
if let Some(loop_id) = self.resolver.get_label_res(id) {
Ok(self.lower_node_id(loop_id))
} else {
Err(hir::LoopIdError::UnresolvedLabel)
}
}
None => self
.loop_scopes
.last()
.cloned()
.map(|id| Ok(self.lower_node_id(id)))
.unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
};
hir::Destination { label: destination.map(|(_, label)| label), target_id }
}
fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
if self.is_in_loop_condition && opt_label.is_none() {
hir::Destination {
label: None,
target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
}
} else {
self.lower_loop_destination(opt_label.map(|label| (id, label)))
}
}
fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
let len = self.catch_scopes.len();
self.catch_scopes.push(catch_id);
let result = f(self);
assert_eq!(
len + 1,
self.catch_scopes.len(),
"catch scopes should be added and removed in stack order"
);
self.catch_scopes.pop().unwrap();
result
}
fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
// We're no longer in the base loop's condition; we're in another loop.
let was_in_loop_condition = self.is_in_loop_condition;
self.is_in_loop_condition = false;
let len = self.loop_scopes.len();
self.loop_scopes.push(loop_id);
let result = f(self);
assert_eq!(
len + 1,
self.loop_scopes.len(),
"loop scopes should be added and removed in stack order"
);
self.loop_scopes.pop().unwrap();
self.is_in_loop_condition = was_in_loop_condition;
result
}
fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
let was_in_loop_condition = self.is_in_loop_condition;
self.is_in_loop_condition = true;
let result = f(self);
self.is_in_loop_condition = was_in_loop_condition;
result
}
fn lower_expr_asm(&mut self, sp: Span, asm: &InlineAsm) -> hir::ExprKind<'hir> {
if self.sess.asm_arch.is_none() {
struct_span_err!(self.sess, sp, E0472, "asm! is unsupported on this target").emit();
}
if asm.options.contains(InlineAsmOptions::ATT_SYNTAX)
&& !matches!(
self.sess.asm_arch,
Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64)
)
{
self.sess
.struct_span_err(sp, "the `att_syntax` option is only supported on x86")
.emit();
}
// Lower operands to HIR, filter_map skips any operands with invalid
// register classes.
let sess = self.sess;
let operands: Vec<_> = asm
.operands
.iter()
.filter_map(|(op, op_sp)| {
let lower_reg = |reg| {
Some(match reg {
InlineAsmRegOrRegClass::Reg(s) => asm::InlineAsmRegOrRegClass::Reg(
asm::InlineAsmReg::parse(
sess.asm_arch?,
|feature| sess.target_features.contains(&Symbol::intern(feature)),
&sess.target,
s,
)
.map_err(|e| {
let msg = format!("invalid register `{}`: {}", s.as_str(), e);
sess.struct_span_err(*op_sp, &msg).emit();
})
.ok()?,
),
InlineAsmRegOrRegClass::RegClass(s) => {
asm::InlineAsmRegOrRegClass::RegClass(
asm::InlineAsmRegClass::parse(sess.asm_arch?, s)
.map_err(|e| {
let msg = format!(
"invalid register class `{}`: {}",
s.as_str(),
e
);
sess.struct_span_err(*op_sp, &msg).emit();
})
.ok()?,
)
}
})
};
// lower_reg is executed last because we need to lower all
// sub-expressions even if we throw them away later.
let op = match *op {
InlineAsmOperand::In { reg, ref expr } => hir::InlineAsmOperand::In {
expr: self.lower_expr_mut(expr),
reg: lower_reg(reg)?,
},
InlineAsmOperand::Out { reg, late, ref expr } => hir::InlineAsmOperand::Out {
late,
expr: expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
reg: lower_reg(reg)?,
},
InlineAsmOperand::InOut { reg, late, ref expr } => {
hir::InlineAsmOperand::InOut {
late,
expr: self.lower_expr_mut(expr),
reg: lower_reg(reg)?,
}
}
InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
hir::InlineAsmOperand::SplitInOut {
late,
in_expr: self.lower_expr_mut(in_expr),
out_expr: out_expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
reg: lower_reg(reg)?,
}
}
InlineAsmOperand::Const { ref expr } => {
hir::InlineAsmOperand::Const { expr: self.lower_expr_mut(expr) }
}
InlineAsmOperand::Sym { ref expr } => {
hir::InlineAsmOperand::Sym { expr: self.lower_expr_mut(expr) }
}
};
Some(op)
})
.collect();
// Stop if there were any errors when lowering the register classes
if operands.len() != asm.operands.len() || sess.asm_arch.is_none() {
return hir::ExprKind::Err;
}
// Validate template modifiers against the register classes for the operands
let asm_arch = sess.asm_arch.unwrap();
for p in &asm.template {
if let InlineAsmTemplatePiece::Placeholder {
operand_idx,
modifier: Some(modifier),
span: placeholder_span,
} = *p
{
let op_sp = asm.operands[operand_idx].1;
match &operands[operand_idx] {
hir::InlineAsmOperand::In { reg, .. }
| hir::InlineAsmOperand::Out { reg, .. }
| hir::InlineAsmOperand::InOut { reg, .. }
| hir::InlineAsmOperand::SplitInOut { reg, .. } => {
let class = reg.reg_class();
let valid_modifiers = class.valid_modifiers(asm_arch);
if !valid_modifiers.contains(&modifier) {
let mut err = sess.struct_span_err(
placeholder_span,
"invalid asm template modifier for this register class",
);
err.span_label(placeholder_span, "template modifier");
err.span_label(op_sp, "argument");
if !valid_modifiers.is_empty() {
let mut mods = format!("`{}`", valid_modifiers[0]);
for m in &valid_modifiers[1..] {
let _ = write!(mods, ", `{}`", m);
}
err.note(&format!(
"the `{}` register class supports \
the following template modifiers: {}",
class.name(),
mods
));
} else {
err.note(&format!(
"the `{}` register class does not support template modifiers",
class.name()
));
}
err.emit();
}
}
hir::InlineAsmOperand::Const { .. } => {
let mut err = sess.struct_span_err(
placeholder_span,
"asm template modifiers are not allowed for `const` arguments",
);
err.span_label(placeholder_span, "template modifier");
err.span_label(op_sp, "argument");
err.emit();
}
hir::InlineAsmOperand::Sym { .. } => {
let mut err = sess.struct_span_err(
placeholder_span,
"asm template modifiers are not allowed for `sym` arguments",
);
err.span_label(placeholder_span, "template modifier");
err.span_label(op_sp, "argument");
err.emit();
}
}
}
}
let mut used_input_regs = FxHashMap::default();
let mut used_output_regs = FxHashMap::default();
for (idx, op) in operands.iter().enumerate() {
let op_sp = asm.operands[idx].1;
if let Some(reg) = op.reg() {
// Validate register classes against currently enabled target
// features. We check that at least one type is available for
// the current target.
let reg_class = reg.reg_class();
let mut required_features: Vec<&str> = vec![];
for &(_, feature) in reg_class.supported_types(asm_arch) {
if let Some(feature) = feature {
if self.sess.target_features.contains(&Symbol::intern(feature)) {
required_features.clear();
break;
} else {
required_features.push(feature);
}
} else {
required_features.clear();
break;
}
}
// We are sorting primitive strs here and can use unstable sort here
required_features.sort_unstable();
required_features.dedup();
match &required_features[..] {
[] => {}
[feature] => {
let msg = format!(
"register class `{}` requires the `{}` target feature",
reg_class.name(),
feature
);
sess.struct_span_err(op_sp, &msg).emit();
}
features => {
let msg = format!(
"register class `{}` requires at least one target feature: {}",
reg_class.name(),
features.join(", ")
);
sess.struct_span_err(op_sp, &msg).emit();
}
}
// Check for conflicts between explicit register operands.
if let asm::InlineAsmRegOrRegClass::Reg(reg) = reg {
let (input, output) = match op {
hir::InlineAsmOperand::In { .. } => (true, false),
// Late output do not conflict with inputs, but normal outputs do
hir::InlineAsmOperand::Out { late, .. } => (!late, true),
hir::InlineAsmOperand::InOut { .. }
| hir::InlineAsmOperand::SplitInOut { .. } => (true, true),
hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {
unreachable!()
}
};
// Flag to output the error only once per operand
let mut skip = false;
reg.overlapping_regs(|r| {
let mut check = |used_regs: &mut FxHashMap<asm::InlineAsmReg, usize>,
input| {
match used_regs.entry(r) {
Entry::Occupied(o) => {
if skip {
return;
}
skip = true;
let idx2 = *o.get();
let op2 = &operands[idx2];
let op_sp2 = asm.operands[idx2].1;
let reg2 = match op2.reg() {
Some(asm::InlineAsmRegOrRegClass::Reg(r)) => r,
_ => unreachable!(),
};
let msg = format!(
"register `{}` conflicts with register `{}`",
reg.name(),
reg2.name()
);
let mut err = sess.struct_span_err(op_sp, &msg);
err.span_label(op_sp, &format!("register `{}`", reg.name()));
err.span_label(op_sp2, &format!("register `{}`", reg2.name()));
match (op, op2) {
(
hir::InlineAsmOperand::In { .. },
hir::InlineAsmOperand::Out { late, .. },
)
| (
hir::InlineAsmOperand::Out { late, .. },
hir::InlineAsmOperand::In { .. },
) => {
assert!(!*late);
let out_op_sp = if input { op_sp2 } else { op_sp };
let msg = "use `lateout` instead of \
`out` to avoid conflict";
err.span_help(out_op_sp, msg);
}
_ => {}
}
err.emit();
}
Entry::Vacant(v) => {
v.insert(idx);
}
}
};
if input {
check(&mut used_input_regs, true);
}
if output {
check(&mut used_output_regs, false);
}
});
}
}
}
let operands = self.arena.alloc_from_iter(operands);
let template = self.arena.alloc_from_iter(asm.template.iter().cloned());
let line_spans = self.arena.alloc_slice(&asm.line_spans[..]);
let hir_asm = hir::InlineAsm { template, operands, options: asm.options, line_spans };
hir::ExprKind::InlineAsm(self.arena.alloc(hir_asm))
}
fn lower_expr_llvm_asm(&mut self, asm: &LlvmInlineAsm) -> hir::ExprKind<'hir> {
let inner = hir::LlvmInlineAsmInner {
inputs: asm.inputs.iter().map(|&(c, _)| c).collect(),
outputs: asm
.outputs
.iter()
.map(|out| hir::LlvmInlineAsmOutput {
constraint: out.constraint,
is_rw: out.is_rw,
is_indirect: out.is_indirect,
span: out.expr.span,
})
.collect(),
asm: asm.asm,
asm_str_style: asm.asm_str_style,
clobbers: asm.clobbers.clone(),
volatile: asm.volatile,
alignstack: asm.alignstack,
dialect: asm.dialect,
};
let hir_asm = hir::LlvmInlineAsm {
inner,
inputs_exprs: self.arena.alloc_from_iter(
asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)),
),
outputs_exprs: self
.arena
.alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))),
};
hir::ExprKind::LlvmInlineAsm(self.arena.alloc(hir_asm))
}
fn lower_field(&mut self, f: &Field) -> hir::Field<'hir> {
hir::Field {
hir_id: self.next_id(),
ident: f.ident,
expr: self.lower_expr(&f.expr),
span: f.span,
is_shorthand: f.is_shorthand,
}
}
fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
match self.generator_kind {
Some(hir::GeneratorKind::Gen) => {}
Some(hir::GeneratorKind::Async(_)) => {
struct_span_err!(
self.sess,
span,
E0727,
"`async` generators are not yet supported"
)
.emit();
}
None => self.generator_kind = Some(hir::GeneratorKind::Gen),
}
let expr =
opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
}
/// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
/// ```rust
/// {
/// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
/// mut iter => {
/// [opt_ident]: loop {
/// let mut __next;
/// match ::std::iter::Iterator::next(&mut iter) {
/// ::std::option::Option::Some(val) => __next = val,
/// ::std::option::Option::None => break
/// };
/// let <pat> = __next;
/// StmtKind::Expr(<body>);
/// }
/// }
/// };
/// result
/// }
/// ```
fn lower_expr_for(
&mut self,
e: &Expr,
pat: &Pat,
head: &Expr,
body: &Block,
opt_label: Option<Label>,
) -> hir::Expr<'hir> {
let orig_head_span = head.span;
// expand <head>
let mut head = self.lower_expr_mut(head);
let desugared_span = self.mark_span_with_reason(
DesugaringKind::ForLoop(ForLoopLoc::Head),
orig_head_span,
None,
);
head.span = desugared_span;
let iter = Ident::with_dummy_span(sym::iter);
let next_ident = Ident::with_dummy_span(sym::__next);
let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
desugared_span,
next_ident,
hir::BindingAnnotation::Mutable,
);
// `::std::option::Option::Some(val) => __next = val`
let pat_arm = {
let val_ident = Ident::with_dummy_span(sym::val);
let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid);
let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid);
let assign = self.arena.alloc(self.expr(
pat.span,
hir::ExprKind::Assign(next_expr, val_expr, pat.span),
ThinVec::new(),
));
let some_pat = self.pat_some(pat.span, val_pat);
self.arm(some_pat, assign)
};
// `::std::option::Option::None => break`
let break_arm = {
let break_expr =
self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
let pat = self.pat_none(e.span);
self.arm(pat, break_expr)
};
// `mut iter`
let (iter_pat, iter_pat_nid) =
self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable);
// `match ::std::iter::Iterator::next(&mut iter) { ... }`
let match_expr = {
let iter = self.expr_ident(desugared_span, iter, iter_pat_nid);
let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter);
let next_expr = self.expr_call_lang_item_fn(
desugared_span,
hir::LangItem::IteratorNext,
arena_vec![self; ref_mut_iter],
);
let arms = arena_vec![self; pat_arm, break_arm];
self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
};
let match_stmt = self.stmt_expr(desugared_span, match_expr);
let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid);
// `let mut __next`
let next_let = self.stmt_let_pat(
ThinVec::new(),
desugared_span,
None,
next_pat,
hir::LocalSource::ForLoopDesugar,
);
// `let <pat> = __next`
let pat = self.lower_pat(pat);
let pat_let = self.stmt_let_pat(
ThinVec::new(),
desugared_span,
Some(next_expr),
pat,
hir::LocalSource::ForLoopDesugar,
);
let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
let body_expr = self.expr_block(body_block, ThinVec::new());
let body_stmt = self.stmt_expr(body.span, body_expr);
let loop_block = self.block_all(
e.span,
arena_vec![self; next_let, match_stmt, pat_let, body_stmt],
None,
);
// `[opt_ident]: loop { ... }`
let kind = hir::ExprKind::Loop(loop_block, opt_label, hir::LoopSource::ForLoop);
let loop_expr = self.arena.alloc(hir::Expr {
hir_id: self.lower_node_id(e.id),
kind,
span: e.span,
attrs: ThinVec::new(),
});
// `mut iter => { ... }`
let iter_arm = self.arm(iter_pat, loop_expr);
let into_iter_span = self.mark_span_with_reason(
DesugaringKind::ForLoop(ForLoopLoc::IntoIter),
orig_head_span,
None,
);
// `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
let into_iter_expr = {
self.expr_call_lang_item_fn(
into_iter_span,
hir::LangItem::IntoIterIntoIter,
arena_vec![self; head],
)
};
let match_expr = self.arena.alloc(self.expr_match(
desugared_span,
into_iter_expr,
arena_vec![self; iter_arm],
hir::MatchSource::ForLoopDesugar,
));
let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
// This is effectively `{ let _result = ...; _result }`.
// The construct was introduced in #21984 and is necessary to make sure that
// temporaries in the `head` expression are dropped and do not leak to the
// surrounding scope of the `match` since the `match` is not a terminating scope.
//
// Also, add the attributes to the outer returned expr node.
self.expr_drop_temps_mut(desugared_span, match_expr, attrs.into())
}
/// Desugar `ExprKind::Try` from: `<expr>?` into:
/// ```rust
/// match Try::into_result(<expr>) {
/// Ok(val) => #[allow(unreachable_code)] val,
/// Err(err) => #[allow(unreachable_code)]
/// // If there is an enclosing `try {...}`:
/// break 'catch_target Try::from_error(From::from(err)),
/// // Otherwise:
/// return Try::from_error(From::from(err)),
/// }
/// ```
fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
let unstable_span = self.mark_span_with_reason(
DesugaringKind::QuestionMark,
span,
self.allow_try_trait.clone(),
);
let try_span = self.sess.source_map().end_point(span);
let try_span = self.mark_span_with_reason(
DesugaringKind::QuestionMark,
try_span,
self.allow_try_trait.clone(),
);
// `Try::into_result(<expr>)`
let scrutinee = {
// expand <expr>
let sub_expr = self.lower_expr_mut(sub_expr);
self.expr_call_lang_item_fn(
unstable_span,
hir::LangItem::TryIntoResult,
arena_vec![self; sub_expr],
)
};
// `#[allow(unreachable_code)]`
let attr = {
// `allow(unreachable_code)`
let allow = {
let allow_ident = Ident::new(sym::allow, span);
let uc_ident = Ident::new(sym::unreachable_code, span);
let uc_nested = attr::mk_nested_word_item(uc_ident);
attr::mk_list_item(allow_ident, vec![uc_nested])
};
attr::mk_attr_outer(allow)
};
let attrs = vec![attr];
// `Ok(val) => #[allow(unreachable_code)] val,`
let ok_arm = {
let val_ident = Ident::with_dummy_span(sym::val);
let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
span,
val_ident,
val_pat_nid,
ThinVec::from(attrs.clone()),
));
let ok_pat = self.pat_ok(span, val_pat);
self.arm(ok_pat, val_expr)
};
// `Err(err) => #[allow(unreachable_code)]
// return Try::from_error(From::from(err)),`
let err_arm = {
let err_ident = Ident::with_dummy_span(sym::err);
let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
let from_expr = {
let err_expr = self.expr_ident_mut(try_span, err_ident, err_local_nid);
self.expr_call_lang_item_fn(
try_span,
hir::LangItem::FromFrom,
arena_vec![self; err_expr],
)
};
let from_err_expr = self.wrap_in_try_constructor(
hir::LangItem::TryFromError,
unstable_span,
from_expr,
unstable_span,
);
let thin_attrs = ThinVec::from(attrs);
let catch_scope = self.catch_scopes.last().copied();
let ret_expr = if let Some(catch_node) = catch_scope {
let target_id = Ok(self.lower_node_id(catch_node));
self.arena.alloc(self.expr(
try_span,
hir::ExprKind::Break(
hir::Destination { label: None, target_id },
Some(from_err_expr),
),
thin_attrs,
))
} else {
self.arena.alloc(self.expr(
try_span,
hir::ExprKind::Ret(Some(from_err_expr)),
thin_attrs,
))
};
let err_pat = self.pat_err(try_span, err_local);
self.arm(err_pat, ret_expr)
};
hir::ExprKind::Match(
scrutinee,
arena_vec![self; err_arm, ok_arm],
hir::MatchSource::TryDesugar,
)
}
// =========================================================================
// Helper methods for building HIR.
// =========================================================================
/// Constructs a `true` or `false` literal expression.
pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> &'hir hir::Expr<'hir> {
let lit = Spanned { span, node: LitKind::Bool(val) };
self.arena.alloc(self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new()))
}
/// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
///
/// In terms of drop order, it has the same effect as wrapping `expr` in
/// `{ let _t = $expr; _t }` but should provide better compile-time performance.
///
/// The drop order can be important in e.g. `if expr { .. }`.
pub(super) fn expr_drop_temps(
&mut self,
span: Span,
expr: &'hir hir::Expr<'hir>,
attrs: AttrVec,
) -> &'hir hir::Expr<'hir> {
self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
}
pub(super) fn expr_drop_temps_mut(
&mut self,
span: Span,
expr: &'hir hir::Expr<'hir>,
attrs: AttrVec,
) -> hir::Expr<'hir> {
self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
}
fn expr_match(
&mut self,
span: Span,
arg: &'hir hir::Expr<'hir>,
arms: &'hir [hir::Arm<'hir>],
source: hir::MatchSource,
) -> hir::Expr<'hir> {
self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
}
fn expr_break(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
self.arena.alloc(self.expr(span, expr_break, attrs))
}
fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
self.expr(
span,
hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
ThinVec::new(),
)
}
fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
}
fn expr_call_mut(
&mut self,
span: Span,
e: &'hir hir::Expr<'hir>,
args: &'hir [hir::Expr<'hir>],
) -> hir::Expr<'hir> {
self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
}
fn expr_call(
&mut self,
span: Span,
e: &'hir hir::Expr<'hir>,
args: &'hir [hir::Expr<'hir>],
) -> &'hir hir::Expr<'hir> {
self.arena.alloc(self.expr_call_mut(span, e, args))
}
fn expr_call_lang_item_fn_mut(
&mut self,
span: Span,
lang_item: hir::LangItem,
args: &'hir [hir::Expr<'hir>],
) -> hir::Expr<'hir> {
let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new()));
self.expr_call_mut(span, path, args)
}
fn expr_call_lang_item_fn(
&mut self,
span: Span,
lang_item: hir::LangItem,
args: &'hir [hir::Expr<'hir>],
) -> &'hir hir::Expr<'hir> {
self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args))
}
fn expr_lang_item_path(
&mut self,
span: Span,
lang_item: hir::LangItem,
attrs: AttrVec,
) -> hir::Expr<'hir> {
self.expr(span, hir::ExprKind::Path(hir::QPath::LangItem(lang_item, span)), attrs)
}
pub(super) fn expr_ident(
&mut self,
sp: Span,
ident: Ident,
binding: hir::HirId,
) -> &'hir hir::Expr<'hir> {
self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
}
pub(super) fn expr_ident_mut(
&mut self,
sp: Span,
ident: Ident,
binding: hir::HirId,
) -> hir::Expr<'hir> {
self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
}
fn expr_ident_with_attrs(
&mut self,
span: Span,
ident: Ident,
binding: hir::HirId,
attrs: AttrVec,
) -> hir::Expr<'hir> {
let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
None,
self.arena.alloc(hir::Path {
span,
res: Res::Local(binding),
segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
}),
));
self.expr(span, expr_path, attrs)
}
fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
let hir_id = self.next_id();
let span = expr.span;
self.expr(
span,
hir::ExprKind::Block(
self.arena.alloc(hir::Block {
stmts: &[],
expr: Some(expr),
hir_id,
rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
span,
targeted_by_break: false,
}),
None,
),
ThinVec::new(),
)
}
fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
let blk = self.block_all(span, &[], None);
let expr = self.expr_block(blk, ThinVec::new());
self.arena.alloc(expr)
}
pub(super) fn expr_block(
&mut self,
b: &'hir hir::Block<'hir>,
attrs: AttrVec,
) -> hir::Expr<'hir> {
self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
}
pub(super) fn expr(
&mut self,
span: Span,
kind: hir::ExprKind<'hir>,
attrs: AttrVec,
) -> hir::Expr<'hir> {
hir::Expr { hir_id: self.next_id(), kind, span, attrs }
}
fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> {
hir::Field { hir_id: self.next_id(), ident, span, expr, is_shorthand: false }
}
fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
hir::Arm {
hir_id: self.next_id(),
attrs: &[],
pat,
guard: None,
span: expr.span,
body: expr,
}
}
}
| 40.795198 | 100 | 0.478712 |
e49404d5ca110bb41b6ba2efddbb657ba2b53003
| 3,309 |
#[doc = "Register `Q4_WORD0` reader"]
pub struct R(crate::R<Q4_WORD0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<Q4_WORD0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<Q4_WORD0_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<Q4_WORD0_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `Q4_WORD0` writer"]
pub struct W(crate::W<Q4_WORD0_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<Q4_WORD0_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 From<crate::W<Q4_WORD0_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<Q4_WORD0_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `SEND_Q4_WORD0` reader - This register stores the content of short packet's first dword"]
pub struct SEND_Q4_WORD0_R(crate::FieldReader<u32, u32>);
impl SEND_Q4_WORD0_R {
#[inline(always)]
pub(crate) fn new(bits: u32) -> Self {
SEND_Q4_WORD0_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SEND_Q4_WORD0_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SEND_Q4_WORD0` writer - This register stores the content of short packet's first dword"]
pub struct SEND_Q4_WORD0_W<'a> {
w: &'a mut W,
}
impl<'a> SEND_Q4_WORD0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = value as u32;
self.w
}
}
impl R {
#[doc = "Bits 0:31 - This register stores the content of short packet's first dword"]
#[inline(always)]
pub fn send_q4_word0(&self) -> SEND_Q4_WORD0_R {
SEND_Q4_WORD0_R::new(self.bits as u32)
}
}
impl W {
#[doc = "Bits 0:31 - This register stores the content of short packet's first dword"]
#[inline(always)]
pub fn send_q4_word0(&mut self) -> SEND_Q4_WORD0_W {
SEND_Q4_WORD0_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "\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 [q4_word0](index.html) module"]
pub struct Q4_WORD0_SPEC;
impl crate::RegisterSpec for Q4_WORD0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [q4_word0::R](R) reader structure"]
impl crate::Readable for Q4_WORD0_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [q4_word0::W](W) writer structure"]
impl crate::Writable for Q4_WORD0_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets Q4_WORD0 to value 0"]
impl crate::Resettable for Q4_WORD0_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 31.817308 | 389 | 0.626775 |
f93bbe2db7e9e9a23715542fa55c69bd08ee21b0
| 7,693 |
use diesel::*;
#[cfg(feature = "postgres")]
mod custom_schemas;
#[cfg(feature = "postgres")]
include!("pg_schema.rs");
#[cfg(feature = "sqlite")]
include!("sqlite_schema.rs");
#[cfg(feature = "mysql")]
include!("mysql_schema.rs");
#[derive(
PartialEq, Eq, Debug, Clone, Queryable, Identifiable, Insertable, AsChangeset, QueryableByName,
)]
#[table_name = "users"]
pub struct User {
pub id: i32,
pub name: String,
pub hair_color: Option<String>,
}
impl User {
pub fn new(id: i32, name: &str) -> Self {
User {
id: id,
name: name.to_string(),
hair_color: None,
}
}
pub fn with_hair_color(id: i32, name: &str, hair_color: &str) -> Self {
User {
id: id,
name: name.to_string(),
hair_color: Some(hair_color.to_string()),
}
}
pub fn new_post(&self, title: &str, body: Option<&str>) -> NewPost {
NewPost::new(self.id, title, body)
}
}
#[derive(PartialEq, Eq, Debug, Clone, Queryable, Identifiable, Associations)]
#[belongs_to(Post)]
pub struct Comment {
id: i32,
post_id: i32,
text: String,
}
impl Comment {
pub fn new(id: i32, post_id: i32, text: &str) -> Self {
Comment {
id: id,
post_id: post_id,
text: text.into(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Queryable, Insertable, Associations, Identifiable)]
#[belongs_to(User)]
#[belongs_to(Post)]
#[table_name = "followings"]
#[primary_key(user_id, post_id)]
pub struct Following {
pub user_id: i32,
pub post_id: i32,
pub email_notifications: bool,
}
#[rustfmt::skip]
#[cfg_attr(feature = "postgres", path = "postgres_specific_schema.rs")]
#[cfg_attr(not(feature = "postgres"), path = "backend_specifics.rs")]
mod backend_specifics;
pub use self::backend_specifics::*;
#[derive(Debug, PartialEq, Eq, Queryable, Clone, Insertable, AsChangeset)]
#[table_name = "users"]
pub struct NewUser {
pub name: String,
pub hair_color: Option<String>,
}
impl NewUser {
pub fn new(name: &str, hair_color: Option<&str>) -> Self {
NewUser {
name: name.to_string(),
hair_color: hair_color.map(|s| s.to_string()),
}
}
}
#[derive(Insertable)]
#[table_name = "posts"]
pub struct NewPost {
user_id: i32,
title: String,
body: Option<String>,
}
impl NewPost {
pub fn new(user_id: i32, title: &str, body: Option<&str>) -> Self {
NewPost {
user_id: user_id,
title: title.into(),
body: body.map(|b| b.into()),
}
}
}
#[derive(Debug, Clone, Copy, Insertable)]
#[table_name = "comments"]
pub struct NewComment<'a>(
#[column_name = "post_id"] pub i32,
#[column_name = "text"] pub &'a str,
);
#[derive(PartialEq, Eq, Debug, Clone, Insertable)]
#[table_name = "fk_tests"]
pub struct FkTest {
id: i32,
fk_id: i32,
}
impl FkTest {
pub fn new(id: i32, fk_id: i32) -> Self {
FkTest {
id: id,
fk_id: fk_id,
}
}
}
#[derive(Queryable, Insertable)]
#[table_name = "nullable_table"]
pub struct NullableColumn {
id: i32,
value: Option<i32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Queryable, Insertable, Identifiable, Associations)]
#[table_name = "likes"]
#[primary_key(user_id, comment_id)]
#[belongs_to(User)]
#[belongs_to(Comment)]
pub struct Like {
pub user_id: i32,
pub comment_id: i32,
}
#[cfg(feature = "postgres")]
pub type TestConnection = PgConnection;
#[cfg(feature = "sqlite")]
pub type TestConnection = SqliteConnection;
#[cfg(feature = "mysql")]
pub type TestConnection = MysqlConnection;
pub type TestBackend = <TestConnection as Connection>::Backend;
//Used to ensure cleanup of one-off tables, e.g. for a table created for a single test
pub struct DropTable<'a> {
pub connection: &'a TestConnection,
pub table_name: &'static str,
}
impl<'a> Drop for DropTable<'a> {
fn drop(&mut self) {
self.connection
.execute(&format!("DROP TABLE {}", self.table_name))
.unwrap();
}
}
pub fn connection() -> TestConnection {
let result = connection_without_transaction();
#[cfg(feature = "sqlite")]
result.execute("PRAGMA foreign_keys = ON").unwrap();
result.begin_test_transaction().unwrap();
result
}
#[cfg(feature = "postgres")]
pub fn connection_without_transaction() -> TestConnection {
let connection_url = dotenv::var("PG_DATABASE_URL")
.or_else(|_| dotenv::var("DATABASE_URL"))
.expect("DATABASE_URL must be set in order to run tests");
PgConnection::establish(&connection_url).unwrap()
}
#[cfg(feature = "sqlite")]
embed_migrations!("../migrations/sqlite");
#[cfg(feature = "sqlite")]
pub fn connection_without_transaction() -> TestConnection {
let connection = SqliteConnection::establish(":memory:").unwrap();
embedded_migrations::run(&connection).unwrap();
connection
}
#[cfg(feature = "mysql")]
pub fn connection_without_transaction() -> TestConnection {
let connection_url = dotenv::var("MYSQL_DATABASE_URL")
.or_else(|_| dotenv::var("DATABASE_URL"))
.expect("DATABASE_URL must be set in order to run tests");
MysqlConnection::establish(&connection_url).unwrap()
}
#[cfg(feature = "postgres")]
pub fn disable_foreign_keys(connection: &TestConnection) {
connection.execute("SET CONSTRAINTS ALL DEFERRED").unwrap();
}
#[cfg(feature = "mysql")]
pub fn disable_foreign_keys(connection: &TestConnection) {
connection.execute("SET FOREIGN_KEY_CHECKS = 0").unwrap();
}
#[cfg(feature = "sqlite")]
pub fn disable_foreign_keys(connection: &TestConnection) {
connection
.execute("PRAGMA defer_foreign_keys = ON")
.unwrap();
}
#[cfg(feature = "sqlite")]
pub fn drop_table_cascade(connection: &TestConnection, table: &str) {
connection
.execute(&format!("DROP TABLE {}", table))
.unwrap();
}
#[cfg(feature = "postgres")]
pub fn drop_table_cascade(connection: &TestConnection, table: &str) {
connection
.execute(&format!("DROP TABLE {} CASCADE", table))
.unwrap();
}
sql_function!(fn nextval(a: sql_types::VarChar) -> sql_types::BigInt);
pub fn connection_with_sean_and_tess_in_users_table() -> TestConnection {
let connection = connection();
insert_sean_and_tess_into_users_table(&connection);
connection
}
pub fn insert_sean_and_tess_into_users_table(connection: &TestConnection) {
connection
.execute("INSERT INTO users (id, name) VALUES (1, 'Sean'), (2, 'Tess')")
.unwrap();
ensure_primary_key_seq_greater_than(2, &connection);
}
pub fn connection_with_nullable_table_data() -> TestConnection {
let connection = connection();
let test_data = vec![
NullableColumn { id: 1, value: None },
NullableColumn { id: 2, value: None },
NullableColumn {
id: 3,
value: Some(1),
},
NullableColumn {
id: 4,
value: Some(2),
},
NullableColumn {
id: 5,
value: Some(1),
},
];
insert_into(nullable_table::table)
.values(&test_data)
.execute(&connection)
.unwrap();
connection
}
fn ensure_primary_key_seq_greater_than(x: i64, connection: &TestConnection) {
if cfg!(feature = "postgres") {
for _ in 0..x {
select(nextval("users_id_seq")).execute(connection).unwrap();
}
}
}
pub fn find_user_by_name(name: &str, connection: &TestConnection) -> User {
users::table
.filter(users::name.eq(name))
.first(connection)
.unwrap()
}
| 25.729097 | 99 | 0.628883 |
50044d21caa5492bfb6b7fdeb1035481e3003e99
| 7,606 |
// Copyright 2021 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::{
errors::FxfsError,
object_store::{
directory::Directory,
filesystem::FxFilesystem,
transaction::{LockKey, Options, TransactionHandler},
ObjectDescriptor, ObjectStore,
},
},
anyhow::{anyhow, bail, Context, Error},
std::sync::Arc,
};
// Volumes are a grouping of an object store and a root directory within this object store. They
// model a hierarchical tree of objects within a single store.
//
// Typically there will be one root volume which is referenced directly by the superblock. This root
// volume stores references to all other volumes on the system (as volumes/foo, volumes/bar, ...).
// For now, this hierarchy is only one deep.
const VOLUMES_DIRECTORY: &str = "volumes";
/// RootVolume is the top-level volume which stores references to all of the other Volumes.
pub struct RootVolume {
_root_directory: Directory<ObjectStore>,
volume_directory: Directory<ObjectStore>,
filesystem: Arc<FxFilesystem>,
}
impl RootVolume {
pub fn volume_directory(&self) -> &Directory<ObjectStore> {
&self.volume_directory
}
/// Creates a new volume. This is not thread-safe.
pub async fn new_volume(&self, volume_name: &str) -> Result<Arc<ObjectStore>, Error> {
let root_store = self.filesystem.root_store();
let store;
let mut transaction =
self.filesystem.clone().new_transaction(&[], Options::default()).await?;
store = root_store.create_child_store(&mut transaction).await?;
let root_directory = Directory::create(&mut transaction, &store).await?;
store.set_root_directory_object_id(&mut transaction, root_directory.object_id());
self.volume_directory
.add_child_volume(&mut transaction, volume_name, store.store_object_id())
.await?;
transaction.commit().await;
Ok(store)
}
/// Returns the volume with the given name. This is not thread-safe.
pub async fn volume(&self, volume_name: &str) -> Result<Arc<ObjectStore>, Error> {
let object_id =
match self.volume_directory.lookup(volume_name).await?.ok_or(FxfsError::NotFound)? {
(object_id, ObjectDescriptor::Volume) => object_id,
_ => bail!(FxfsError::Inconsistent),
};
Ok(if let Some(volume_store) = self.filesystem.store(object_id) {
volume_store
} else {
self.filesystem.root_store().open_store(object_id).await?
})
}
pub async fn open_or_create_volume(
&self,
volume_name: &str,
) -> Result<Arc<ObjectStore>, Error> {
match self.volume(volume_name).await {
Ok(volume) => Ok(volume),
Err(e) => {
let cause = e.root_cause().downcast_ref::<FxfsError>().cloned();
if let Some(FxfsError::NotFound) = cause {
self.new_volume(volume_name).await
} else {
Err(e)
}
}
}
}
}
/// Returns the root volume for the filesystem or creates it if it does not exist.
pub async fn root_volume(fs: &Arc<FxFilesystem>) -> Result<RootVolume, Error> {
let root_store = fs.root_store();
let root_directory = Directory::open(&root_store, root_store.root_directory_object_id())
.await
.context("Unable to open root volume directory")?;
let mut transaction = None;
let volume_directory = loop {
match root_directory.lookup(VOLUMES_DIRECTORY).await? {
None => {
if let Some(mut transaction) = transaction {
let directory = root_directory
.create_child_dir(&mut transaction, VOLUMES_DIRECTORY)
.await?;
transaction.commit().await;
break directory;
} else {
transaction = Some(
fs.clone()
.new_transaction(
&[LockKey::object(
root_store.store_object_id(),
root_directory.object_id(),
)],
Options::default(),
)
.await?,
);
}
}
Some((object_id, ObjectDescriptor::Directory)) => {
break Directory::open(&root_store, object_id)
.await
.context("unable to open volumes directory")?;
}
_ => {
return Err(anyhow!(FxfsError::Inconsistent)
.context("Unexpected type for volumes directory"));
}
}
};
Ok(RootVolume { _root_directory: root_directory, volume_directory, filesystem: fs.clone() })
}
#[cfg(test)]
mod tests {
use {
super::root_volume,
crate::object_store::{
directory::Directory,
filesystem::{Filesystem, FxFilesystem, SyncOptions},
transaction::{Options, TransactionHandler},
},
anyhow::Error,
fuchsia_async as fasync,
storage_device::{fake_device::FakeDevice, DeviceHolder},
};
#[fasync::run_singlethreaded(test)]
async fn test_lookup_nonexistent_volume() -> Result<(), Error> {
let device = DeviceHolder::new(FakeDevice::new(4096, 512));
let filesystem = FxFilesystem::new_empty(device).await?;
let root_volume = root_volume(&filesystem).await.expect("root_volume failed");
root_volume.volume("vol").await.err().expect("Volume shouldn't exist");
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn test_add_volume() {
let device = DeviceHolder::new(FakeDevice::new(4096, 512));
let filesystem = FxFilesystem::new_empty(device).await.expect("new_empty failed");
{
let root_volume = root_volume(&filesystem).await.expect("root_volume failed");
let store = root_volume.new_volume("vol").await.expect("new_volume failed");
let mut transaction = filesystem
.clone()
.new_transaction(&[], Options::default())
.await
.expect("new transaction failed");
let root_directory = Directory::open(&store, store.root_directory_object_id())
.await
.expect("open failed");
root_directory
.create_child_file(&mut transaction, "foo")
.await
.expect("create_child_file failed");
transaction.commit().await;
filesystem.sync(SyncOptions::default()).await.expect("sync failed");
};
{
let filesystem =
FxFilesystem::open(filesystem.take_device().await).await.expect("open failed");
let root_volume = root_volume(&filesystem).await.expect("root_volume failed");
let volume = root_volume.volume("vol").await.expect("volume failed");
let root_directory = Directory::open(&volume, volume.root_directory_object_id())
.await
.expect("open failed");
root_directory.lookup("foo").await.expect("lookup failed").expect("not found");
};
}
}
| 39.005128 | 100 | 0.577439 |
9cfbdbacbab064578dd4802dd15f0fb595191307
| 5,018 |
use std::{cmp::Ordering, sync::Arc};
use crate::{
ray::Ray,
shapes::collide::{Collide, HitRecord},
utils::Vec3,
};
/// Axis Aligned Bounding Box.
/// It is defined by its lowest and highest corners
#[derive(Clone, Copy)]
pub struct AABB {
min: Vec3,
max: Vec3,
}
impl AABB {
/// Creates a new AABB
pub fn new(min: Vec3, max: Vec3) -> Self {
let e = 0.000001;
let diff = max - min;
let mut min = min;
let mut max = max;
if diff.x < e {
min.x -= e;
max.x += e;
} else if diff.y < e {
min.y -= e;
max.y += e;
} else if diff.z < e {
min.z -= e;
max.z += e;
}
AABB { min, max }
}
/// Returns if the AABB was hit
pub fn hit(&self, ray: &Ray, t_min: f64, t_max: f64) -> bool {
let (mut min, mut max) = (t_min, t_max);
for i in 0..3 {
let (t0, t1) = get_interval(self.min[i], self.max[i], ray.origin[i], ray.direction[i]);
min = t0.max(min);
max = t1.min(max);
if max <= min {
return false;
}
}
return true;
}
fn get_longer_axis(&self) -> usize {
let mut max = 0.0;
let mut axis = 0;
for a in 0..3 {
let diff = self.max[a] - self.min[a];
if diff > max {
axis = a;
max = diff;
}
}
axis
}
}
fn get_interval(min: f64, max: f64, origin: f64, direction: f64) -> (f64, f64) {
if direction == 0.0 {
return (f64::INFINITY, f64::INFINITY);
}
let t0 = (min - origin) / direction;
let t1 = (max - origin) / direction;
let (t0, t1) = (t0.min(t1), t0.max(t1));
(t0, t1)
}
pub fn surrounding_box(a: AABB, b: AABB) -> AABB {
let lowest = Vec3::new(
a.min.x.min(b.min.x),
a.min.y.min(b.min.y),
a.min.z.min(b.min.z),
);
let highest = Vec3::new(
a.max.x.max(b.max.x),
a.max.y.max(b.max.y),
a.max.z.max(b.max.z),
);
AABB::new(lowest, highest)
}
type ArcCollide = Arc<dyn Collide + Send + Sync>;
pub fn get_bounding_box<T>(objects: &[Arc<T>]) -> AABB
where
T: ?Sized,
T: Collide + Send + Sync,
{
if objects.len() < 1 {
panic!("Please provide a vector with at least one element");
}
let mut aabb = objects[0].get_bounding_box().unwrap();
for i in 1..objects.len() {
aabb = surrounding_box(aabb, objects[i].get_bounding_box().unwrap());
}
aabb
}
fn box_compare_on(axis: usize) -> Box<dyn FnMut(&ArcCollide, &ArcCollide) -> Ordering> {
Box::new(move |a: &ArcCollide, b: &ArcCollide| {
if a.get_bounding_box().unwrap().min[axis] < b.get_bounding_box().unwrap().min[axis] {
Ordering::Less
} else {
Ordering::Greater
}
})
}
/// Bounding Volume Hierarchy.
/// Tree like structure to divide the scene into AABB and speed up ray/object intersection calculations.
pub struct BVH {
left: ArcCollide,
right: ArcCollide,
aabb: AABB,
}
impl Collide for BVH {
fn get_intersection(&self, ray: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> {
if !self.aabb.hit(ray, t_min, t_max) {
return None;
}
let hit_left = self.left.get_intersection(ray, t_min, t_max);
let t_max = if hit_left.is_some() {
hit_left.as_ref().unwrap().t
} else {
t_max
};
let hit_right = self.right.get_intersection(ray, t_min, t_max);
if hit_right.is_some() {
return hit_right;
} else if hit_left.is_some() {
return hit_left;
} else {
return None;
}
}
fn get_bounding_box(&self) -> Option<AABB> {
Some(self.aabb)
}
}
impl BVH {
pub fn new(objects: &mut Vec<ArcCollide>, start: usize, end: usize) -> Self {
// Choose an axis to separate the objects in two groups
let aabb = get_bounding_box(&objects[start..end]);
let axis = aabb.get_longer_axis();
// Sort the objects based on the axis we chose
let comparator = box_compare_on(axis);
objects[start..end].sort_by(comparator);
// Take care of the leafs of our tree
if end - start == 1 {
return BVH {
left: objects[start].clone(),
right: objects[start].clone(),
aabb,
};
} else if end - start == 2 {
return BVH {
left: objects[start].clone(),
right: objects[start + 1].clone(),
aabb,
};
}
let mid = (end + start) / 2;
// Separate our objects in two groups and calculate the BVH for those two groups
BVH {
left: Arc::new(BVH::new(objects, start, mid)),
right: Arc::new(BVH::new(objects, mid, end)),
aabb,
}
}
}
| 26.978495 | 104 | 0.512156 |
62c46ed6dd427728e1386e32042435d136d7a1b6
| 11,478 |
#![feature(test)]
extern crate test;
use crossbeam_channel::unbounded;
use log::*;
use rand::{thread_rng, Rng};
use rayon::prelude::*;
use solana_core::banking_stage::{create_test_recorder, BankingStage};
use solana_core::cluster_info::ClusterInfo;
use solana_core::cluster_info::Node;
use solana_core::poh_recorder::WorkingBankEntry;
use solana_ledger::blockstore_processor::process_entries;
use solana_ledger::entry::{next_hash, Entry};
use solana_ledger::genesis_utils::{create_genesis_config, GenesisConfigInfo};
use solana_ledger::{blockstore::Blockstore, get_tmp_ledger_path};
use solana_perf::packet::to_packets_chunked;
use solana_perf::test_tx::test_tx;
use solana_runtime::bank::Bank;
use solana_sdk::genesis_config::GenesisConfig;
use solana_sdk::hash::Hash;
use solana_sdk::message::Message;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::Keypair;
use solana_sdk::signature::Signature;
use solana_sdk::signature::Signer;
use solana_sdk::system_instruction;
use solana_sdk::system_transaction;
use solana_sdk::timing::{duration_as_us, timestamp};
use solana_sdk::transaction::Transaction;
use std::sync::atomic::Ordering;
use std::sync::mpsc::Receiver;
use std::sync::Arc;
use std::time::{Duration, Instant};
use test::Bencher;
fn check_txs(receiver: &Arc<Receiver<WorkingBankEntry>>, ref_tx_count: usize) {
let mut total = 0;
let now = Instant::now();
loop {
if let Ok((_bank, (entry, _tick_height))) = receiver.recv_timeout(Duration::new(1, 0)) {
total += entry.transactions.len();
}
if total >= ref_tx_count {
break;
}
if now.elapsed().as_secs() > 60 {
break;
}
}
assert_eq!(total, ref_tx_count);
}
#[bench]
fn bench_consume_buffered(bencher: &mut Bencher) {
let GenesisConfigInfo { genesis_config, .. } = create_genesis_config(100_000);
let bank = Arc::new(Bank::new(&genesis_config));
let ledger_path = get_tmp_ledger_path!();
let my_pubkey = Pubkey::new_rand();
{
let blockstore = Arc::new(
Blockstore::open(&ledger_path).expect("Expected to be able to open database ledger"),
);
let (exit, poh_recorder, poh_service, _signal_receiver) =
create_test_recorder(&bank, &blockstore, None);
let tx = test_tx();
let len = 4096;
let chunk_size = 1024;
let batches = to_packets_chunked(&vec![tx; len], chunk_size);
let mut packets = vec![];
for batch in batches {
let batch_len = batch.packets.len();
packets.push((batch, vec![0usize; batch_len]));
}
// This tests the performance of buffering packets.
// If the packet buffers are copied, performance will be poor.
bencher.iter(move || {
let _ignored = BankingStage::consume_buffered_packets(
&my_pubkey,
&poh_recorder,
&mut packets,
10_000,
None,
);
});
exit.store(true, Ordering::Relaxed);
poh_service.join().unwrap();
}
let _unused = Blockstore::destroy(&ledger_path);
}
fn make_accounts_txs(txes: usize, mint_keypair: &Keypair, hash: Hash) -> Vec<Transaction> {
let to_pubkey = Pubkey::new_rand();
let dummy = system_transaction::transfer(mint_keypair, &to_pubkey, 1, hash);
(0..txes)
.into_par_iter()
.map(|_| {
let mut new = dummy.clone();
let sig: Vec<u8> = (0..64).map(|_| thread_rng().gen()).collect();
new.message.account_keys[0] = Pubkey::new_rand();
new.message.account_keys[1] = Pubkey::new_rand();
new.signatures = vec![Signature::new(&sig[0..64])];
new
})
.collect()
}
fn make_programs_txs(txes: usize, hash: Hash) -> Vec<Transaction> {
let progs = 4;
(0..txes)
.map(|_| {
let mut instructions = vec![];
let from_key = Keypair::new();
for _ in 1..progs {
let to_key = Pubkey::new_rand();
instructions.push(system_instruction::transfer(&from_key.pubkey(), &to_key, 1));
}
let message = Message::new(&instructions, Some(&from_key.pubkey()));
Transaction::new(&[&from_key], message, hash)
})
.collect()
}
enum TransactionType {
Accounts,
Programs,
}
fn bench_banking(bencher: &mut Bencher, tx_type: TransactionType) {
solana_logger::setup();
let num_threads = BankingStage::num_threads() as usize;
// a multiple of packet chunk duplicates to avoid races
const CHUNKS: usize = 8;
const PACKETS_PER_BATCH: usize = 192;
let txes = PACKETS_PER_BATCH * num_threads * CHUNKS;
let mint_total = 1_000_000_000_000;
let GenesisConfigInfo {
mut genesis_config,
mint_keypair,
..
} = create_genesis_config(mint_total);
// Set a high ticks_per_slot so we don't run out of ticks
// during the benchmark
genesis_config.ticks_per_slot = 10_000;
let (verified_sender, verified_receiver) = unbounded();
let (vote_sender, vote_receiver) = unbounded();
let bank = Arc::new(Bank::new(&genesis_config));
debug!("threads: {} txs: {}", num_threads, txes);
let transactions = match tx_type {
TransactionType::Accounts => make_accounts_txs(txes, &mint_keypair, genesis_config.hash()),
TransactionType::Programs => make_programs_txs(txes, genesis_config.hash()),
};
// fund all the accounts
transactions.iter().for_each(|tx| {
let fund = system_transaction::transfer(
&mint_keypair,
&tx.message.account_keys[0],
mint_total / txes as u64,
genesis_config.hash(),
);
let x = bank.process_transaction(&fund);
x.unwrap();
});
//sanity check, make sure all the transactions can execute sequentially
transactions.iter().for_each(|tx| {
let res = bank.process_transaction(&tx);
assert!(res.is_ok(), "sanity test transactions");
});
bank.clear_signatures();
//sanity check, make sure all the transactions can execute in parallel
let res = bank.process_transactions(&transactions);
for r in res {
assert!(r.is_ok(), "sanity parallel execution");
}
bank.clear_signatures();
let verified: Vec<_> = to_packets_chunked(&transactions, PACKETS_PER_BATCH);
let ledger_path = get_tmp_ledger_path!();
{
let blockstore = Arc::new(
Blockstore::open(&ledger_path).expect("Expected to be able to open database ledger"),
);
let (exit, poh_recorder, poh_service, signal_receiver) =
create_test_recorder(&bank, &blockstore, None);
let cluster_info = ClusterInfo::new_with_invalid_keypair(Node::new_localhost().info);
let cluster_info = Arc::new(cluster_info);
let _banking_stage = BankingStage::new(
&cluster_info,
&poh_recorder,
verified_receiver,
vote_receiver,
None,
);
poh_recorder.lock().unwrap().set_bank(&bank);
let chunk_len = verified.len() / CHUNKS;
let mut start = 0;
// This is so that the signal_receiver does not go out of scope after the closure.
// If it is dropped before poh_service, then poh_service will error when
// calling send() on the channel.
let signal_receiver = Arc::new(signal_receiver);
let signal_receiver2 = signal_receiver;
bencher.iter(move || {
let now = Instant::now();
let mut sent = 0;
for v in verified[start..start + chunk_len].chunks(chunk_len / num_threads) {
debug!(
"sending... {}..{} {} v.len: {}",
start,
start + chunk_len,
timestamp(),
v.len(),
);
for xv in v {
sent += xv.packets.len();
}
verified_sender.send(v.to_vec()).unwrap();
}
check_txs(&signal_receiver2, txes / CHUNKS);
// This signature clear may not actually clear the signatures
// in this chunk, but since we rotate between CHUNKS then
// we should clear them by the time we come around again to re-use that chunk.
bank.clear_signatures();
trace!(
"time: {} checked: {} sent: {}",
duration_as_us(&now.elapsed()),
txes / CHUNKS,
sent,
);
start += chunk_len;
start %= verified.len();
});
drop(vote_sender);
exit.store(true, Ordering::Relaxed);
poh_service.join().unwrap();
}
let _unused = Blockstore::destroy(&ledger_path);
}
#[bench]
fn bench_banking_stage_multi_accounts(bencher: &mut Bencher) {
bench_banking(bencher, TransactionType::Accounts);
}
#[bench]
fn bench_banking_stage_multi_programs(bencher: &mut Bencher) {
bench_banking(bencher, TransactionType::Programs);
}
fn simulate_process_entries(
randomize_txs: bool,
mint_keypair: &Keypair,
mut tx_vector: Vec<Transaction>,
genesis_config: &GenesisConfig,
keypairs: &[Keypair],
initial_lamports: u64,
num_accounts: usize,
) {
let bank = Arc::new(Bank::new(genesis_config));
for i in 0..(num_accounts / 2) {
bank.transfer(initial_lamports, mint_keypair, &keypairs[i * 2].pubkey())
.unwrap();
}
for i in (0..num_accounts).step_by(2) {
tx_vector.push(system_transaction::transfer(
&keypairs[i],
&keypairs[i + 1].pubkey(),
initial_lamports,
bank.last_blockhash(),
));
}
// Transfer lamports to each other
let entry = Entry {
num_hashes: 1,
hash: next_hash(&bank.last_blockhash(), 1, &tx_vector),
transactions: tx_vector,
};
process_entries(&bank, &[entry], randomize_txs, None, None).unwrap();
}
fn bench_process_entries(randomize_txs: bool, bencher: &mut Bencher) {
// entropy multiplier should be big enough to provide sufficient entropy
// but small enough to not take too much time while executing the test.
let entropy_multiplier: usize = 25;
let initial_lamports = 100;
// number of accounts need to be in multiple of 4 for correct
// execution of the test.
let num_accounts = entropy_multiplier * 4;
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config((num_accounts + 1) as u64 * initial_lamports);
let mut keypairs: Vec<Keypair> = vec![];
let tx_vector: Vec<Transaction> = Vec::with_capacity(num_accounts / 2);
for _ in 0..num_accounts {
let keypair = Keypair::new();
keypairs.push(keypair);
}
bencher.iter(|| {
simulate_process_entries(
randomize_txs,
&mint_keypair,
tx_vector.clone(),
&genesis_config,
&keypairs,
initial_lamports,
num_accounts,
);
});
}
#[bench]
fn bench_process_entries_without_order_shuffeling(bencher: &mut Bencher) {
bench_process_entries(false, bencher);
}
#[bench]
fn bench_process_entries_with_order_shuffeling(bencher: &mut Bencher) {
bench_process_entries(true, bencher);
}
| 33.95858 | 99 | 0.615874 |
38a99777ff0fc9e68f4e871ce90a17ec2aaf4cf4
| 852 |
use crate::binary::{leaf_sum, node_sum};
use crate::common::{Bytes32, Position};
use core::fmt::Debug;
#[derive(Clone, PartialEq, Debug)]
pub struct Node {
position: Position,
hash: Bytes32,
}
impl Node {
pub fn create_leaf(index: u64, data: &[u8]) -> Self {
let position = Position::from_leaf_index(index);
let hash = leaf_sum(data);
Self { position, hash }
}
pub fn create_node(left_child: &Self, right_child: &Self) -> Self {
let position = left_child.position().parent();
let hash = node_sum(left_child.hash(), right_child.hash());
Self { position, hash }
}
pub fn position(&self) -> Position {
self.position
}
pub fn key(&self) -> u64 {
self.position().in_order_index()
}
pub fn hash(&self) -> &Bytes32 {
&self.hash
}
}
| 23.027027 | 71 | 0.592723 |
ed095ab5fda36e66d558a69594cc9373a0ef24c9
| 5,575 |
use std::{collections::{HashSet}, fs::File, io::{self, BufRead}, path::Path, str::FromStr};
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Cave {
name: String,
small: bool,
start: bool,
end: bool,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Line {
a: Cave,
b: Cave,
start: bool,
end: bool,
}
impl FromStr for Line {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (a, b) = s
.split_once("-")
.map(|(x, y)| (Cave::from_str(x).unwrap(), Cave::from_str(y).unwrap()))
.unwrap();
Ok(Line {
a: a.clone(),
b: b.clone(),
start: a.start,
end: b.end
})
}
}
impl FromStr for Cave {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Cave { name: s.to_string(), small: !(s.to_uppercase() == s) && s != "end", end: s == "end", start: s == "start"})
}
}
fn read_lines<P>(filename: P) -> io::Result<Vec<Line>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
let mut lines: Vec<Line> = Vec::new();
let mut inverted_line: Vec<Line> = Vec::new();
io::BufReader::new(file).lines().for_each(|line| lines.push(Line::from_str(line.unwrap().as_str()).unwrap()));
lines.iter().for_each(|line| {
if line.end == false && line.start == false{ // && (!line.a.small || !line.b.small) {
inverted_line.push(Line{
a: Cave{
name: line.b.name.clone(),
small: line.b.small,
start: line.b.start,
end: line.b.end
},
b: Cave{
name: line.a.name.clone(),
small: line.a.small,
start: line.a.start,
end: line.a.end
},
start: false,
end: false
})
}
}) ;
inverted_line.iter().for_each(|line| lines.push(line.clone()));
Ok(lines)
}
fn main() {
let input = read_lines("input").unwrap();
let counter_part_1 = generate_path(input.clone(), false);
println!("Part 1 #: {}", counter_part_1);
let counter_part_1 = generate_path(input.clone(), true);
println!("Part 2 #: {}", counter_part_1);
}
fn generate_path(input: Vec<Line>, allow_one_duplicate: bool) -> u64 {
let mut counter = 0;
let mut i = 0;
let mut path_list: Vec<Vec<Line>> = Vec::new();
path_list.push(vec![Line{a: Cave{name: "-->".to_string(), small: false, start: false, end: false }, b: Cave{name: "start".to_string(), small: false, start: true, end: false}, start: true, end: false}]);
loop {
if !path_list[i].last().unwrap().end {
let next_steps: Vec<Line> = get_next_steps(&input, &path_list[i], allow_one_duplicate);
for next_step in next_steps {
let mut new_line = path_list[i].clone();
new_line.push(next_step.clone());
path_list.push(new_line.clone());
}
} else {
//let final_path = lista_parole[i].iter().map(|e| e.b.name.to_string()).collect::<Vec<String>>().join(",");
//println!("{}", final_path);
counter +=1;
}
i += 1;
if path_list.len() == i {
break;
}
}
counter
}
fn get_next_steps(input: &Vec<Line>, partial_list: &Vec<Line>, allow_one_duplicate: bool) -> Vec<Line> {
let mut duplicate = false;
let small_caves = partial_list.iter().map(|e| e.b.clone())
.filter(|e| e.small)
.collect::<Vec<Cave>>();
if (1..small_caves.len()).any(|i| small_caves[i..].contains(&small_caves[i - 1])){
// println!("found duplicate in {:?} ", small_caves_in_path);
duplicate = true;
}
if allow_one_duplicate {
return input
.iter()
.filter(|line| line.a.name == partial_list.last().unwrap().b.name.to_string())
.filter(|line| !line.b.small || !duplicate || !small_caves.contains(&line.b))
.map(|line| line.to_owned())
.collect();
}
return input.iter()
.filter(|line | line.a.name == partial_list.last().unwrap().b.name.to_string())
.filter(|line| !line.b.small || (line.b.small && !small_caves.contains(&line.b)))
.map(|line | line.to_owned()).collect();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parsing_part1a() {
let lines = read_lines("test_input").unwrap();
// println!("lines {:#?}", lines);
assert_eq!(generate_path(lines.clone(), false), 10);
}
#[test]
fn test_parsing_part2a() {
let lines = read_lines("test_input").unwrap();
// println!("lines {:#?}", lines);
assert_eq!(generate_path(lines.clone(), true), 36);
}
#[test]
fn test_parsing_part1b() {
let lines = read_lines("test_input_2").unwrap();
assert_eq!(generate_path(lines, false), 19);
}
#[test]
fn test_parsing_part2b() {
let lines = read_lines("test_input_2").unwrap();
assert_eq!(generate_path(lines, true), 103);
}
#[test]
fn test_parsing_part1c() {
let lines = read_lines("test_input_3").unwrap();
assert_eq!(generate_path(lines, false), 226);
}
#[test]
fn test_parsing_part2c() {
let lines = read_lines("test_input_3").unwrap();
assert_eq!(generate_path(lines, true), 3509);
}
}
| 30.631868 | 206 | 0.529327 |
bb23cb2d9599c7c118dfd9b84abe73101fdd1484
| 1,961 |
#![allow(deprecated)]
use clap::{AppFlags, AppSettings};
use serde::{de::DeserializeSeed, Deserialize};
enum_de!(AppSettings,AppSetting1,
#[derive(Deserialize, Clone, Copy)]
#[cfg_attr(feature = "kebab-case-key" ,serde(rename_all = "kebab-case"))]
#[cfg_attr(feature = "snake-case-key" ,serde(rename_all = "snake_case"))]
{
IgnoreErrors,
WaitOnError,
AllowHyphenValues,
AllowNegativeNumbers,
AllArgsOverrideSelf,
AllowMissingPositional,
TrailingVarArg,
DontDelimitTrailingValues,
InferLongArgs,
InferSubcommands,
SubcommandRequired,
SubcommandRequiredElseHelp,
AllowExternalSubcommands,
#[cfg(feature = "unstable-multicall")]
Multicall,
AllowInvalidUtf8ForExternalSubcommands,
UseLongFormatForHelpSubcommand,
SubcommandsNegateReqs,
ArgsNegateSubcommands,
SubcommandPrecedenceOverArg,
ArgRequiredElseHelp,
DeriveDisplayOrder,
DontCollapseArgsInUsage,
NextLineHelp,
DisableColoredHelp,
DisableHelpFlag,
DisableHelpSubcommand,
DisableVersionFlag,
PropagateVersion,
Hidden,
HidePossibleValues,
HelpExpected,
NoBinaryName,
NoAutoHelp,
NoAutoVersion,}
);
pub(crate) struct AppSettingSeed;
impl<'de> DeserializeSeed<'de> for AppSettingSeed {
type Value = AppSettings;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
AppSetting1::deserialize(deserializer).map(|s| s.into())
}
}
pub(crate) struct AppSettingsSeed;
impl<'de> DeserializeSeed<'de> for AppSettingsSeed {
type Value = AppFlags;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
Vec::<AppSetting1>::deserialize(deserializer).map(|s| {
s.into_iter()
.fold(AppFlags::default(), |a, b| a | AppSettings::from(b))
})
}
}
| 26.863014 | 77 | 0.681795 |
64f6d6e1b1684018dba643ce9bea7b97ae96653d
| 2,564 |
use crate::{Atom, RelativeTime};
use nom::branch::alt;
use nom::bytes::complete::tag_no_case;
use nom::character::complete::char;
use nom::multi::separated_list1;
use nom::{IResult, Parser};
impl Atom for RelativeTime {
fn parse(i: &str) -> IResult<&str, Self> {
components
.map(|components| {
let mut hours = None;
let mut minutes = None;
let mut seconds = None;
for component in components {
match component {
Component::H(h) => hours = Some(h),
Component::M(m) => minutes = Some(m),
Component::S(s) => seconds = Some(s),
}
}
Self {
hours,
minutes,
seconds,
}
})
.parse(i)
}
}
enum Component {
H(usize),
M(usize),
S(usize),
}
fn components(i: &str) -> IResult<&str, Vec<Component>> {
separated_list1(char(' '), component)(i)
}
fn component(i: &str) -> IResult<&str, Component> {
let h = usize::parse
.and(tag_no_case("h"))
.map(|(value, _)| Component::H(value));
let m = usize::parse
.and(tag_no_case("m"))
.map(|(value, _)| Component::M(value));
let s = usize::parse
.and(tag_no_case("s"))
.map(|(value, _)| Component::S(value));
alt((h, m, s))(i)
}
#[cfg(test)]
mod tests {
use super::*;
use test_case::test_case;
#[test_case("1h" => RelativeTime { hours: Some(1), ..Default::default() } ; "1h")]
#[test_case("12h" => RelativeTime { hours: Some(12), ..Default::default() } ; "12h")]
//
#[test_case("1m" => RelativeTime { minutes: Some(1), ..Default::default() } ; "1m")]
#[test_case("12m" => RelativeTime { minutes: Some(12), ..Default::default() } ; "12m")]
//
#[test_case("1s" => RelativeTime { seconds: Some(1), ..Default::default() } ; "1s")]
#[test_case("12s" => RelativeTime { seconds: Some(12), ..Default::default() } ; "12s")]
//
#[test_case("12h 34m" => RelativeTime { hours: Some(12), minutes: Some(34), ..Default::default() } ; "12h 34m")]
#[test_case("12m 34s" => RelativeTime { minutes: Some(12), seconds: Some(34), ..Default::default() } ; "12m 34s")]
#[test_case("12h 34m 56s" => RelativeTime { hours: Some(12), minutes: Some(34), seconds: Some(56) } ; "12h 34m 56s")]
fn test(input: &str) -> RelativeTime {
RelativeTime::parse_unwrap(input)
}
}
| 31.654321 | 121 | 0.515991 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.