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
|
---|---|---|---|---|---|
ef2285502f43acc80c81db8772efddc6f207ffee | 1,022 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use md5::{Digest, Md5};
use serde::{Deserialize, Serialize};
/// A utility to enable gradual rollout of large codegen changes.
/// Can be constructed as the Default which passes or a percentage between 0 and
/// 100.
#[derive(Default, Debug, Serialize, Deserialize, Clone, Copy)]
pub struct Rollout(Option<u8>);
impl Rollout {
/// Checks some key deterministically and passes on average the given
/// percentage of the rollout.
/// A typical key to pass in could be the fragment or operation name.
pub fn check(&self, key: impl AsRef<[u8]>) -> bool {
if let Some(percentage) = self.0 {
let hash = Md5::digest(key.as_ref());
let hash: u16 = ((hash[1] as u16) << 8) | (hash[0] as u16);
(hash % 100) < (percentage as u16)
} else {
true
}
}
}
| 32.967742 | 80 | 0.634051 |
23f5a168c73dce4df89accc1440f1b7243b7fb31 | 5,247 | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account_address::{AccountAddress, ADDRESS_LENGTH};
use crypto::{signing, HashValue, PrivateKey, PublicKey, Signature};
use failure::Error;
use proptest::{prelude::*, sample, strategy::LazyJust};
use std::convert::TryFrom;
/// ValidatorSigner associates an author with public and private keys with helpers for signing and
/// validating. This struct can be used for all signing operations including block and network
/// signing, respectively.
#[derive(Debug, Clone)]
pub struct ValidatorSigner {
author: AccountAddress,
public_key: PublicKey,
private_key: PrivateKey,
}
impl ValidatorSigner {
pub fn new(
account_address: AccountAddress,
public_key: PublicKey,
private_key: PrivateKey,
) -> Self {
ValidatorSigner {
author: account_address,
public_key,
private_key,
}
}
/// Generate the genesis block signer information.
pub fn genesis() -> Self {
let (private_key, public_key) = signing::generate_genesis_keypair();
Self::new(AccountAddress::from(public_key), public_key, private_key)
}
/// Generate a random set of public and private keys and author information.
pub fn random() -> Self {
let (private_key, public_key) = signing::generate_keypair();
ValidatorSigner {
author: AccountAddress::from(public_key),
public_key,
private_key,
}
}
/// For test only - makes signer with nicely looking account address that has specified integer
/// as fist byte, and rest are zeroes
pub fn from_int(num: u8) -> Self {
let mut address = [0; ADDRESS_LENGTH];
address[0] = num;
let (private_key, public_key) = signing::generate_keypair();
ValidatorSigner {
author: AccountAddress::try_from(&address[..]).unwrap(),
public_key,
private_key,
}
}
/// Constructs a signature for `message` using `private_key`.
pub fn sign_message(&self, message: HashValue) -> Result<Signature, Error> {
signing::sign_message(message, &self.private_key)
}
/// Checks that `signature` is valid for `message` using `public_key`.
pub fn verify_message(&self, message: HashValue, signature: &Signature) -> Result<(), Error> {
signing::verify_signature(message, signature, &self.public_key)
}
/// Returns the author associated with this signer.
pub fn author(&self) -> AccountAddress {
self.author
}
/// Returns the public key associated with this signer.
pub fn public_key(&self) -> PublicKey {
self.public_key
}
}
#[allow(clippy::redundant_closure)]
pub fn arb_keypair() -> impl Strategy<Value = (PrivateKey, PublicKey)> {
prop_oneof![
// The no_shrink here reflects that particular keypair choices out
// of random options are irrelevant.
LazyJust::new(|| signing::generate_keypair()).no_shrink(),
LazyJust::new(|| signing::generate_genesis_keypair()),
]
}
prop_compose! {
pub fn signer_strategy(key_pair_strategy: impl Strategy<Value = (PrivateKey, PublicKey)>)(
keypair in key_pair_strategy) -> ValidatorSigner {
let (private_key, public_key) = keypair;
let account_address = AccountAddress::from(public_key);
ValidatorSigner::new(account_address, public_key, private_key)
}
}
#[allow(clippy::redundant_closure)]
pub fn rand_signer() -> impl Strategy<Value = ValidatorSigner> {
// random signers warrant no shrinkage.
signer_strategy(arb_keypair()).no_shrink()
}
#[allow(clippy::redundant_closure)]
pub fn arb_signer() -> impl Strategy<Value = ValidatorSigner> {
prop_oneof![rand_signer(), LazyJust::new(|| ValidatorSigner::genesis()),]
}
fn select_keypair(
key_pairs: Vec<(PrivateKey, PublicKey)>,
) -> impl Strategy<Value = (PrivateKey, PublicKey)> {
// no_shrink() => shrinking is not relevant as signers are equivalent.
sample::select(key_pairs).no_shrink()
}
pub fn mostly_in_keypair_pool(
key_pairs: Vec<(PrivateKey, PublicKey)>,
) -> impl Strategy<Value = ValidatorSigner> {
prop::strategy::Union::new_weighted(vec![
(9, signer_strategy(select_keypair(key_pairs)).boxed()),
(1, arb_signer().boxed()),
])
}
#[cfg(test)]
mod tests {
use crate::{
account_address::AccountAddress,
validator_signer::{arb_keypair, arb_signer, ValidatorSigner},
};
use crypto::HashValue;
use proptest::prelude::*;
proptest! {
#[test]
fn test_new_signer(keypair in arb_keypair()){
let (private_key, public_key) = keypair;
let signer = ValidatorSigner::new(AccountAddress::from(public_key), public_key, private_key);
prop_assert_eq!(public_key, signer.public_key());
}
#[test]
fn test_signer(signer in arb_signer(), message in HashValue::arbitrary()) {
let signature = signer.sign_message(message).unwrap();
prop_assert!(signer
.verify_message(message, &signature)
.is_ok());
}
}
}
| 33.851613 | 105 | 0.653326 |
f531412c3d5a972dc0ed1f7fbe4f4271dbdcc54b | 13,321 | use std::fs::File;
use syn::{Ident};
use std::io;
use std::io::Write;
use std::collections::HashMap;
use std::fs;
use std::sync::Mutex;
lazy_static! {
static ref CSHARPMAP: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("bool", "byte");
m.insert("c_char", "sbyte");
m.insert("i8", "sbyte");
m.insert("c_schar", "sbyte");
m.insert("c_char_pntr", "string");
m.insert("u8", "byte");
m.insert("c_uchar", "byte");
m.insert("u16", "ushort");
m.insert("c_ushort", "ushort");
m.insert("i16", "short");
m.insert("c_short", "short");
m.insert("c_void", "IntPtr");
m.insert("u32", "uint");
m.insert("c_uint", "uint");
m.insert("i32", "int");
m.insert("c_int", "int");
m.insert("f32", "float");
m.insert("c_float", "float");
m.insert("i64", "long");
m.insert("u64", "ulong");
m.insert("c_long", "long");
m.insert("c_longlong", "long");
m.insert("c_double", "double");
m.insert("f64", "double");
m
};
static ref CPPMAP: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("bool", "bool");
m.insert("c_char", "signed char");
m.insert("c_char_pntr", "char");
m.insert("i8", "int8_t");
m.insert("c_schar", "signed char");
m.insert("u8", "uint8_t");
m.insert("c_uchar", "unsigned char");
m.insert("u16", "uint16_t");
m.insert("c_ushort", "unsigned short");
m.insert("i16", "int16_t");
m.insert("c_short", "short");
m.insert("c_void", "void");
m.insert("u32", "uint32_t");
m.insert("c_uint", "unsigned int");
m.insert("i32", "int32_t");
m.insert("c_int", "int");
m.insert("f32", "float");
m.insert("c_float", "float");
m.insert("i64", "int64_t");
m.insert("u64", "uint64_t");
m.insert("c_long", "long long int");
m.insert("c_longlong", "long long int");
m.insert("c_ulong", "unsigned long long int");
m.insert("c_ulonglong", "unsigned long long int");
m.insert("c_double", "double");
m.insert("f64", "double");
m
};
static ref PYMAP: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("bool", "c_bool");
m.insert("c_char", "c_byte");
m.insert("i8", "c_byte");
m.insert("c_schar", "c_byte");
m.insert("c_char_pntr", "c_char_p");
m.insert("u8", "c_ubyte");
m.insert("c_uchar", "c_ubyte");
m.insert("u16", "c_ushort");
m.insert("c_ushort", "c_ushort");
m.insert("i16", "c_short");
m.insert("c_short", "c_short");
m.insert("c_void", "c_void_p");
m.insert("u32", "c_uint");
m.insert("c_uint", "c_uint");
m.insert("i32", "c_int");
m.insert("c_int", "c_int");
m.insert("f32", "c_float");
m.insert("c_float", "c_float");
m.insert("i64", "c_longlong");
m.insert("u64", "c_ulonglong");
m.insert("c_long", "c_longlong");
m.insert("c_longlong", "c_longlong");
m.insert("c_ulong", "c_ulonglong");
m.insert("c_ulonglong", "c_ulonglong");
m.insert("c_double", "c_double");
m.insert("f64", "c_double");
m
};
static ref PY_USED_TYPES: Mutex<Vec<&'static str>> = {
let mut v = Vec::new();
v.push("Structure");
Mutex::new(v)
};
static ref PY_LINES: Mutex<Vec<String>> = {
let p = Vec::new();
Mutex::new(p)
};
}
pub enum LanguageType {
CPP,
Python,
CSharp,
}
pub fn create_directory() -> io::Result<()> {
fs::create_dir_all("./target/TranslateOutput")?;
Ok(())
}
///adds a simple type like i32 or other struct to the file
pub fn add_simple_type(file: &mut File, ltype: LanguageType, name: Ident, dtype: Ident) {
if dtype.to_string() == "i128" || dtype.to_string() == "u128" {
panic!("There is no mapping for 128 bit integer types");
}
match ltype {
LanguageType::CPP => {
match CPPMAP.get(&dtype.as_ref()) {
Some(t) => write!(file, "\t{} {};\n", t, name).unwrap(),
None => write!(file, "\t{} {};\n", dtype, name).unwrap()
}
},
LanguageType::Python => {
match PYMAP.get(&dtype.as_ref()) {
Some(t) => {
PY_LINES.lock().unwrap().push(format!(" (\"{}\", {}),\n", name, t));
//write!(file, " (\"{}\", {}),\n", name, t).unwrap();
let mut pyused = PY_USED_TYPES.lock().unwrap();
if !pyused.contains(t){
pyused.push(t);
}
},
None => {
PY_LINES.lock().unwrap().push(format!(" (\"{}\", {}),\n", name, dtype));
//write!(file, " (\"{}\", {}),\n", name, dtype).unwrap()
}
}
}
LanguageType::CSharp => {
match CSHARPMAP.get(&dtype.as_ref()) {
Some(t) => write!(file, "\t\tpublic {} {};\n", t, name).unwrap(),
None => write!(file, "\t\tpublic {} {};\n", dtype, name).unwrap()
}
}
}
}
///adds an array type to the file
pub fn add_array(file: &mut File, ltype: LanguageType, name: Ident, length: u64, dtype: Ident) {
if dtype.to_string() == "i128" || dtype.to_string() == "u128" {
panic!("There is no mapping for 128 bit integer types");
}
match ltype {
LanguageType::CPP => {
match CPPMAP.get(&dtype.as_ref()) {
Some(t) => write!(file, "\t{} {}[{}];\n", t, name, length).unwrap(),
None => write!(file, "\t{} {}[{}];\n", dtype, name, length).unwrap()
}
},
LanguageType::Python => {
match PYMAP.get(&dtype.as_ref()) {
Some(t) => {
PY_LINES.lock().unwrap().push(format!(" (\"{}\", {} * {}),\n", name, t, length));
//write!(file, " (\"{}\", {} * {}),\n", name, t, length).unwrap();
let mut pyused = PY_USED_TYPES.lock().unwrap();
if !pyused.contains(t){
pyused.push(t);
}
},
None => {
PY_LINES.lock().unwrap().push(format!(" (\"{}\", {} * {}),\n", name, dtype, length));
//write!(file, " (\"{}\", {} * {}),\n", name, dtype, length).unwrap()
}
}
}
LanguageType::CSharp => {
match CSHARPMAP.get(&dtype.as_ref()) {
Some(t) => {
if t == &"string" {
write!(file, "\t\t[MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeConst={})]\n", length).unwrap();
} else {
write!(file, "\t\t[MarshalAs(UnmanagedType.ByValArray, SizeConst = {})]\n", length).unwrap();
}
write!(file, "\t\tpublic {}[] {};\n", t, name).unwrap();
},
None => {
write!(file, "\t\t[MarshalAs(UnmanagedType.ByValArray, SizeConst = {})]\n", length).unwrap();
write!(file, "\t\tpublic {}[] {};\n", dtype, name).unwrap();
}
}
}
}
}
///adds a pointer type to the file
pub fn add_pointer(file: &mut File, ltype: LanguageType, name: Ident, dtype: Ident) {
let mut dtype_lookup_val = dtype.to_string();
if dtype_lookup_val == "i128" || dtype_lookup_val == "u128" {
panic!("There is no mapping for 128 bit integer types");
}
//change dtype to _pntr if it's a c_char
if dtype.to_string() == "c_char" {
dtype_lookup_val.push_str("_pntr");
}
match ltype {
LanguageType::CPP => {
match CPPMAP.get(&dtype_lookup_val.as_ref()) {
Some(t) => write!(file, "\t{}* {};\n", t, name).unwrap(),
None => write!(file, "\t{}* {};\n", dtype, name).unwrap()
}
},
LanguageType::Python => {
let mut usedpntr = false;
let mut pyused = PY_USED_TYPES.lock().unwrap();
match PYMAP.get(&dtype_lookup_val.as_ref()) {
Some(t) => {
if dtype_lookup_val != "c_char_pntr" && dtype_lookup_val != "c_void" {
//write!(file, " (\"{}\", POINTER({})),\n", name, t).unwrap();
PY_LINES.lock().unwrap().push(format!(" (\"{}\", POINTER({})),\n", name, t));
usedpntr = true;
} else {
//write!(file, " (\"{}\", {}),\n", name, t).unwrap();
PY_LINES.lock().unwrap().push(format!(" (\"{}\", {}),\n", name, t));
}
if !pyused.contains(t){
pyused.push(t);
}
},
None => {
//write!(file, " (\"{}\", POINTER({})),\n", name, dtype).unwrap();
PY_LINES.lock().unwrap().push(format!(" (\"{}\", POINTER({})),\n", name, dtype));
usedpntr = true;
}
}
if usedpntr && !pyused.contains(&"POINTER") {
pyused.push("POINTER");
}
},
LanguageType::CSharp =>{
match CSHARPMAP.get(&dtype_lookup_val.as_ref()) {
//if it's a c_char or another known type
Some(t) => {
//if it's a c_char pointer
if dtype_lookup_val == "c_char_pntr" {
write!(file, "\t\t[MarshalAs(UnmanagedType.LPStr)]\n").unwrap();
write!(file, "\t\tpublic {} {};\n", t, name).unwrap();
}
//if it's any other mapped type just do an IntPtr for now
//further, more complex, mapping will need to be done later
//todo: better mapping (https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.unmanagedtype(v=vs.110).aspx)
//for right now, there'll be a comment describing what type it is
else {
write!(file, "\t\t//This is a '{}' type\n", name).unwrap();
write!(file, "\t\tpublic IntPtr {};\n", name).unwrap();
}
}
//if it's some other struct
None => {
write!(file, "\t\t[MarshalAs(UnmanagedType.LPStruct)]\n").unwrap();
write!(file, "\t\tpublic {} {};\n", dtype, name).unwrap();
}
}
}
}
//todo: add more args here
}
pub fn start_struct(file: &mut File, ltype: LanguageType, structname: Ident) {
match ltype {
LanguageType::CPP => {
write!(file, "typedef struct {}Tag {{\n", structname).unwrap();
},
LanguageType::CSharp => {
write!(file, "\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct {}\n\t{{\n", structname).unwrap();
},
LanguageType::Python => {
//write!(file, "class {}(Structure):\n", structname).unwrap();
//write!(file, " _fields_ = [\n").unwrap();
PY_LINES.lock().unwrap().push(format!("class {}(Structure):\n", structname));
PY_LINES.lock().unwrap().push(format!(" _fields_ = [\n"));
}
}
}
///nicely closes the struct
pub fn close_struct(file: &mut File, ltype: LanguageType, structname: Ident) {
match ltype {
LanguageType::CPP => {
write!(file, "}} {};\n\n", structname).unwrap();
},
LanguageType::CSharp => {
write!(file, "\t}}\n\n").unwrap();
},
LanguageType::Python => {
//write!(file, " ]\n\n").unwrap();
PY_LINES.lock().unwrap().push(format!(" ]\n\n"));
}
}
}
pub fn close_file(file: &mut File, ltype: LanguageType) {
match ltype {
LanguageType::CPP => {
write!(file, "\n#endif").unwrap();
},
LanguageType::CSharp => {
write!(file, "\n}}").unwrap();
},
LanguageType::Python => {
write!(file, "\n").unwrap();
let used_py = PY_USED_TYPES.lock().unwrap();
let mut ctypestring: String = String::from("from ctypes import ");
for ctype in used_py.iter() {
ctypestring.push_str(&format!("{},", ctype));
}
//remove the last comma
ctypestring.pop();
write!(file, "{}\n\n", ctypestring).unwrap();
//write all of the lines in PY_LINES
for line in PY_LINES.lock().unwrap().iter() {
write!(file, "{}", line).unwrap();
}
}
}
} | 39.883234 | 146 | 0.458599 |
1cee0d0a7c112445aa13a3f73dd9ab6013d6e9ce | 5,562 | // Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_base::RuntimeTracker;
use common_macros::databend_main;
use common_meta_embedded::MetaEmbedded;
use common_metrics::init_default_metrics_recorder;
use common_tracing::init_global_tracing;
use common_tracing::set_panic_hook;
use common_tracing::tracing;
use databend_query::api::HttpService;
use databend_query::api::RpcService;
use databend_query::configs::Config;
use databend_query::metrics::MetricService;
use databend_query::servers::ClickHouseHandler;
use databend_query::servers::HttpHandler;
use databend_query::servers::MySQLHandler;
use databend_query::servers::Server;
use databend_query::servers::ShutdownHandle;
use databend_query::sessions::SessionManager;
#[databend_main]
async fn main(_global_tracker: Arc<RuntimeTracker>) -> common_exception::Result<()> {
let conf: Config = Config::load()?;
if conf.meta.address.is_empty() {
MetaEmbedded::init_global_meta_store(conf.meta.embedded_dir.clone()).await?;
}
let app_name = format!(
"databend-query-{}@{}:{}",
conf.query.cluster_id, conf.query.mysql_handler_host, conf.query.mysql_handler_port
);
//let _guards = init_tracing_with_file(
let _guards = init_global_tracing(
app_name.as_str(),
conf.log.dir.as_str(),
conf.log.level.as_str(),
);
init_default_metrics_recorder();
set_panic_hook();
tracing::info!("{:?}", conf);
tracing::info!(
"DatabendQuery {}",
*databend_query::configs::DATABEND_COMMIT_VERSION,
);
let session_manager = SessionManager::from_conf(conf.clone()).await?;
let mut shutdown_handle = ShutdownHandle::create(session_manager.clone());
// MySQL handler.
{
let hostname = conf.query.mysql_handler_host.clone();
let listening = format!("{}:{}", hostname, conf.query.mysql_handler_port);
let mut handler = MySQLHandler::create(session_manager.clone());
let listening = handler.start(listening.parse()?).await?;
shutdown_handle.add_service(handler);
tracing::info!(
"MySQL handler listening on {}, Usage: mysql -uroot -h{} -P{}",
listening,
listening.ip(),
listening.port(),
);
}
// ClickHouse handler.
{
let hostname = conf.query.clickhouse_handler_host.clone();
let listening = format!("{}:{}", hostname, conf.query.clickhouse_handler_port);
let mut srv = ClickHouseHandler::create(session_manager.clone());
let listening = srv.start(listening.parse()?).await?;
shutdown_handle.add_service(srv);
tracing::info!(
"ClickHouse handler listening on {}, Usage: clickhouse-client --host {} --port {}",
listening,
listening.ip(),
listening.port(),
);
}
// HTTP handler.
{
let hostname = conf.query.http_handler_host.clone();
let listening = format!("{}:{}", hostname, conf.query.http_handler_port);
let mut srv = HttpHandler::create(session_manager.clone());
let listening = srv.start(listening.parse()?).await?;
shutdown_handle.add_service(srv);
let http_handler_usage = HttpHandler::usage(listening);
tracing::info!(
"Http handler listening on {} {}",
listening,
http_handler_usage
);
}
// Metric API service.
{
let address = conf.query.metric_api_address.clone();
let mut srv = MetricService::create(session_manager.clone());
let listening = srv.start(address.parse()?).await?;
shutdown_handle.add_service(srv);
tracing::info!("Metric API server listening on {}/metrics", listening);
}
// HTTP API service.
{
let address = conf.query.admin_api_address.clone();
let mut srv = HttpService::create(session_manager.clone());
let listening = srv.start(address.parse()?).await?;
shutdown_handle.add_service(srv);
tracing::info!("HTTP API server listening on {}", listening);
}
// RPC API service.
{
let address = conf.query.flight_api_address.clone();
let mut srv = RpcService::create(session_manager.clone());
let listening = srv.start(address.parse()?).await?;
shutdown_handle.add_service(srv);
tracing::info!("RPC API server listening on {}", listening);
}
// Cluster register.
{
let cluster_discovery = session_manager.get_cluster_discovery();
let register_to_metastore = cluster_discovery.register_to_metastore(&conf);
register_to_metastore.await?;
tracing::info!(
"Databend query has been registered:{:?} to metasrv:[{:?}].",
conf.query.cluster_id,
conf.meta.address
);
}
tracing::info!("Ready for connections.");
shutdown_handle.wait_for_termination_request().await;
tracing::info!("Shutdown server.");
Ok(())
}
| 34.981132 | 95 | 0.657857 |
6a668c347ee20423df37af897a658288e399d25c | 418,807 | use super::{
intrinsics::{
tbaa_label, type_to_llvm, CtxType, FunctionCache, GlobalCache, Intrinsics, MemoryCache,
},
// stackmap::{StackmapEntry, StackmapEntryKind, StackmapRegistry, ValueSemantic},
state::{ControlFrame, ExtraInfo, IfElseState, State},
};
use inkwell::{
attributes::AttributeLoc,
builder::Builder,
context::Context,
module::{Linkage, Module},
passes::PassManager,
targets::{FileType, TargetMachine},
types::{BasicType, FloatMathType, IntType, PointerType, VectorType},
values::{
BasicValue, BasicValueEnum, FloatValue, FunctionValue, InstructionOpcode, InstructionValue,
IntValue, PhiValue, PointerValue, VectorValue,
},
AddressSpace, AtomicOrdering, AtomicRMWBinOp, DLLStorageClass, FloatPredicate, IntPredicate,
};
use smallvec::SmallVec;
use crate::abi::{get_abi, Abi};
use crate::config::{CompiledKind, LLVM};
use crate::object_file::{load_object_file, CompiledFunction};
use wasmer_compiler::wasmparser::{MemoryImmediate, Operator};
use wasmer_compiler::{
wptype_to_type, CompileError, FunctionBodyData, MiddlewareBinaryReader, ModuleMiddlewareChain,
ModuleTranslationState, RelocationTarget, Symbol, SymbolRegistry,
};
use wasmer_types::entity::PrimaryMap;
use wasmer_types::{
FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, MemoryIndex, SignatureIndex,
TableIndex, Type,
};
use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle, VMOffsets};
const FUNCTION_SECTION: &str = "__TEXT,wasmer_function";
fn to_compile_error(err: impl std::error::Error) -> CompileError {
CompileError::Codegen(format!("{}", err))
}
pub struct FuncTranslator {
ctx: Context,
target_machine: TargetMachine,
abi: Box<dyn Abi>,
}
impl FuncTranslator {
pub fn new(target_machine: TargetMachine) -> Self {
let abi = get_abi(&target_machine);
Self {
ctx: Context::create(),
target_machine,
abi,
}
}
pub fn translate_to_module(
&self,
wasm_module: &ModuleInfo,
module_translation: &ModuleTranslationState,
local_func_index: &LocalFunctionIndex,
function_body: &FunctionBodyData,
config: &LLVM,
memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
_table_styles: &PrimaryMap<TableIndex, TableStyle>,
symbol_registry: &dyn SymbolRegistry,
) -> Result<Module, CompileError> {
// The function type, used for the callbacks.
let function = CompiledKind::Local(*local_func_index);
let func_index = wasm_module.func_index(*local_func_index);
let function_name =
symbol_registry.symbol_to_name(Symbol::LocalFunction(*local_func_index));
let module_name = match wasm_module.name.as_ref() {
None => format!("<anonymous module> function {}", function_name),
Some(module_name) => format!("module {} function {}", module_name, function_name),
};
let module = self.ctx.create_module(module_name.as_str());
let target_machine = &self.target_machine;
let target_triple = target_machine.get_triple();
module.set_triple(&target_triple);
module.set_data_layout(&target_machine.get_target_data().get_data_layout());
let wasm_fn_type = wasm_module
.signatures
.get(wasm_module.functions[func_index])
.unwrap();
// TODO: pointer width
let offsets = VMOffsets::new(8, &wasm_module);
let intrinsics = Intrinsics::declare(&module, &self.ctx);
let (func_type, func_attrs) =
self.abi
.func_type_to_llvm(&self.ctx, &intrinsics, Some(&offsets), wasm_fn_type)?;
let func = module.add_function(&function_name, func_type, Some(Linkage::External));
for (attr, attr_loc) in &func_attrs {
func.add_attribute(*attr_loc, *attr);
}
func.add_attribute(AttributeLoc::Function, intrinsics.stack_probe);
func.set_personality_function(intrinsics.personality);
func.as_global_value().set_section(FUNCTION_SECTION);
func.set_linkage(Linkage::DLLExport);
func.as_global_value()
.set_dll_storage_class(DLLStorageClass::Export);
let entry = self.ctx.append_basic_block(func, "entry");
let start_of_code = self.ctx.append_basic_block(func, "start_of_code");
let return_ = self.ctx.append_basic_block(func, "return");
let alloca_builder = self.ctx.create_builder();
let cache_builder = self.ctx.create_builder();
let builder = self.ctx.create_builder();
cache_builder.position_at_end(entry);
let br = cache_builder.build_unconditional_branch(start_of_code);
alloca_builder.position_before(&br);
cache_builder.position_before(&br);
builder.position_at_end(start_of_code);
let mut state = State::new();
builder.position_at_end(return_);
let phis: SmallVec<[PhiValue; 1]> = wasm_fn_type
.results()
.iter()
.map(|&wasm_ty| type_to_llvm(&intrinsics, wasm_ty).map(|ty| builder.build_phi(ty, "")))
.collect::<Result<_, _>>()?;
state.push_block(return_, phis);
builder.position_at_end(start_of_code);
let mut reader = MiddlewareBinaryReader::new_with_offset(
function_body.data,
function_body.module_offset,
);
reader.set_middleware_chain(
config
.middlewares
.generate_function_middleware_chain(*local_func_index),
);
let mut params = vec![];
let first_param =
if func_type.get_return_type().is_none() && wasm_fn_type.results().len() > 1 {
2
} else {
1
};
let mut is_first_alloca = true;
let mut insert_alloca = |ty, name| {
let alloca = alloca_builder.build_alloca(ty, name);
if is_first_alloca {
alloca_builder.position_at(entry, &alloca.as_instruction_value().unwrap());
is_first_alloca = false;
}
alloca
};
for idx in 0..wasm_fn_type.params().len() {
let ty = wasm_fn_type.params()[idx];
let ty = type_to_llvm(&intrinsics, ty)?;
let value = func
.get_nth_param((idx as u32).checked_add(first_param).unwrap())
.unwrap();
let alloca = insert_alloca(ty, "param");
cache_builder.build_store(alloca, value);
params.push(alloca);
}
let mut locals = vec![];
let num_locals = reader.read_local_count()?;
for _ in 0..num_locals {
let (count, ty) = reader.read_local_decl()?;
let ty = wptype_to_type(ty).map_err(to_compile_error)?;
let ty = type_to_llvm(&intrinsics, ty)?;
for _ in 0..count {
let alloca = insert_alloca(ty, "local");
cache_builder.build_store(alloca, ty.const_zero());
locals.push(alloca);
}
}
let mut params_locals = params.clone();
params_locals.extend(locals.iter().cloned());
let mut fcg = LLVMFunctionCodeGenerator {
context: &self.ctx,
builder,
alloca_builder,
intrinsics: &intrinsics,
state,
function: func,
locals: params_locals,
ctx: CtxType::new(wasm_module, &func, &cache_builder, &*self.abi),
unreachable_depth: 0,
memory_styles,
_table_styles,
module: &module,
module_translation,
wasm_module,
symbol_registry,
abi: &*self.abi,
};
fcg.ctx.add_func(
func_index,
func.as_global_value().as_pointer_value(),
fcg.ctx.basic(),
&func_attrs,
);
while fcg.state.has_control_frames() {
let pos = reader.current_position() as u32;
let op = reader.read_operator()?;
fcg.translate_operator(op, pos)?;
}
fcg.finalize(wasm_fn_type)?;
if let Some(ref callbacks) = config.callbacks {
callbacks.preopt_ir(&function, &module);
}
let pass_manager = PassManager::create(());
if config.enable_verifier {
pass_manager.add_verifier_pass();
}
pass_manager.add_type_based_alias_analysis_pass();
pass_manager.add_sccp_pass();
pass_manager.add_prune_eh_pass();
pass_manager.add_dead_arg_elimination_pass();
pass_manager.add_lower_expect_intrinsic_pass();
pass_manager.add_scalar_repl_aggregates_pass();
pass_manager.add_instruction_combining_pass();
pass_manager.add_jump_threading_pass();
pass_manager.add_correlated_value_propagation_pass();
pass_manager.add_cfg_simplification_pass();
pass_manager.add_reassociate_pass();
pass_manager.add_loop_rotate_pass();
pass_manager.add_loop_unswitch_pass();
pass_manager.add_ind_var_simplify_pass();
pass_manager.add_licm_pass();
pass_manager.add_loop_vectorize_pass();
pass_manager.add_instruction_combining_pass();
pass_manager.add_sccp_pass();
pass_manager.add_reassociate_pass();
pass_manager.add_cfg_simplification_pass();
pass_manager.add_gvn_pass();
pass_manager.add_memcpy_optimize_pass();
pass_manager.add_dead_store_elimination_pass();
pass_manager.add_bit_tracking_dce_pass();
pass_manager.add_instruction_combining_pass();
pass_manager.add_reassociate_pass();
pass_manager.add_cfg_simplification_pass();
pass_manager.add_slp_vectorize_pass();
pass_manager.add_early_cse_pass();
pass_manager.run_on(&module);
if let Some(ref callbacks) = config.callbacks {
callbacks.postopt_ir(&function, &module);
}
Ok(module)
}
pub fn translate(
&self,
wasm_module: &ModuleInfo,
module_translation: &ModuleTranslationState,
local_func_index: &LocalFunctionIndex,
function_body: &FunctionBodyData,
config: &LLVM,
memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
table_styles: &PrimaryMap<TableIndex, TableStyle>,
symbol_registry: &dyn SymbolRegistry,
) -> Result<CompiledFunction, CompileError> {
let module = self.translate_to_module(
wasm_module,
module_translation,
local_func_index,
function_body,
config,
memory_styles,
table_styles,
symbol_registry,
)?;
let function = CompiledKind::Local(*local_func_index);
let target_machine = &self.target_machine;
let memory_buffer = target_machine
.write_to_memory_buffer(&module, FileType::Object)
.unwrap();
if let Some(ref callbacks) = config.callbacks {
callbacks.obj_memory_buffer(&function, &memory_buffer);
}
let mem_buf_slice = memory_buffer.as_slice();
load_object_file(
mem_buf_slice,
FUNCTION_SECTION,
RelocationTarget::LocalFunc(*local_func_index),
|name: &String| {
Ok(
if let Some(Symbol::LocalFunction(local_func_index)) =
symbol_registry.name_to_symbol(name)
{
Some(RelocationTarget::LocalFunc(local_func_index))
} else {
None
},
)
},
)
}
}
impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
// Create a vector where each lane contains the same value.
fn splat_vector(
&self,
value: BasicValueEnum<'ctx>,
vec_ty: VectorType<'ctx>,
) -> VectorValue<'ctx> {
// Use insert_element to insert the element into an undef vector, then use
// shuffle vector to copy that lane to all lanes.
self.builder.build_shuffle_vector(
self.builder.build_insert_element(
vec_ty.get_undef(),
value,
self.intrinsics.i32_zero,
"",
),
vec_ty.get_undef(),
self.intrinsics
.i32_ty
.vec_type(vec_ty.get_size())
.const_zero(),
"",
)
}
// Convert floating point vector to integer and saturate when out of range.
// https://github.com/WebAssembly/nontrapping-float-to-int-conversions/blob/master/proposals/nontrapping-float-to-int-conversion/Overview.md
fn trunc_sat<T: FloatMathType<'ctx>>(
&self,
fvec_ty: T,
ivec_ty: T::MathConvType,
lower_bound: u64, // Exclusive (least representable value)
upper_bound: u64, // Exclusive (greatest representable value)
int_min_value: u64,
int_max_value: u64,
value: IntValue<'ctx>,
) -> IntValue<'ctx> {
// a) Compare vector with itself to identify NaN lanes.
// b) Compare vector with splat of inttofp(upper_bound) to identify
// lanes that need to saturate to max.
// c) Compare vector with splat of inttofp(lower_bound) to identify
// lanes that need to saturate to min.
// d) Use vector select (not shuffle) to pick from either the
// splat vector or the input vector depending on whether the
// comparison indicates that we have an unrepresentable value. Replace
// unrepresentable values with zero.
// e) Now that the value is safe, fpto[su]i it.
// f) Use our previous comparison results to replace certain zeros with
// int_min or int_max.
let fvec_ty = fvec_ty.as_basic_type_enum().into_vector_type();
let ivec_ty = ivec_ty.as_basic_type_enum().into_vector_type();
let fvec_element_ty = fvec_ty.get_element_type().into_float_type();
let ivec_element_ty = ivec_ty.get_element_type().into_int_type();
let is_signed = int_min_value != 0;
let int_min_value = self.splat_vector(
ivec_element_ty
.const_int(int_min_value, is_signed)
.as_basic_value_enum(),
ivec_ty,
);
let int_max_value = self.splat_vector(
ivec_element_ty
.const_int(int_max_value, is_signed)
.as_basic_value_enum(),
ivec_ty,
);
let lower_bound = if is_signed {
self.builder.build_signed_int_to_float(
ivec_element_ty.const_int(lower_bound, is_signed),
fvec_element_ty,
"",
)
} else {
self.builder.build_unsigned_int_to_float(
ivec_element_ty.const_int(lower_bound, is_signed),
fvec_element_ty,
"",
)
};
let upper_bound = if is_signed {
self.builder.build_signed_int_to_float(
ivec_element_ty.const_int(upper_bound, is_signed),
fvec_element_ty,
"",
)
} else {
self.builder.build_unsigned_int_to_float(
ivec_element_ty.const_int(upper_bound, is_signed),
fvec_element_ty,
"",
)
};
let value = self
.builder
.build_bitcast(value, fvec_ty, "")
.into_vector_value();
let zero = fvec_ty.const_zero();
let lower_bound = self.splat_vector(lower_bound.as_basic_value_enum(), fvec_ty);
let upper_bound = self.splat_vector(upper_bound.as_basic_value_enum(), fvec_ty);
let nan_cmp = self
.builder
.build_float_compare(FloatPredicate::UNO, value, zero, "nan");
let above_upper_bound_cmp = self.builder.build_float_compare(
FloatPredicate::OGT,
value,
upper_bound,
"above_upper_bound",
);
let below_lower_bound_cmp = self.builder.build_float_compare(
FloatPredicate::OLT,
value,
lower_bound,
"below_lower_bound",
);
let not_representable = self.builder.build_or(
self.builder.build_or(nan_cmp, above_upper_bound_cmp, ""),
below_lower_bound_cmp,
"not_representable_as_int",
);
let value = self
.builder
.build_select(not_representable, zero, value, "safe_to_convert")
.into_vector_value();
let value = if is_signed {
self.builder
.build_float_to_signed_int(value, ivec_ty, "as_int")
} else {
self.builder
.build_float_to_unsigned_int(value, ivec_ty, "as_int")
};
let value = self
.builder
.build_select(above_upper_bound_cmp, int_max_value, value, "")
.into_vector_value();
let res = self
.builder
.build_select(below_lower_bound_cmp, int_min_value, value, "")
.into_vector_value();
self.builder
.build_bitcast(res, self.intrinsics.i128_ty, "")
.into_int_value()
}
// Convert floating point vector to integer and saturate when out of range.
// https://github.com/WebAssembly/nontrapping-float-to-int-conversions/blob/master/proposals/nontrapping-float-to-int-conversion/Overview.md
fn trunc_sat_scalar(
&self,
int_ty: IntType<'ctx>,
lower_bound: u64, // Exclusive (least representable value)
upper_bound: u64, // Exclusive (greatest representable value)
int_min_value: u64,
int_max_value: u64,
value: FloatValue<'ctx>,
) -> IntValue<'ctx> {
// TODO: this is a scalarized version of the process in trunc_sat. Either
// we should merge with trunc_sat, or we should simplify this function.
// a) Compare value with itself to identify NaN.
// b) Compare value inttofp(upper_bound) to identify values that need to
// saturate to max.
// c) Compare value with inttofp(lower_bound) to identify values that need
// to saturate to min.
// d) Use select to pick from either zero or the input vector depending on
// whether the comparison indicates that we have an unrepresentable
// value.
// e) Now that the value is safe, fpto[su]i it.
// f) Use our previous comparison results to replace certain zeros with
// int_min or int_max.
let is_signed = int_min_value != 0;
let int_min_value = int_ty.const_int(int_min_value, is_signed);
let int_max_value = int_ty.const_int(int_max_value, is_signed);
let lower_bound = if is_signed {
self.builder.build_signed_int_to_float(
int_ty.const_int(lower_bound, is_signed),
value.get_type(),
"",
)
} else {
self.builder.build_unsigned_int_to_float(
int_ty.const_int(lower_bound, is_signed),
value.get_type(),
"",
)
};
let upper_bound = if is_signed {
self.builder.build_signed_int_to_float(
int_ty.const_int(upper_bound, is_signed),
value.get_type(),
"",
)
} else {
self.builder.build_unsigned_int_to_float(
int_ty.const_int(upper_bound, is_signed),
value.get_type(),
"",
)
};
let zero = value.get_type().const_zero();
let nan_cmp = self
.builder
.build_float_compare(FloatPredicate::UNO, value, zero, "nan");
let above_upper_bound_cmp = self.builder.build_float_compare(
FloatPredicate::OGT,
value,
upper_bound,
"above_upper_bound",
);
let below_lower_bound_cmp = self.builder.build_float_compare(
FloatPredicate::OLT,
value,
lower_bound,
"below_lower_bound",
);
let not_representable = self.builder.build_or(
self.builder.build_or(nan_cmp, above_upper_bound_cmp, ""),
below_lower_bound_cmp,
"not_representable_as_int",
);
let value = self
.builder
.build_select(not_representable, zero, value, "safe_to_convert")
.into_float_value();
let value = if is_signed {
self.builder
.build_float_to_signed_int(value, int_ty, "as_int")
} else {
self.builder
.build_float_to_unsigned_int(value, int_ty, "as_int")
};
let value = self
.builder
.build_select(above_upper_bound_cmp, int_max_value, value, "")
.into_int_value();
let value = self
.builder
.build_select(below_lower_bound_cmp, int_min_value, value, "")
.into_int_value();
self.builder
.build_bitcast(value, int_ty, "")
.into_int_value()
}
fn trap_if_not_representable_as_int(
&self,
lower_bound: u64, // Inclusive (not a trapping value)
upper_bound: u64, // Inclusive (not a trapping value)
value: FloatValue,
) {
let float_ty = value.get_type();
let int_ty = if float_ty == self.intrinsics.f32_ty {
self.intrinsics.i32_ty
} else {
self.intrinsics.i64_ty
};
let lower_bound = self
.builder
.build_bitcast(int_ty.const_int(lower_bound, false), float_ty, "")
.into_float_value();
let upper_bound = self
.builder
.build_bitcast(int_ty.const_int(upper_bound, false), float_ty, "")
.into_float_value();
// The 'U' in the float predicate is short for "unordered" which means that
// the comparison will compare true if either operand is a NaN. Thus, NaNs
// are out of bounds.
let above_upper_bound_cmp = self.builder.build_float_compare(
FloatPredicate::UGT,
value,
upper_bound,
"above_upper_bound",
);
let below_lower_bound_cmp = self.builder.build_float_compare(
FloatPredicate::ULT,
value,
lower_bound,
"below_lower_bound",
);
let out_of_bounds = self.builder.build_or(
above_upper_bound_cmp,
below_lower_bound_cmp,
"out_of_bounds",
);
let failure_block = self
.context
.append_basic_block(self.function, "conversion_failure_block");
let continue_block = self
.context
.append_basic_block(self.function, "conversion_success_block");
self.builder
.build_conditional_branch(out_of_bounds, failure_block, continue_block);
self.builder.position_at_end(failure_block);
let is_nan = self
.builder
.build_float_compare(FloatPredicate::UNO, value, value, "is_nan");
let trap_code = self.builder.build_select(
is_nan,
self.intrinsics.trap_bad_conversion_to_integer,
self.intrinsics.trap_illegal_arithmetic,
"",
);
self.builder
.build_call(self.intrinsics.throw_trap, &[trap_code], "throw");
self.builder.build_unreachable();
self.builder.position_at_end(continue_block);
}
fn trap_if_zero_or_overflow(&self, left: IntValue, right: IntValue) {
let int_type = left.get_type();
let (min_value, neg_one_value) = if int_type == self.intrinsics.i32_ty {
let min_value = int_type.const_int(i32::min_value() as u64, false);
let neg_one_value = int_type.const_int(-1i32 as u32 as u64, false);
(min_value, neg_one_value)
} else if int_type == self.intrinsics.i64_ty {
let min_value = int_type.const_int(i64::min_value() as u64, false);
let neg_one_value = int_type.const_int(-1i64 as u64, false);
(min_value, neg_one_value)
} else {
unreachable!()
};
let divisor_is_zero = self.builder.build_int_compare(
IntPredicate::EQ,
right,
int_type.const_zero(),
"divisor_is_zero",
);
let should_trap = self.builder.build_or(
divisor_is_zero,
self.builder.build_and(
self.builder
.build_int_compare(IntPredicate::EQ, left, min_value, "left_is_min"),
self.builder.build_int_compare(
IntPredicate::EQ,
right,
neg_one_value,
"right_is_neg_one",
),
"div_will_overflow",
),
"div_should_trap",
);
let should_trap = self
.builder
.build_call(
self.intrinsics.expect_i1,
&[
should_trap.as_basic_value_enum(),
self.intrinsics.i1_ty.const_zero().as_basic_value_enum(),
],
"should_trap_expect",
)
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let shouldnt_trap_block = self
.context
.append_basic_block(self.function, "shouldnt_trap_block");
let should_trap_block = self
.context
.append_basic_block(self.function, "should_trap_block");
self.builder
.build_conditional_branch(should_trap, should_trap_block, shouldnt_trap_block);
self.builder.position_at_end(should_trap_block);
let trap_code = self.builder.build_select(
divisor_is_zero,
self.intrinsics.trap_integer_division_by_zero,
self.intrinsics.trap_illegal_arithmetic,
"",
);
self.builder
.build_call(self.intrinsics.throw_trap, &[trap_code], "throw");
self.builder.build_unreachable();
self.builder.position_at_end(shouldnt_trap_block);
}
fn trap_if_zero(&self, value: IntValue) {
let int_type = value.get_type();
let should_trap = self.builder.build_int_compare(
IntPredicate::EQ,
value,
int_type.const_zero(),
"divisor_is_zero",
);
let should_trap = self
.builder
.build_call(
self.intrinsics.expect_i1,
&[
should_trap.as_basic_value_enum(),
self.intrinsics.i1_ty.const_zero().as_basic_value_enum(),
],
"should_trap_expect",
)
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let shouldnt_trap_block = self
.context
.append_basic_block(self.function, "shouldnt_trap_block");
let should_trap_block = self
.context
.append_basic_block(self.function, "should_trap_block");
self.builder
.build_conditional_branch(should_trap, should_trap_block, shouldnt_trap_block);
self.builder.position_at_end(should_trap_block);
self.builder.build_call(
self.intrinsics.throw_trap,
&[self.intrinsics.trap_integer_division_by_zero],
"throw",
);
self.builder.build_unreachable();
self.builder.position_at_end(shouldnt_trap_block);
}
fn v128_into_int_vec(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
int_vec_ty: VectorType<'ctx>,
) -> (VectorValue<'ctx>, ExtraInfo) {
let (value, info) = if info.has_pending_f32_nan() {
let value = self
.builder
.build_bitcast(value, self.intrinsics.f32x4_ty, "");
(self.canonicalize_nans(value), info.strip_pending())
} else if info.has_pending_f64_nan() {
let value = self
.builder
.build_bitcast(value, self.intrinsics.f64x2_ty, "");
(self.canonicalize_nans(value), info.strip_pending())
} else {
(value, info)
};
(
self.builder
.build_bitcast(value, int_vec_ty, "")
.into_vector_value(),
info,
)
}
fn v128_into_i8x16(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> (VectorValue<'ctx>, ExtraInfo) {
self.v128_into_int_vec(value, info, self.intrinsics.i8x16_ty)
}
fn v128_into_i16x8(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> (VectorValue<'ctx>, ExtraInfo) {
self.v128_into_int_vec(value, info, self.intrinsics.i16x8_ty)
}
fn v128_into_i32x4(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> (VectorValue<'ctx>, ExtraInfo) {
self.v128_into_int_vec(value, info, self.intrinsics.i32x4_ty)
}
fn v128_into_i64x2(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> (VectorValue<'ctx>, ExtraInfo) {
self.v128_into_int_vec(value, info, self.intrinsics.i64x2_ty)
}
// If the value is pending a 64-bit canonicalization, do it now.
// Return a f32x4 vector.
fn v128_into_f32x4(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> (VectorValue<'ctx>, ExtraInfo) {
let (value, info) = if info.has_pending_f64_nan() {
let value = self
.builder
.build_bitcast(value, self.intrinsics.f64x2_ty, "");
(self.canonicalize_nans(value), info.strip_pending())
} else {
(value, info)
};
(
self.builder
.build_bitcast(value, self.intrinsics.f32x4_ty, "")
.into_vector_value(),
info,
)
}
// If the value is pending a 32-bit canonicalization, do it now.
// Return a f64x2 vector.
fn v128_into_f64x2(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> (VectorValue<'ctx>, ExtraInfo) {
let (value, info) = if info.has_pending_f32_nan() {
let value = self
.builder
.build_bitcast(value, self.intrinsics.f32x4_ty, "");
(self.canonicalize_nans(value), info.strip_pending())
} else {
(value, info)
};
(
self.builder
.build_bitcast(value, self.intrinsics.f64x2_ty, "")
.into_vector_value(),
info,
)
}
fn apply_pending_canonicalization(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> BasicValueEnum<'ctx> {
if info.has_pending_f32_nan() {
if value.get_type().is_vector_type()
|| value.get_type() == self.intrinsics.i128_ty.as_basic_type_enum()
{
let ty = value.get_type();
let value = self
.builder
.build_bitcast(value, self.intrinsics.f32x4_ty, "");
let value = self.canonicalize_nans(value);
self.builder.build_bitcast(value, ty, "")
} else {
self.canonicalize_nans(value)
}
} else if info.has_pending_f64_nan() {
if value.get_type().is_vector_type()
|| value.get_type() == self.intrinsics.i128_ty.as_basic_type_enum()
{
let ty = value.get_type();
let value = self
.builder
.build_bitcast(value, self.intrinsics.f64x2_ty, "");
let value = self.canonicalize_nans(value);
self.builder.build_bitcast(value, ty, "")
} else {
self.canonicalize_nans(value)
}
} else {
value
}
}
// Replaces any NaN with the canonical QNaN, otherwise leaves the value alone.
fn canonicalize_nans(&self, value: BasicValueEnum<'ctx>) -> BasicValueEnum<'ctx> {
let f_ty = value.get_type();
if f_ty.is_vector_type() {
let value = value.into_vector_value();
let f_ty = f_ty.into_vector_type();
let zero = f_ty.const_zero();
let nan_cmp = self
.builder
.build_float_compare(FloatPredicate::UNO, value, zero, "nan");
let canonical_qnan = f_ty
.get_element_type()
.into_float_type()
.const_float(std::f64::NAN);
let canonical_qnan = self.splat_vector(canonical_qnan.as_basic_value_enum(), f_ty);
self.builder
.build_select(nan_cmp, canonical_qnan, value, "")
.as_basic_value_enum()
} else {
let value = value.into_float_value();
let f_ty = f_ty.into_float_type();
let zero = f_ty.const_zero();
let nan_cmp = self
.builder
.build_float_compare(FloatPredicate::UNO, value, zero, "nan");
let canonical_qnan = f_ty.const_float(std::f64::NAN);
self.builder
.build_select(nan_cmp, canonical_qnan, value, "")
.as_basic_value_enum()
}
}
// If this memory access must trap when out of bounds (i.e. it is a memory
// access written in the user program as opposed to one used by our VM)
// then mark that it can't be delete.
fn mark_memaccess_nodelete(
&mut self,
memory_index: MemoryIndex,
memaccess: InstructionValue<'ctx>,
) -> Result<(), CompileError> {
if let MemoryCache::Static { base_ptr: _ } = self.ctx.memory(
memory_index,
self.intrinsics,
self.module,
self.memory_styles,
) {
// The best we've got is `volatile`.
// TODO: convert unwrap fail to CompileError
memaccess.set_volatile(true).unwrap();
}
Ok(())
}
fn annotate_user_memaccess(
&mut self,
memory_index: MemoryIndex,
_memarg: &MemoryImmediate,
alignment: u32,
memaccess: InstructionValue<'ctx>,
) -> Result<(), CompileError> {
match memaccess.get_opcode() {
InstructionOpcode::Load | InstructionOpcode::Store => {
memaccess.set_alignment(alignment).unwrap();
}
_ => {}
};
self.mark_memaccess_nodelete(memory_index, memaccess)?;
tbaa_label(
&self.module,
self.intrinsics,
format!("memory {}", memory_index.as_u32()),
memaccess,
);
Ok(())
}
fn resolve_memory_ptr(
&mut self,
memory_index: MemoryIndex,
memarg: &MemoryImmediate,
ptr_ty: PointerType<'ctx>,
var_offset: IntValue<'ctx>,
value_size: usize,
) -> Result<PointerValue<'ctx>, CompileError> {
let builder = &self.builder;
let intrinsics = &self.intrinsics;
let context = &self.context;
let function = &self.function;
// Compute the offset into the storage.
let imm_offset = intrinsics.i64_ty.const_int(memarg.offset as u64, false);
let var_offset = builder.build_int_z_extend(var_offset, intrinsics.i64_ty, "");
let offset = builder.build_int_add(var_offset, imm_offset, "");
// Look up the memory base (as pointer) and bounds (as unsigned integer).
let base_ptr =
match self
.ctx
.memory(memory_index, intrinsics, self.module, self.memory_styles)
{
MemoryCache::Dynamic {
ptr_to_base_ptr,
ptr_to_current_length,
} => {
// Bounds check it.
let minimum = self.wasm_module.memories[memory_index].minimum;
let value_size_v = intrinsics.i64_ty.const_int(value_size as u64, false);
let ptr_in_bounds = if offset.is_const() {
// When the offset is constant, if it's below the minimum
// memory size, we've statically shown that it's safe.
let load_offset_end = offset.const_add(value_size_v);
let ptr_in_bounds = load_offset_end.const_int_compare(
IntPredicate::ULE,
intrinsics.i64_ty.const_int(minimum.bytes().0 as u64, false),
);
if ptr_in_bounds.get_zero_extended_constant() == Some(1) {
Some(ptr_in_bounds)
} else {
None
}
} else {
None
}
.unwrap_or_else(|| {
let load_offset_end = builder.build_int_add(offset, value_size_v, "");
let current_length = builder
.build_load(ptr_to_current_length, "")
.into_int_value();
tbaa_label(
self.module,
self.intrinsics,
format!("memory {} length", memory_index.as_u32()),
current_length.as_instruction_value().unwrap(),
);
let current_length =
builder.build_int_z_extend(current_length, intrinsics.i64_ty, "");
builder.build_int_compare(
IntPredicate::ULE,
load_offset_end,
current_length,
"",
)
});
if !ptr_in_bounds.is_constant_int()
|| ptr_in_bounds.get_zero_extended_constant().unwrap() != 1
{
// LLVM may have folded this into 'i1 true' in which case we know
// the pointer is in bounds. LLVM may also have folded it into a
// constant expression, not known to be either true or false yet.
// If it's false, unknown-but-constant, or not-a-constant, emit a
// runtime bounds check. LLVM may yet succeed at optimizing it away.
let ptr_in_bounds = builder
.build_call(
intrinsics.expect_i1,
&[
ptr_in_bounds.as_basic_value_enum(),
intrinsics.i1_ty.const_int(1, true).as_basic_value_enum(),
],
"ptr_in_bounds_expect",
)
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let in_bounds_continue_block =
context.append_basic_block(*function, "in_bounds_continue_block");
let not_in_bounds_block =
context.append_basic_block(*function, "not_in_bounds_block");
builder.build_conditional_branch(
ptr_in_bounds,
in_bounds_continue_block,
not_in_bounds_block,
);
builder.position_at_end(not_in_bounds_block);
builder.build_call(
intrinsics.throw_trap,
&[intrinsics.trap_memory_oob],
"throw",
);
builder.build_unreachable();
builder.position_at_end(in_bounds_continue_block);
}
let ptr_to_base = builder.build_load(ptr_to_base_ptr, "").into_pointer_value();
tbaa_label(
self.module,
self.intrinsics,
format!("memory base_ptr {}", memory_index.as_u32()),
ptr_to_base.as_instruction_value().unwrap(),
);
ptr_to_base
}
MemoryCache::Static { base_ptr } => base_ptr,
};
let value_ptr = unsafe { builder.build_gep(base_ptr, &[offset], "") };
Ok(builder
.build_bitcast(value_ptr, ptr_ty, "")
.into_pointer_value())
}
fn trap_if_misaligned(&self, memarg: &MemoryImmediate, ptr: PointerValue<'ctx>) {
let align = memarg.align;
let value = self
.builder
.build_ptr_to_int(ptr, self.intrinsics.i64_ty, "");
let and = self.builder.build_and(
value,
self.intrinsics.i64_ty.const_int((align - 1).into(), false),
"misaligncheck",
);
let aligned =
self.builder
.build_int_compare(IntPredicate::EQ, and, self.intrinsics.i64_zero, "");
let aligned = self
.builder
.build_call(
self.intrinsics.expect_i1,
&[
aligned.as_basic_value_enum(),
self.intrinsics
.i1_ty
.const_int(1, false)
.as_basic_value_enum(),
],
"",
)
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let continue_block = self
.context
.append_basic_block(self.function, "aligned_access_continue_block");
let not_aligned_block = self
.context
.append_basic_block(self.function, "misaligned_trap_block");
self.builder
.build_conditional_branch(aligned, continue_block, not_aligned_block);
self.builder.position_at_end(not_aligned_block);
self.builder.build_call(
self.intrinsics.throw_trap,
&[self.intrinsics.trap_unaligned_atomic],
"throw",
);
self.builder.build_unreachable();
self.builder.position_at_end(continue_block);
}
fn finalize(&mut self, wasm_fn_type: &FunctionType) -> Result<(), CompileError> {
let func_type = self.function.get_type();
let results = self.state.popn_save_extra(wasm_fn_type.results().len())?;
let results = results
.into_iter()
.map(|(v, i)| self.apply_pending_canonicalization(v, i));
if wasm_fn_type.results().is_empty() {
self.builder.build_return(None);
} else if self.abi.is_sret(wasm_fn_type)? {
let sret = self
.function
.get_first_param()
.unwrap()
.into_pointer_value();
let mut struct_value = sret
.get_type()
.get_element_type()
.into_struct_type()
.get_undef();
for (idx, value) in results.enumerate() {
let value = self.builder.build_bitcast(
value,
type_to_llvm(&self.intrinsics, wasm_fn_type.results()[idx])?,
"",
);
struct_value = self
.builder
.build_insert_value(struct_value, value, idx as u32, "")
.unwrap()
.into_struct_value();
}
self.builder.build_store(sret, struct_value);
self.builder.build_return(None);
} else {
self.builder
.build_return(Some(&self.abi.pack_values_for_register_return(
&self.intrinsics,
&self.builder,
&results.collect::<Vec<_>>(),
&func_type,
)?));
}
Ok(())
}
}
/*
fn emit_stack_map<'ctx>(
intrinsics: &Intrinsics<'ctx>,
builder: &Builder<'ctx>,
local_function_id: usize,
target: &mut StackmapRegistry,
kind: StackmapEntryKind,
locals: &[PointerValue],
state: &State<'ctx>,
_ctx: &mut CtxType<'ctx>,
opcode_offset: usize,
) {
let stackmap_id = target.entries.len();
let mut params = Vec::with_capacity(2 + locals.len() + state.stack.len());
params.push(
intrinsics
.i64_ty
.const_int(stackmap_id as u64, false)
.as_basic_value_enum(),
);
params.push(intrinsics.i32_ty.const_zero().as_basic_value_enum());
let locals: Vec<_> = locals.iter().map(|x| x.as_basic_value_enum()).collect();
let mut value_semantics: Vec<ValueSemantic> =
Vec::with_capacity(locals.len() + state.stack.len());
params.extend_from_slice(&locals);
value_semantics.extend((0..locals.len()).map(ValueSemantic::WasmLocal));
params.extend(state.stack.iter().map(|x| x.0));
value_semantics.extend((0..state.stack.len()).map(ValueSemantic::WasmStack));
// FIXME: Information needed for Abstract -> Runtime state transform is not fully preserved
// to accelerate compilation and reduce memory usage. Check this again when we try to support
// "full" LLVM OSR.
assert_eq!(params.len(), value_semantics.len() + 2);
builder.build_call(intrinsics.experimental_stackmap, ¶ms, "");
target.entries.push(StackmapEntry {
kind,
local_function_id,
local_count: locals.len(),
stack_count: state.stack.len(),
opcode_offset,
value_semantics,
is_start: true,
});
}
fn finalize_opcode_stack_map<'ctx>(
intrinsics: &Intrinsics<'ctx>,
builder: &Builder<'ctx>,
local_function_id: usize,
target: &mut StackmapRegistry,
kind: StackmapEntryKind,
opcode_offset: usize,
) {
let stackmap_id = target.entries.len();
builder.build_call(
intrinsics.experimental_stackmap,
&[
intrinsics
.i64_ty
.const_int(stackmap_id as u64, false)
.as_basic_value_enum(),
intrinsics.i32_ty.const_zero().as_basic_value_enum(),
],
"opcode_stack_map_end",
);
target.entries.push(StackmapEntry {
kind,
local_function_id,
local_count: 0,
stack_count: 0,
opcode_offset,
value_semantics: vec![],
is_start: false,
});
}
*/
pub struct LLVMFunctionCodeGenerator<'ctx, 'a> {
context: &'ctx Context,
builder: Builder<'ctx>,
alloca_builder: Builder<'ctx>,
intrinsics: &'a Intrinsics<'ctx>,
state: State<'ctx>,
function: FunctionValue<'ctx>,
locals: Vec<PointerValue<'ctx>>, // Contains params and locals
ctx: CtxType<'ctx, 'a>,
unreachable_depth: usize,
memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
_table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
// This is support for stackmaps:
/*
stackmaps: Rc<RefCell<StackmapRegistry>>,
index: usize,
opcode_offset: usize,
track_state: bool,
*/
module: &'a Module<'ctx>,
module_translation: &'a ModuleTranslationState,
wasm_module: &'a ModuleInfo,
symbol_registry: &'a dyn SymbolRegistry,
abi: &'a dyn Abi,
}
impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
fn translate_operator(&mut self, op: Operator, _source_loc: u32) -> Result<(), CompileError> {
// TODO: remove this vmctx by moving everything into CtxType. Values
// computed off vmctx usually benefit from caching.
let vmctx = &self.ctx.basic().into_pointer_value();
//let opcode_offset: Option<usize> = None;
if !self.state.reachable {
match op {
Operator::Block { ty: _ } | Operator::Loop { ty: _ } | Operator::If { ty: _ } => {
self.unreachable_depth += 1;
return Ok(());
}
Operator::Else => {
if self.unreachable_depth != 0 {
return Ok(());
}
}
Operator::End => {
if self.unreachable_depth != 0 {
self.unreachable_depth -= 1;
return Ok(());
}
}
_ => {
return Ok(());
}
}
}
match op {
/***************************
* Control Flow instructions.
* https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#control-flow-instructions
***************************/
Operator::Block { ty } => {
let current_block = self
.builder
.get_insert_block()
.ok_or_else(|| CompileError::Codegen("not currently in a block".to_string()))?;
let end_block = self.context.append_basic_block(self.function, "end");
self.builder.position_at_end(end_block);
let phis: SmallVec<[PhiValue<'ctx>; 1]> = self
.module_translation
.blocktype_params_results(ty)?
.1
.iter()
.map(|&wp_ty| {
wptype_to_type(wp_ty)
.map_err(to_compile_error)
.and_then(|wasm_ty| {
type_to_llvm(self.intrinsics, wasm_ty)
.map(|ty| self.builder.build_phi(ty, ""))
})
})
.collect::<Result<_, _>>()?;
self.state.push_block(end_block, phis);
self.builder.position_at_end(current_block);
}
Operator::Loop { ty } => {
let loop_body = self.context.append_basic_block(self.function, "loop_body");
let loop_next = self.context.append_basic_block(self.function, "loop_outer");
let pre_loop_block = self.builder.get_insert_block().unwrap();
self.builder.build_unconditional_branch(loop_body);
self.builder.position_at_end(loop_next);
let blocktypes = self.module_translation.blocktype_params_results(ty)?;
let phis = blocktypes
.1
.iter()
.map(|&wp_ty| {
wptype_to_type(wp_ty)
.map_err(to_compile_error)
.and_then(|wasm_ty| {
type_to_llvm(self.intrinsics, wasm_ty)
.map(|ty| self.builder.build_phi(ty, ""))
})
})
.collect::<Result<_, _>>()?;
self.builder.position_at_end(loop_body);
let loop_phis: SmallVec<[PhiValue<'ctx>; 1]> = blocktypes
.0
.iter()
.map(|&wp_ty| {
wptype_to_type(wp_ty)
.map_err(to_compile_error)
.and_then(|wasm_ty| {
type_to_llvm(self.intrinsics, wasm_ty)
.map(|ty| self.builder.build_phi(ty, ""))
})
})
.collect::<Result<_, _>>()?;
for phi in loop_phis.iter().rev() {
let (value, info) = self.state.pop1_extra()?;
let value = self.apply_pending_canonicalization(value, info);
phi.add_incoming(&[(&value, pre_loop_block)]);
}
for phi in &loop_phis {
self.state.push1(phi.as_basic_value());
}
/*
if self.track_state {
if let Some(offset) = opcode_offset {
let mut stackmaps = self.stackmaps.borrow_mut();
emit_stack_map(
self.intrinsics,
self.builder,
self.index,
&mut *stackmaps,
StackmapEntryKind::Loop,
&self.self.locals,
state,
ctx,
offset,
);
let signal_mem = ctx.signal_mem();
let iv = self.builder
.build_store(signal_mem, self.context.i8_type().const_zero());
// Any 'store' can be made volatile.
iv.set_volatile(true).unwrap();
finalize_opcode_stack_map(
self.intrinsics,
self.builder,
self.index,
&mut *stackmaps,
StackmapEntryKind::Loop,
offset,
);
}
}
*/
self.state.push_loop(loop_body, loop_next, loop_phis, phis);
}
Operator::Br { relative_depth } => {
let frame = self.state.frame_at_depth(relative_depth)?;
let current_block = self
.builder
.get_insert_block()
.ok_or_else(|| CompileError::Codegen("not currently in a block".to_string()))?;
let phis = if frame.is_loop() {
frame.loop_body_phis()
} else {
frame.phis()
};
let len = phis.len();
let values = self.state.peekn_extra(len)?;
let values = values
.iter()
.map(|(v, info)| self.apply_pending_canonicalization(*v, *info));
// For each result of the block we're branching to,
// pop a value off the value stack and load it into
// the corresponding phi.
for (phi, value) in phis.iter().zip(values) {
phi.add_incoming(&[(&value, current_block)]);
}
self.builder.build_unconditional_branch(*frame.br_dest());
self.state.popn(len)?;
self.state.reachable = false;
}
Operator::BrIf { relative_depth } => {
let cond = self.state.pop1()?;
let frame = self.state.frame_at_depth(relative_depth)?;
let current_block = self
.builder
.get_insert_block()
.ok_or_else(|| CompileError::Codegen("not currently in a block".to_string()))?;
let phis = if frame.is_loop() {
frame.loop_body_phis()
} else {
frame.phis()
};
let param_stack = self.state.peekn_extra(phis.len())?;
let param_stack = param_stack
.iter()
.map(|(v, info)| self.apply_pending_canonicalization(*v, *info));
for (phi, value) in phis.iter().zip(param_stack) {
phi.add_incoming(&[(&value, current_block)]);
}
let else_block = self.context.append_basic_block(self.function, "else");
let cond_value = self.builder.build_int_compare(
IntPredicate::NE,
cond.into_int_value(),
self.intrinsics.i32_zero,
"",
);
self.builder
.build_conditional_branch(cond_value, *frame.br_dest(), else_block);
self.builder.position_at_end(else_block);
}
Operator::BrTable { ref table } => {
let current_block = self
.builder
.get_insert_block()
.ok_or_else(|| CompileError::Codegen("not currently in a block".to_string()))?;
let mut label_depths = table.targets().collect::<Result<Vec<_>, _>>()?;
let default_depth = label_depths.pop().unwrap().0;
let index = self.state.pop1()?;
let default_frame = self.state.frame_at_depth(default_depth)?;
let phis = if default_frame.is_loop() {
default_frame.loop_body_phis()
} else {
default_frame.phis()
};
let args = self.state.peekn(phis.len())?;
for (phi, value) in phis.iter().zip(args.iter()) {
phi.add_incoming(&[(value, current_block)]);
}
let cases: Vec<_> = label_depths
.iter()
.enumerate()
.map(|(case_index, &(depth, _))| {
let frame_result: Result<&ControlFrame, CompileError> =
self.state.frame_at_depth(depth);
let frame = match frame_result {
Ok(v) => v,
Err(e) => return Err(e),
};
let case_index_literal =
self.context.i32_type().const_int(case_index as u64, false);
for (phi, value) in frame.phis().iter().zip(args.iter()) {
phi.add_incoming(&[(value, current_block)]);
}
Ok((case_index_literal, *frame.br_dest()))
})
.collect::<Result<_, _>>()?;
self.builder.build_switch(
index.into_int_value(),
*default_frame.br_dest(),
&cases[..],
);
let args_len = args.len();
self.state.popn(args_len)?;
self.state.reachable = false;
}
Operator::If { ty } => {
let current_block = self
.builder
.get_insert_block()
.ok_or_else(|| CompileError::Codegen("not currently in a block".to_string()))?;
let if_then_block = self.context.append_basic_block(self.function, "if_then");
let if_else_block = self.context.append_basic_block(self.function, "if_else");
let end_block = self.context.append_basic_block(self.function, "if_end");
let end_phis = {
self.builder.position_at_end(end_block);
let phis = self
.module_translation
.blocktype_params_results(ty)?
.1
.iter()
.map(|&wp_ty| {
wptype_to_type(wp_ty)
.map_err(to_compile_error)
.and_then(|wasm_ty| {
type_to_llvm(self.intrinsics, wasm_ty)
.map(|ty| self.builder.build_phi(ty, ""))
})
})
.collect::<Result<_, _>>()?;
self.builder.position_at_end(current_block);
phis
};
let cond = self.state.pop1()?;
let cond_value = self.builder.build_int_compare(
IntPredicate::NE,
cond.into_int_value(),
self.intrinsics.i32_zero,
"",
);
self.builder
.build_conditional_branch(cond_value, if_then_block, if_else_block);
self.builder.position_at_end(if_else_block);
let block_param_types = self
.module_translation
.blocktype_params_results(ty)?
.0
.iter()
.map(|&wp_ty| {
wptype_to_type(wp_ty)
.map_err(to_compile_error)
.and_then(|wasm_ty| type_to_llvm(self.intrinsics, wasm_ty))
})
.collect::<Result<Vec<_>, _>>()?;
let else_phis: SmallVec<[PhiValue<'ctx>; 1]> = block_param_types
.iter()
.map(|&ty| self.builder.build_phi(ty, ""))
.collect();
self.builder.position_at_end(if_then_block);
let then_phis: SmallVec<[PhiValue<'ctx>; 1]> = block_param_types
.iter()
.map(|&ty| self.builder.build_phi(ty, ""))
.collect();
for (else_phi, then_phi) in else_phis.iter().rev().zip(then_phis.iter().rev()) {
let (value, info) = self.state.pop1_extra()?;
let value = self.apply_pending_canonicalization(value, info);
else_phi.add_incoming(&[(&value, current_block)]);
then_phi.add_incoming(&[(&value, current_block)]);
}
for phi in then_phis.iter() {
self.state.push1(phi.as_basic_value());
}
self.state.push_if(
if_then_block,
if_else_block,
end_block,
then_phis,
else_phis,
end_phis,
);
}
Operator::Else => {
if self.state.reachable {
let frame = self.state.frame_at_depth(0)?;
let current_block = self.builder.get_insert_block().ok_or_else(|| {
CompileError::Codegen("not currently in a block".to_string())
})?;
for phi in frame.phis().to_vec().iter().rev() {
let (value, info) = self.state.pop1_extra()?;
let value = self.apply_pending_canonicalization(value, info);
phi.add_incoming(&[(&value, current_block)])
}
let frame = self.state.frame_at_depth(0)?;
self.builder.build_unconditional_branch(*frame.code_after());
}
let (if_else_block, if_else_state) = if let ControlFrame::IfElse {
if_else,
if_else_state,
..
} = self.state.frame_at_depth_mut(0)?
{
(if_else, if_else_state)
} else {
unreachable!()
};
*if_else_state = IfElseState::Else;
self.builder.position_at_end(*if_else_block);
self.state.reachable = true;
if let ControlFrame::IfElse { else_phis, .. } = self.state.frame_at_depth(0)? {
// Push our own 'else' phi nodes to the stack.
for phi in else_phis.clone().iter() {
self.state.push1(phi.as_basic_value());
}
};
}
Operator::End => {
let frame = self.state.pop_frame()?;
let current_block = self
.builder
.get_insert_block()
.ok_or_else(|| CompileError::Codegen("not currently in a block".to_string()))?;
if self.state.reachable {
for phi in frame.phis().iter().rev() {
let (value, info) = self.state.pop1_extra()?;
let value = self.apply_pending_canonicalization(value, info);
phi.add_incoming(&[(&value, current_block)]);
}
self.builder.build_unconditional_branch(*frame.code_after());
}
if let ControlFrame::IfElse {
if_else,
next,
if_else_state,
else_phis,
..
} = &frame
{
if let IfElseState::If = if_else_state {
for (phi, else_phi) in frame.phis().iter().zip(else_phis.iter()) {
phi.add_incoming(&[(&else_phi.as_basic_value(), *if_else)]);
}
self.builder.position_at_end(*if_else);
self.builder.build_unconditional_branch(*next);
}
}
self.builder.position_at_end(*frame.code_after());
self.state.reset_stack(&frame);
self.state.reachable = true;
// Push each phi value to the value stack.
for phi in frame.phis() {
if phi.count_incoming() != 0 {
self.state.push1(phi.as_basic_value());
} else {
let basic_ty = phi.as_basic_value().get_type();
let placeholder_value = basic_ty.const_zero();
self.state.push1(placeholder_value);
phi.as_instruction().erase_from_basic_block();
}
}
}
Operator::Return => {
let current_block = self
.builder
.get_insert_block()
.ok_or_else(|| CompileError::Codegen("not currently in a block".to_string()))?;
let frame = self.state.outermost_frame()?;
for phi in frame.phis().to_vec().iter().rev() {
let (arg, info) = self.state.pop1_extra()?;
let arg = self.apply_pending_canonicalization(arg, info);
phi.add_incoming(&[(&arg, current_block)]);
}
let frame = self.state.outermost_frame()?;
self.builder.build_unconditional_branch(*frame.br_dest());
self.state.reachable = false;
}
Operator::Unreachable => {
// Emit an unreachable instruction.
// If llvm cannot prove that this is never reached,
// it will emit a `ud2` instruction on x86_64 arches.
// Comment out this `if` block to allow spectests to pass.
// TODO: fix this
/*
if let Some(offset) = opcode_offset {
if self.track_state {
let mut stackmaps = self.stackmaps.borrow_mut();
emit_stack_map(
self.intrinsics,
self.builder,
self.index,
&mut *stackmaps,
StackmapEntryKind::Trappable,
&self.self.locals,
state,
ctx,
offset,
);
self.builder.build_call(self.intrinsics.trap, &[], "trap");
finalize_opcode_stack_map(
self.intrinsics,
self.builder,
self.index,
&mut *stackmaps,
StackmapEntryKind::Trappable,
offset,
);
}
}
*/
self.builder.build_call(
self.intrinsics.throw_trap,
&[self.intrinsics.trap_unreachable],
"throw",
);
self.builder.build_unreachable();
self.state.reachable = false;
}
/***************************
* Basic instructions.
* https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#basic-instructions
***************************/
Operator::Nop => {
// Do nothing.
}
Operator::Drop => {
self.state.pop1()?;
}
// Generate const values.
Operator::I32Const { value } => {
let i = self.intrinsics.i32_ty.const_int(value as u64, false);
let info = if is_f32_arithmetic(value as u32) {
ExtraInfo::arithmetic_f32()
} else {
Default::default()
};
self.state.push1_extra(i, info);
}
Operator::I64Const { value } => {
let i = self.intrinsics.i64_ty.const_int(value as u64, false);
let info = if is_f64_arithmetic(value as u64) {
ExtraInfo::arithmetic_f64()
} else {
Default::default()
};
self.state.push1_extra(i, info);
}
Operator::F32Const { value } => {
let bits = self.intrinsics.i32_ty.const_int(value.bits() as u64, false);
let info = if is_f32_arithmetic(value.bits()) {
ExtraInfo::arithmetic_f32()
} else {
Default::default()
};
let f = self
.builder
.build_bitcast(bits, self.intrinsics.f32_ty, "f");
self.state.push1_extra(f, info);
}
Operator::F64Const { value } => {
let bits = self.intrinsics.i64_ty.const_int(value.bits(), false);
let info = if is_f64_arithmetic(value.bits()) {
ExtraInfo::arithmetic_f64()
} else {
Default::default()
};
let f = self
.builder
.build_bitcast(bits, self.intrinsics.f64_ty, "f");
self.state.push1_extra(f, info);
}
Operator::V128Const { value } => {
let mut hi: [u8; 8] = Default::default();
let mut lo: [u8; 8] = Default::default();
hi.copy_from_slice(&value.bytes()[0..8]);
lo.copy_from_slice(&value.bytes()[8..16]);
let packed = [u64::from_le_bytes(hi), u64::from_le_bytes(lo)];
let i = self
.intrinsics
.i128_ty
.const_int_arbitrary_precision(&packed);
let mut quad1: [u8; 4] = Default::default();
let mut quad2: [u8; 4] = Default::default();
let mut quad3: [u8; 4] = Default::default();
let mut quad4: [u8; 4] = Default::default();
quad1.copy_from_slice(&value.bytes()[0..4]);
quad2.copy_from_slice(&value.bytes()[4..8]);
quad3.copy_from_slice(&value.bytes()[8..12]);
quad4.copy_from_slice(&value.bytes()[12..16]);
let mut info: ExtraInfo = Default::default();
if is_f32_arithmetic(u32::from_le_bytes(quad1))
&& is_f32_arithmetic(u32::from_le_bytes(quad2))
&& is_f32_arithmetic(u32::from_le_bytes(quad3))
&& is_f32_arithmetic(u32::from_le_bytes(quad4))
{
info |= ExtraInfo::arithmetic_f32();
}
if is_f64_arithmetic(packed[0]) && is_f64_arithmetic(packed[1]) {
info |= ExtraInfo::arithmetic_f64();
}
self.state.push1_extra(i, info);
}
Operator::I8x16Splat => {
let (v, i) = self.state.pop1_extra()?;
let v = v.into_int_value();
let v = self
.builder
.build_int_truncate(v, self.intrinsics.i8_ty, "");
let res = self.splat_vector(v.as_basic_value_enum(), self.intrinsics.i8x16_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(res, i);
}
Operator::I16x8Splat => {
let (v, i) = self.state.pop1_extra()?;
let v = v.into_int_value();
let v = self
.builder
.build_int_truncate(v, self.intrinsics.i16_ty, "");
let res = self.splat_vector(v.as_basic_value_enum(), self.intrinsics.i16x8_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(res, i);
}
Operator::I32x4Splat => {
let (v, i) = self.state.pop1_extra()?;
let res = self.splat_vector(v, self.intrinsics.i32x4_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(res, i);
}
Operator::I64x2Splat => {
let (v, i) = self.state.pop1_extra()?;
let res = self.splat_vector(v, self.intrinsics.i64x2_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(res, i);
}
Operator::F32x4Splat => {
let (v, i) = self.state.pop1_extra()?;
let res = self.splat_vector(v, self.intrinsics.f32x4_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
// The spec is unclear, we interpret splat as preserving NaN
// payload bits.
self.state.push1_extra(res, i);
}
Operator::F64x2Splat => {
let (v, i) = self.state.pop1_extra()?;
let res = self.splat_vector(v, self.intrinsics.f64x2_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
// The spec is unclear, we interpret splat as preserving NaN
// payload bits.
self.state.push1_extra(res, i);
}
// Operate on self.locals.
Operator::LocalGet { local_index } => {
let pointer_value = self.locals[local_index as usize];
let v = self.builder.build_load(pointer_value, "");
tbaa_label(
&self.module,
self.intrinsics,
format!("local {}", local_index),
v.as_instruction_value().unwrap(),
);
self.state.push1(v);
}
Operator::LocalSet { local_index } => {
let pointer_value = self.locals[local_index as usize];
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let store = self.builder.build_store(pointer_value, v);
tbaa_label(
&self.module,
self.intrinsics,
format!("local {}", local_index),
store,
);
}
Operator::LocalTee { local_index } => {
let pointer_value = self.locals[local_index as usize];
let (v, i) = self.state.peek1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let store = self.builder.build_store(pointer_value, v);
tbaa_label(
&self.module,
self.intrinsics,
format!("local {}", local_index),
store,
);
}
Operator::GlobalGet { global_index } => {
let global_index = GlobalIndex::from_u32(global_index);
match self
.ctx
.global(global_index, self.intrinsics, self.module)?
{
GlobalCache::Const { value } => {
self.state.push1(*value);
}
GlobalCache::Mut { ptr_to_value } => {
let value = self.builder.build_load(*ptr_to_value, "");
tbaa_label(
self.module,
self.intrinsics,
format!("global {}", global_index.as_u32()),
value.as_instruction_value().unwrap(),
);
self.state.push1(value);
}
}
}
Operator::GlobalSet { global_index } => {
let global_index = GlobalIndex::from_u32(global_index);
match self
.ctx
.global(global_index, self.intrinsics, self.module)?
{
GlobalCache::Const { value: _ } => {
return Err(CompileError::Codegen(format!(
"global.set on immutable global index {}",
global_index.as_u32()
)))
}
GlobalCache::Mut { ptr_to_value } => {
let ptr_to_value = *ptr_to_value;
let (value, info) = self.state.pop1_extra()?;
let value = self.apply_pending_canonicalization(value, info);
let store = self.builder.build_store(ptr_to_value, value);
tbaa_label(
self.module,
self.intrinsics,
format!("global {}", global_index.as_u32()),
store,
);
}
}
}
Operator::Select => {
let ((v1, i1), (v2, i2), (cond, _)) = self.state.pop3_extra()?;
// We don't bother canonicalizing 'cond' here because we only
// compare it to zero, and that's invariant under
// canonicalization.
// If the pending bits of v1 and v2 are the same, we can pass
// them along to the result. Otherwise, apply pending
// canonicalizations now.
let (v1, i1, v2, i2) = if i1.has_pending_f32_nan() != i2.has_pending_f32_nan()
|| i1.has_pending_f64_nan() != i2.has_pending_f64_nan()
{
(
self.apply_pending_canonicalization(v1, i1),
i1.strip_pending(),
self.apply_pending_canonicalization(v2, i2),
i2.strip_pending(),
)
} else {
(v1, i1, v2, i2)
};
let cond_value = self.builder.build_int_compare(
IntPredicate::NE,
cond.into_int_value(),
self.intrinsics.i32_zero,
"",
);
let res = self.builder.build_select(cond_value, v1, v2, "");
let info = {
let mut info = i1.strip_pending() & i2.strip_pending();
if i1.has_pending_f32_nan() {
debug_assert!(i2.has_pending_f32_nan());
info |= ExtraInfo::pending_f32_nan();
}
if i1.has_pending_f64_nan() {
debug_assert!(i2.has_pending_f64_nan());
info |= ExtraInfo::pending_f64_nan();
}
info
};
self.state.push1_extra(res, info);
}
Operator::Call { function_index } => {
let func_index = FunctionIndex::from_u32(function_index);
let sigindex = &self.wasm_module.functions[func_index];
let func_type = &self.wasm_module.signatures[*sigindex];
let FunctionCache {
func,
vmctx: callee_vmctx,
attrs,
} = if let Some(local_func_index) = self.wasm_module.local_func_index(func_index) {
let function_name = self
.symbol_registry
.symbol_to_name(Symbol::LocalFunction(local_func_index));
self.ctx.local_func(
local_func_index,
func_index,
self.intrinsics,
self.module,
self.context,
func_type,
&function_name,
)?
} else {
self.ctx
.func(func_index, self.intrinsics, self.context, func_type)?
};
let func = *func;
let callee_vmctx = *callee_vmctx;
let attrs = attrs.clone();
/*
let func_ptr = self.llvm.functions.borrow_mut()[&func_index];
(params, func_ptr.as_global_value().as_pointer_value())
*/
let params = self.state.popn_save_extra(func_type.params().len())?;
// Apply pending canonicalizations.
let params =
params
.iter()
.zip(func_type.params().iter())
.map(|((v, info), wasm_ty)| match wasm_ty {
Type::F32 => self.builder.build_bitcast(
self.apply_pending_canonicalization(*v, *info),
self.intrinsics.f32_ty,
"",
),
Type::F64 => self.builder.build_bitcast(
self.apply_pending_canonicalization(*v, *info),
self.intrinsics.f64_ty,
"",
),
Type::V128 => self.apply_pending_canonicalization(*v, *info),
_ => *v,
});
let params = self.abi.args_to_call(
&self.alloca_builder,
func_type,
callee_vmctx.into_pointer_value(),
&func.get_type().get_element_type().into_function_type(),
params.collect::<Vec<_>>().as_slice(),
);
/*
if self.track_state {
if let Some(offset) = opcode_offset {
let mut stackmaps = self.stackmaps.borrow_mut();
emit_stack_map(
&info,
self.intrinsics,
self.builder,
self.index,
&mut *stackmaps,
StackmapEntryKind::Call,
&self.locals,
state,
ctx,
offset,
)
}
}
*/
let call_site = self.builder.build_call(func, ¶ms, "");
for (attr, attr_loc) in attrs {
call_site.add_attribute(attr_loc, attr);
}
/*
if self.track_state {
if let Some(offset) = opcode_offset {
let mut stackmaps = self.stackmaps.borrow_mut();
finalize_opcode_stack_map(
self.intrinsics,
self.builder,
self.index,
&mut *stackmaps,
StackmapEntryKind::Call,
offset,
)
}
}
*/
self.abi
.rets_from_call(&self.builder, &self.intrinsics, call_site, func_type)
.iter()
.for_each(|ret| self.state.push1(*ret));
}
Operator::CallIndirect { index, table_index } => {
let sigindex = SignatureIndex::from_u32(index);
let func_type = &self.wasm_module.signatures[sigindex];
let expected_dynamic_sigindex =
self.ctx
.dynamic_sigindex(sigindex, self.intrinsics, self.module);
let (table_base, table_bound) = self.ctx.table(
TableIndex::from_u32(table_index),
self.intrinsics,
self.module,
);
let func_index = self.state.pop1()?.into_int_value();
// We assume the table has the `anyfunc` element type.
let casted_table_base = self.builder.build_pointer_cast(
table_base,
self.intrinsics.anyfunc_ty.ptr_type(AddressSpace::Generic),
"casted_table_base",
);
let anyfunc_struct_ptr = unsafe {
self.builder.build_in_bounds_gep(
casted_table_base,
&[func_index],
"anyfunc_struct_ptr",
)
};
// Load things from the anyfunc data structure.
let (func_ptr, found_dynamic_sigindex, ctx_ptr) = (
self.builder
.build_load(
self.builder
.build_struct_gep(anyfunc_struct_ptr, 0, "func_ptr_ptr")
.unwrap(),
"func_ptr",
)
.into_pointer_value(),
self.builder
.build_load(
self.builder
.build_struct_gep(anyfunc_struct_ptr, 1, "sigindex_ptr")
.unwrap(),
"sigindex",
)
.into_int_value(),
self.builder.build_load(
self.builder
.build_struct_gep(anyfunc_struct_ptr, 2, "ctx_ptr_ptr")
.unwrap(),
"ctx_ptr",
),
);
let truncated_table_bounds = self.builder.build_int_truncate(
table_bound,
self.intrinsics.i32_ty,
"truncated_table_bounds",
);
// First, check if the index is outside of the table bounds.
let index_in_bounds = self.builder.build_int_compare(
IntPredicate::ULT,
func_index,
truncated_table_bounds,
"index_in_bounds",
);
let index_in_bounds = self
.builder
.build_call(
self.intrinsics.expect_i1,
&[
index_in_bounds.as_basic_value_enum(),
self.intrinsics
.i1_ty
.const_int(1, false)
.as_basic_value_enum(),
],
"index_in_bounds_expect",
)
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let in_bounds_continue_block = self
.context
.append_basic_block(self.function, "in_bounds_continue_block");
let not_in_bounds_block = self
.context
.append_basic_block(self.function, "not_in_bounds_block");
self.builder.build_conditional_branch(
index_in_bounds,
in_bounds_continue_block,
not_in_bounds_block,
);
self.builder.position_at_end(not_in_bounds_block);
self.builder.build_call(
self.intrinsics.throw_trap,
&[self.intrinsics.trap_table_access_oob],
"throw",
);
self.builder.build_unreachable();
self.builder.position_at_end(in_bounds_continue_block);
// Next, check if the table element is initialized.
let elem_initialized = self.builder.build_is_not_null(func_ptr, "");
// Next, check if the signature id is correct.
let sigindices_equal = self.builder.build_int_compare(
IntPredicate::EQ,
expected_dynamic_sigindex,
found_dynamic_sigindex,
"sigindices_equal",
);
let initialized_and_sigindices_match =
self.builder
.build_and(elem_initialized, sigindices_equal, "");
// Tell llvm that `expected_dynamic_sigindex` should equal `found_dynamic_sigindex`.
let initialized_and_sigindices_match = self
.builder
.build_call(
self.intrinsics.expect_i1,
&[
initialized_and_sigindices_match.as_basic_value_enum(),
self.intrinsics
.i1_ty
.const_int(1, false)
.as_basic_value_enum(),
],
"initialized_and_sigindices_match_expect",
)
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let continue_block = self
.context
.append_basic_block(self.function, "continue_block");
let sigindices_notequal_block = self
.context
.append_basic_block(self.function, "sigindices_notequal_block");
self.builder.build_conditional_branch(
initialized_and_sigindices_match,
continue_block,
sigindices_notequal_block,
);
self.builder.position_at_end(sigindices_notequal_block);
let trap_code = self.builder.build_select(
elem_initialized,
self.intrinsics.trap_call_indirect_sig,
self.intrinsics.trap_call_indirect_null,
"",
);
self.builder
.build_call(self.intrinsics.throw_trap, &[trap_code], "throw");
self.builder.build_unreachable();
self.builder.position_at_end(continue_block);
let (llvm_func_type, llvm_func_attrs) = self.abi.func_type_to_llvm(
&self.context,
&self.intrinsics,
Some(self.ctx.get_offsets()),
func_type,
)?;
let params = self.state.popn_save_extra(func_type.params().len())?;
// Apply pending canonicalizations.
let params =
params
.iter()
.zip(func_type.params().iter())
.map(|((v, info), wasm_ty)| match wasm_ty {
Type::F32 => self.builder.build_bitcast(
self.apply_pending_canonicalization(*v, *info),
self.intrinsics.f32_ty,
"",
),
Type::F64 => self.builder.build_bitcast(
self.apply_pending_canonicalization(*v, *info),
self.intrinsics.f64_ty,
"",
),
Type::V128 => self.apply_pending_canonicalization(*v, *info),
_ => *v,
});
let params = self.abi.args_to_call(
&self.alloca_builder,
func_type,
ctx_ptr.into_pointer_value(),
&llvm_func_type,
params.collect::<Vec<_>>().as_slice(),
);
let typed_func_ptr = self.builder.build_pointer_cast(
func_ptr,
llvm_func_type.ptr_type(AddressSpace::Generic),
"typed_func_ptr",
);
/*
if self.track_state {
if let Some(offset) = opcode_offset {
let mut stackmaps = self.stackmaps.borrow_mut();
emit_stack_map(
&info,
self.intrinsics,
self.builder,
self.index,
&mut *stackmaps,
StackmapEntryKind::Call,
&self.locals,
state,
ctx,
offset,
)
}
}
*/
let call_site = self
.builder
.build_call(typed_func_ptr, ¶ms, "indirect_call");
for (attr, attr_loc) in llvm_func_attrs {
call_site.add_attribute(attr_loc, attr);
}
/*
if self.track_state {
if let Some(offset) = opcode_offset {
let mut stackmaps = self.stackmaps.borrow_mut();
finalize_opcode_stack_map(
self.intrinsics,
self.builder,
self.index,
&mut *stackmaps,
StackmapEntryKind::Call,
offset,
)
}
}
*/
self.abi
.rets_from_call(&self.builder, &self.intrinsics, call_site, func_type)
.iter()
.for_each(|ret| self.state.push1(*ret));
}
/***************************
* Integer Arithmetic instructions.
* https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#integer-arithmetic-instructions
***************************/
Operator::I32Add | Operator::I64Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let res = self.builder.build_int_add(v1, v2, "");
self.state.push1(res);
}
Operator::I8x16Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self.builder.build_int_add(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self.builder.build_int_add(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self.builder.build_int_add(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I64x2Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i64x2(v1, i1);
let (v2, _) = self.v128_into_i64x2(v2, i2);
let res = self.builder.build_int_add(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16AddSatS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_call(
self.intrinsics.sadd_sat_i8x16,
&[v1.as_basic_value_enum(), v2.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8AddSatS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_call(
self.intrinsics.sadd_sat_i16x8,
&[v1.as_basic_value_enum(), v2.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16AddSatU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_call(
self.intrinsics.uadd_sat_i8x16,
&[v1.as_basic_value_enum(), v2.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8AddSatU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_call(
self.intrinsics.uadd_sat_i16x8,
&[v1.as_basic_value_enum(), v2.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32Sub | Operator::I64Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let res = self.builder.build_int_sub(v1, v2, "");
self.state.push1(res);
}
Operator::I8x16Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self.builder.build_int_sub(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self.builder.build_int_sub(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self.builder.build_int_sub(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I64x2Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i64x2(v1, i1);
let (v2, _) = self.v128_into_i64x2(v2, i2);
let res = self.builder.build_int_sub(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16SubSatS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_call(
self.intrinsics.ssub_sat_i8x16,
&[v1.as_basic_value_enum(), v2.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8SubSatS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_call(
self.intrinsics.ssub_sat_i16x8,
&[v1.as_basic_value_enum(), v2.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16SubSatU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_call(
self.intrinsics.usub_sat_i8x16,
&[v1.as_basic_value_enum(), v2.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8SubSatU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_call(
self.intrinsics.usub_sat_i16x8,
&[v1.as_basic_value_enum(), v2.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32Mul | Operator::I64Mul => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let res = self.builder.build_int_mul(v1, v2, "");
self.state.push1(res);
}
Operator::I16x8Mul => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self.builder.build_int_mul(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4Mul => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self.builder.build_int_mul(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I64x2Mul => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i64x2(v1, i1);
let (v2, _) = self.v128_into_i64x2(v2, i2);
let res = self.builder.build_int_mul(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32DivS | Operator::I64DivS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
self.trap_if_zero_or_overflow(v1, v2);
let res = self.builder.build_int_signed_div(v1, v2, "");
self.state.push1(res);
}
Operator::I32DivU | Operator::I64DivU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
self.trap_if_zero(v2);
let res = self.builder.build_int_unsigned_div(v1, v2, "");
self.state.push1(res);
}
Operator::I32RemS | Operator::I64RemS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let int_type = v1.get_type();
let (min_value, neg_one_value) = if int_type == self.intrinsics.i32_ty {
let min_value = int_type.const_int(i32::min_value() as u64, false);
let neg_one_value = int_type.const_int(-1i32 as u32 as u64, false);
(min_value, neg_one_value)
} else if int_type == self.intrinsics.i64_ty {
let min_value = int_type.const_int(i64::min_value() as u64, false);
let neg_one_value = int_type.const_int(-1i64 as u64, false);
(min_value, neg_one_value)
} else {
unreachable!()
};
self.trap_if_zero(v2);
// "Overflow also leads to undefined behavior; this is a rare
// case, but can occur, for example, by taking the remainder of
// a 32-bit division of -2147483648 by -1. (The remainder
// doesn’t actually overflow, but this rule lets srem be
// implemented using instructions that return both the result
// of the division and the remainder.)"
// -- https://llvm.org/docs/LangRef.html#srem-instruction
//
// In Wasm, the i32.rem_s i32.const -2147483648 i32.const -1 is
// i32.const 0. We implement this by swapping out the left value
// for 0 in this case.
let will_overflow = self.builder.build_and(
self.builder
.build_int_compare(IntPredicate::EQ, v1, min_value, "left_is_min"),
self.builder.build_int_compare(
IntPredicate::EQ,
v2,
neg_one_value,
"right_is_neg_one",
),
"srem_will_overflow",
);
let v1 = self
.builder
.build_select(will_overflow, int_type.const_zero(), v1, "")
.into_int_value();
let res = self.builder.build_int_signed_rem(v1, v2, "");
self.state.push1(res);
}
Operator::I32RemU | Operator::I64RemU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
self.trap_if_zero(v2);
let res = self.builder.build_int_unsigned_rem(v1, v2, "");
self.state.push1(res);
}
Operator::I32And | Operator::I64And | Operator::V128And => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let res = self.builder.build_and(v1, v2, "");
self.state.push1(res);
}
Operator::I32Or | Operator::I64Or | Operator::V128Or => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let res = self.builder.build_or(v1, v2, "");
self.state.push1(res);
}
Operator::I32Xor | Operator::I64Xor | Operator::V128Xor => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let res = self.builder.build_xor(v1, v2, "");
self.state.push1(res);
}
Operator::V128AndNot => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let v2 = self.builder.build_not(v2, "");
let res = self.builder.build_and(v1, v2, "");
self.state.push1(res);
}
Operator::V128Bitselect => {
let ((v1, i1), (v2, i2), (cond, cond_info)) = self.state.pop3_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let cond = self.apply_pending_canonicalization(cond, cond_info);
let v1 = self
.builder
.build_bitcast(v1, self.intrinsics.i1x128_ty, "")
.into_vector_value();
let v2 = self
.builder
.build_bitcast(v2, self.intrinsics.i1x128_ty, "")
.into_vector_value();
let cond = self
.builder
.build_bitcast(cond, self.intrinsics.i1x128_ty, "")
.into_vector_value();
let res = self.builder.build_select(cond, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32Shl => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i32_ty.const_int(31u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let res = self.builder.build_left_shift(v1, v2, "");
self.state.push1(res);
}
Operator::I64Shl => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i64_ty.const_int(63u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let res = self.builder.build_left_shift(v1, v2, "");
self.state.push1(res);
}
Operator::I8x16Shl => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 = self
.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(7, false), "");
let v2 = self
.builder
.build_int_truncate(v2, self.intrinsics.i8_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i8x16_ty);
let res = self.builder.build_left_shift(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8Shl => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(15, false), "");
let v2 = self
.builder
.build_int_truncate(v2, self.intrinsics.i16_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i16x8_ty);
let res = self.builder.build_left_shift(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4Shl => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(31, false), "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i32x4_ty);
let res = self.builder.build_left_shift(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I64x2Shl => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i64x2(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(63, false), "");
let v2 = self
.builder
.build_int_z_extend(v2, self.intrinsics.i64_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i64x2_ty);
let res = self.builder.build_left_shift(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32ShrS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i32_ty.const_int(31u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let res = self.builder.build_right_shift(v1, v2, true, "");
self.state.push1(res);
}
Operator::I64ShrS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i64_ty.const_int(63u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let res = self.builder.build_right_shift(v1, v2, true, "");
self.state.push1(res);
}
Operator::I8x16ShrS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 = self
.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(7, false), "");
let v2 = self
.builder
.build_int_truncate(v2, self.intrinsics.i8_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i8x16_ty);
let res = self.builder.build_right_shift(v1, v2, true, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8ShrS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(15, false), "");
let v2 = self
.builder
.build_int_truncate(v2, self.intrinsics.i16_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i16x8_ty);
let res = self.builder.build_right_shift(v1, v2, true, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4ShrS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(31, false), "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i32x4_ty);
let res = self.builder.build_right_shift(v1, v2, true, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I64x2ShrS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i64x2(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(63, false), "");
let v2 = self
.builder
.build_int_z_extend(v2, self.intrinsics.i64_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i64x2_ty);
let res = self.builder.build_right_shift(v1, v2, true, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32ShrU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i32_ty.const_int(31u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let res = self.builder.build_right_shift(v1, v2, false, "");
self.state.push1(res);
}
Operator::I64ShrU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i64_ty.const_int(63u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let res = self.builder.build_right_shift(v1, v2, false, "");
self.state.push1(res);
}
Operator::I8x16ShrU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 = self
.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(7, false), "");
let v2 = self
.builder
.build_int_truncate(v2, self.intrinsics.i8_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i8x16_ty);
let res = self.builder.build_right_shift(v1, v2, false, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8ShrU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(15, false), "");
let v2 = self
.builder
.build_int_truncate(v2, self.intrinsics.i16_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i16x8_ty);
let res = self.builder.build_right_shift(v1, v2, false, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4ShrU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(31, false), "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i32x4_ty);
let res = self.builder.build_right_shift(v1, v2, false, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I64x2ShrU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i64x2(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let v2 =
self.builder
.build_and(v2, self.intrinsics.i32_ty.const_int(63, false), "");
let v2 = self
.builder
.build_int_z_extend(v2, self.intrinsics.i64_ty, "");
let v2 = self.splat_vector(v2.as_basic_value_enum(), self.intrinsics.i64x2_ty);
let res = self.builder.build_right_shift(v1, v2, false, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32Rotl => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i32_ty.const_int(31u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let lhs = self.builder.build_left_shift(v1, v2, "");
let rhs = {
let negv2 = self.builder.build_int_neg(v2, "");
let rhs = self.builder.build_and(negv2, mask, "");
self.builder.build_right_shift(v1, rhs, false, "")
};
let res = self.builder.build_or(lhs, rhs, "");
self.state.push1(res);
}
Operator::I64Rotl => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i64_ty.const_int(63u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let lhs = self.builder.build_left_shift(v1, v2, "");
let rhs = {
let negv2 = self.builder.build_int_neg(v2, "");
let rhs = self.builder.build_and(negv2, mask, "");
self.builder.build_right_shift(v1, rhs, false, "")
};
let res = self.builder.build_or(lhs, rhs, "");
self.state.push1(res);
}
Operator::I32Rotr => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i32_ty.const_int(31u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let lhs = self.builder.build_right_shift(v1, v2, false, "");
let rhs = {
let negv2 = self.builder.build_int_neg(v2, "");
let rhs = self.builder.build_and(negv2, mask, "");
self.builder.build_left_shift(v1, rhs, "")
};
let res = self.builder.build_or(lhs, rhs, "");
self.state.push1(res);
}
Operator::I64Rotr => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let mask = self.intrinsics.i64_ty.const_int(63u64, false);
let v2 = self.builder.build_and(v2, mask, "");
let lhs = self.builder.build_right_shift(v1, v2, false, "");
let rhs = {
let int_width = self.intrinsics.i64_ty.const_int(64 as u64, false);
let rhs = self.builder.build_int_sub(int_width, v2, "");
self.builder.build_left_shift(v1, rhs, "")
};
let res = self.builder.build_or(lhs, rhs, "");
self.state.push1(res);
}
Operator::I32Clz => {
let (input, info) = self.state.pop1_extra()?;
let input = self.apply_pending_canonicalization(input, info);
let is_zero_undef = self.intrinsics.i1_zero.as_basic_value_enum();
let res = self
.builder
.build_call(self.intrinsics.ctlz_i32, &[input, is_zero_undef], "")
.try_as_basic_value()
.left()
.unwrap();
self.state.push1_extra(res, ExtraInfo::arithmetic_f32());
}
Operator::I64Clz => {
let (input, info) = self.state.pop1_extra()?;
let input = self.apply_pending_canonicalization(input, info);
let is_zero_undef = self.intrinsics.i1_zero.as_basic_value_enum();
let res = self
.builder
.build_call(self.intrinsics.ctlz_i64, &[input, is_zero_undef], "")
.try_as_basic_value()
.left()
.unwrap();
self.state.push1_extra(res, ExtraInfo::arithmetic_f64());
}
Operator::I32Ctz => {
let (input, info) = self.state.pop1_extra()?;
let input = self.apply_pending_canonicalization(input, info);
let is_zero_undef = self.intrinsics.i1_zero.as_basic_value_enum();
let res = self
.builder
.build_call(self.intrinsics.cttz_i32, &[input, is_zero_undef], "")
.try_as_basic_value()
.left()
.unwrap();
self.state.push1_extra(res, ExtraInfo::arithmetic_f32());
}
Operator::I64Ctz => {
let (input, info) = self.state.pop1_extra()?;
let input = self.apply_pending_canonicalization(input, info);
let is_zero_undef = self.intrinsics.i1_zero.as_basic_value_enum();
let res = self
.builder
.build_call(self.intrinsics.cttz_i64, &[input, is_zero_undef], "")
.try_as_basic_value()
.left()
.unwrap();
self.state.push1_extra(res, ExtraInfo::arithmetic_f64());
}
Operator::I32Popcnt => {
let (input, info) = self.state.pop1_extra()?;
let input = self.apply_pending_canonicalization(input, info);
let res = self
.builder
.build_call(self.intrinsics.ctpop_i32, &[input], "")
.try_as_basic_value()
.left()
.unwrap();
self.state.push1_extra(res, ExtraInfo::arithmetic_f32());
}
Operator::I64Popcnt => {
let (input, info) = self.state.pop1_extra()?;
let input = self.apply_pending_canonicalization(input, info);
let res = self
.builder
.build_call(self.intrinsics.ctpop_i64, &[input], "")
.try_as_basic_value()
.left()
.unwrap();
self.state.push1_extra(res, ExtraInfo::arithmetic_f64());
}
Operator::I32Eqz => {
let input = self.state.pop1()?.into_int_value();
let cond = self.builder.build_int_compare(
IntPredicate::EQ,
input,
self.intrinsics.i32_zero,
"",
);
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(res, ExtraInfo::arithmetic_f32());
}
Operator::I64Eqz => {
let input = self.state.pop1()?.into_int_value();
let cond = self.builder.build_int_compare(
IntPredicate::EQ,
input,
self.intrinsics.i64_zero,
"",
);
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(res, ExtraInfo::arithmetic_f64());
}
Operator::I8x16Abs => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i8x16(v, i);
let seven = self.intrinsics.i8_ty.const_int(7, false);
let seven = VectorType::const_vector(&[seven; 16]);
let all_sign_bits = self.builder.build_right_shift(v, seven, true, "");
let xor = self.builder.build_xor(v, all_sign_bits, "");
let res = self.builder.build_int_sub(xor, all_sign_bits, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8Abs => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i16x8(v, i);
let fifteen = self.intrinsics.i16_ty.const_int(15, false);
let fifteen = VectorType::const_vector(&[fifteen; 8]);
let all_sign_bits = self.builder.build_right_shift(v, fifteen, true, "");
let xor = self.builder.build_xor(v, all_sign_bits, "");
let res = self.builder.build_int_sub(xor, all_sign_bits, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4Abs => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i32x4(v, i);
let thirtyone = self.intrinsics.i32_ty.const_int(31, false);
let thirtyone = VectorType::const_vector(&[thirtyone; 4]);
let all_sign_bits = self.builder.build_right_shift(v, thirtyone, true, "");
let xor = self.builder.build_xor(v, all_sign_bits, "");
let res = self.builder.build_int_sub(xor, all_sign_bits, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16MinS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::SLT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16MinU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::ULT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16MaxS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::SGT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16MaxU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::UGT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8MinS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::SLT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8MinU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::ULT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8MaxS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::SGT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8MaxU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::UGT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4MinS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::SLT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4MinU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::ULT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4MaxS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::SGT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4MaxU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let cmp = self
.builder
.build_int_compare(IntPredicate::UGT, v1, v2, "");
let res = self.builder.build_select(cmp, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16RoundingAverageU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
// This approach is faster on x86-64 when the PAVG[BW]
// instructions are available. On other platforms, an alternative
// implementation appears likely to outperform, described here:
// %a = or %v1, %v2
// %b = and %a, 1
// %v1 = lshr %v1, 1
// %v2 = lshr %v2, 1
// %sum = add %v1, %v2
// %res = add %sum, %b
let ext_ty = self.intrinsics.i16_ty.vec_type(16);
let one = self.intrinsics.i16_ty.const_int(1, false);
let one = VectorType::const_vector(&[one; 16]);
let v1 = self.builder.build_int_z_extend(v1, ext_ty, "");
let v2 = self.builder.build_int_z_extend(v2, ext_ty, "");
let res =
self.builder
.build_int_add(self.builder.build_int_add(one, v1, ""), v2, "");
let res = self.builder.build_right_shift(res, one, false, "");
let res = self
.builder
.build_int_truncate(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8RoundingAverageU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
// This approach is faster on x86-64 when the PAVG[BW]
// instructions are available. On other platforms, an alternative
// implementation appears likely to outperform, described here:
// %a = or %v1, %v2
// %b = and %a, 1
// %v1 = lshr %v1, 1
// %v2 = lshr %v2, 1
// %sum = add %v1, %v2
// %res = add %sum, %b
let ext_ty = self.intrinsics.i32_ty.vec_type(8);
let one = self.intrinsics.i32_ty.const_int(1, false);
let one = VectorType::const_vector(&[one; 8]);
let v1 = self.builder.build_int_z_extend(v1, ext_ty, "");
let v2 = self.builder.build_int_z_extend(v2, ext_ty, "");
let res =
self.builder
.build_int_add(self.builder.build_int_add(one, v1, ""), v2, "");
let res = self.builder.build_right_shift(res, one, false, "");
let res = self
.builder
.build_int_truncate(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
/***************************
* Floating-Point Arithmetic instructions.
* https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#floating-point-arithmetic-instructions
***************************/
Operator::F32Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let res = self.builder.build_float_add(v1, v2, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f32_nan(),
);
}
Operator::F64Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let res = self.builder.build_float_add(v1, v2, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f64_nan(),
);
}
Operator::F32x4Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f32x4(v1, i1);
let (v2, i2) = self.v128_into_f32x4(v2, i2);
let res = self.builder.build_float_add(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f32_nan(),
);
}
Operator::F64x2Add => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f64x2(v1, i1);
let (v2, i2) = self.v128_into_f64x2(v2, i2);
let res = self.builder.build_float_add(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f64_nan(),
);
}
Operator::F32Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let res = self.builder.build_float_sub(v1, v2, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f32_nan(),
);
}
Operator::F64Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let res = self.builder.build_float_sub(v1, v2, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f64_nan(),
);
}
Operator::F32x4Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f32x4(v1, i1);
let (v2, i2) = self.v128_into_f32x4(v2, i2);
let res = self.builder.build_float_sub(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f32_nan(),
);
}
Operator::F64x2Sub => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f64x2(v1, i1);
let (v2, i2) = self.v128_into_f64x2(v2, i2);
let res = self.builder.build_float_sub(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f64_nan(),
);
}
Operator::F32Mul => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let res = self.builder.build_float_mul(v1, v2, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f32_nan(),
);
}
Operator::F64Mul => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let res = self.builder.build_float_mul(v1, v2, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f64_nan(),
);
}
Operator::F32x4Mul => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f32x4(v1, i1);
let (v2, i2) = self.v128_into_f32x4(v2, i2);
let res = self.builder.build_float_mul(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f32_nan(),
);
}
Operator::F64x2Mul => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f64x2(v1, i1);
let (v2, i2) = self.v128_into_f64x2(v2, i2);
let res = self.builder.build_float_mul(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(
res,
(i1.strip_pending() & i2.strip_pending()) | ExtraInfo::pending_f64_nan(),
);
}
Operator::F32Div => {
let (v1, v2) = self.state.pop2()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let res = self.builder.build_float_div(v1, v2, "");
self.state.push1_extra(res, ExtraInfo::pending_f32_nan());
}
Operator::F64Div => {
let (v1, v2) = self.state.pop2()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let res = self.builder.build_float_div(v1, v2, "");
self.state.push1_extra(res, ExtraInfo::pending_f64_nan());
}
Operator::F32x4Div => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f32x4(v1, i1);
let (v2, _) = self.v128_into_f32x4(v2, i2);
let res = self.builder.build_float_div(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(res, ExtraInfo::pending_f32_nan());
}
Operator::F64x2Div => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f64x2(v1, i1);
let (v2, _) = self.v128_into_f64x2(v2, i2);
let res = self.builder.build_float_div(v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1_extra(res, ExtraInfo::pending_f64_nan());
}
Operator::F32Sqrt => {
let input = self.state.pop1()?;
let res = self
.builder
.build_call(self.intrinsics.sqrt_f32, &[input], "")
.try_as_basic_value()
.left()
.unwrap();
self.state.push1_extra(res, ExtraInfo::pending_f32_nan());
}
Operator::F64Sqrt => {
let input = self.state.pop1()?;
let res = self
.builder
.build_call(self.intrinsics.sqrt_f64, &[input], "")
.try_as_basic_value()
.left()
.unwrap();
self.state.push1_extra(res, ExtraInfo::pending_f64_nan());
}
Operator::F32x4Sqrt => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_f32x4(v, i);
let res = self
.builder
.build_call(self.intrinsics.sqrt_f32x4, &[v.as_basic_value_enum()], "")
.try_as_basic_value()
.left()
.unwrap();
let bits = self
.builder
.build_bitcast(res, self.intrinsics.i128_ty, "bits");
self.state.push1_extra(bits, ExtraInfo::pending_f32_nan());
}
Operator::F64x2Sqrt => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_f64x2(v, i);
let res = self
.builder
.build_call(self.intrinsics.sqrt_f64x2, &[v.as_basic_value_enum()], "")
.try_as_basic_value()
.left()
.unwrap();
let bits = self
.builder
.build_bitcast(res, self.intrinsics.i128_ty, "bits");
self.state.push1(bits);
}
Operator::F32Min => {
// This implements the same logic as LLVM's @llvm.minimum
// intrinsic would, but x86 lowering of that intrinsic
// encounters a fatal error in LLVM 8 and LLVM 9.
let (v1, v2) = self.state.pop2()?;
// To detect min(-0.0, 0.0), we check whether the integer
// representations are equal. There's one other case where that
// can happen: non-canonical NaNs. Here we unconditionally
// canonicalize the NaNs.
let v1 = self.canonicalize_nans(v1);
let v2 = self.canonicalize_nans(v2);
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let v1_is_nan = self.builder.build_float_compare(
FloatPredicate::UNO,
v1,
self.intrinsics.f32_zero,
"nan",
);
let v2_is_not_nan = self.builder.build_float_compare(
FloatPredicate::ORD,
v2,
self.intrinsics.f32_zero,
"notnan",
);
let v1_repr = self
.builder
.build_bitcast(v1, self.intrinsics.i32_ty, "")
.into_int_value();
let v2_repr = self
.builder
.build_bitcast(v2, self.intrinsics.i32_ty, "")
.into_int_value();
let repr_ne =
self.builder
.build_int_compare(IntPredicate::NE, v1_repr, v2_repr, "");
let float_eq = self
.builder
.build_float_compare(FloatPredicate::OEQ, v1, v2, "");
let min_cmp = self
.builder
.build_float_compare(FloatPredicate::OLT, v1, v2, "");
let negative_zero = self.intrinsics.f32_ty.const_float(-0.0);
let v2 = self
.builder
.build_select(
self.builder.build_and(
self.builder.build_and(float_eq, repr_ne, ""),
v2_is_not_nan,
"",
),
negative_zero,
v2,
"",
)
.into_float_value();
let res = self.builder.build_select(
self.builder.build_or(v1_is_nan, min_cmp, ""),
v1,
v2,
"",
);
// Because inputs were canonicalized, we always produce
// canonical NaN outputs. No pending NaN cleanup.
self.state.push1_extra(res, ExtraInfo::arithmetic_f32());
}
Operator::F64Min => {
// This implements the same logic as LLVM's @llvm.minimum
// intrinsic would, but x86 lowering of that intrinsic
// encounters a fatal error in LLVM 8 and LLVM 9.
let (v1, v2) = self.state.pop2()?;
// To detect min(-0.0, 0.0), we check whether the integer
// representations are equal. There's one other case where that
// can happen: non-canonical NaNs. Here we unconditionally
// canonicalize the NaNs.
let v1 = self.canonicalize_nans(v1);
let v2 = self.canonicalize_nans(v2);
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let v1_is_nan = self.builder.build_float_compare(
FloatPredicate::UNO,
v1,
self.intrinsics.f64_zero,
"nan",
);
let v2_is_not_nan = self.builder.build_float_compare(
FloatPredicate::ORD,
v2,
self.intrinsics.f64_zero,
"notnan",
);
let v1_repr = self
.builder
.build_bitcast(v1, self.intrinsics.i64_ty, "")
.into_int_value();
let v2_repr = self
.builder
.build_bitcast(v2, self.intrinsics.i64_ty, "")
.into_int_value();
let repr_ne =
self.builder
.build_int_compare(IntPredicate::NE, v1_repr, v2_repr, "");
let float_eq = self
.builder
.build_float_compare(FloatPredicate::OEQ, v1, v2, "");
let min_cmp = self
.builder
.build_float_compare(FloatPredicate::OLT, v1, v2, "");
let negative_zero = self.intrinsics.f64_ty.const_float(-0.0);
let v2 = self
.builder
.build_select(
self.builder.build_and(
self.builder.build_and(float_eq, repr_ne, ""),
v2_is_not_nan,
"",
),
negative_zero,
v2,
"",
)
.into_float_value();
let res = self.builder.build_select(
self.builder.build_or(v1_is_nan, min_cmp, ""),
v1,
v2,
"",
);
// Because inputs were canonicalized, we always produce
// canonical NaN outputs. No pending NaN cleanup.
self.state.push1_extra(res, ExtraInfo::arithmetic_f64());
}
Operator::F32x4Min => {
// a) check v1 and v2 for NaN
// b) check v2 for zero
// c) check v1 for sign
//
// We pick v1 iff
// v1 is NaN or
// v2 is not NaN and either
// v1 < v2 or
// v2 is ±zero and v1 is negative.
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f32x4(v1, i1);
let (v2, i2) = self.v128_into_f32x4(v2, i2);
let v1 = if !i1.is_arithmetic_f32() {
self.canonicalize_nans(v1.as_basic_value_enum())
.into_vector_value()
} else {
v1
};
let v2 = if !i2.is_arithmetic_f32() {
self.canonicalize_nans(v2.as_basic_value_enum())
.into_vector_value()
} else {
v2
};
let v1_is_nan = self.builder.build_float_compare(
FloatPredicate::UNO,
v1,
self.intrinsics.f32x4_zero,
"v1nan",
);
let v2_is_notnan = self.builder.build_float_compare(
FloatPredicate::ORD,
v2,
self.intrinsics.f32x4_zero,
"v2notnan",
);
let v2_is_zero = self.builder.build_float_compare(
FloatPredicate::OEQ,
v2,
self.intrinsics.f32x4_zero,
"v2zero",
);
let v1_is_negative = self.builder.build_float_compare(
FloatPredicate::OLT,
self.builder
.build_call(
self.intrinsics.copysign_f32x4,
&[
VectorType::const_vector(
&[self
.intrinsics
.f32_ty
.const_float(1.0)
.as_basic_value_enum();
4],
)
.as_basic_value_enum(),
v1.as_basic_value_enum(),
],
"",
)
.try_as_basic_value()
.left()
.unwrap()
.into_vector_value(),
self.intrinsics.f32x4_zero,
"v1neg",
);
let v1_lt_v2 = self
.builder
.build_float_compare(FloatPredicate::OLT, v1, v2, "");
let pick_v1 = self.builder.build_or(
v1_is_nan,
self.builder.build_and(
v2_is_notnan,
self.builder.build_or(
v1_lt_v2,
self.builder.build_and(v1_is_negative, v2_is_zero, ""),
"",
),
"",
),
"",
);
let res = self.builder.build_select(pick_v1, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F64x2Min => {
// a) check v1 and v2 for NaN
// b) check v2 for zero
// c) check v1 for sign
//
// We pick v1 iff
// v1 is NaN or
// v2 is not NaN and either
// v1 < v2 or
// v2 is ±zero and v1 is negative.
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f64x2(v1, i1);
let (v2, i2) = self.v128_into_f64x2(v2, i2);
let v1 = if !i1.is_arithmetic_f64() {
self.canonicalize_nans(v1.as_basic_value_enum())
.into_vector_value()
} else {
v1
};
let v2 = if !i2.is_arithmetic_f64() {
self.canonicalize_nans(v2.as_basic_value_enum())
.into_vector_value()
} else {
v2
};
let v1_is_nan = self.builder.build_float_compare(
FloatPredicate::UNO,
v1,
self.intrinsics.f64x2_zero,
"v1nan",
);
let v2_is_notnan = self.builder.build_float_compare(
FloatPredicate::ORD,
v2,
self.intrinsics.f64x2_zero,
"v2notnan",
);
let v2_is_zero = self.builder.build_float_compare(
FloatPredicate::OEQ,
v2,
self.intrinsics.f64x2_zero,
"v2zero",
);
let v1_is_negative = self.builder.build_float_compare(
FloatPredicate::OLT,
self.builder
.build_call(
self.intrinsics.copysign_f64x2,
&[
VectorType::const_vector(
&[self
.intrinsics
.f64_ty
.const_float(1.0)
.as_basic_value_enum();
2],
)
.as_basic_value_enum(),
v1.as_basic_value_enum(),
],
"",
)
.try_as_basic_value()
.left()
.unwrap()
.into_vector_value(),
self.intrinsics.f64x2_zero,
"v1neg",
);
let v1_lt_v2 = self
.builder
.build_float_compare(FloatPredicate::OLT, v1, v2, "");
let pick_v1 = self.builder.build_or(
v1_is_nan,
self.builder.build_and(
v2_is_notnan,
self.builder.build_or(
v1_lt_v2,
self.builder.build_and(v1_is_negative, v2_is_zero, ""),
"",
),
"",
),
"",
);
let res = self.builder.build_select(pick_v1, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F32Max => {
// This implements the same logic as LLVM's @llvm.maximum
// intrinsic would, but x86 lowering of that intrinsic
// encounters a fatal error in LLVM 8 and LLVM 9.
let (v1, v2) = self.state.pop2()?;
// To detect min(-0.0, 0.0), we check whether the integer
// representations are equal. There's one other case where that
// can happen: non-canonical NaNs. Here we unconditionally
// canonicalize the NaNs.
let v1 = self.canonicalize_nans(v1);
let v2 = self.canonicalize_nans(v2);
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let v1_is_nan = self.builder.build_float_compare(
FloatPredicate::UNO,
v1,
self.intrinsics.f32_zero,
"nan",
);
let v2_is_not_nan = self.builder.build_float_compare(
FloatPredicate::ORD,
v2,
self.intrinsics.f32_zero,
"notnan",
);
let v1_repr = self
.builder
.build_bitcast(v1, self.intrinsics.i32_ty, "")
.into_int_value();
let v2_repr = self
.builder
.build_bitcast(v2, self.intrinsics.i32_ty, "")
.into_int_value();
let repr_ne =
self.builder
.build_int_compare(IntPredicate::NE, v1_repr, v2_repr, "");
let float_eq = self
.builder
.build_float_compare(FloatPredicate::OEQ, v1, v2, "");
let min_cmp = self
.builder
.build_float_compare(FloatPredicate::OGT, v1, v2, "");
let v2 = self
.builder
.build_select(
self.builder.build_and(
self.builder.build_and(float_eq, repr_ne, ""),
v2_is_not_nan,
"",
),
self.intrinsics.f32_zero,
v2,
"",
)
.into_float_value();
let res = self.builder.build_select(
self.builder.build_or(v1_is_nan, min_cmp, ""),
v1,
v2,
"",
);
// Because inputs were canonicalized, we always produce
// canonical NaN outputs. No pending NaN cleanup.
self.state.push1_extra(res, ExtraInfo::arithmetic_f32());
}
Operator::F64Max => {
// This implements the same logic as LLVM's @llvm.maximum
// intrinsic would, but x86 lowering of that intrinsic
// encounters a fatal error in LLVM 8 and LLVM 9.
let (v1, v2) = self.state.pop2()?;
// To detect min(-0.0, 0.0), we check whether the integer
// representations are equal. There's one other case where that
// can happen: non-canonical NaNs. Here we unconditionally
// canonicalize the NaNs.
let v1 = self.canonicalize_nans(v1);
let v2 = self.canonicalize_nans(v2);
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let v1_is_nan = self.builder.build_float_compare(
FloatPredicate::UNO,
v1,
self.intrinsics.f64_zero,
"nan",
);
let v2_is_not_nan = self.builder.build_float_compare(
FloatPredicate::ORD,
v2,
self.intrinsics.f64_zero,
"notnan",
);
let v1_repr = self
.builder
.build_bitcast(v1, self.intrinsics.i64_ty, "")
.into_int_value();
let v2_repr = self
.builder
.build_bitcast(v2, self.intrinsics.i64_ty, "")
.into_int_value();
let repr_ne =
self.builder
.build_int_compare(IntPredicate::NE, v1_repr, v2_repr, "");
let float_eq = self
.builder
.build_float_compare(FloatPredicate::OEQ, v1, v2, "");
let min_cmp = self
.builder
.build_float_compare(FloatPredicate::OGT, v1, v2, "");
let v2 = self
.builder
.build_select(
self.builder.build_and(
self.builder.build_and(float_eq, repr_ne, ""),
v2_is_not_nan,
"",
),
self.intrinsics.f64_zero,
v2,
"",
)
.into_float_value();
let res = self.builder.build_select(
self.builder.build_or(v1_is_nan, min_cmp, ""),
v1,
v2,
"",
);
// Because inputs were canonicalized, we always produce
// canonical NaN outputs. No pending NaN cleanup.
self.state.push1_extra(res, ExtraInfo::arithmetic_f64());
}
Operator::F32x4Max => {
// a) check v1 and v2 for NaN
// b) check v2 for zero
// c) check v1 for sign
//
// We pick v1 iff
// v1 is NaN or
// v2 is not NaN and either
// v1 > v2 or
// v1 is ±zero and v2 is negative.
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f32x4(v1, i1);
let (v2, i2) = self.v128_into_f32x4(v2, i2);
let v1 = if !i1.is_arithmetic_f32() {
self.canonicalize_nans(v1.as_basic_value_enum())
.into_vector_value()
} else {
v1
};
let v2 = if !i2.is_arithmetic_f32() {
self.canonicalize_nans(v2.as_basic_value_enum())
.into_vector_value()
} else {
v2
};
let v1_is_nan = self.builder.build_float_compare(
FloatPredicate::UNO,
v1,
self.intrinsics.f32x4_zero,
"v1nan",
);
let v2_is_notnan = self.builder.build_float_compare(
FloatPredicate::ORD,
v2,
self.intrinsics.f32x4_zero,
"v2notnan",
);
let v1_is_zero = self.builder.build_float_compare(
FloatPredicate::OEQ,
v1,
self.intrinsics.f32x4_zero,
"v1zero",
);
let v2_is_negative = self.builder.build_float_compare(
FloatPredicate::OLT,
self.builder
.build_call(
self.intrinsics.copysign_f32x4,
&[
VectorType::const_vector(
&[self
.intrinsics
.f32_ty
.const_float(1.0)
.as_basic_value_enum();
4],
)
.as_basic_value_enum(),
v2.as_basic_value_enum(),
],
"",
)
.try_as_basic_value()
.left()
.unwrap()
.into_vector_value(),
self.intrinsics.f32x4_zero,
"v2neg",
);
let v1_gt_v2 = self
.builder
.build_float_compare(FloatPredicate::OGT, v1, v2, "");
let pick_v1 = self.builder.build_or(
v1_is_nan,
self.builder.build_and(
v2_is_notnan,
self.builder.build_or(
v1_gt_v2,
self.builder.build_and(v1_is_zero, v2_is_negative, ""),
"",
),
"",
),
"",
);
let res = self.builder.build_select(pick_v1, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F64x2Max => {
// a) check v1 and v2 for NaN
// b) check v2 for zero
// c) check v1 for sign
//
// We pick v1 iff
// v1 is NaN or
// v2 is not NaN and either
// v1 > v2 or
// v1 is ±zero and v2 is negative.
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f64x2(v1, i1);
let (v2, i2) = self.v128_into_f64x2(v2, i2);
let v1 = if !i1.is_arithmetic_f64() {
self.canonicalize_nans(v1.as_basic_value_enum())
.into_vector_value()
} else {
v1
};
let v2 = if !i2.is_arithmetic_f64() {
self.canonicalize_nans(v2.as_basic_value_enum())
.into_vector_value()
} else {
v2
};
let v1_is_nan = self.builder.build_float_compare(
FloatPredicate::UNO,
v1,
self.intrinsics.f64x2_zero,
"v1nan",
);
let v2_is_notnan = self.builder.build_float_compare(
FloatPredicate::ORD,
v2,
self.intrinsics.f64x2_zero,
"v2notnan",
);
let v1_is_zero = self.builder.build_float_compare(
FloatPredicate::OEQ,
v1,
self.intrinsics.f64x2_zero,
"v1zero",
);
let v2_is_negative = self.builder.build_float_compare(
FloatPredicate::OLT,
self.builder
.build_call(
self.intrinsics.copysign_f64x2,
&[
VectorType::const_vector(
&[self
.intrinsics
.f64_ty
.const_float(1.0)
.as_basic_value_enum();
2],
)
.as_basic_value_enum(),
v2.as_basic_value_enum(),
],
"",
)
.try_as_basic_value()
.left()
.unwrap()
.into_vector_value(),
self.intrinsics.f64x2_zero,
"v2neg",
);
let v1_gt_v2 = self
.builder
.build_float_compare(FloatPredicate::OGT, v1, v2, "");
let pick_v1 = self.builder.build_or(
v1_is_nan,
self.builder.build_and(
v2_is_notnan,
self.builder.build_or(
v1_gt_v2,
self.builder.build_and(v1_is_zero, v2_is_negative, ""),
"",
),
"",
),
"",
);
let res = self.builder.build_select(pick_v1, v1, v2, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F32Ceil => {
let (input, info) = self.state.pop1_extra()?;
let res = self
.builder
.build_call(self.intrinsics.ceil_f32, &[input], "")
.try_as_basic_value()
.left()
.unwrap();
self.state
.push1_extra(res, info | ExtraInfo::pending_f32_nan());
}
Operator::F64Ceil => {
let (input, info) = self.state.pop1_extra()?;
let res = self
.builder
.build_call(self.intrinsics.ceil_f64, &[input], "")
.try_as_basic_value()
.left()
.unwrap();
self.state
.push1_extra(res, info | ExtraInfo::pending_f64_nan());
}
Operator::F32Floor => {
let (input, info) = self.state.pop1_extra()?;
let res = self
.builder
.build_call(self.intrinsics.floor_f32, &[input], "")
.try_as_basic_value()
.left()
.unwrap();
self.state
.push1_extra(res, info | ExtraInfo::pending_f32_nan());
}
Operator::F64Floor => {
let (input, info) = self.state.pop1_extra()?;
let res = self
.builder
.build_call(self.intrinsics.floor_f64, &[input], "")
.try_as_basic_value()
.left()
.unwrap();
self.state
.push1_extra(res, info | ExtraInfo::pending_f64_nan());
}
Operator::F32Trunc => {
let (v, i) = self.state.pop1_extra()?;
let res = self
.builder
.build_call(self.intrinsics.trunc_f32, &[v.as_basic_value_enum()], "")
.try_as_basic_value()
.left()
.unwrap();
self.state
.push1_extra(res, i | ExtraInfo::pending_f32_nan());
}
Operator::F64Trunc => {
let (v, i) = self.state.pop1_extra()?;
let res = self
.builder
.build_call(self.intrinsics.trunc_f64, &[v.as_basic_value_enum()], "")
.try_as_basic_value()
.left()
.unwrap();
self.state
.push1_extra(res, i | ExtraInfo::pending_f64_nan());
}
Operator::F32Nearest => {
let (v, i) = self.state.pop1_extra()?;
let res = self
.builder
.build_call(
self.intrinsics.nearbyint_f32,
&[v.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
self.state
.push1_extra(res, i | ExtraInfo::pending_f32_nan());
}
Operator::F64Nearest => {
let (v, i) = self.state.pop1_extra()?;
let res = self
.builder
.build_call(
self.intrinsics.nearbyint_f64,
&[v.as_basic_value_enum()],
"",
)
.try_as_basic_value()
.left()
.unwrap();
self.state
.push1_extra(res, i | ExtraInfo::pending_f64_nan());
}
Operator::F32Abs => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let res = self
.builder
.build_call(self.intrinsics.fabs_f32, &[v.as_basic_value_enum()], "")
.try_as_basic_value()
.left()
.unwrap();
// The exact NaN returned by F32Abs is fully defined. Do not
// adjust.
self.state.push1_extra(res, i.strip_pending());
}
Operator::F64Abs => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let res = self
.builder
.build_call(self.intrinsics.fabs_f64, &[v.as_basic_value_enum()], "")
.try_as_basic_value()
.left()
.unwrap();
// The exact NaN returned by F64Abs is fully defined. Do not
// adjust.
self.state.push1_extra(res, i.strip_pending());
}
Operator::F32x4Abs => {
let (v, i) = self.state.pop1_extra()?;
let v =
self.builder
.build_bitcast(v.into_int_value(), self.intrinsics.f32x4_ty, "");
let v = self.apply_pending_canonicalization(v, i);
let res = self
.builder
.build_call(self.intrinsics.fabs_f32x4, &[v.as_basic_value_enum()], "")
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
// The exact NaN returned by F32x4Abs is fully defined. Do not
// adjust.
self.state.push1_extra(res, i.strip_pending());
}
Operator::F64x2Abs => {
let (v, i) = self.state.pop1_extra()?;
let v =
self.builder
.build_bitcast(v.into_int_value(), self.intrinsics.f64x2_ty, "");
let v = self.apply_pending_canonicalization(v, i);
let res = self
.builder
.build_call(self.intrinsics.fabs_f64x2, &[v], "")
.try_as_basic_value()
.left()
.unwrap();
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
// The exact NaN returned by F32x4Abs is fully defined. Do not
// adjust.
self.state.push1_extra(res, i.strip_pending());
}
Operator::F32x4Neg => {
let (v, i) = self.state.pop1_extra()?;
let v =
self.builder
.build_bitcast(v.into_int_value(), self.intrinsics.f32x4_ty, "");
let v = self
.apply_pending_canonicalization(v, i)
.into_vector_value();
let res = self.builder.build_float_neg(v, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
// The exact NaN returned by F32x4Neg is fully defined. Do not
// adjust.
self.state.push1_extra(res, i.strip_pending());
}
Operator::F64x2Neg => {
let (v, i) = self.state.pop1_extra()?;
let v =
self.builder
.build_bitcast(v.into_int_value(), self.intrinsics.f64x2_ty, "");
let v = self
.apply_pending_canonicalization(v, i)
.into_vector_value();
let res = self.builder.build_float_neg(v, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
// The exact NaN returned by F64x2Neg is fully defined. Do not
// adjust.
self.state.push1_extra(res, i.strip_pending());
}
Operator::F32Neg | Operator::F64Neg => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i).into_float_value();
let res = self.builder.build_float_neg(v, "");
// The exact NaN returned by F32Neg and F64Neg are fully defined.
// Do not adjust.
self.state.push1_extra(res, i.strip_pending());
}
Operator::F32Copysign => {
let ((mag, mag_info), (sgn, sgn_info)) = self.state.pop2_extra()?;
let mag = self.apply_pending_canonicalization(mag, mag_info);
let sgn = self.apply_pending_canonicalization(sgn, sgn_info);
let res = self
.builder
.build_call(self.intrinsics.copysign_f32, &[mag, sgn], "")
.try_as_basic_value()
.left()
.unwrap();
// The exact NaN returned by F32Copysign is fully defined.
// Do not adjust.
self.state.push1_extra(res, mag_info.strip_pending());
}
Operator::F64Copysign => {
let ((mag, mag_info), (sgn, sgn_info)) = self.state.pop2_extra()?;
let mag = self.apply_pending_canonicalization(mag, mag_info);
let sgn = self.apply_pending_canonicalization(sgn, sgn_info);
let res = self
.builder
.build_call(self.intrinsics.copysign_f64, &[mag, sgn], "")
.try_as_basic_value()
.left()
.unwrap();
// The exact NaN returned by F32Copysign is fully defined.
// Do not adjust.
self.state.push1_extra(res, mag_info.strip_pending());
}
/***************************
* Integer Comparison instructions.
* https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#integer-comparison-instructions
***************************/
Operator::I32Eq | Operator::I64Eq => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self.builder.build_int_compare(IntPredicate::EQ, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16Eq => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self.builder.build_int_compare(IntPredicate::EQ, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8Eq => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self.builder.build_int_compare(IntPredicate::EQ, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4Eq => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self.builder.build_int_compare(IntPredicate::EQ, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32Ne | Operator::I64Ne => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self.builder.build_int_compare(IntPredicate::NE, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16Ne => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self.builder.build_int_compare(IntPredicate::NE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8Ne => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self.builder.build_int_compare(IntPredicate::NE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4Ne => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self.builder.build_int_compare(IntPredicate::NE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32LtS | Operator::I64LtS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self
.builder
.build_int_compare(IntPredicate::SLT, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16LtS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SLT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8LtS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SLT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4LtS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SLT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32LtU | Operator::I64LtU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self
.builder
.build_int_compare(IntPredicate::ULT, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I8x16LtU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::ULT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8LtU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::ULT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4LtU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::ULT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32LeS | Operator::I64LeS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self
.builder
.build_int_compare(IntPredicate::SLE, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16LeS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SLE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8LeS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SLE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4LeS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SLE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32LeU | Operator::I64LeU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self
.builder
.build_int_compare(IntPredicate::ULE, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16LeU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::ULE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8LeU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::ULE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4LeU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::ULE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32GtS | Operator::I64GtS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self
.builder
.build_int_compare(IntPredicate::SGT, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16GtS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SGT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8GtS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SGT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4GtS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SGT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32GtU | Operator::I64GtU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self
.builder
.build_int_compare(IntPredicate::UGT, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16GtU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::UGT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8GtU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::UGT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4GtU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::UGT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32GeS | Operator::I64GeS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self
.builder
.build_int_compare(IntPredicate::SGE, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I8x16GeS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SGE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8GeS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SGE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4GeS => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::SGE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32GeU | Operator::I64GeU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let (v1, v2) = (v1.into_int_value(), v2.into_int_value());
let cond = self
.builder
.build_int_compare(IntPredicate::UGE, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16GeU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let (v2, _) = self.v128_into_i8x16(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::UGE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i8x16_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8GeU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::UGE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4GeU => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let res = self
.builder
.build_int_compare(IntPredicate::UGE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
/***************************
* Floating-Point Comparison instructions.
* https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#floating-point-comparison-instructions
***************************/
Operator::F32Eq | Operator::F64Eq => {
let (v1, v2) = self.state.pop2()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let cond = self
.builder
.build_float_compare(FloatPredicate::OEQ, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::F32x4Eq => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f32x4(v1, i1);
let (v2, _) = self.v128_into_f32x4(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OEQ, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F64x2Eq => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f64x2(v1, i1);
let (v2, _) = self.v128_into_f64x2(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OEQ, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i64x2_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F32Ne | Operator::F64Ne => {
let (v1, v2) = self.state.pop2()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let cond = self
.builder
.build_float_compare(FloatPredicate::UNE, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::F32x4Ne => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f32x4(v1, i1);
let (v2, _) = self.v128_into_f32x4(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::UNE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F64x2Ne => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f64x2(v1, i1);
let (v2, _) = self.v128_into_f64x2(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::UNE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i64x2_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F32Lt | Operator::F64Lt => {
let (v1, v2) = self.state.pop2()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let cond = self
.builder
.build_float_compare(FloatPredicate::OLT, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::F32x4Lt => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f32x4(v1, i1);
let (v2, _) = self.v128_into_f32x4(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OLT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F64x2Lt => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f64x2(v1, i1);
let (v2, _) = self.v128_into_f64x2(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OLT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i64x2_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F32Le | Operator::F64Le => {
let (v1, v2) = self.state.pop2()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let cond = self
.builder
.build_float_compare(FloatPredicate::OLE, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::F32x4Le => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f32x4(v1, i1);
let (v2, _) = self.v128_into_f32x4(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OLE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F64x2Le => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f64x2(v1, i1);
let (v2, _) = self.v128_into_f64x2(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OLE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i64x2_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F32Gt | Operator::F64Gt => {
let (v1, v2) = self.state.pop2()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let cond = self
.builder
.build_float_compare(FloatPredicate::OGT, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::F32x4Gt => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f32x4(v1, i1);
let (v2, _) = self.v128_into_f32x4(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OGT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F64x2Gt => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f64x2(v1, i1);
let (v2, _) = self.v128_into_f64x2(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OGT, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i64x2_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F32Ge | Operator::F64Ge => {
let (v1, v2) = self.state.pop2()?;
let (v1, v2) = (v1.into_float_value(), v2.into_float_value());
let cond = self
.builder
.build_float_compare(FloatPredicate::OGE, v1, v2, "");
let res = self
.builder
.build_int_z_extend(cond, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::F32x4Ge => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f32x4(v1, i1);
let (v2, _) = self.v128_into_f32x4(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OGE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F64x2Ge => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_f64x2(v1, i1);
let (v2, _) = self.v128_into_f64x2(v2, i2);
let res = self
.builder
.build_float_compare(FloatPredicate::OGE, v1, v2, "");
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i64x2_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
/***************************
* Conversion instructions.
* https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#conversion-instructions
***************************/
Operator::I32WrapI64 => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self
.builder
.build_int_truncate(v, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I64ExtendI32S => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self
.builder
.build_int_s_extend(v, self.intrinsics.i64_ty, "");
self.state.push1(res);
}
Operator::I64ExtendI32U => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self
.builder
.build_int_z_extend(v, self.intrinsics.i64_ty, "");
self.state.push1_extra(res, ExtraInfo::arithmetic_f64());
}
Operator::I16x8WidenLowI8x16S => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i8x16(v, i);
let low = self.builder.build_shuffle_vector(
v,
v.get_type().get_undef(),
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(0, false),
self.intrinsics.i32_ty.const_int(1, false),
self.intrinsics.i32_ty.const_int(2, false),
self.intrinsics.i32_ty.const_int(3, false),
self.intrinsics.i32_ty.const_int(4, false),
self.intrinsics.i32_ty.const_int(5, false),
self.intrinsics.i32_ty.const_int(6, false),
self.intrinsics.i32_ty.const_int(7, false),
]),
"",
);
let res = self
.builder
.build_int_s_extend(low, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8WidenHighI8x16S => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i8x16(v, i);
let low = self.builder.build_shuffle_vector(
v,
v.get_type().get_undef(),
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(8, false),
self.intrinsics.i32_ty.const_int(9, false),
self.intrinsics.i32_ty.const_int(10, false),
self.intrinsics.i32_ty.const_int(11, false),
self.intrinsics.i32_ty.const_int(12, false),
self.intrinsics.i32_ty.const_int(13, false),
self.intrinsics.i32_ty.const_int(14, false),
self.intrinsics.i32_ty.const_int(15, false),
]),
"",
);
let res = self
.builder
.build_int_s_extend(low, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8WidenLowI8x16U => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i8x16(v, i);
let low = self.builder.build_shuffle_vector(
v,
v.get_type().get_undef(),
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(0, false),
self.intrinsics.i32_ty.const_int(1, false),
self.intrinsics.i32_ty.const_int(2, false),
self.intrinsics.i32_ty.const_int(3, false),
self.intrinsics.i32_ty.const_int(4, false),
self.intrinsics.i32_ty.const_int(5, false),
self.intrinsics.i32_ty.const_int(6, false),
self.intrinsics.i32_ty.const_int(7, false),
]),
"",
);
let res = self
.builder
.build_int_z_extend(low, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8WidenHighI8x16U => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i8x16(v, i);
let low = self.builder.build_shuffle_vector(
v,
v.get_type().get_undef(),
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(8, false),
self.intrinsics.i32_ty.const_int(9, false),
self.intrinsics.i32_ty.const_int(10, false),
self.intrinsics.i32_ty.const_int(11, false),
self.intrinsics.i32_ty.const_int(12, false),
self.intrinsics.i32_ty.const_int(13, false),
self.intrinsics.i32_ty.const_int(14, false),
self.intrinsics.i32_ty.const_int(15, false),
]),
"",
);
let res = self
.builder
.build_int_z_extend(low, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4WidenLowI16x8S => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i16x8(v, i);
let low = self.builder.build_shuffle_vector(
v,
v.get_type().get_undef(),
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(0, false),
self.intrinsics.i32_ty.const_int(1, false),
self.intrinsics.i32_ty.const_int(2, false),
self.intrinsics.i32_ty.const_int(3, false),
]),
"",
);
let res = self
.builder
.build_int_s_extend(low, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4WidenHighI16x8S => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i16x8(v, i);
let low = self.builder.build_shuffle_vector(
v,
v.get_type().get_undef(),
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(4, false),
self.intrinsics.i32_ty.const_int(5, false),
self.intrinsics.i32_ty.const_int(6, false),
self.intrinsics.i32_ty.const_int(7, false),
]),
"",
);
let res = self
.builder
.build_int_s_extend(low, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4WidenLowI16x8U => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i16x8(v, i);
let low = self.builder.build_shuffle_vector(
v,
v.get_type().get_undef(),
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(0, false),
self.intrinsics.i32_ty.const_int(1, false),
self.intrinsics.i32_ty.const_int(2, false),
self.intrinsics.i32_ty.const_int(3, false),
]),
"",
);
let res = self
.builder
.build_int_z_extend(low, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4WidenHighI16x8U => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i16x8(v, i);
let low = self.builder.build_shuffle_vector(
v,
v.get_type().get_undef(),
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(4, false),
self.intrinsics.i32_ty.const_int(5, false),
self.intrinsics.i32_ty.const_int(6, false),
self.intrinsics.i32_ty.const_int(7, false),
]),
"",
);
let res = self
.builder
.build_int_z_extend(low, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16NarrowI16x8S => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let min = self.intrinsics.i16_ty.const_int(0xff80, false);
let max = self.intrinsics.i16_ty.const_int(0x007f, false);
let min = VectorType::const_vector(&[min; 8]);
let max = VectorType::const_vector(&[max; 8]);
let apply_min_clamp_v1 =
self.builder
.build_int_compare(IntPredicate::SLT, v1, min, "");
let apply_max_clamp_v1 =
self.builder
.build_int_compare(IntPredicate::SGT, v1, max, "");
let apply_min_clamp_v2 =
self.builder
.build_int_compare(IntPredicate::SLT, v2, min, "");
let apply_max_clamp_v2 =
self.builder
.build_int_compare(IntPredicate::SGT, v2, max, "");
let v1 = self
.builder
.build_select(apply_min_clamp_v1, min, v1, "")
.into_vector_value();
let v1 = self
.builder
.build_select(apply_max_clamp_v1, max, v1, "")
.into_vector_value();
let v1 = self
.builder
.build_int_truncate(v1, self.intrinsics.i8_ty.vec_type(8), "");
let v2 = self
.builder
.build_select(apply_min_clamp_v2, min, v2, "")
.into_vector_value();
let v2 = self
.builder
.build_select(apply_max_clamp_v2, max, v2, "")
.into_vector_value();
let v2 = self
.builder
.build_int_truncate(v2, self.intrinsics.i8_ty.vec_type(8), "");
let res = self.builder.build_shuffle_vector(
v1,
v2,
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(0, false),
self.intrinsics.i32_ty.const_int(1, false),
self.intrinsics.i32_ty.const_int(2, false),
self.intrinsics.i32_ty.const_int(3, false),
self.intrinsics.i32_ty.const_int(4, false),
self.intrinsics.i32_ty.const_int(5, false),
self.intrinsics.i32_ty.const_int(6, false),
self.intrinsics.i32_ty.const_int(7, false),
self.intrinsics.i32_ty.const_int(8, false),
self.intrinsics.i32_ty.const_int(9, false),
self.intrinsics.i32_ty.const_int(10, false),
self.intrinsics.i32_ty.const_int(11, false),
self.intrinsics.i32_ty.const_int(12, false),
self.intrinsics.i32_ty.const_int(13, false),
self.intrinsics.i32_ty.const_int(14, false),
self.intrinsics.i32_ty.const_int(15, false),
]),
"",
);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16NarrowI16x8U => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let (v2, _) = self.v128_into_i16x8(v2, i2);
let min = self.intrinsics.i16x8_ty.const_zero();
let max = self.intrinsics.i16_ty.const_int(0x00ff, false);
let max = VectorType::const_vector(&[max; 8]);
let apply_min_clamp_v1 =
self.builder
.build_int_compare(IntPredicate::SLT, v1, min, "");
let apply_max_clamp_v1 =
self.builder
.build_int_compare(IntPredicate::SGT, v1, max, "");
let apply_min_clamp_v2 =
self.builder
.build_int_compare(IntPredicate::SLT, v2, min, "");
let apply_max_clamp_v2 =
self.builder
.build_int_compare(IntPredicate::SGT, v2, max, "");
let v1 = self
.builder
.build_select(apply_min_clamp_v1, min, v1, "")
.into_vector_value();
let v1 = self
.builder
.build_select(apply_max_clamp_v1, max, v1, "")
.into_vector_value();
let v1 = self
.builder
.build_int_truncate(v1, self.intrinsics.i8_ty.vec_type(8), "");
let v2 = self
.builder
.build_select(apply_min_clamp_v2, min, v2, "")
.into_vector_value();
let v2 = self
.builder
.build_select(apply_max_clamp_v2, max, v2, "")
.into_vector_value();
let v2 = self
.builder
.build_int_truncate(v2, self.intrinsics.i8_ty.vec_type(8), "");
let res = self.builder.build_shuffle_vector(
v1,
v2,
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(0, false),
self.intrinsics.i32_ty.const_int(1, false),
self.intrinsics.i32_ty.const_int(2, false),
self.intrinsics.i32_ty.const_int(3, false),
self.intrinsics.i32_ty.const_int(4, false),
self.intrinsics.i32_ty.const_int(5, false),
self.intrinsics.i32_ty.const_int(6, false),
self.intrinsics.i32_ty.const_int(7, false),
self.intrinsics.i32_ty.const_int(8, false),
self.intrinsics.i32_ty.const_int(9, false),
self.intrinsics.i32_ty.const_int(10, false),
self.intrinsics.i32_ty.const_int(11, false),
self.intrinsics.i32_ty.const_int(12, false),
self.intrinsics.i32_ty.const_int(13, false),
self.intrinsics.i32_ty.const_int(14, false),
self.intrinsics.i32_ty.const_int(15, false),
]),
"",
);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8NarrowI32x4S => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let min = self.intrinsics.i32_ty.const_int(0xffff8000, false);
let max = self.intrinsics.i32_ty.const_int(0x00007fff, false);
let min = VectorType::const_vector(&[min; 4]);
let max = VectorType::const_vector(&[max; 4]);
let apply_min_clamp_v1 =
self.builder
.build_int_compare(IntPredicate::SLT, v1, min, "");
let apply_max_clamp_v1 =
self.builder
.build_int_compare(IntPredicate::SGT, v1, max, "");
let apply_min_clamp_v2 =
self.builder
.build_int_compare(IntPredicate::SLT, v2, min, "");
let apply_max_clamp_v2 =
self.builder
.build_int_compare(IntPredicate::SGT, v2, max, "");
let v1 = self
.builder
.build_select(apply_min_clamp_v1, min, v1, "")
.into_vector_value();
let v1 = self
.builder
.build_select(apply_max_clamp_v1, max, v1, "")
.into_vector_value();
let v1 =
self.builder
.build_int_truncate(v1, self.intrinsics.i16_ty.vec_type(4), "");
let v2 = self
.builder
.build_select(apply_min_clamp_v2, min, v2, "")
.into_vector_value();
let v2 = self
.builder
.build_select(apply_max_clamp_v2, max, v2, "")
.into_vector_value();
let v2 =
self.builder
.build_int_truncate(v2, self.intrinsics.i16_ty.vec_type(4), "");
let res = self.builder.build_shuffle_vector(
v1,
v2,
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(0, false),
self.intrinsics.i32_ty.const_int(1, false),
self.intrinsics.i32_ty.const_int(2, false),
self.intrinsics.i32_ty.const_int(3, false),
self.intrinsics.i32_ty.const_int(4, false),
self.intrinsics.i32_ty.const_int(5, false),
self.intrinsics.i32_ty.const_int(6, false),
self.intrinsics.i32_ty.const_int(7, false),
]),
"",
);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8NarrowI32x4U => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i32x4(v1, i1);
let (v2, _) = self.v128_into_i32x4(v2, i2);
let min = self.intrinsics.i32x4_ty.const_zero();
let max = self.intrinsics.i32_ty.const_int(0xffff, false);
let max = VectorType::const_vector(&[max; 4]);
let apply_min_clamp_v1 =
self.builder
.build_int_compare(IntPredicate::SLT, v1, min, "");
let apply_max_clamp_v1 =
self.builder
.build_int_compare(IntPredicate::SGT, v1, max, "");
let apply_min_clamp_v2 =
self.builder
.build_int_compare(IntPredicate::SLT, v2, min, "");
let apply_max_clamp_v2 =
self.builder
.build_int_compare(IntPredicate::SGT, v2, max, "");
let v1 = self
.builder
.build_select(apply_min_clamp_v1, min, v1, "")
.into_vector_value();
let v1 = self
.builder
.build_select(apply_max_clamp_v1, max, v1, "")
.into_vector_value();
let v1 =
self.builder
.build_int_truncate(v1, self.intrinsics.i16_ty.vec_type(4), "");
let v2 = self
.builder
.build_select(apply_min_clamp_v2, min, v2, "")
.into_vector_value();
let v2 = self
.builder
.build_select(apply_max_clamp_v2, max, v2, "")
.into_vector_value();
let v2 =
self.builder
.build_int_truncate(v2, self.intrinsics.i16_ty.vec_type(4), "");
let res = self.builder.build_shuffle_vector(
v1,
v2,
VectorType::const_vector(&[
self.intrinsics.i32_ty.const_int(0, false),
self.intrinsics.i32_ty.const_int(1, false),
self.intrinsics.i32_ty.const_int(2, false),
self.intrinsics.i32_ty.const_int(3, false),
self.intrinsics.i32_ty.const_int(4, false),
self.intrinsics.i32_ty.const_int(5, false),
self.intrinsics.i32_ty.const_int(6, false),
self.intrinsics.i32_ty.const_int(7, false),
]),
"",
);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4TruncSatF32x4S => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self.trunc_sat(
self.intrinsics.f32x4_ty,
self.intrinsics.i32x4_ty,
LEF32_GEQ_I32_MIN,
GEF32_LEQ_I32_MAX,
std::i32::MIN as u64,
std::i32::MAX as u64,
v,
);
self.state.push1(res);
}
Operator::I32x4TruncSatF32x4U => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self.trunc_sat(
self.intrinsics.f32x4_ty,
self.intrinsics.i32x4_ty,
LEF32_GEQ_U32_MIN,
GEF32_LEQ_U32_MAX,
std::u32::MIN as u64,
std::u32::MAX as u64,
v,
);
self.state.push1(res);
}
// Operator::I64x2TruncSatF64x2S => {
// let (v, i) = self.state.pop1_extra()?;
// let v = self.apply_pending_canonicalization(v, i);
// let v = v.into_int_value();
// let res = self.trunc_sat(
// self.intrinsics.f64x2_ty,
// self.intrinsics.i64x2_ty,
// std::i64::MIN as u64,
// std::i64::MAX as u64,
// std::i64::MIN as u64,
// std::i64::MAX as u64,
// v,
// );
// self.state.push1(res);
// }
// Operator::I64x2TruncSatF64x2U => {
// let (v, i) = self.state.pop1_extra()?;
// let v = self.apply_pending_canonicalization(v, i);
// let v = v.into_int_value();
// let res = self.trunc_sat(
// self.intrinsics.f64x2_ty,
// self.intrinsics.i64x2_ty,
// std::u64::MIN,
// std::u64::MAX,
// std::u64::MIN,
// std::u64::MAX,
// v,
// );
// self.state.push1(res);
// }
Operator::I32TruncF32S => {
let v1 = self.state.pop1()?.into_float_value();
self.trap_if_not_representable_as_int(
0xcf000000, // -2147483600.0
0x4effffff, // 2147483500.0
v1,
);
let res = self
.builder
.build_float_to_signed_int(v1, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I32TruncF64S => {
let v1 = self.state.pop1()?.into_float_value();
self.trap_if_not_representable_as_int(
0xc1e00000001fffff, // -2147483648.9999995
0x41dfffffffffffff, // 2147483647.9999998
v1,
);
let res = self
.builder
.build_float_to_signed_int(v1, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I32TruncSatF32S => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_float_value();
let res = self.trunc_sat_scalar(
self.intrinsics.i32_ty,
LEF32_GEQ_I32_MIN,
GEF32_LEQ_I32_MAX,
std::i32::MIN as u32 as u64,
std::i32::MAX as u32 as u64,
v,
);
self.state.push1(res);
}
Operator::I32TruncSatF64S => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_float_value();
let res = self.trunc_sat_scalar(
self.intrinsics.i32_ty,
LEF64_GEQ_I32_MIN,
GEF64_LEQ_I32_MAX,
std::i32::MIN as u64,
std::i32::MAX as u64,
v,
);
self.state.push1(res);
}
Operator::I64TruncF32S => {
let v1 = self.state.pop1()?.into_float_value();
self.trap_if_not_representable_as_int(
0xdf000000, // -9223372000000000000.0
0x5effffff, // 9223371500000000000.0
v1,
);
let res = self
.builder
.build_float_to_signed_int(v1, self.intrinsics.i64_ty, "");
self.state.push1(res);
}
Operator::I64TruncF64S => {
let v1 = self.state.pop1()?.into_float_value();
self.trap_if_not_representable_as_int(
0xc3e0000000000000, // -9223372036854776000.0
0x43dfffffffffffff, // 9223372036854775000.0
v1,
);
let res = self
.builder
.build_float_to_signed_int(v1, self.intrinsics.i64_ty, "");
self.state.push1(res);
}
Operator::I64TruncSatF32S => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_float_value();
let res = self.trunc_sat_scalar(
self.intrinsics.i64_ty,
LEF32_GEQ_I64_MIN,
GEF32_LEQ_I64_MAX,
std::i64::MIN as u64,
std::i64::MAX as u64,
v,
);
self.state.push1(res);
}
Operator::I64TruncSatF64S => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_float_value();
let res = self.trunc_sat_scalar(
self.intrinsics.i64_ty,
LEF64_GEQ_I64_MIN,
GEF64_LEQ_I64_MAX,
std::i64::MIN as u64,
std::i64::MAX as u64,
v,
);
self.state.push1(res);
}
Operator::I32TruncF32U => {
let v1 = self.state.pop1()?.into_float_value();
self.trap_if_not_representable_as_int(
0xbf7fffff, // -0.99999994
0x4f7fffff, // 4294967000.0
v1,
);
let res = self
.builder
.build_float_to_unsigned_int(v1, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I32TruncF64U => {
let v1 = self.state.pop1()?.into_float_value();
self.trap_if_not_representable_as_int(
0xbfefffffffffffff, // -0.9999999999999999
0x41efffffffffffff, // 4294967295.9999995
v1,
);
let res = self
.builder
.build_float_to_unsigned_int(v1, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I32TruncSatF32U => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_float_value();
let res = self.trunc_sat_scalar(
self.intrinsics.i32_ty,
LEF32_GEQ_U32_MIN,
GEF32_LEQ_U32_MAX,
std::u32::MIN as u64,
std::u32::MAX as u64,
v,
);
self.state.push1(res);
}
Operator::I32TruncSatF64U => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_float_value();
let res = self.trunc_sat_scalar(
self.intrinsics.i32_ty,
LEF64_GEQ_U32_MIN,
GEF64_LEQ_U32_MAX,
std::u32::MIN as u64,
std::u32::MAX as u64,
v,
);
self.state.push1(res);
}
Operator::I64TruncF32U => {
let v1 = self.state.pop1()?.into_float_value();
self.trap_if_not_representable_as_int(
0xbf7fffff, // -0.99999994
0x5f7fffff, // 18446743000000000000.0
v1,
);
let res = self
.builder
.build_float_to_unsigned_int(v1, self.intrinsics.i64_ty, "");
self.state.push1(res);
}
Operator::I64TruncF64U => {
let v1 = self.state.pop1()?.into_float_value();
self.trap_if_not_representable_as_int(
0xbfefffffffffffff, // -0.9999999999999999
0x43efffffffffffff, // 18446744073709550000.0
v1,
);
let res = self
.builder
.build_float_to_unsigned_int(v1, self.intrinsics.i64_ty, "");
self.state.push1(res);
}
Operator::I64TruncSatF32U => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_float_value();
let res = self.trunc_sat_scalar(
self.intrinsics.i64_ty,
LEF32_GEQ_U64_MIN,
GEF32_LEQ_U64_MAX,
std::u64::MIN,
std::u64::MAX,
v,
);
self.state.push1(res);
}
Operator::I64TruncSatF64U => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_float_value();
let res = self.trunc_sat_scalar(
self.intrinsics.i64_ty,
LEF64_GEQ_U64_MIN,
GEF64_LEQ_U64_MAX,
std::u64::MIN,
std::u64::MAX,
v,
);
self.state.push1(res);
}
Operator::F32DemoteF64 => {
let v = self.state.pop1()?;
let v = v.into_float_value();
let res = self
.builder
.build_float_trunc(v, self.intrinsics.f32_ty, "");
self.state.push1_extra(res, ExtraInfo::pending_f32_nan());
}
Operator::F64PromoteF32 => {
let v = self.state.pop1()?;
let v = v.into_float_value();
let res = self.builder.build_float_ext(v, self.intrinsics.f64_ty, "");
self.state.push1_extra(res, ExtraInfo::pending_f64_nan());
}
Operator::F32ConvertI32S | Operator::F32ConvertI64S => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self
.builder
.build_signed_int_to_float(v, self.intrinsics.f32_ty, "");
self.state.push1(res);
}
Operator::F64ConvertI32S | Operator::F64ConvertI64S => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self
.builder
.build_signed_int_to_float(v, self.intrinsics.f64_ty, "");
self.state.push1(res);
}
Operator::F32ConvertI32U | Operator::F32ConvertI64U => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self
.builder
.build_unsigned_int_to_float(v, self.intrinsics.f32_ty, "");
self.state.push1(res);
}
Operator::F64ConvertI32U | Operator::F64ConvertI64U => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let v = v.into_int_value();
let res = self
.builder
.build_unsigned_int_to_float(v, self.intrinsics.f64_ty, "");
self.state.push1(res);
}
Operator::F32x4ConvertI32x4S => {
let v = self.state.pop1()?;
let v = self
.builder
.build_bitcast(v, self.intrinsics.i32x4_ty, "")
.into_vector_value();
let res = self
.builder
.build_signed_int_to_float(v, self.intrinsics.f32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::F32x4ConvertI32x4U => {
let v = self.state.pop1()?;
let v = self
.builder
.build_bitcast(v, self.intrinsics.i32x4_ty, "")
.into_vector_value();
let res = self
.builder
.build_unsigned_int_to_float(v, self.intrinsics.f32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
// Operator::F64x2ConvertI64x2S => {
// let v = self.state.pop1()?;
// let v = self
// .builder
// .build_bitcast(v, self.intrinsics.i64x2_ty, "")
// .into_vector_value();
// let res = self
// .builder
// .build_signed_int_to_float(v, self.intrinsics.f64x2_ty, "");
// let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
// self.state.push1(res);
// }
// Operator::F64x2ConvertI64x2U => {
// let v = self.state.pop1()?;
// let v = self
// .builder
// .build_bitcast(v, self.intrinsics.i64x2_ty, "")
// .into_vector_value();
// let res = self
// .builder
// .build_unsigned_int_to_float(v, self.intrinsics.f64x2_ty, "");
// let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
// self.state.push1(res);
// }
Operator::I32ReinterpretF32 => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let ret = self.builder.build_bitcast(v, self.intrinsics.i32_ty, "");
self.state.push1_extra(ret, ExtraInfo::arithmetic_f32());
}
Operator::I64ReinterpretF64 => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let ret = self.builder.build_bitcast(v, self.intrinsics.i64_ty, "");
self.state.push1_extra(ret, ExtraInfo::arithmetic_f64());
}
Operator::F32ReinterpretI32 => {
let (v, i) = self.state.pop1_extra()?;
let ret = self.builder.build_bitcast(v, self.intrinsics.f32_ty, "");
self.state.push1_extra(ret, i);
}
Operator::F64ReinterpretI64 => {
let (v, i) = self.state.pop1_extra()?;
let ret = self.builder.build_bitcast(v, self.intrinsics.f64_ty, "");
self.state.push1_extra(ret, i);
}
/***************************
* Sign-extension operators.
* https://github.com/WebAssembly/sign-extension-ops/blob/master/proposals/sign-extension-ops/Overview.md
***************************/
Operator::I32Extend8S => {
let value = self.state.pop1()?.into_int_value();
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let extended_value =
self.builder
.build_int_s_extend(narrow_value, self.intrinsics.i32_ty, "");
self.state.push1(extended_value);
}
Operator::I32Extend16S => {
let value = self.state.pop1()?.into_int_value();
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let extended_value =
self.builder
.build_int_s_extend(narrow_value, self.intrinsics.i32_ty, "");
self.state.push1(extended_value);
}
Operator::I64Extend8S => {
let value = self.state.pop1()?.into_int_value();
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let extended_value =
self.builder
.build_int_s_extend(narrow_value, self.intrinsics.i64_ty, "");
self.state.push1(extended_value);
}
Operator::I64Extend16S => {
let value = self.state.pop1()?.into_int_value();
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let extended_value =
self.builder
.build_int_s_extend(narrow_value, self.intrinsics.i64_ty, "");
self.state.push1(extended_value);
}
Operator::I64Extend32S => {
let value = self.state.pop1()?.into_int_value();
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let extended_value =
self.builder
.build_int_s_extend(narrow_value, self.intrinsics.i64_ty, "");
self.state.push1(extended_value);
}
/***************************
* Load and Store instructions.
* https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#load-and-store-instructions
***************************/
Operator::I32Load { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
let result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
result.as_instruction_value().unwrap(),
)?;
self.state.push1(result);
}
Operator::I64Load { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
result.as_instruction_value().unwrap(),
)?;
self.state.push1(result);
}
Operator::F32Load { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.f32_ptr_ty,
offset,
4,
)?;
let result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
result.as_instruction_value().unwrap(),
)?;
self.state.push1(result);
}
Operator::F64Load { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.f64_ptr_ty,
offset,
8,
)?;
let result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
result.as_instruction_value().unwrap(),
)?;
self.state.push1(result);
}
Operator::V128Load { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i128_ptr_ty,
offset,
16,
)?;
let result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
result.as_instruction_value().unwrap(),
)?;
self.state.push1(result);
}
Operator::I32Store { ref memarg } => {
let value = self.state.pop1()?;
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
let dead_load = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
dead_load.as_instruction_value().unwrap(),
)?;
let store = self.builder.build_store(effective_address, value);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
}
Operator::I64Store { ref memarg } => {
let value = self.state.pop1()?;
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let dead_load = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
dead_load.as_instruction_value().unwrap(),
)?;
let store = self.builder.build_store(effective_address, value);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
}
Operator::F32Store { ref memarg } => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.f32_ptr_ty,
offset,
4,
)?;
let dead_load = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
dead_load.as_instruction_value().unwrap(),
)?;
let store = self.builder.build_store(effective_address, v);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
}
Operator::F64Store { ref memarg } => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.f64_ptr_ty,
offset,
8,
)?;
let dead_load = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
dead_load.as_instruction_value().unwrap(),
)?;
let store = self.builder.build_store(effective_address, v);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
}
Operator::V128Store { ref memarg } => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i);
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i128_ptr_ty,
offset,
16,
)?;
let dead_load = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
dead_load.as_instruction_value().unwrap(),
)?;
let store = self.builder.build_store(effective_address, v);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
}
Operator::I32Load8S { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
let narrow_result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result = self.builder.build_int_s_extend(
narrow_result.into_int_value(),
self.intrinsics.i32_ty,
"",
);
self.state.push1(result);
}
Operator::I32Load16S { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
let narrow_result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result = self.builder.build_int_s_extend(
narrow_result.into_int_value(),
self.intrinsics.i32_ty,
"",
);
self.state.push1(result);
}
Operator::I64Load8S { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
let narrow_result = self
.builder
.build_load(effective_address, "")
.into_int_value();
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result =
self.builder
.build_int_s_extend(narrow_result, self.intrinsics.i64_ty, "");
self.state.push1(result);
}
Operator::I64Load16S { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
let narrow_result = self
.builder
.build_load(effective_address, "")
.into_int_value();
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result =
self.builder
.build_int_s_extend(narrow_result, self.intrinsics.i64_ty, "");
self.state.push1(result);
}
Operator::I64Load32S { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
let narrow_result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result = self.builder.build_int_s_extend(
narrow_result.into_int_value(),
self.intrinsics.i64_ty,
"",
);
self.state.push1(result);
}
Operator::I32Load8U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
let narrow_result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result = self.builder.build_int_z_extend(
narrow_result.into_int_value(),
self.intrinsics.i32_ty,
"",
);
self.state.push1_extra(result, ExtraInfo::arithmetic_f32());
}
Operator::I32Load16U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
let narrow_result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result = self.builder.build_int_z_extend(
narrow_result.into_int_value(),
self.intrinsics.i32_ty,
"",
);
self.state.push1_extra(result, ExtraInfo::arithmetic_f32());
}
Operator::I64Load8U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
let narrow_result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result = self.builder.build_int_z_extend(
narrow_result.into_int_value(),
self.intrinsics.i64_ty,
"",
);
self.state.push1_extra(result, ExtraInfo::arithmetic_f64());
}
Operator::I64Load16U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
let narrow_result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result = self.builder.build_int_z_extend(
narrow_result.into_int_value(),
self.intrinsics.i64_ty,
"",
);
self.state.push1_extra(result, ExtraInfo::arithmetic_f64());
}
Operator::I64Load32U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
let narrow_result = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
narrow_result.as_instruction_value().unwrap(),
)?;
let result = self.builder.build_int_z_extend(
narrow_result.into_int_value(),
self.intrinsics.i64_ty,
"",
);
self.state.push1_extra(result, ExtraInfo::arithmetic_f64());
}
Operator::I32Store8 { ref memarg } | Operator::I64Store8 { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
let dead_load = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
dead_load.as_instruction_value().unwrap(),
)?;
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let store = self.builder.build_store(effective_address, narrow_value);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
}
Operator::I32Store16 { ref memarg } | Operator::I64Store16 { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
let dead_load = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
dead_load.as_instruction_value().unwrap(),
)?;
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let store = self.builder.build_store(effective_address, narrow_value);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
}
Operator::I64Store32 { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
let dead_load = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
dead_load.as_instruction_value().unwrap(),
)?;
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let store = self.builder.build_store(effective_address, narrow_value);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
}
Operator::I8x16Neg => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i8x16(v, i);
let res = self.builder.build_int_sub(v.get_type().const_zero(), v, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8Neg => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i16x8(v, i);
let res = self.builder.build_int_sub(v.get_type().const_zero(), v, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4Neg => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i32x4(v, i);
let res = self.builder.build_int_sub(v.get_type().const_zero(), v, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I64x2Neg => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i64x2(v, i);
let res = self.builder.build_int_sub(v.get_type().const_zero(), v, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Not => {
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i).into_int_value();
let res = self.builder.build_not(v, "");
self.state.push1(res);
}
Operator::V128AnyTrue => {
// | Operator::I64x2AnyTrue
// Skip canonicalization, it never changes non-zero values to zero or vice versa.
let v = self.state.pop1()?.into_int_value();
let res = self.builder.build_int_compare(
IntPredicate::NE,
v,
v.get_type().const_zero(),
"",
);
let res = self
.builder
.build_int_z_extend(res, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16AllTrue | Operator::I16x8AllTrue | Operator::I32x4AllTrue => {
// | Operator::I64x2AllTrue
let vec_ty = match op {
Operator::I8x16AllTrue => self.intrinsics.i8x16_ty,
Operator::I16x8AllTrue => self.intrinsics.i16x8_ty,
Operator::I32x4AllTrue => self.intrinsics.i32x4_ty,
// Operator::I64x2AllTrue => self.intrinsics.i64x2_ty,
_ => unreachable!(),
};
let (v, i) = self.state.pop1_extra()?;
let v = self.apply_pending_canonicalization(v, i).into_int_value();
let lane_int_ty = self.context.custom_width_int_type(vec_ty.get_size());
let vec = self
.builder
.build_bitcast(v, vec_ty, "vec")
.into_vector_value();
let mask = self.builder.build_int_compare(
IntPredicate::NE,
vec,
vec_ty.const_zero(),
"mask",
);
let cmask = self
.builder
.build_bitcast(mask, lane_int_ty, "cmask")
.into_int_value();
let res = self.builder.build_int_compare(
IntPredicate::EQ,
cmask,
lane_int_ty.const_int(std::u64::MAX, true),
"",
);
let res = self
.builder
.build_int_z_extend(res, self.intrinsics.i32_ty, "");
self.state.push1_extra(
res,
ExtraInfo::arithmetic_f32() | ExtraInfo::arithmetic_f64(),
);
}
Operator::I8x16ExtractLaneS { lane } => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i8x16(v, i);
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self
.builder
.build_extract_element(v, idx, "")
.into_int_value();
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I8x16ExtractLaneU { lane } => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i8x16(v, i);
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self
.builder
.build_extract_element(v, idx, "")
.into_int_value();
let res = self
.builder
.build_int_z_extend(res, self.intrinsics.i32_ty, "");
self.state.push1_extra(res, ExtraInfo::arithmetic_f32());
}
Operator::I16x8ExtractLaneS { lane } => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i16x8(v, i);
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self
.builder
.build_extract_element(v, idx, "")
.into_int_value();
let res = self
.builder
.build_int_s_extend(res, self.intrinsics.i32_ty, "");
self.state.push1(res);
}
Operator::I16x8ExtractLaneU { lane } => {
let (v, i) = self.state.pop1_extra()?;
let (v, _) = self.v128_into_i16x8(v, i);
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self
.builder
.build_extract_element(v, idx, "")
.into_int_value();
let res = self
.builder
.build_int_z_extend(res, self.intrinsics.i32_ty, "");
self.state.push1_extra(res, ExtraInfo::arithmetic_f32());
}
Operator::I32x4ExtractLane { lane } => {
let (v, i) = self.state.pop1_extra()?;
let (v, i) = self.v128_into_i32x4(v, i);
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_extract_element(v, idx, "");
self.state.push1_extra(res, i);
}
Operator::I64x2ExtractLane { lane } => {
let (v, i) = self.state.pop1_extra()?;
let (v, i) = self.v128_into_i64x2(v, i);
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_extract_element(v, idx, "");
self.state.push1_extra(res, i);
}
Operator::F32x4ExtractLane { lane } => {
let (v, i) = self.state.pop1_extra()?;
let (v, i) = self.v128_into_f32x4(v, i);
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_extract_element(v, idx, "");
self.state.push1_extra(res, i);
}
Operator::F64x2ExtractLane { lane } => {
let (v, i) = self.state.pop1_extra()?;
let (v, i) = self.v128_into_f64x2(v, i);
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_extract_element(v, idx, "");
self.state.push1_extra(res, i);
}
Operator::I8x16ReplaceLane { lane } => {
let ((v1, i1), (v2, _)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i8x16(v1, i1);
let v2 = v2.into_int_value();
let v2 = self.builder.build_int_cast(v2, self.intrinsics.i8_ty, "");
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_insert_element(v1, v2, idx, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I16x8ReplaceLane { lane } => {
let ((v1, i1), (v2, _)) = self.state.pop2_extra()?;
let (v1, _) = self.v128_into_i16x8(v1, i1);
let v2 = v2.into_int_value();
let v2 = self.builder.build_int_cast(v2, self.intrinsics.i16_ty, "");
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_insert_element(v1, v2, idx, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I32x4ReplaceLane { lane } => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_i32x4(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let i2 = i2.strip_pending();
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_insert_element(v1, v2, idx, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state
.push1_extra(res, i1 & i2 & ExtraInfo::arithmetic_f32());
}
Operator::I64x2ReplaceLane { lane } => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_i64x2(v1, i1);
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = v2.into_int_value();
let i2 = i2.strip_pending();
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_insert_element(v1, v2, idx, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state
.push1_extra(res, i1 & i2 & ExtraInfo::arithmetic_f64());
}
Operator::F32x4ReplaceLane { lane } => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f32x4(v1, i1);
let push_pending_f32_nan_to_result =
i1.has_pending_f32_nan() && i2.has_pending_f32_nan();
let (v1, v2) = if !push_pending_f32_nan_to_result {
(
self.apply_pending_canonicalization(v1.as_basic_value_enum(), i1)
.into_vector_value(),
self.apply_pending_canonicalization(v2.as_basic_value_enum(), i2)
.into_float_value(),
)
} else {
(v1, v2.into_float_value())
};
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_insert_element(v1, v2, idx, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
let info = if push_pending_f32_nan_to_result {
ExtraInfo::pending_f32_nan()
} else {
i1.strip_pending() & i2.strip_pending()
};
self.state.push1_extra(res, info);
}
Operator::F64x2ReplaceLane { lane } => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let (v1, i1) = self.v128_into_f64x2(v1, i1);
let push_pending_f64_nan_to_result =
i1.has_pending_f64_nan() && i2.has_pending_f64_nan();
let (v1, v2) = if !push_pending_f64_nan_to_result {
(
self.apply_pending_canonicalization(v1.as_basic_value_enum(), i1)
.into_vector_value(),
self.apply_pending_canonicalization(v2.as_basic_value_enum(), i2)
.into_float_value(),
)
} else {
(v1, v2.into_float_value())
};
let idx = self.intrinsics.i32_ty.const_int(lane.into(), false);
let res = self.builder.build_insert_element(v1, v2, idx, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
let info = if push_pending_f64_nan_to_result {
ExtraInfo::pending_f64_nan()
} else {
i1.strip_pending() & i2.strip_pending()
};
self.state.push1_extra(res, info);
}
Operator::I8x16Swizzle => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v1 = self
.builder
.build_bitcast(v1, self.intrinsics.i8x16_ty, "")
.into_vector_value();
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = self
.builder
.build_bitcast(v2, self.intrinsics.i8x16_ty, "")
.into_vector_value();
let lanes = self.intrinsics.i8_ty.const_int(16, false);
let lanes =
self.splat_vector(lanes.as_basic_value_enum(), self.intrinsics.i8x16_ty);
let mut res = self.intrinsics.i8x16_ty.get_undef();
let idx_out_of_range = self.builder.build_int_compare(
IntPredicate::UGE,
v2,
lanes,
"idx_out_of_range",
);
let idx_clamped = self
.builder
.build_select(
idx_out_of_range,
self.intrinsics.i8x16_ty.const_zero(),
v2,
"idx_clamped",
)
.into_vector_value();
for i in 0..16 {
let idx = self
.builder
.build_extract_element(
idx_clamped,
self.intrinsics.i32_ty.const_int(i, false),
"idx",
)
.into_int_value();
let replace_with_zero = self
.builder
.build_extract_element(
idx_out_of_range,
self.intrinsics.i32_ty.const_int(i, false),
"replace_with_zero",
)
.into_int_value();
let elem = self
.builder
.build_extract_element(v1, idx, "elem")
.into_int_value();
let elem_or_zero = self.builder.build_select(
replace_with_zero,
self.intrinsics.i8_zero,
elem,
"elem_or_zero",
);
res = self.builder.build_insert_element(
res,
elem_or_zero,
self.intrinsics.i32_ty.const_int(i, false),
"",
);
}
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::I8x16Shuffle { lanes } => {
let ((v1, i1), (v2, i2)) = self.state.pop2_extra()?;
let v1 = self.apply_pending_canonicalization(v1, i1);
let v1 = self
.builder
.build_bitcast(v1, self.intrinsics.i8x16_ty, "")
.into_vector_value();
let v2 = self.apply_pending_canonicalization(v2, i2);
let v2 = self
.builder
.build_bitcast(v2, self.intrinsics.i8x16_ty, "")
.into_vector_value();
let mask = VectorType::const_vector(
lanes
.iter()
.map(|l| self.intrinsics.i32_ty.const_int((*l).into(), false))
.collect::<Vec<IntValue>>()
.as_slice(),
);
let res = self.builder.build_shuffle_vector(v1, v2, mask, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load8x8S { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let v = self.builder.build_load(effective_address, "");
let v = self
.builder
.build_bitcast(v, self.intrinsics.i8_ty.vec_type(8), "")
.into_vector_value();
let res = self
.builder
.build_int_s_extend(v, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load8x8U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let v = self.builder.build_load(effective_address, "");
let v = self
.builder
.build_bitcast(v, self.intrinsics.i8_ty.vec_type(8), "")
.into_vector_value();
let res = self
.builder
.build_int_z_extend(v, self.intrinsics.i16x8_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load16x4S { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let v = self.builder.build_load(effective_address, "");
let v = self
.builder
.build_bitcast(v, self.intrinsics.i16_ty.vec_type(4), "")
.into_vector_value();
let res = self
.builder
.build_int_s_extend(v, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load16x4U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let v = self.builder.build_load(effective_address, "");
let v = self
.builder
.build_bitcast(v, self.intrinsics.i16_ty.vec_type(4), "")
.into_vector_value();
let res = self
.builder
.build_int_z_extend(v, self.intrinsics.i32x4_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load32x2S { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let v = self.builder.build_load(effective_address, "");
let v = self
.builder
.build_bitcast(v, self.intrinsics.i32_ty.vec_type(2), "")
.into_vector_value();
let res = self
.builder
.build_int_s_extend(v, self.intrinsics.i64x2_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load32x2U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let v = self.builder.build_load(effective_address, "");
let v = self
.builder
.build_bitcast(v, self.intrinsics.i32_ty.vec_type(2), "")
.into_vector_value();
let res = self
.builder
.build_int_z_extend(v, self.intrinsics.i64x2_ty, "");
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load32Zero { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
let elem = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
elem.as_instruction_value().unwrap(),
)?;
let res = self.builder.build_int_z_extend(
elem.into_int_value(),
self.intrinsics.i128_ty,
"",
);
self.state.push1(res);
}
Operator::V128Load64Zero { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let elem = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
elem.as_instruction_value().unwrap(),
)?;
let res = self.builder.build_int_z_extend(
elem.into_int_value(),
self.intrinsics.i128_ty,
"",
);
self.state.push1(res);
}
Operator::V128Load8Splat { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
let elem = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
elem.as_instruction_value().unwrap(),
)?;
let res = self.splat_vector(elem, self.intrinsics.i8x16_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load16Splat { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
let elem = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
elem.as_instruction_value().unwrap(),
)?;
let res = self.splat_vector(elem, self.intrinsics.i16x8_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load32Splat { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
let elem = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
elem.as_instruction_value().unwrap(),
)?;
let res = self.splat_vector(elem, self.intrinsics.i32x4_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::V128Load64Splat { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
let elem = self.builder.build_load(effective_address, "");
self.annotate_user_memaccess(
memory_index,
memarg,
1,
elem.as_instruction_value().unwrap(),
)?;
let res = self.splat_vector(elem, self.intrinsics.i64x2_ty);
let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, "");
self.state.push1(res);
}
Operator::AtomicFence { flags: _ } => {
// Fence is a nop.
//
// Fence was added to preserve information about fences from
// source languages. If in the future Wasm extends the memory
// model, and if we hadn't recorded what fences used to be there,
// it would lead to data races that weren't present in the
// original source language.
}
Operator::I32AtomicLoad { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let result = self.builder.build_load(effective_address, "");
let load = result.as_instruction_value().unwrap();
self.annotate_user_memaccess(memory_index, memarg, 4, load)?;
load.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
self.state.push1(result);
}
Operator::I64AtomicLoad { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let result = self.builder.build_load(effective_address, "");
let load = result.as_instruction_value().unwrap();
self.annotate_user_memaccess(memory_index, memarg, 8, load)?;
load.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
self.state.push1(result);
}
Operator::I32AtomicLoad8U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_result = self
.builder
.build_load(effective_address, "")
.into_int_value();
let load = narrow_result.as_instruction_value().unwrap();
self.annotate_user_memaccess(memory_index, memarg, 1, load)?;
load.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
let result =
self.builder
.build_int_z_extend(narrow_result, self.intrinsics.i32_ty, "");
self.state.push1_extra(result, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicLoad16U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_result = self
.builder
.build_load(effective_address, "")
.into_int_value();
let load = narrow_result.as_instruction_value().unwrap();
self.annotate_user_memaccess(memory_index, memarg, 2, load)?;
load.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
let result =
self.builder
.build_int_z_extend(narrow_result, self.intrinsics.i32_ty, "");
self.state.push1_extra(result, ExtraInfo::arithmetic_f32());
}
Operator::I64AtomicLoad8U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_result = self
.builder
.build_load(effective_address, "")
.into_int_value();
let load = narrow_result.as_instruction_value().unwrap();
self.annotate_user_memaccess(memory_index, memarg, 1, load)?;
load.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
let result =
self.builder
.build_int_z_extend(narrow_result, self.intrinsics.i64_ty, "");
self.state.push1_extra(result, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicLoad16U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_result = self
.builder
.build_load(effective_address, "")
.into_int_value();
let load = narrow_result.as_instruction_value().unwrap();
self.annotate_user_memaccess(memory_index, memarg, 2, load)?;
load.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
let result =
self.builder
.build_int_z_extend(narrow_result, self.intrinsics.i64_ty, "");
self.state.push1_extra(result, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicLoad32U { ref memarg } => {
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_result = self
.builder
.build_load(effective_address, "")
.into_int_value();
let load = narrow_result.as_instruction_value().unwrap();
self.annotate_user_memaccess(memory_index, memarg, 4, load)?;
load.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
let result =
self.builder
.build_int_z_extend(narrow_result, self.intrinsics.i64_ty, "");
self.state.push1_extra(result, ExtraInfo::arithmetic_f64());
}
Operator::I32AtomicStore { ref memarg } => {
let value = self.state.pop1()?;
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let store = self.builder.build_store(effective_address, value);
self.annotate_user_memaccess(memory_index, memarg, 4, store)?;
store
.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
}
Operator::I64AtomicStore { ref memarg } => {
let value = self.state.pop1()?;
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let store = self.builder.build_store(effective_address, value);
self.annotate_user_memaccess(memory_index, memarg, 8, store)?;
store
.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
}
Operator::I32AtomicStore8 { ref memarg } | Operator::I64AtomicStore8 { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let store = self.builder.build_store(effective_address, narrow_value);
self.annotate_user_memaccess(memory_index, memarg, 1, store)?;
store
.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
}
Operator::I32AtomicStore16 { ref memarg }
| Operator::I64AtomicStore16 { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let store = self.builder.build_store(effective_address, narrow_value);
self.annotate_user_memaccess(memory_index, memarg, 2, store)?;
store
.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
}
Operator::I64AtomicStore32 { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let store = self.builder.build_store(effective_address, narrow_value);
self.annotate_user_memaccess(memory_index, memarg, 4, store)?;
store
.set_atomic_ordering(AtomicOrdering::SequentiallyConsistent)
.unwrap();
}
Operator::I32AtomicRmw8AddU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Add,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
tbaa_label(
&self.module,
self.intrinsics,
format!("memory {}", memory_index.as_u32()),
old.as_instruction_value().unwrap(),
);
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmw16AddU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Add,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
tbaa_label(
&self.module,
self.intrinsics,
format!("memory {}", memory_index.as_u32()),
old.as_instruction_value().unwrap(),
);
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmwAdd { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Add,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
tbaa_label(
&self.module,
self.intrinsics,
format!("memory {}", memory_index.as_u32()),
old.as_instruction_value().unwrap(),
);
self.state.push1(old);
}
Operator::I64AtomicRmw8AddU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Add,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw16AddU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Add,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw32AddU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Add,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmwAdd { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Add,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I32AtomicRmw8SubU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Sub,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmw16SubU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Sub,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmwSub { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Sub,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I64AtomicRmw8SubU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Sub,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I64AtomicRmw16SubU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Sub,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw32SubU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Sub,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmwSub { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Sub,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I32AtomicRmw8AndU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::And,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmw16AndU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::And,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmwAnd { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::And,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I64AtomicRmw8AndU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::And,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw16AndU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::And,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw32AndU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::And,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmwAnd { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::And,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I32AtomicRmw8OrU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Or,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmw16OrU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Or,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmwOr { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Or,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I64AtomicRmw8OrU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Or,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw16OrU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Or,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw32OrU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Or,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmwOr { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Or,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I32AtomicRmw8XorU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xor,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmw16XorU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xor,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmwXor { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xor,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I64AtomicRmw8XorU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xor,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw16XorU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xor,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw32XorU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xor,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmwXor { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xor,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I32AtomicRmw8XchgU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xchg,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmw16XchgU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xchg,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmwXchg { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xchg,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I64AtomicRmw8XchgU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xchg,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw16XchgU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xchg,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw32XchgU { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_value =
self.builder
.build_int_truncate(value, self.intrinsics.i32_ty, "");
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xchg,
effective_address,
narrow_value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmwXchg { ref memarg } => {
let value = self.state.pop1()?.into_int_value();
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_atomicrmw(
AtomicRMWBinOp::Xchg,
effective_address,
value,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
self.state.push1(old);
}
Operator::I32AtomicRmw8CmpxchgU { ref memarg } => {
let ((cmp, cmp_info), (new, new_info)) = self.state.pop2_extra()?;
let cmp = self.apply_pending_canonicalization(cmp, cmp_info);
let new = self.apply_pending_canonicalization(new, new_info);
let (cmp, new) = (cmp.into_int_value(), new.into_int_value());
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_cmp = self
.builder
.build_int_truncate(cmp, self.intrinsics.i8_ty, "");
let narrow_new = self
.builder
.build_int_truncate(new, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_cmpxchg(
effective_address,
narrow_cmp,
narrow_new,
AtomicOrdering::SequentiallyConsistent,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_extract_value(old, 0, "")
.unwrap()
.into_int_value();
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmw16CmpxchgU { ref memarg } => {
let ((cmp, cmp_info), (new, new_info)) = self.state.pop2_extra()?;
let cmp = self.apply_pending_canonicalization(cmp, cmp_info);
let new = self.apply_pending_canonicalization(new, new_info);
let (cmp, new) = (cmp.into_int_value(), new.into_int_value());
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_cmp = self
.builder
.build_int_truncate(cmp, self.intrinsics.i16_ty, "");
let narrow_new = self
.builder
.build_int_truncate(new, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_cmpxchg(
effective_address,
narrow_cmp,
narrow_new,
AtomicOrdering::SequentiallyConsistent,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_extract_value(old, 0, "")
.unwrap()
.into_int_value();
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i32_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f32());
}
Operator::I32AtomicRmwCmpxchg { ref memarg } => {
let ((cmp, cmp_info), (new, new_info)) = self.state.pop2_extra()?;
let cmp = self.apply_pending_canonicalization(cmp, cmp_info);
let new = self.apply_pending_canonicalization(new, new_info);
let (cmp, new) = (cmp.into_int_value(), new.into_int_value());
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_cmpxchg(
effective_address,
cmp,
new,
AtomicOrdering::SequentiallyConsistent,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self.builder.build_extract_value(old, 0, "").unwrap();
self.state.push1(old);
}
Operator::I64AtomicRmw8CmpxchgU { ref memarg } => {
let ((cmp, cmp_info), (new, new_info)) = self.state.pop2_extra()?;
let cmp = self.apply_pending_canonicalization(cmp, cmp_info);
let new = self.apply_pending_canonicalization(new, new_info);
let (cmp, new) = (cmp.into_int_value(), new.into_int_value());
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i8_ptr_ty,
offset,
1,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_cmp = self
.builder
.build_int_truncate(cmp, self.intrinsics.i8_ty, "");
let narrow_new = self
.builder
.build_int_truncate(new, self.intrinsics.i8_ty, "");
let old = self
.builder
.build_cmpxchg(
effective_address,
narrow_cmp,
narrow_new,
AtomicOrdering::SequentiallyConsistent,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_extract_value(old, 0, "")
.unwrap()
.into_int_value();
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw16CmpxchgU { ref memarg } => {
let ((cmp, cmp_info), (new, new_info)) = self.state.pop2_extra()?;
let cmp = self.apply_pending_canonicalization(cmp, cmp_info);
let new = self.apply_pending_canonicalization(new, new_info);
let (cmp, new) = (cmp.into_int_value(), new.into_int_value());
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i16_ptr_ty,
offset,
2,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_cmp = self
.builder
.build_int_truncate(cmp, self.intrinsics.i16_ty, "");
let narrow_new = self
.builder
.build_int_truncate(new, self.intrinsics.i16_ty, "");
let old = self
.builder
.build_cmpxchg(
effective_address,
narrow_cmp,
narrow_new,
AtomicOrdering::SequentiallyConsistent,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_extract_value(old, 0, "")
.unwrap()
.into_int_value();
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmw32CmpxchgU { ref memarg } => {
let ((cmp, cmp_info), (new, new_info)) = self.state.pop2_extra()?;
let cmp = self.apply_pending_canonicalization(cmp, cmp_info);
let new = self.apply_pending_canonicalization(new, new_info);
let (cmp, new) = (cmp.into_int_value(), new.into_int_value());
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i32_ptr_ty,
offset,
4,
)?;
self.trap_if_misaligned(memarg, effective_address);
let narrow_cmp = self
.builder
.build_int_truncate(cmp, self.intrinsics.i32_ty, "");
let narrow_new = self
.builder
.build_int_truncate(new, self.intrinsics.i32_ty, "");
let old = self
.builder
.build_cmpxchg(
effective_address,
narrow_cmp,
narrow_new,
AtomicOrdering::SequentiallyConsistent,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self
.builder
.build_extract_value(old, 0, "")
.unwrap()
.into_int_value();
let old = self
.builder
.build_int_z_extend(old, self.intrinsics.i64_ty, "");
self.state.push1_extra(old, ExtraInfo::arithmetic_f64());
}
Operator::I64AtomicRmwCmpxchg { ref memarg } => {
let ((cmp, cmp_info), (new, new_info)) = self.state.pop2_extra()?;
let cmp = self.apply_pending_canonicalization(cmp, cmp_info);
let new = self.apply_pending_canonicalization(new, new_info);
let (cmp, new) = (cmp.into_int_value(), new.into_int_value());
let offset = self.state.pop1()?.into_int_value();
let memory_index = MemoryIndex::from_u32(0);
let effective_address = self.resolve_memory_ptr(
memory_index,
memarg,
self.intrinsics.i64_ptr_ty,
offset,
8,
)?;
self.trap_if_misaligned(memarg, effective_address);
let old = self
.builder
.build_cmpxchg(
effective_address,
cmp,
new,
AtomicOrdering::SequentiallyConsistent,
AtomicOrdering::SequentiallyConsistent,
)
.unwrap();
self.annotate_user_memaccess(
memory_index,
memarg,
0,
old.as_instruction_value().unwrap(),
)?;
let old = self.builder.build_extract_value(old, 0, "").unwrap();
self.state.push1(old);
}
Operator::MemoryGrow { mem, mem_byte: _ } => {
let memory_index = MemoryIndex::from_u32(mem);
let delta = self.state.pop1()?;
let grow_fn_ptr = self.ctx.memory_grow(memory_index, self.intrinsics);
let grow = self.builder.build_call(
grow_fn_ptr,
&[
vmctx.as_basic_value_enum(),
delta,
self.intrinsics
.i32_ty
.const_int(mem.into(), false)
.as_basic_value_enum(),
],
"",
);
self.state.push1(grow.try_as_basic_value().left().unwrap());
}
Operator::MemorySize { mem, mem_byte: _ } => {
let memory_index = MemoryIndex::from_u32(mem);
let size_fn_ptr = self.ctx.memory_size(memory_index, self.intrinsics);
let size = self.builder.build_call(
size_fn_ptr,
&[
vmctx.as_basic_value_enum(),
self.intrinsics
.i32_ty
.const_int(mem.into(), false)
.as_basic_value_enum(),
],
"",
);
size.add_attribute(AttributeLoc::Function, self.intrinsics.readonly);
self.state.push1(size.try_as_basic_value().left().unwrap());
}
_ => {
return Err(CompileError::Codegen(format!(
"Operator {:?} unimplemented",
op
)));
}
}
Ok(())
}
}
fn is_f32_arithmetic(bits: u32) -> bool {
// Mask off sign bit.
let bits = bits & 0x7FFF_FFFF;
bits < 0x7FC0_0000
}
fn is_f64_arithmetic(bits: u64) -> bool {
// Mask off sign bit.
let bits = bits & 0x7FFF_FFFF_FFFF_FFFF;
bits < 0x7FF8_0000_0000_0000
}
// Constants for the bounds of truncation operations. These are the least or
// greatest exact floats in either f32 or f64 representation
// greater-than-or-equal-to (for least) or less-than-or-equal-to (for greatest)
// the i32 or i64 or u32 or u64 min (for least) or max (for greatest), when
// rounding towards zero.
/// Least Exact Float (32 bits) greater-than-or-equal-to i32::MIN when rounding towards zero.
const LEF32_GEQ_I32_MIN: u64 = std::i32::MIN as u64;
/// Greatest Exact Float (32 bits) less-than-or-equal-to i32::MAX when rounding towards zero.
const GEF32_LEQ_I32_MAX: u64 = 2147483520; // bits as f32: 0x4eff_ffff
/// Least Exact Float (64 bits) greater-than-or-equal-to i32::MIN when rounding towards zero.
const LEF64_GEQ_I32_MIN: u64 = std::i32::MIN as u64;
/// Greatest Exact Float (64 bits) less-than-or-equal-to i32::MAX when rounding towards zero.
const GEF64_LEQ_I32_MAX: u64 = std::i32::MAX as u64;
/// Least Exact Float (32 bits) greater-than-or-equal-to u32::MIN when rounding towards zero.
const LEF32_GEQ_U32_MIN: u64 = std::u32::MIN as u64;
/// Greatest Exact Float (32 bits) less-than-or-equal-to u32::MAX when rounding towards zero.
const GEF32_LEQ_U32_MAX: u64 = 4294967040; // bits as f32: 0x4f7f_ffff
/// Least Exact Float (64 bits) greater-than-or-equal-to u32::MIN when rounding towards zero.
const LEF64_GEQ_U32_MIN: u64 = std::u32::MIN as u64;
/// Greatest Exact Float (64 bits) less-than-or-equal-to u32::MAX when rounding towards zero.
const GEF64_LEQ_U32_MAX: u64 = 4294967295; // bits as f64: 0x41ef_ffff_ffff_ffff
/// Least Exact Float (32 bits) greater-than-or-equal-to i64::MIN when rounding towards zero.
const LEF32_GEQ_I64_MIN: u64 = std::i64::MIN as u64;
/// Greatest Exact Float (32 bits) less-than-or-equal-to i64::MAX when rounding towards zero.
const GEF32_LEQ_I64_MAX: u64 = 9223371487098961920; // bits as f32: 0x5eff_ffff
/// Least Exact Float (64 bits) greater-than-or-equal-to i64::MIN when rounding towards zero.
const LEF64_GEQ_I64_MIN: u64 = std::i64::MIN as u64;
/// Greatest Exact Float (64 bits) less-than-or-equal-to i64::MAX when rounding towards zero.
const GEF64_LEQ_I64_MAX: u64 = 9223372036854774784; // bits as f64: 0x43df_ffff_ffff_ffff
/// Least Exact Float (32 bits) greater-than-or-equal-to u64::MIN when rounding towards zero.
const LEF32_GEQ_U64_MIN: u64 = std::u64::MIN;
/// Greatest Exact Float (32 bits) less-than-or-equal-to u64::MAX when rounding towards zero.
const GEF32_LEQ_U64_MAX: u64 = 18446742974197923840; // bits as f32: 0x5f7f_ffff
/// Least Exact Float (64 bits) greater-than-or-equal-to u64::MIN when rounding towards zero.
const LEF64_GEQ_U64_MIN: u64 = std::u64::MIN;
/// Greatest Exact Float (64 bits) less-than-or-equal-to u64::MAX when rounding towards zero.
const GEF64_LEQ_U64_MAX: u64 = 18446744073709549568; // bits as f64: 0x43ef_ffff_ffff_ffff
| 44.482953 | 144 | 0.46434 |
f8f300c639821c54a1b199e08cf9aec16fcad6d9 | 1,674 | use crate::auth::token_response::Tokens;
use actix_web::client::{Client, ClientRequest};
use actix_web::http::Uri;
use serde::de::DeserializeOwned;
// re-export parameter class and timerange
pub mod charts;
pub mod params;
pub use params::*;
const PERSONALIZATION_ENDPOINT: &'static str = "https://api.spotify.com/v1/me/top/";
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum PersonalizationData {
Artists,
Tracks,
}
impl PersonalizationData {
fn get_endpoint_path(self) -> &'static str {
use PersonalizationData::*;
match self {
Artists => "artists",
Tracks => "tracks",
}
}
/// Get the endpoint of Spotify's API.
pub fn get_endpoint(self) -> Uri {
format!("{}{}", PERSONALIZATION_ENDPOINT, self.get_endpoint_path())
.parse()
.unwrap()
}
/// Make a request to Spotify to get data.
pub fn make_req(self, tokens: &Tokens, params: &PersonalizationParams) -> ClientRequest {
let client = Client::default();
client
.get(self.get_endpoint())
.timeout(std::time::Duration::new(30, 0))
.bearer_auth(&tokens.access_token)
.query(params)
.unwrap()
}
/// Get a spotify data as deserialized json.
pub async fn get_data<T: DeserializeOwned>(
self,
tokens: &Tokens,
params: &PersonalizationParams,
) -> Result<T, String> {
self.make_req(tokens, params)
.send()
.await
.map_err(|err| err.to_string())?
.json::<T>()
.await
.map_err(|e| e.to_string())
}
}
| 27.442623 | 93 | 0.581243 |
72fc5e43579c1d35e676fa27aa79f3ce0a3cb509 | 36,585 | // @generated SignedSource<<5017de08d0f6489d8f0a1d320ef46e2d>>
mod compile_relay_artifacts;
use compile_relay_artifacts::transform_fixture;
use fixture_tests::test_fixture;
#[test]
fn client_conditions() {
let input = include_str!("compile_relay_artifacts/fixtures/client-conditions.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-conditions.expected");
test_fixture(transform_fixture, "client-conditions.graphql", "compile_relay_artifacts/fixtures/client-conditions.expected", input, expected);
}
#[test]
fn client_fields_in_inline_fragments() {
let input = include_str!("compile_relay_artifacts/fixtures/client-fields-in-inline-fragments.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-fields-in-inline-fragments.expected");
test_fixture(transform_fixture, "client-fields-in-inline-fragments.graphql", "compile_relay_artifacts/fixtures/client-fields-in-inline-fragments.expected", input, expected);
}
#[test]
fn client_fields_of_client_type() {
let input = include_str!("compile_relay_artifacts/fixtures/client-fields-of-client-type.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-fields-of-client-type.expected");
test_fixture(transform_fixture, "client-fields-of-client-type.graphql", "compile_relay_artifacts/fixtures/client-fields-of-client-type.expected", input, expected);
}
#[test]
fn client_fields_on_roots() {
let input = include_str!("compile_relay_artifacts/fixtures/client-fields-on-roots.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-fields-on-roots.expected");
test_fixture(transform_fixture, "client-fields-on-roots.graphql", "compile_relay_artifacts/fixtures/client-fields-on-roots.expected", input, expected);
}
#[test]
fn client_fragment_spreads() {
let input = include_str!("compile_relay_artifacts/fixtures/client-fragment-spreads.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-fragment-spreads.expected");
test_fixture(transform_fixture, "client-fragment-spreads.graphql", "compile_relay_artifacts/fixtures/client-fragment-spreads.expected", input, expected);
}
#[test]
fn client_fragment_spreads_in_query() {
let input = include_str!("compile_relay_artifacts/fixtures/client-fragment-spreads-in-query.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-fragment-spreads-in-query.expected");
test_fixture(transform_fixture, "client-fragment-spreads-in-query.graphql", "compile_relay_artifacts/fixtures/client-fragment-spreads-in-query.expected", input, expected);
}
#[test]
fn client_inline_fragments() {
let input = include_str!("compile_relay_artifacts/fixtures/client-inline-fragments.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-inline-fragments.expected");
test_fixture(transform_fixture, "client-inline-fragments.graphql", "compile_relay_artifacts/fixtures/client-inline-fragments.expected", input, expected);
}
#[test]
fn client_inline_fragments_in_query() {
let input = include_str!("compile_relay_artifacts/fixtures/client-inline-fragments-in-query.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-inline-fragments-in-query.expected");
test_fixture(transform_fixture, "client-inline-fragments-in-query.graphql", "compile_relay_artifacts/fixtures/client-inline-fragments-in-query.expected", input, expected);
}
#[test]
fn client_linked_fields() {
let input = include_str!("compile_relay_artifacts/fixtures/client-linked-fields.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-linked-fields.expected");
test_fixture(transform_fixture, "client-linked-fields.graphql", "compile_relay_artifacts/fixtures/client-linked-fields.expected", input, expected);
}
#[test]
fn client_scalar_fields() {
let input = include_str!("compile_relay_artifacts/fixtures/client-scalar-fields.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/client-scalar-fields.expected");
test_fixture(transform_fixture, "client-scalar-fields.graphql", "compile_relay_artifacts/fixtures/client-scalar-fields.expected", input, expected);
}
#[test]
fn complex_arguments() {
let input = include_str!("compile_relay_artifacts/fixtures/complex-arguments.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/complex-arguments.expected");
test_fixture(transform_fixture, "complex-arguments.graphql", "compile_relay_artifacts/fixtures/complex-arguments.expected", input, expected);
}
#[test]
fn complex_arguments_in_list() {
let input = include_str!("compile_relay_artifacts/fixtures/complex-arguments-in-list.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/complex-arguments-in-list.expected");
test_fixture(transform_fixture, "complex-arguments-in-list.graphql", "compile_relay_artifacts/fixtures/complex-arguments-in-list.expected", input, expected);
}
#[test]
fn complex_arguments_with_mutliple_variables() {
let input = include_str!("compile_relay_artifacts/fixtures/complex-arguments-with-mutliple-variables.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/complex-arguments-with-mutliple-variables.expected");
test_fixture(transform_fixture, "complex-arguments-with-mutliple-variables.graphql", "compile_relay_artifacts/fixtures/complex-arguments-with-mutliple-variables.expected", input, expected);
}
#[test]
fn connection() {
let input = include_str!("compile_relay_artifacts/fixtures/connection.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/connection.expected");
test_fixture(transform_fixture, "connection.graphql", "compile_relay_artifacts/fixtures/connection.expected", input, expected);
}
#[test]
fn connection_with_aliased_edges_page_info() {
let input = include_str!("compile_relay_artifacts/fixtures/connection-with-aliased-edges-page_info.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/connection-with-aliased-edges-page_info.expected");
test_fixture(transform_fixture, "connection-with-aliased-edges-page_info.graphql", "compile_relay_artifacts/fixtures/connection-with-aliased-edges-page_info.expected", input, expected);
}
#[test]
fn connection_with_dynamic_key() {
let input = include_str!("compile_relay_artifacts/fixtures/connection-with-dynamic-key.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/connection-with-dynamic-key.expected");
test_fixture(transform_fixture, "connection-with-dynamic-key.graphql", "compile_relay_artifacts/fixtures/connection-with-dynamic-key.expected", input, expected);
}
#[test]
fn connection_with_dynamic_key_missing_variable_definition_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/connection-with-dynamic-key-missing-variable-definition.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/connection-with-dynamic-key-missing-variable-definition.invalid.expected");
test_fixture(transform_fixture, "connection-with-dynamic-key-missing-variable-definition.invalid.graphql", "compile_relay_artifacts/fixtures/connection-with-dynamic-key-missing-variable-definition.invalid.expected", input, expected);
}
#[test]
fn defer_multiple_fragments_same_parent() {
let input = include_str!("compile_relay_artifacts/fixtures/defer-multiple-fragments-same-parent.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/defer-multiple-fragments-same-parent.expected");
test_fixture(transform_fixture, "defer-multiple-fragments-same-parent.graphql", "compile_relay_artifacts/fixtures/defer-multiple-fragments-same-parent.expected", input, expected);
}
#[test]
fn explicit_null_argument() {
let input = include_str!("compile_relay_artifacts/fixtures/explicit-null-argument.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/explicit-null-argument.expected");
test_fixture(transform_fixture, "explicit-null-argument.graphql", "compile_relay_artifacts/fixtures/explicit-null-argument.expected", input, expected);
}
#[test]
fn false_positive_circular_fragment_reference_regression() {
let input = include_str!("compile_relay_artifacts/fixtures/false-positive-circular-fragment-reference-regression.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/false-positive-circular-fragment-reference-regression.expected");
test_fixture(transform_fixture, "false-positive-circular-fragment-reference-regression.graphql", "compile_relay_artifacts/fixtures/false-positive-circular-fragment-reference-regression.expected", input, expected);
}
#[test]
fn fragment_on_node_interface() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-on-node-interface.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-on-node-interface.expected");
test_fixture(transform_fixture, "fragment-on-node-interface.graphql", "compile_relay_artifacts/fixtures/fragment-on-node-interface.expected", input, expected);
}
#[test]
fn fragment_on_object_implementing_node_interface() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-on-object-implementing-node-interface.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-on-object-implementing-node-interface.expected");
test_fixture(transform_fixture, "fragment-on-object-implementing-node-interface.graphql", "compile_relay_artifacts/fixtures/fragment-on-object-implementing-node-interface.expected", input, expected);
}
#[test]
fn fragment_on_query() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-on-query.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-on-query.expected");
test_fixture(transform_fixture, "fragment-on-query.graphql", "compile_relay_artifacts/fixtures/fragment-on-query.expected", input, expected);
}
#[test]
fn fragment_on_query_with_cycle_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-on-query-with-cycle.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-on-query-with-cycle.invalid.expected");
test_fixture(transform_fixture, "fragment-on-query-with-cycle.invalid.graphql", "compile_relay_artifacts/fixtures/fragment-on-query-with-cycle.invalid.expected", input, expected);
}
#[test]
fn fragment_on_viewer() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-on-viewer.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-on-viewer.expected");
test_fixture(transform_fixture, "fragment-on-viewer.graphql", "compile_relay_artifacts/fixtures/fragment-on-viewer.expected", input, expected);
}
#[test]
fn fragment_with_defer_arguments() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-with-defer-arguments.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-with-defer-arguments.expected");
test_fixture(transform_fixture, "fragment-with-defer-arguments.graphql", "compile_relay_artifacts/fixtures/fragment-with-defer-arguments.expected", input, expected);
}
#[test]
fn fragment_with_defer_arguments_without_label() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-with-defer-arguments-without-label.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-with-defer-arguments-without-label.expected");
test_fixture(transform_fixture, "fragment-with-defer-arguments-without-label.graphql", "compile_relay_artifacts/fixtures/fragment-with-defer-arguments-without-label.expected", input, expected);
}
#[test]
fn fragment_with_defer_on_abstract_type() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-with-defer-on-abstract-type.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-with-defer-on-abstract-type.expected");
test_fixture(transform_fixture, "fragment-with-defer-on-abstract-type.graphql", "compile_relay_artifacts/fixtures/fragment-with-defer-on-abstract-type.expected", input, expected);
}
#[test]
fn fragment_with_defer_on_client_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-with-defer-on-client.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-with-defer-on-client.invalid.expected");
test_fixture(transform_fixture, "fragment-with-defer-on-client.invalid.graphql", "compile_relay_artifacts/fixtures/fragment-with-defer-on-client.invalid.expected", input, expected);
}
#[test]
fn fragment_with_match_directive() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-with-match-directive.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-with-match-directive.expected");
test_fixture(transform_fixture, "fragment-with-match-directive.graphql", "compile_relay_artifacts/fixtures/fragment-with-match-directive.expected", input, expected);
}
#[test]
fn fragment_with_stream() {
let input = include_str!("compile_relay_artifacts/fixtures/fragment-with-stream.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/fragment-with-stream.expected");
test_fixture(transform_fixture, "fragment-with-stream.graphql", "compile_relay_artifacts/fixtures/fragment-with-stream.expected", input, expected);
}
#[test]
fn id_as_alias_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/id-as-alias.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/id-as-alias.invalid.expected");
test_fixture(transform_fixture, "id-as-alias.invalid.graphql", "compile_relay_artifacts/fixtures/id-as-alias.invalid.expected", input, expected);
}
#[test]
fn inline_and_mask_are_incompatible_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/inline-and-mask-are-incompatible.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/inline-and-mask-are-incompatible.invalid.expected");
test_fixture(transform_fixture, "inline-and-mask-are-incompatible.invalid.graphql", "compile_relay_artifacts/fixtures/inline-and-mask-are-incompatible.invalid.expected", input, expected);
}
#[test]
fn inline_data_fragment() {
let input = include_str!("compile_relay_artifacts/fixtures/inline-data-fragment.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/inline-data-fragment.expected");
test_fixture(transform_fixture, "inline-data-fragment.graphql", "compile_relay_artifacts/fixtures/inline-data-fragment.expected", input, expected);
}
#[test]
fn inline_data_fragment_global_vars() {
let input = include_str!("compile_relay_artifacts/fixtures/inline-data-fragment-global-vars.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/inline-data-fragment-global-vars.expected");
test_fixture(transform_fixture, "inline-data-fragment-global-vars.graphql", "compile_relay_artifacts/fixtures/inline-data-fragment-global-vars.expected", input, expected);
}
#[test]
fn inline_data_fragment_local_args() {
let input = include_str!("compile_relay_artifacts/fixtures/inline-data-fragment-local-args.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/inline-data-fragment-local-args.expected");
test_fixture(transform_fixture, "inline-data-fragment-local-args.graphql", "compile_relay_artifacts/fixtures/inline-data-fragment-local-args.expected", input, expected);
}
#[test]
fn kitchen_sink() {
let input = include_str!("compile_relay_artifacts/fixtures/kitchen-sink.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/kitchen-sink.expected");
test_fixture(transform_fixture, "kitchen-sink.graphql", "compile_relay_artifacts/fixtures/kitchen-sink.expected", input, expected);
}
#[test]
fn linked_handle_field() {
let input = include_str!("compile_relay_artifacts/fixtures/linked-handle-field.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/linked-handle-field.expected");
test_fixture(transform_fixture, "linked-handle-field.graphql", "compile_relay_artifacts/fixtures/linked-handle-field.expected", input, expected);
}
#[test]
fn match_field_overlap_across_documents() {
let input = include_str!("compile_relay_artifacts/fixtures/match-field-overlap-across-documents.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/match-field-overlap-across-documents.expected");
test_fixture(transform_fixture, "match-field-overlap-across-documents.graphql", "compile_relay_artifacts/fixtures/match-field-overlap-across-documents.expected", input, expected);
}
#[test]
fn match_on_child_of_plural() {
let input = include_str!("compile_relay_artifacts/fixtures/match-on-child-of-plural.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/match-on-child-of-plural.expected");
test_fixture(transform_fixture, "match-on-child-of-plural.graphql", "compile_relay_artifacts/fixtures/match-on-child-of-plural.expected", input, expected);
}
#[test]
fn match_with_invalid_key_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/match-with-invalid-key.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/match-with-invalid-key.invalid.expected");
test_fixture(transform_fixture, "match-with-invalid-key.invalid.graphql", "compile_relay_artifacts/fixtures/match-with-invalid-key.invalid.expected", input, expected);
}
#[test]
fn match_with_variable_key_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/match-with-variable-key.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/match-with-variable-key.invalid.expected");
test_fixture(transform_fixture, "match-with-variable-key.invalid.graphql", "compile_relay_artifacts/fixtures/match-with-variable-key.invalid.expected", input, expected);
}
#[test]
fn missing_argument_on_field_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/missing-argument-on-field.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/missing-argument-on-field.invalid.expected");
test_fixture(transform_fixture, "missing-argument-on-field.invalid.graphql", "compile_relay_artifacts/fixtures/missing-argument-on-field.invalid.expected", input, expected);
}
#[test]
fn module_overlap_across_documents() {
let input = include_str!("compile_relay_artifacts/fixtures/module-overlap-across-documents.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/module-overlap-across-documents.expected");
test_fixture(transform_fixture, "module-overlap-across-documents.graphql", "compile_relay_artifacts/fixtures/module-overlap-across-documents.expected", input, expected);
}
#[test]
fn module_overlap_within_document_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/module-overlap-within-document.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/module-overlap-within-document.invalid.expected");
test_fixture(transform_fixture, "module-overlap-within-document.invalid.graphql", "compile_relay_artifacts/fixtures/module-overlap-within-document.invalid.expected", input, expected);
}
#[test]
fn multiple_modules_different_component_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/multiple-modules-different-component.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/multiple-modules-different-component.invalid.expected");
test_fixture(transform_fixture, "multiple-modules-different-component.invalid.graphql", "compile_relay_artifacts/fixtures/multiple-modules-different-component.invalid.expected", input, expected);
}
#[test]
fn multiple_modules_different_fragment_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/multiple-modules-different-fragment.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/multiple-modules-different-fragment.invalid.expected");
test_fixture(transform_fixture, "multiple-modules-different-fragment.invalid.graphql", "compile_relay_artifacts/fixtures/multiple-modules-different-fragment.invalid.expected", input, expected);
}
#[test]
fn multiple_modules_same_selections() {
let input = include_str!("compile_relay_artifacts/fixtures/multiple-modules-same-selections.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/multiple-modules-same-selections.expected");
test_fixture(transform_fixture, "multiple-modules-same-selections.graphql", "compile_relay_artifacts/fixtures/multiple-modules-same-selections.expected", input, expected);
}
#[test]
fn multiple_modules_with_key() {
let input = include_str!("compile_relay_artifacts/fixtures/multiple-modules-with-key.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/multiple-modules-with-key.expected");
test_fixture(transform_fixture, "multiple-modules-with-key.graphql", "compile_relay_artifacts/fixtures/multiple-modules-with-key.expected", input, expected);
}
#[test]
fn multiple_modules_without_key_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/multiple-modules-without-key.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/multiple-modules-without-key.invalid.expected");
test_fixture(transform_fixture, "multiple-modules-without-key.invalid.graphql", "compile_relay_artifacts/fixtures/multiple-modules-without-key.invalid.expected", input, expected);
}
#[test]
fn nested_conditions() {
let input = include_str!("compile_relay_artifacts/fixtures/nested_conditions.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/nested_conditions.expected");
test_fixture(transform_fixture, "nested_conditions.graphql", "compile_relay_artifacts/fixtures/nested_conditions.expected", input, expected);
}
#[test]
fn original_client_fields_test() {
let input = include_str!("compile_relay_artifacts/fixtures/original-client-fields-test.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/original-client-fields-test.expected");
test_fixture(transform_fixture, "original-client-fields-test.graphql", "compile_relay_artifacts/fixtures/original-client-fields-test.expected", input, expected);
}
#[test]
fn plural_fragment() {
let input = include_str!("compile_relay_artifacts/fixtures/plural-fragment.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/plural-fragment.expected");
test_fixture(transform_fixture, "plural-fragment.graphql", "compile_relay_artifacts/fixtures/plural-fragment.expected", input, expected);
}
#[test]
fn query_with_conditional_module() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-conditional-module.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-conditional-module.expected");
test_fixture(transform_fixture, "query-with-conditional-module.graphql", "compile_relay_artifacts/fixtures/query-with-conditional-module.expected", input, expected);
}
#[test]
fn query_with_fragment_variables() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-fragment-variables.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-fragment-variables.expected");
test_fixture(transform_fixture, "query-with-fragment-variables.graphql", "compile_relay_artifacts/fixtures/query-with-fragment-variables.expected", input, expected);
}
#[test]
fn query_with_match_directive() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive.expected");
test_fixture(transform_fixture, "query-with-match-directive.graphql", "compile_relay_artifacts/fixtures/query-with-match-directive.expected", input, expected);
}
#[test]
fn query_with_match_directive_no_inline_experimental() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive-no-inline-experimental.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive-no-inline-experimental.expected");
test_fixture(transform_fixture, "query-with-match-directive-no-inline-experimental.graphql", "compile_relay_artifacts/fixtures/query-with-match-directive-no-inline-experimental.expected", input, expected);
}
#[test]
fn query_with_match_directive_no_modules_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive-no-modules.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive-no-modules.invalid.expected");
test_fixture(transform_fixture, "query-with-match-directive-no-modules.invalid.graphql", "compile_relay_artifacts/fixtures/query-with-match-directive-no-modules.invalid.expected", input, expected);
}
#[test]
fn query_with_match_directive_with_extra_argument() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive-with-extra-argument.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive-with-extra-argument.expected");
test_fixture(transform_fixture, "query-with-match-directive-with-extra-argument.graphql", "compile_relay_artifacts/fixtures/query-with-match-directive-with-extra-argument.expected", input, expected);
}
#[test]
fn query_with_match_directive_with_typename() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive-with-typename.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-match-directive-with-typename.expected");
test_fixture(transform_fixture, "query-with-match-directive-with-typename.graphql", "compile_relay_artifacts/fixtures/query-with-match-directive-with-typename.expected", input, expected);
}
#[test]
fn query_with_module_directive() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-module-directive.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-module-directive.expected");
test_fixture(transform_fixture, "query-with-module-directive.graphql", "compile_relay_artifacts/fixtures/query-with-module-directive.expected", input, expected);
}
#[test]
fn query_with_raw_response_type_directive() {
let input = include_str!("compile_relay_artifacts/fixtures/query-with-raw-response-type-directive.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/query-with-raw-response-type-directive.expected");
test_fixture(transform_fixture, "query-with-raw-response-type-directive.graphql", "compile_relay_artifacts/fixtures/query-with-raw-response-type-directive.expected", input, expected);
}
#[test]
fn refetchable_connection() {
let input = include_str!("compile_relay_artifacts/fixtures/refetchable-connection.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/refetchable-connection.expected");
test_fixture(transform_fixture, "refetchable-connection.graphql", "compile_relay_artifacts/fixtures/refetchable-connection.expected", input, expected);
}
#[test]
fn refetchable_connection_custom_handler() {
let input = include_str!("compile_relay_artifacts/fixtures/refetchable-connection-custom-handler.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/refetchable-connection-custom-handler.expected");
test_fixture(transform_fixture, "refetchable-connection-custom-handler.graphql", "compile_relay_artifacts/fixtures/refetchable-connection-custom-handler.expected", input, expected);
}
#[test]
fn refetchable_fragment_on_node_with_missing_id() {
let input = include_str!("compile_relay_artifacts/fixtures/refetchable-fragment-on-node-with-missing-id.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/refetchable-fragment-on-node-with-missing-id.expected");
test_fixture(transform_fixture, "refetchable-fragment-on-node-with-missing-id.graphql", "compile_relay_artifacts/fixtures/refetchable-fragment-on-node-with-missing-id.expected", input, expected);
}
#[test]
fn refetchable_fragment_with_connection() {
let input = include_str!("compile_relay_artifacts/fixtures/refetchable-fragment-with-connection.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/refetchable-fragment-with-connection.expected");
test_fixture(transform_fixture, "refetchable-fragment-with-connection.graphql", "compile_relay_artifacts/fixtures/refetchable-fragment-with-connection.expected", input, expected);
}
#[test]
fn refetchable_fragment_with_connection_bidirectional() {
let input = include_str!("compile_relay_artifacts/fixtures/refetchable-fragment-with-connection-bidirectional.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/refetchable-fragment-with-connection-bidirectional.expected");
test_fixture(transform_fixture, "refetchable-fragment-with-connection-bidirectional.graphql", "compile_relay_artifacts/fixtures/refetchable-fragment-with-connection-bidirectional.expected", input, expected);
}
#[test]
fn refetchable_fragment_with_connection_with_stream() {
let input = include_str!("compile_relay_artifacts/fixtures/refetchable-fragment-with-connection-with-stream.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/refetchable-fragment-with-connection-with-stream.expected");
test_fixture(transform_fixture, "refetchable-fragment-with-connection-with-stream.graphql", "compile_relay_artifacts/fixtures/refetchable-fragment-with-connection-with-stream.expected", input, expected);
}
#[test]
fn relay_client_id_field() {
let input = include_str!("compile_relay_artifacts/fixtures/relay-client-id-field.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/relay-client-id-field.expected");
test_fixture(transform_fixture, "relay-client-id-field.graphql", "compile_relay_artifacts/fixtures/relay-client-id-field.expected", input, expected);
}
#[test]
fn scalar_handle_field() {
let input = include_str!("compile_relay_artifacts/fixtures/scalar-handle-field.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/scalar-handle-field.expected");
test_fixture(transform_fixture, "scalar-handle-field.graphql", "compile_relay_artifacts/fixtures/scalar-handle-field.expected", input, expected);
}
#[test]
fn sibling_client_selections() {
let input = include_str!("compile_relay_artifacts/fixtures/sibling-client-selections.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/sibling-client-selections.expected");
test_fixture(transform_fixture, "sibling-client-selections.graphql", "compile_relay_artifacts/fixtures/sibling-client-selections.expected", input, expected);
}
#[test]
fn stable_literals() {
let input = include_str!("compile_relay_artifacts/fixtures/stable-literals.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/stable-literals.expected");
test_fixture(transform_fixture, "stable-literals.graphql", "compile_relay_artifacts/fixtures/stable-literals.expected", input, expected);
}
#[test]
fn stream_connection() {
let input = include_str!("compile_relay_artifacts/fixtures/stream-connection.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/stream-connection.expected");
test_fixture(transform_fixture, "stream-connection.graphql", "compile_relay_artifacts/fixtures/stream-connection.expected", input, expected);
}
#[test]
fn unions() {
let input = include_str!("compile_relay_artifacts/fixtures/unions.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unions.expected");
test_fixture(transform_fixture, "unions.graphql", "compile_relay_artifacts/fixtures/unions.expected", input, expected);
}
#[test]
fn unknown_root_variable_in_fragment_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/unknown-root-variable-in-fragment.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unknown-root-variable-in-fragment.invalid.expected");
test_fixture(transform_fixture, "unknown-root-variable-in-fragment.invalid.graphql", "compile_relay_artifacts/fixtures/unknown-root-variable-in-fragment.invalid.expected", input, expected);
}
#[test]
fn unmasked_fragment_spreads_dup_arguments() {
let input = include_str!("compile_relay_artifacts/fixtures/unmasked-fragment-spreads-dup-arguments.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unmasked-fragment-spreads-dup-arguments.expected");
test_fixture(transform_fixture, "unmasked-fragment-spreads-dup-arguments.graphql", "compile_relay_artifacts/fixtures/unmasked-fragment-spreads-dup-arguments.expected", input, expected);
}
#[test]
fn unmasked_fragment_spreads_global_arguments() {
let input = include_str!("compile_relay_artifacts/fixtures/unmasked-fragment-spreads-global-arguments.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unmasked-fragment-spreads-global-arguments.expected");
test_fixture(transform_fixture, "unmasked-fragment-spreads-global-arguments.graphql", "compile_relay_artifacts/fixtures/unmasked-fragment-spreads-global-arguments.expected", input, expected);
}
#[test]
fn unmasked_fragment_spreads_local_arguments_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/unmasked-fragment-spreads-local-arguments.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unmasked-fragment-spreads-local-arguments.invalid.expected");
test_fixture(transform_fixture, "unmasked-fragment-spreads-local-arguments.invalid.graphql", "compile_relay_artifacts/fixtures/unmasked-fragment-spreads-local-arguments.invalid.expected", input, expected);
}
#[test]
fn unmasked_fragment_spreads_recursive() {
let input = include_str!("compile_relay_artifacts/fixtures/unmasked-fragment-spreads-recursive.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unmasked-fragment-spreads-recursive.expected");
test_fixture(transform_fixture, "unmasked-fragment-spreads-recursive.graphql", "compile_relay_artifacts/fixtures/unmasked-fragment-spreads-recursive.expected", input, expected);
}
#[test]
fn unused_fragment_argdef_invalid() {
let input = include_str!("compile_relay_artifacts/fixtures/unused-fragment-argdef.invalid.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unused-fragment-argdef.invalid.expected");
test_fixture(transform_fixture, "unused-fragment-argdef.invalid.graphql", "compile_relay_artifacts/fixtures/unused-fragment-argdef.invalid.expected", input, expected);
}
#[test]
fn unused_fragment_argdef_unchecked() {
let input = include_str!("compile_relay_artifacts/fixtures/unused-fragment-argdef-unchecked.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unused-fragment-argdef-unchecked.expected");
test_fixture(transform_fixture, "unused-fragment-argdef-unchecked.graphql", "compile_relay_artifacts/fixtures/unused-fragment-argdef-unchecked.expected", input, expected);
}
#[test]
fn unused_variables_removed_from_print_not_codegen() {
let input = include_str!("compile_relay_artifacts/fixtures/unused-variables-removed-from-print-not-codegen.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/unused-variables-removed-from-print-not-codegen.expected");
test_fixture(transform_fixture, "unused-variables-removed-from-print-not-codegen.graphql", "compile_relay_artifacts/fixtures/unused-variables-removed-from-print-not-codegen.expected", input, expected);
}
#[test]
fn viewer_query() {
let input = include_str!("compile_relay_artifacts/fixtures/viewer-query.graphql");
let expected = include_str!("compile_relay_artifacts/fixtures/viewer-query.expected");
test_fixture(transform_fixture, "viewer-query.graphql", "compile_relay_artifacts/fixtures/viewer-query.expected", input, expected);
}
| 62.219388 | 237 | 0.803526 |
d67576d4586e3896f2cd294915505810b331a946 | 3,520 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
chained_bft::{
consensus_types::quorum_cert::QuorumCert,
test_utils::{mock_storage::MockStorage, TestPayload},
},
state_replication::StateComputer,
};
use failure::Result;
use futures::{channel::mpsc, future, Future, FutureExt};
use solana_libra_crypto::{hash::ACCUMULATOR_PLACEHOLDER_HASH, HashValue};
use solana_libra_executor::{ExecutedState, StateComputeResult};
use solana_libra_logger::prelude::*;
use solana_libra_types::crypto_proxies::LedgerInfoWithSignatures;
use std::{pin::Pin, sync::Arc};
use termion::color::*;
pub struct MockStateComputer {
commit_callback: mpsc::UnboundedSender<LedgerInfoWithSignatures>,
consensus_db: Arc<MockStorage<TestPayload>>,
}
impl MockStateComputer {
pub fn new(
commit_callback: mpsc::UnboundedSender<LedgerInfoWithSignatures>,
consensus_db: Arc<MockStorage<TestPayload>>,
) -> Self {
MockStateComputer {
commit_callback,
consensus_db,
}
}
}
impl StateComputer for MockStateComputer {
type Payload = Vec<usize>;
fn compute(
&self,
_parent_id: HashValue,
_block_id: HashValue,
_transactions: &Self::Payload,
) -> Pin<Box<dyn Future<Output = Result<StateComputeResult>> + Send>> {
future::ok(StateComputeResult {
executed_state: ExecutedState {
state_id: *ACCUMULATOR_PLACEHOLDER_HASH,
version: 0,
validators: None,
},
compute_status: vec![],
})
.boxed()
}
fn commit(
&self,
commit: LedgerInfoWithSignatures,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
self.consensus_db
.commit_to_storage(commit.ledger_info().clone());
self.commit_callback
.unbounded_send(commit)
.expect("Fail to notify about commit.");
future::ok(()).boxed()
}
fn sync_to(&self, commit: QuorumCert) -> Pin<Box<dyn Future<Output = Result<bool>> + Send>> {
debug!(
"{}Fake sync{} to block id {}",
Fg(Blue),
Fg(Reset),
commit.ledger_info().ledger_info().consensus_block_id()
);
self.consensus_db
.commit_to_storage(commit.ledger_info().ledger_info().clone());
self.commit_callback
.unbounded_send(commit.ledger_info().clone())
.expect("Fail to notify about sync");
async { Ok(true) }.boxed()
}
}
pub struct EmptyStateComputer;
impl StateComputer for EmptyStateComputer {
type Payload = TestPayload;
fn compute(
&self,
_parent_id: HashValue,
_block_id: HashValue,
_transactions: &Self::Payload,
) -> Pin<Box<dyn Future<Output = Result<StateComputeResult>> + Send>> {
future::ok(StateComputeResult {
executed_state: ExecutedState {
state_id: *ACCUMULATOR_PLACEHOLDER_HASH,
version: 0,
validators: None,
},
compute_status: vec![],
})
.boxed()
}
fn commit(
&self,
_commit: LedgerInfoWithSignatures,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
future::ok(()).boxed()
}
fn sync_to(&self, _commit: QuorumCert) -> Pin<Box<dyn Future<Output = Result<bool>> + Send>> {
async { Ok(true) }.boxed()
}
}
| 30.08547 | 98 | 0.603409 |
213a713913e8a0ce152946900dd4ebc70d003338 | 15,247 | use httpmock::{Method::GET, MockRef, MockServer};
use serial_test::serial;
mod common;
use goose::goose::GooseTaskSet;
use goose::prelude::*;
use goose::GooseConfiguration;
// Paths used in load tests performed during these tests.
const INDEX_PATH: &str = "/";
const REDIRECT_PATH: &str = "/redirect";
const REDIRECT2_PATH: &str = "/redirect2";
const REDIRECT3_PATH: &str = "/redirect3";
const ABOUT_PATH: &str = "/about.php";
// Indexes to the above paths.
const INDEX_KEY: usize = 0;
const REDIRECT_KEY: usize = 1;
const REDIRECT_KEY2: usize = 2;
const REDIRECT_KEY3: usize = 3;
const ABOUT_KEY: usize = 4;
const SERVER1_INDEX_KEY: usize = 0;
const SERVER1_ABOUT_KEY: usize = 1;
const SERVER1_REDIRECT_KEY: usize = 2;
const SERVER2_INDEX_KEY: usize = 3;
const SERVER2_ABOUT_KEY: usize = 4;
// Load test configuration.
const EXPECT_WORKERS: usize = 4;
const USERS: usize = 9;
const RUN_TIME: usize = 3;
// There are multiple test variations in this file.
#[derive(Clone)]
enum TestType {
// Chain many different redirects together.
Chain,
// Redirect between domains.
Domain,
// Permanently redirect between domains.
Sticky,
}
// Test task.
pub async fn get_index(user: &GooseUser) -> GooseTaskResult {
let _goose = user.get(INDEX_PATH).await?;
Ok(())
}
// Test task.
pub async fn get_about(user: &GooseUser) -> GooseTaskResult {
let _goose = user.get(ABOUT_PATH).await?;
Ok(())
}
// Test task.
pub async fn get_redirect(user: &GooseUser) -> GooseTaskResult {
// Load REDIRECT_PATH and follow redirects to ABOUT_PATH.
let mut goose = user.get(REDIRECT_PATH).await?;
if let Ok(r) = goose.response {
match r.text().await {
Ok(html) => {
// Confirm that we followed redirects and loaded the about page.
if !html.contains("about page") {
return user.set_failure(
"about page body wrong",
&mut goose.request,
None,
None,
);
}
}
Err(e) => {
return user.set_failure(
format!("unexpected error parsing about page: {}", e).as_str(),
&mut goose.request,
None,
None,
);
}
}
}
Ok(())
}
// Test task.
pub async fn get_domain_redirect(user: &GooseUser) -> GooseTaskResult {
let _goose = user.get(REDIRECT_PATH).await?;
Ok(())
}
// Sets up the endpoints used to test redirects.
fn setup_mock_server_endpoints<'a>(
test_type: &TestType,
server: &'a MockServer,
server2: Option<&'a MockServer>,
) -> Vec<MockRef<'a>> {
match test_type {
TestType::Chain => {
vec![
// First set up INDEX_PATH, store in vector at INDEX_KEY.
server.mock(|when, then| {
when.method(GET).path(INDEX_PATH);
then.status(200);
}),
// Next set up REDIRECT_PATH, store in vector at REDIRECT_KEY.
server.mock(|when, then| {
when.method(GET).path(REDIRECT_PATH);
then.status(301).header("Location", REDIRECT2_PATH);
}),
// Next set up REDIRECT2_PATH, store in vector at REDIRECT2_KEY.
server.mock(|when, then| {
when.method(GET).path(REDIRECT2_PATH);
then.status(302).header("Location", REDIRECT3_PATH);
}),
// Next set up REDIRECT3_PATH, store in vector at REDIRECT3_KEY.
server.mock(|when, then| {
when.method(GET).path(REDIRECT3_PATH);
then.status(303).header("Location", ABOUT_PATH);
}),
// Next set up ABOUT_PATH, store in vector at ABOUT_KEY.
server.mock(|when, then| {
when.method(GET).path(ABOUT_PATH);
then.status(200)
.body("<HTML><BODY>about page</BODY></HTML>");
}),
]
}
TestType::Domain | TestType::Sticky => {
vec![
// First set up INDEX_PATH, store in vector at SERVER1_INDEX_KEY.
server.mock(|when, then| {
when.method(GET).path(INDEX_PATH);
then.status(200);
}),
// Next set up ABOUT_PATH, store in vector at SERVER1_ABOUT_KEY.
server.mock(|when, then| {
when.method(GET).path(ABOUT_PATH);
then.status(200)
.body("<HTML><BODY>about page</BODY></HTML>");
}),
// Next set up REDIRECT_PATH, store in vector at SERVER1_REDIRECT_KEY.
server.mock(|when, then| {
when.method(GET).path(REDIRECT_PATH);
then.status(301)
.header("Location", &server2.unwrap().url(INDEX_PATH));
}),
// Next set up INDEX_PATH on server 2, store in vector at SERVER2_INDEX_KEY.
server2.unwrap().mock(|when, then| {
when.method(GET).path(INDEX_PATH);
then.status(200);
}),
// Next set up ABOUT_PATH on server 2, store in vector at SERVER2_ABOUT_KEY.
server2.unwrap().mock(|when, then| {
when.method(GET).path(ABOUT_PATH);
then.status(200);
}),
]
}
}
}
// Build appropriate configuration for these tests.
fn common_build_configuration(
server: &MockServer,
sticky: bool,
worker: Option<bool>,
manager: Option<usize>,
) -> GooseConfiguration {
if let Some(expect_workers) = manager {
if sticky {
common::build_configuration(
&server,
vec![
"--sticky-follow",
"--manager",
"--expect-workers",
&expect_workers.to_string(),
"--users",
&USERS.to_string(),
"--hatch-rate",
&USERS.to_string(),
"--run-time",
&RUN_TIME.to_string(),
],
)
} else {
common::build_configuration(
&server,
vec![
"--manager",
"--expect-workers",
&expect_workers.to_string(),
"--users",
&USERS.to_string(),
"--hatch-rate",
&USERS.to_string(),
"--run-time",
&RUN_TIME.to_string(),
],
)
}
} else if worker.is_some() {
common::build_configuration(&server, vec!["--worker"])
} else if sticky {
common::build_configuration(
&server,
vec![
"--sticky-follow",
"--users",
&USERS.to_string(),
"--hatch-rate",
&USERS.to_string(),
"--run-time",
&RUN_TIME.to_string(),
],
)
} else {
common::build_configuration(
&server,
vec![
"--users",
&USERS.to_string(),
"--hatch-rate",
&USERS.to_string(),
"--run-time",
&RUN_TIME.to_string(),
],
)
}
}
// Helper to confirm all variations generate appropriate results.
fn validate_redirect(test_type: &TestType, mock_endpoints: &[MockRef]) {
match test_type {
TestType::Chain => {
// Confirm that all pages are loaded, even those not requested directly but
// that are only loaded due to redirects.
assert!(mock_endpoints[INDEX_KEY].hits() > 0);
assert!(mock_endpoints[REDIRECT_KEY].hits() > 0);
assert!(mock_endpoints[REDIRECT_KEY2].hits() > 0);
assert!(mock_endpoints[REDIRECT_KEY3].hits() > 0);
assert!(mock_endpoints[ABOUT_KEY].hits() > 0);
// Confirm the entire redirect chain is loaded the same number of times.
mock_endpoints[REDIRECT_KEY].assert_hits(mock_endpoints[REDIRECT_KEY2].hits());
mock_endpoints[REDIRECT_KEY].assert_hits(mock_endpoints[REDIRECT_KEY3].hits());
mock_endpoints[REDIRECT_KEY].assert_hits(mock_endpoints[ABOUT_KEY].hits());
}
TestType::Domain => {
// All pages on Server1 are loaded.
assert!(mock_endpoints[SERVER1_INDEX_KEY].hits() > 0);
assert!(mock_endpoints[SERVER1_REDIRECT_KEY].hits() > 0);
assert!(mock_endpoints[SERVER1_ABOUT_KEY].hits() > 0);
// GooseUsers are redirected to Server2 correctly.
assert!(mock_endpoints[SERVER2_INDEX_KEY].hits() > 0);
// GooseUsers do not stick to Server2 and load the other page.
mock_endpoints[SERVER2_ABOUT_KEY].assert_hits(0);
}
TestType::Sticky => {
// Each GooseUser loads the redirect on Server1 one time.
println!(
"SERVER1_REDIRECT: {}, USERS: {}",
mock_endpoints[SERVER1_REDIRECT_KEY].hits(),
USERS,
);
println!(
"SERVER1_INDEX: {}, SERVER1_ABOUT: {}",
mock_endpoints[SERVER1_INDEX_KEY].hits(),
mock_endpoints[SERVER1_ABOUT_KEY].hits(),
);
println!(
"SERVER2_INDEX: {}, SERVER2_ABOUT: {}",
mock_endpoints[SERVER2_INDEX_KEY].hits(),
mock_endpoints[SERVER2_ABOUT_KEY].hits(),
);
mock_endpoints[SERVER1_REDIRECT_KEY].assert_hits(USERS);
// Redirected to Server2, no user load anything else on Server1.
mock_endpoints[SERVER1_INDEX_KEY].assert_hits(0);
mock_endpoints[SERVER1_ABOUT_KEY].assert_hits(0);
// All GooseUsers go on to load pages on Server2.
assert!(mock_endpoints[SERVER2_INDEX_KEY].hits() > 0);
assert!(mock_endpoints[SERVER2_ABOUT_KEY].hits() > 0);
}
}
}
// Returns the appropriate taskset needed to build these tests.
fn get_tasks(test_type: &TestType) -> GooseTaskSet {
match test_type {
TestType::Chain => {
taskset!("LoadTest")
// Load index directly.
.register_task(task!(get_index))
// Load redirect path, redirect to redirect2 path, redirect to
// redirect3 path, redirect to about.
.register_task(task!(get_redirect))
}
TestType::Domain | TestType::Sticky => {
taskset!("LoadTest")
// First load redirect, takes this request only to another domain.
.register_task(task!(get_domain_redirect))
// Load index.
.register_task(task!(get_index))
// Load about.
.register_task(task!(get_about))
}
}
}
// Helper to run all standalone tests.
fn run_standalone_test(test_type: TestType) {
// Start the mock servers.
let server1 = MockServer::start();
let server2 = MockServer::start();
// Setup the endpoints needed for this test on the mock server.
let mock_endpoints = setup_mock_server_endpoints(&test_type, &server1, Some(&server2));
// Build appropriate configuration.
let sticky = match test_type {
TestType::Sticky => true,
TestType::Chain | TestType::Domain => false,
};
let configuration = common_build_configuration(&server1, sticky, None, None);
// Run the Goose Attack.
common::run_load_test(
common::build_load_test(configuration, &get_tasks(&test_type), None, None),
None,
);
// Confirm that the load test was actually redirected.
validate_redirect(&test_type, &mock_endpoints);
}
// Helper to run all standalone tests.
fn run_gaggle_test(test_type: TestType) {
// Start the mock servers.
let server1 = MockServer::start();
let server2 = MockServer::start();
// Setup the endpoints needed for this test on the mock server.
let mock_endpoints = setup_mock_server_endpoints(&test_type, &server1, Some(&server2));
// Build appropriate Worker configuration.
let sticky = match test_type {
TestType::Sticky => true,
TestType::Chain | TestType::Domain => false,
};
let worker_configuration = common_build_configuration(&server1, sticky, Some(true), None);
// Build the load test for the Workers.
let worker_goose_attack =
common::build_load_test(worker_configuration, &get_tasks(&test_type), None, None);
// Workers launched in own threads, store thread handles.
let worker_handles = common::launch_gaggle_workers(worker_goose_attack, EXPECT_WORKERS);
// Build Manager configuration.
let manager_configuration =
common_build_configuration(&server1, sticky, None, Some(EXPECT_WORKERS));
// Build the load test for the Workers.
let manager_goose_attack =
common::build_load_test(manager_configuration, &get_tasks(&test_type), None, None);
// Run the Goose Attack.
common::run_load_test(manager_goose_attack, Some(worker_handles));
// Confirm that the load test was actually redirected.
validate_redirect(&test_type, &mock_endpoints);
}
#[test]
// Request a page that redirects multiple times with different redirect headers.
fn test_redirect() {
run_standalone_test(TestType::Chain);
}
#[test]
#[cfg_attr(not(feature = "gaggle"), ignore)]
#[serial]
// Request a page that redirects multiple times with different redirect headers,
// in Gaggle mode.
fn test_redirect_gaggle() {
run_gaggle_test(TestType::Chain);
}
#[test]
// Request a page that redirects to another domain.
// Different domains are simulated with multiple mock servers running on different
// ports.
fn test_domain_redirect() {
run_standalone_test(TestType::Domain);
}
#[test]
#[cfg_attr(not(feature = "gaggle"), ignore)]
#[serial]
// Request a page that redirects to another domain, in Gaggle mode.
// Different domains are simulated with multiple mock servers running on different
// ports.
fn test_domain_redirect_gaggle() {
run_gaggle_test(TestType::Domain);
}
#[test]
// Request a page that redirects to another domain with --sticky-follow enabled.
// Different domains are simulated with multiple mock servers running on different
// ports.
fn test_sticky_domain_redirect() {
run_standalone_test(TestType::Sticky);
}
#[test]
#[cfg_attr(not(feature = "gaggle"), ignore)]
#[serial]
// Request a page that redirects to another domain with --sticky-follow enabled, in
// Gaggle mode.
// Different domains are simulated with multiple mock servers running on different
// ports.
fn test_sticky_domain_redirect_gaggle() {
run_gaggle_test(TestType::Sticky);
}
| 35.293981 | 94 | 0.573555 |
0e606756df4396d3f7355a0342d102b4cf05f149 | 17,924 | use super::ModuleKind;
use crate::{
domain::{audio::AudioId, image::ImageId},
media::MediaLibrary,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{collections::HashSet, convert::TryFrom, fmt::Debug, hash::Hash};
/// Memory Game Body.
pub mod memory;
/// Talking Poster Body.
pub mod poster;
/// Video Body.
pub mod video;
/// Listen & Learn Body.
pub mod tapping_board;
/// Drag & Drop Body.
pub mod drag_drop;
/// Cover Body.
pub mod cover;
/// Resource Cover Body.
pub mod resource_cover;
/// Flashcards .
pub mod flashcards;
/// Quiz Game
pub mod card_quiz;
/// Matching
pub mod matching;
/// Legacy
pub mod legacy;
/// Groups that share types
pub mod _groups;
/// Body kinds for Modules.
#[derive(Clone, Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Body {
/// Module is a memory game, and has a memory game's body.
MemoryGame(memory::ModuleData),
/// Module is matching game, and has a matching game's body.
Matching(matching::ModuleData),
/// Module is flashcards, and has a flashcard's body.
Flashcards(flashcards::ModuleData),
/// Module is a quiz game, and has a quiz game's body.
CardQuiz(card_quiz::ModuleData),
/// Module is a poster, and has a talking poster's body.
Poster(poster::ModuleData),
/// Module is a Video, and has a video body.
Video(video::ModuleData),
/// Module is a Listen & Learn, and has a Listen & Learn's body.
TappingBoard(tapping_board::ModuleData),
/// Module is a drag & drop, and has a drag & drop's body.
DragDrop(drag_drop::ModuleData),
/// Module is a [`Cover`](super::ModuleKind::Cover).
///
/// Cover for Module type
Cover(cover::ModuleData),
/// Module is a Resource Cover.
ResourceCover(resource_cover::ModuleData),
/// Module is a legacy, and has a legacy's body.
Legacy(legacy::ModuleData),
}
impl Body {
/// create a new Body for a given ModuleKind
pub fn new(kind: super::ModuleKind) -> Self {
match kind {
super::ModuleKind::Cover => Self::Cover(cover::ModuleData::default()),
super::ModuleKind::ResourceCover => {
Self::ResourceCover(resource_cover::ModuleData::default())
}
super::ModuleKind::Memory => Self::MemoryGame(memory::ModuleData::default()),
super::ModuleKind::CardQuiz => Self::CardQuiz(card_quiz::ModuleData::default()),
super::ModuleKind::Flashcards => Self::Flashcards(flashcards::ModuleData::default()),
super::ModuleKind::Matching => Self::Matching(matching::ModuleData::default()),
super::ModuleKind::Poster => Self::Poster(poster::ModuleData::default()),
super::ModuleKind::Video => Self::Video(video::ModuleData::default()),
super::ModuleKind::TappingBoard => {
Self::TappingBoard(tapping_board::ModuleData::default())
}
super::ModuleKind::DragDrop => Self::DragDrop(drag_drop::ModuleData::default()),
super::ModuleKind::Legacy => Self::Legacy(legacy::ModuleData::default()),
_ => unimplemented!("TODO!"),
}
}
/// Convert this container to a Body wrapper of a specific kind
pub fn convert_to_body(&self, kind: ModuleKind) -> Result<Self, &'static str> {
match self {
Self::MemoryGame(data) => data.convert_to_body(kind),
Self::Matching(data) => data.convert_to_body(kind),
Self::Flashcards(data) => data.convert_to_body(kind),
Self::CardQuiz(data) => data.convert_to_body(kind),
Self::Poster(data) => data.convert_to_body(kind),
Self::Video(data) => data.convert_to_body(kind),
Self::TappingBoard(data) => data.convert_to_body(kind),
Self::DragDrop(data) => data.convert_to_body(kind),
Self::Cover(data) => data.convert_to_body(kind),
Self::ResourceCover(data) => data.convert_to_body(kind),
Self::Legacy(data) => data.convert_to_body(kind),
}
}
}
/// Extension trait for interop
/// impl on inner body data
pub trait BodyExt<Mode: ModeExt, Step: StepExt>:
BodyConvert + TryFrom<Body> + Serialize + DeserializeOwned + Clone + Debug
{
/// get choose mode list. By default it's the full list
/// but that can be overridden to re-order or hide some modes
fn choose_mode_list() -> Vec<Mode> {
Mode::get_list()
}
/// get self as a Body
fn as_body(&self) -> Body;
/// is complete
fn is_complete(&self) -> bool;
/// is legacy
fn is_legacy() -> bool {
false
}
/// should wait for manual phase change to Init
fn has_preload() -> bool {
false
}
/// get the kind from the type itself
fn kind() -> super::ModuleKind;
/// given a Mode, get a new Self
/// will usually populate an inner .content
fn new_mode(mode: Mode) -> Self;
/// requires an additional step of choosing the mode
fn requires_choose_mode(&self) -> bool;
/// Get the current theme
fn get_theme(&self) -> Option<ThemeChoice>;
/// Set editor state step
fn set_editor_state_step(&mut self, step: Step);
/// Set editor state steps completed
fn set_editor_state_steps_completed(&mut self, steps_completed: HashSet<Step>);
/// Get editor state step
fn get_editor_state_step(&self) -> Option<Step>;
/// Get editor state steps completed
fn get_editor_state_steps_completed(&self) -> Option<HashSet<Step>>;
/// Insert a completed step
fn insert_editor_state_step_completed(&mut self, step: Step) {
if let Some(mut steps_completed) = self.get_editor_state_steps_completed() {
steps_completed.insert(step);
self.set_editor_state_steps_completed(steps_completed);
}
}
/// Convert this inner data to a Body wrapper of a specific kind
fn convert_to_body(&self, kind: ModuleKind) -> Result<Body, &'static str> {
match kind {
ModuleKind::Memory => Ok(Body::MemoryGame(self.convert_to_memory()?)),
ModuleKind::Matching => Ok(Body::Matching(self.convert_to_matching()?)),
ModuleKind::Flashcards => Ok(Body::Flashcards(self.convert_to_flashcards()?)),
ModuleKind::CardQuiz => Ok(Body::CardQuiz(self.convert_to_card_quiz()?)),
ModuleKind::Poster => Ok(Body::Poster(self.convert_to_poster()?)),
ModuleKind::Video => Ok(Body::Video(self.convert_to_video()?)),
ModuleKind::TappingBoard => Ok(Body::TappingBoard(self.convert_to_tapping_board()?)),
ModuleKind::DragDrop => Ok(Body::DragDrop(self.convert_to_drag_drop()?)),
ModuleKind::Cover => Ok(Body::Cover(self.convert_to_cover()?)),
ModuleKind::ResourceCover => Ok(Body::ResourceCover(self.convert_to_resource_cover()?)),
ModuleKind::Legacy => Ok(Body::Legacy(self.convert_to_legacy()?)),
_ => unimplemented!(
"cannot convert from {} to {}",
Self::kind().as_str(),
kind.as_str()
),
}
}
}
/// These will all error by default.
/// Modules that can be converted between eachother must override
/// The relevant methods
pub trait BodyConvert {
/// Get a list of valid conversion targets
fn convertable_list() -> Vec<ModuleKind> {
Vec::new()
}
/// Memory game
fn convert_to_memory(&self) -> Result<memory::ModuleData, &'static str> {
Err("cannot convert to memory game!")
}
/// Matching
fn convert_to_matching(&self) -> Result<matching::ModuleData, &'static str> {
Err("cannot convert to matching!")
}
/// Flashcards
fn convert_to_flashcards(&self) -> Result<flashcards::ModuleData, &'static str> {
Err("cannot convert to matching!")
}
/// Quiz game
fn convert_to_card_quiz(&self) -> Result<card_quiz::ModuleData, &'static str> {
Err("cannot convert to quiz game!")
}
/// Talking Poster
fn convert_to_poster(&self) -> Result<poster::ModuleData, &'static str> {
Err("cannot convert to talking poster!")
}
/// Listen & Learn
fn convert_to_tapping_board(&self) -> Result<tapping_board::ModuleData, &'static str> {
Err("cannot convert to Listen & Learn!")
}
/// Drag & Drop
fn convert_to_drag_drop(&self) -> Result<drag_drop::ModuleData, &'static str> {
Err("cannot convert to drag & drop!")
}
/// Cover
fn convert_to_cover(&self) -> Result<cover::ModuleData, &'static str> {
Err("cannot convert to cover!")
}
/// Resource Cover
fn convert_to_resource_cover(&self) -> Result<resource_cover::ModuleData, &'static str> {
Err("cannot convert to resource cover!")
}
/// Video
fn convert_to_video(&self) -> Result<video::ModuleData, &'static str> {
Err("cannot convert to video!")
}
/// Legacy
fn convert_to_legacy(&self) -> Result<legacy::ModuleData, &'static str> {
Err("cannot convert to legacy!")
}
}
/// Extenstion trait for modes
pub trait ModeExt: Copy + Default + PartialEq + Eq + Hash {
/// get a list of all the modes
/// (becomes the default in Choose page, which can be overriden in BodyExt)
fn get_list() -> Vec<Self>;
/// get the mode itself as a string id
fn as_str_id(&self) -> &'static str;
/// for headers, labels, etc.
fn label(&self) -> &'static str;
/// Image tag filters for search
/// The actual ImageTag enum variants are in components
fn image_tag_filters(&self) -> Option<Vec<i16>> {
None
}
/// Image tag priorities for search
/// The actual ImageTag enum variants are in components
fn image_tag_priorities(&self) -> Option<Vec<i16>> {
None
}
}
/// impl ModeExt for empty modes
/// this is a special case and should only be used
/// where the module genuinely ignores the mode
/// one example is the Cover module
impl ModeExt for () {
fn get_list() -> Vec<Self> {
vec![]
}
fn as_str_id(&self) -> &'static str {
""
}
fn label(&self) -> &'static str {
""
}
}
impl Body {
/// Gets this body's related [`ModuleKind`](super::ModuleKind)
pub fn kind(&self) -> super::ModuleKind {
match self {
Self::Cover(_) => super::ModuleKind::Cover,
Self::ResourceCover(_) => super::ModuleKind::ResourceCover,
Self::MemoryGame(_) => super::ModuleKind::Memory,
Self::Flashcards(_) => super::ModuleKind::Flashcards,
Self::CardQuiz(_) => super::ModuleKind::CardQuiz,
Self::Matching(_) => super::ModuleKind::Matching,
Self::Poster(_) => super::ModuleKind::Poster,
Self::Video(_) => super::ModuleKind::Video,
Self::TappingBoard(_) => super::ModuleKind::TappingBoard,
Self::DragDrop(_) => super::ModuleKind::DragDrop,
Self::Legacy(_) => super::ModuleKind::Legacy,
}
}
}
/* The following are things which are often used by multiple modules */
/// Generic editor state which must be preserved between sessions
/// Although these are saved to the db, they aren't relevant for playback
#[derive(Clone, Default, Serialize, Deserialize, Debug)]
pub struct EditorState<STEP>
where
STEP: StepExt,
{
/// the current step
pub step: STEP,
/// the completed steps
pub steps_completed: HashSet<STEP>,
}
/// This extension trait makes it possible to keep the Step
/// functionality generic and at a higher level than the module itself
pub trait StepExt: Copy + Default + PartialEq + Eq + Hash + Debug {
/// Get the next step from current step
fn next(&self) -> Option<Self>;
/// Get the step as a number
fn as_number(&self) -> usize;
/// Label to display (will be localized)
fn label(&self) -> &'static str;
/// List of all available steps
fn get_list() -> Vec<Self>;
/// Get the step which is synonymous with "preview"
/// TODO: this could probably be derived as a combo
/// of get_list() and next() (i.e. the first step to return None)
fn get_preview() -> Self;
/// Auto-implemented, check whether current step is "preview"
fn is_preview(&self) -> bool {
*self == Self::get_preview()
}
}
/// impl StepExt for empty steps
/// this is a special case and should only be used
/// where the module genuinely ignores the step
/// one example is the Legacy module
impl StepExt for () {
fn next(&self) -> Option<Self> {
None
}
fn as_number(&self) -> usize {
0
}
fn label(&self) -> &'static str {
""
}
fn get_list() -> Vec<Self> {
Vec::new()
}
fn get_preview() -> Self {
()
}
}
/// Theme choice, either jig or override
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub enum ThemeChoice {
/// Use the jig's theme
Jig,
/// Override it with a per-module choice
Override(ThemeId),
}
impl Default for ThemeChoice {
fn default() -> Self {
Self::Jig
}
}
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
/// Audio
pub struct Audio {
/// The Audio Id
pub id: AudioId,
/// The Media Library
pub lib: MediaLibrary,
}
/// Instructions for a module.
#[derive(Clone, Default, Serialize, Deserialize, Debug)]
pub struct Instructions {
/// Text displayed in banner
pub text: Option<String>,
/// Audio played on module start
pub audio: Option<Audio>,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
/// Background
pub enum Background {
/// Color
Color(Option<rgb::RGBA8>),
/// Any other image
Image(Image),
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
/// Images need id and lib
pub struct Image {
/// The Image Id
pub id: ImageId,
/// The MediaLibrary
pub lib: MediaLibrary,
}
#[derive(Clone, Default, Serialize, Deserialize, Debug, PartialEq)]
/// Vector of 2 floats
pub struct Vec2(pub [f64; 2]);
impl From<(f64, f64)> for Vec2 {
fn from((x, y): (f64, f64)) -> Self {
Self([x, y])
}
}
impl From<Vec2> for (f64, f64) {
fn from(v: Vec2) -> Self {
(v.0[0], v.0[1])
}
}
#[derive(Clone, Default, Serialize, Deserialize, Debug, PartialEq)]
/// Vector of 3 floats
pub struct Vec3(pub [f64; 3]);
impl From<(f64, f64, f64)> for Vec3 {
fn from((x, y, z): (f64, f64, f64)) -> Self {
Self([x, y, z])
}
}
impl From<Vec3> for (f64, f64, f64) {
fn from(v: Vec3) -> Self {
(v.0[0], v.0[1], v.0[2])
}
}
#[derive(Clone, Default, Serialize, Deserialize, Debug, PartialEq)]
/// Vector of 4 floats, also used as a Quaternion
pub struct Vec4(pub [f64; 4]);
impl From<(f64, f64, f64, f64)> for Vec4 {
fn from((x, y, z, w): (f64, f64, f64, f64)) -> Self {
Self([x, y, z, w])
}
}
impl From<Vec4> for (f64, f64, f64, f64) {
fn from(v: Vec4) -> Self {
(v.0[0], v.0[1], v.0[2], v.0[3])
}
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
/// Visual Transform
pub struct Transform {
/// Translation
pub translation: Vec3,
/// Rotation Quaternion
pub rotation: Vec4,
/// Scale for each axis
pub scale: Vec3,
/// Origin
pub origin: Vec3,
}
/// Theme Ids. Used in various modules
/// See the frontend extension trait for more info
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Debug)]
#[repr(i16)]
#[cfg_attr(feature = "backend", derive(sqlx::Type))]
pub enum ThemeId {
#[allow(missing_docs)]
Blank,
#[allow(missing_docs)]
Jigzi,
#[allow(missing_docs)]
Chalkboard,
#[allow(missing_docs)]
MyNotebook,
#[allow(missing_docs)]
BackToSchool,
#[allow(missing_docs)]
MyWorkspace,
#[allow(missing_docs)]
Comix,
#[allow(missing_docs)]
Surreal,
#[allow(missing_docs)]
Abstract,
#[allow(missing_docs)]
Denim,
#[allow(missing_docs)]
HappyBrush,
#[allow(missing_docs)]
Graffiti,
#[allow(missing_docs)]
JewishText,
#[allow(missing_docs)]
ShabbatShalom,
#[allow(missing_docs)]
RoshHashana,
#[allow(missing_docs)]
AppleWithHoney,
#[allow(missing_docs)]
Pomegranate,
#[allow(missing_docs)]
YomKippur,
#[allow(missing_docs)]
HappySukkot,
#[allow(missing_docs)]
Sukkot,
#[allow(missing_docs)]
IlluminatingHanukkah,
#[allow(missing_docs)]
Chanukah,
#[allow(missing_docs)]
ChanukahLights,
#[allow(missing_docs)]
Purim,
#[allow(missing_docs)]
PurimFeast,
#[allow(missing_docs)]
PurimSweets,
#[allow(missing_docs)]
HappyPassover,
#[allow(missing_docs)]
PassoveMatza,
#[allow(missing_docs)]
PassoverSeder,
#[allow(missing_docs)]
HappyShavuot,
#[allow(missing_docs)]
ShavuotDishes,
#[allow(missing_docs)]
ShavuotFields,
#[allow(missing_docs)]
OurIsrael,
#[allow(missing_docs)]
Israel,
#[allow(missing_docs)]
JerusalemCity,
#[allow(missing_docs)]
JerusalemWall,
#[allow(missing_docs)]
LovelySpring,
#[allow(missing_docs)]
Spring,
#[allow(missing_docs)]
WatermelonSummer,
#[allow(missing_docs)]
SummerPool,
#[allow(missing_docs)]
ExcitingFall,
#[allow(missing_docs)]
Autumn,
#[allow(missing_docs)]
WinterSnow,
#[allow(missing_docs)]
IceAge,
#[allow(missing_docs)]
LostInSpace,
#[allow(missing_docs)]
Space,
#[allow(missing_docs)]
Camping,
#[allow(missing_docs)]
HappyBirthday,
#[allow(missing_docs)]
Jungle,
#[allow(missing_docs)]
OurPlanet,
#[allow(missing_docs)]
Theater,
#[allow(missing_docs)]
Travel,
}
impl Default for ThemeId {
fn default() -> Self {
Self::Blank
}
}
| 29.335516 | 100 | 0.622183 |
2327804166a56f7123ca91b1db315d0a1f140f0e | 3,919 | use anyhow::*;
use regex::{self};
use std::{collections::HashSet, error, fs, iter::once, path::Path, str::FromStr};
use embuild::{bindgen, build, kconfig};
pub const STABLE_PATCHES: &[&str] = &[
"patches/missing_xtensa_atomics_fix.diff",
"patches/pthread_destructor_fix.diff",
"patches/ping_setsockopt_fix.diff",
];
#[allow(unused)]
pub const MASTER_PATCHES: &[&str] = &[];
const ALL_COMPONENTS: &[&str] = &[
// TODO: Put all IDF components here
"comp_pthread_enabled",
"comp_nvs_flash_enabled",
"comp_esp_http_client_enabled",
"comp_esp_http_server_enabled",
"comp_espcoredump_enabled",
"comp_app_update_enabled",
"comp_esp_serial_slave_link_enabled",
"comp_spi_flash_enabled",
"comp_esp_adc_cal_enabled",
];
pub struct EspIdfBuildOutput {
pub cincl_args: build::CInclArgs,
pub link_args: Option<build::LinkArgs>,
pub kconfig_args: Box<dyn Iterator<Item = (String, kconfig::Value)>>,
pub components: EspIdfComponents,
pub bindgen: bindgen::Factory,
}
pub struct EspIdfComponents(Vec<&'static str>);
impl EspIdfComponents {
pub fn new() -> Self {
Self(ALL_COMPONENTS.iter().map(|s| *s).collect::<Vec<_>>())
}
#[allow(dead_code)]
pub fn from<I, S>(enabled: I) -> Self
where
I: Iterator<Item = S>,
S: Into<String>,
{
let enabled = enabled.map(Into::into).collect::<HashSet<_>>();
Self(
ALL_COMPONENTS
.iter()
.map(|s| *s)
.filter(|s| enabled.contains(*s))
.collect::<Vec<_>>(),
)
}
pub fn clang_args<'a>(&'a self) -> impl Iterator<Item = String> + 'a {
self.0
.iter()
.map(|s| format!("-DESP_IDF_{}", s.to_uppercase()))
}
pub fn cfg_args<'a>(&'a self) -> impl Iterator<Item = String> + 'a {
self.0.iter().map(|c| format!("esp_idf_{}", c))
}
}
pub struct EspIdfVersion {
pub major: u32,
pub minor: u32,
pub patch: u32,
}
impl EspIdfVersion {
pub fn parse(bindings_file: impl AsRef<Path>) -> Result<Self> {
let bindings_content = fs::read_to_string(bindings_file.as_ref())?;
Ok(Self {
major: Self::grab_const(&bindings_content, "ESP_IDF_VERSION_MAJOR", "u32")?,
minor: Self::grab_const(&bindings_content, "ESP_IDF_VERSION_MINOR", "u32")?,
patch: Self::grab_const(bindings_content, "ESP_IDF_VERSION_PATCH", "u32")?,
})
}
pub fn cfg_args(&self) -> impl Iterator<Item = String> {
once(format!(
"esp_idf_full_version=\"{}.{}.{}\"",
self.major, self.minor, self.patch
))
.chain(once(format!(
"esp_idf_version=\"{}.{}\"",
self.major, self.minor
)))
.chain(once(format!("esp_idf_major_version=\"{}\"", self.major)))
.chain(once(format!("esp_idf_minor_version=\"{}\"", self.minor)))
.chain(once(format!("esp_idf_patch_version=\"{}\"", self.patch)))
}
fn grab_const<T>(
text: impl AsRef<str>,
const_name: impl AsRef<str>,
const_type: impl AsRef<str>,
) -> Result<T>
where
T: FromStr,
T::Err: error::Error + Send + Sync + 'static,
{
// Future: Consider using bindgen::callbacks::ParseCallbacks for grabbing macro-based constants. Should be more reliable compared to grepping
let const_name = const_name.as_ref();
let value = regex::Regex::new(&format!(
r"\s+const\s+{}\s*:\s*{}\s*=\s*(\S+)\s*;",
const_name,
const_type.as_ref()
))?
.captures(text.as_ref())
.ok_or_else(|| anyhow!("Failed to capture constant {}", const_name))?
.get(1)
.ok_or_else(|| anyhow!("Failed to capture the value of constant {}", const_name))?
.as_str()
.parse::<T>()?;
Ok(value)
}
}
| 29.916031 | 149 | 0.581781 |
61184302886d2e793f6ac080d2cf31bcc778d665 | 628 | fn main() {
let weechat = match pkg_config::probe_library("weechat") {
Ok(weechat) => weechat,
Err(error) => panic!(format!(
"Unable to find weechat.pc. Error: [[ {} ]]\n\
... Ensure that an up-to-date weechat is installed, and if your distro has it, \
the weechat-dev package as well.",
error
)),
};
let mut config = cc::Build::new();
for path in weechat.include_paths {
config.include(path);
}
config
.file("src/ffi/weecord.c")
.flag("-Wall")
.flag("-Wextra")
.compile("libweecord.a");
}
| 29.904762 | 93 | 0.525478 |
edc712865f8aa9785d42f3acfabbfee092304513 | 2,179 | mod arrayimpl;
mod factory;
pub use self::arrayimpl::*;
use pyo3::{
exceptions::PyNotImplementedError, exceptions::PyValueError, prelude::*, types::PyList,
wrap_pyfunction,
};
use std::convert::TryFrom;
pub fn setup_module(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(array, m)?)?;
m.add_class::<NdArrayD>()?;
m.add_class::<NdArrayB>()?;
m.add_class::<NdArrayI>()?;
m.add_class::<PyNdIndex>()?;
Ok(())
}
#[pyclass]
#[derive(Clone)]
pub struct PyNdIndex {
pub inner: Vec<u32>,
}
#[pymethods]
impl PyNdIndex {
#[new]
pub fn new(inp: &PyAny) -> PyResult<Self> {
let shape = if let Ok(shape) = inp.extract::<Vec<u32>>() {
shape
} else if let Ok(n) = inp.extract::<u32>() {
if n == 0 {
vec![0]
} else {
vec![n]
}
} else {
todo!()
};
Ok(Self { inner: shape })
}
}
type Factory = fn(Python, Vec<u32>, &PyList) -> Result<Py<PyAny>, PyErr>;
#[pyfunction]
pub fn array(py: Python, shape: PyObject) -> PyResult<PyObject> {
let mut dims = Vec::new();
let shape: &PyList = shape.extract(py).or_else(|_| {
shape
.extract(py)
.map_err(|err| {
PyValueError::new_err(format!("Failed to convert input to a list {:?}", err))
})
.map(|f: f32| PyList::new(py, vec![f]))
})?;
let factory: Factory = {
let mut shape = shape;
loop {
dims.push(u32::try_from(shape.len()).expect("expected dimensions to fit into 32 bits"));
let i = shape.get_item(0);
if let Ok(i) = i.downcast() {
shape = i;
} else if i.extract::<bool>().is_ok() {
break factory::array_bool;
} else if i.extract::<f32>().is_ok() {
break factory::array_f32;
} else {
return Err(PyNotImplementedError::new_err(format!(
"Value with unexpected type: {:?}",
i
)));
}
}
};
factory(py, dims, shape)
}
| 26.901235 | 100 | 0.502524 |
2f855824f882d8c968cb14b83c86a6c571bb4362 | 1,593 | mod handshaking;
mod status;
mod login;
mod play;
use bytes::Bytes;
use io::Deserializer;
use io::connection::{Connection, ConnectionState};
use protocol::packets::handshaking::serverbound::Packet as HandshakingPacket;
use protocol::packets::status::serverbound::Packet as StatusPacket;
use protocol::packets::login::serverbound::Packet as LoginPacket;
use protocol::packets::play::serverbound::Packet as PlayPacket;
use failure::Fallible;
use log::trace;
pub trait Handler {
type Context;
fn handle(&mut self, context: &mut Self::Context) -> Fallible<()>;
}
impl Handler for Connection {
type Context = Bytes;
fn handle(&mut self, bytes: &mut Self::Context) -> Fallible<()> {
trace!("during state {:?}, received bytes: {:?}", self.state, bytes.as_ref());
match self.state {
ConnectionState::Handshaking => {
let mut packet: HandshakingPacket = Deserializer::from(bytes.clone()).deserialize()?;
packet.handle(self)
},
ConnectionState::Status => {
let mut packet: StatusPacket = Deserializer::from(bytes.clone()).deserialize()?;
packet.handle(self)
},
ConnectionState::Login => {
let mut packet: LoginPacket = Deserializer::from(bytes.clone()).deserialize()?;
packet.handle(self)
},
ConnectionState::Play => {
let mut packet: PlayPacket = Deserializer::from(bytes.clone()).deserialize()?;
packet.handle(self)
}
}
}
}
| 31.235294 | 101 | 0.610169 |
dbbc5f1dc1d2f1481ed5ad8fe92f6b516daa31da | 12,186 | //! Module containing the DICOM Transfer Syntax data structure and related methods.
//! Similar to the DcmCodec in DCMTK, the `TransferSyntax` contains all of the necessary
//! algorithms for decoding and encoding DICOM data in a certain transfer syntax.
//!
//! This crate does not host specific transfer syntaxes. Instead, they are created in
//! other crates and registered in the global transfer syntax registry, which implements
//! [`TransferSyntaxIndex`]. For more
//! information, please see the `dicom-transfer-syntax-registry` crate.
//!
//! [`TransferSyntaxIndex`]: ./trait.TransferSyntaxIndex.html
pub mod explicit_be;
pub mod explicit_le;
pub mod implicit_le;
use crate::decode::basic::BasicDecoder;
use crate::decode::DecodeFrom;
use crate::encode::EncodeTo;
use std::io::{Read, Write};
pub use byteordered::Endianness;
/// A decoder with its type erased.
pub type DynDecoder<S> = Box<dyn DecodeFrom<S>>;
/// An encoder with its type erased.
pub type DynEncoder<W> = Box<dyn EncodeTo<W>>;
/// A DICOM transfer syntax specifier. The data RW adapter `A` specifies
/// custom codec capabilities when required.
#[derive(Debug)]
pub struct TransferSyntax<A = DynDataRWAdapter> {
/// The unique identifier of the transfer syntax.
uid: &'static str,
/// The name of the transfer syntax.
name: &'static str,
/// The byte order of data.
byte_order: Endianness,
/// Whether the transfer syntax mandates an explicit value representation,
/// or the VR is implicit.
explicit_vr: bool,
/// The transfer syntax' requirements and implemented capabilities.
codec: Codec<A>,
}
#[cfg(feature = "inventory-registry")]
// Collect transfer syntax specifiers from other crates.
inventory::collect!(TransferSyntax);
/// Trait for containers of transfer syntax specifiers.
///
/// Types implementing this trait are held responsible for populating
/// themselves with a set of transfer syntaxes, which can be fully supported,
/// partially supported, or not supported. Usually, only one implementation
/// of this trait is used for the entire program.
pub trait TransferSyntaxIndex {
/// Obtain a DICOM transfer syntax by its respective UID.
///
/// Implementations of this method should be robust to the possible
/// presence of a trailing null characters (`\0`) in `uid`.
fn get(&self, uid: &str) -> Option<&TransferSyntax>;
}
impl<T: ?Sized> TransferSyntaxIndex for &T
where
T: TransferSyntaxIndex,
{
fn get(&self, uid: &str) -> Option<&TransferSyntax> {
(**self).get(uid)
}
}
#[cfg(feature = "inventory-registry")]
#[macro_export]
/// Submit a transfer syntax specifier to be supported by the
/// program's runtime. This is to be used by crates wishing to provide
/// additional support for a certain transfer syntax using the
/// main transfer syntax registry.
///
/// This macro does actually "run" anything, so place it outside of a
/// function body at the root of the crate.
macro_rules! submit_transfer_syntax {
($ts: expr) => {
inventory::submit! {
($ts).erased()
}
};
}
#[cfg(not(feature = "inventory-registry"))]
#[macro_export]
/// Submit a transfer syntax specifier to be supported by the
/// program's runtime. This is to be used by crates wishing to provide
/// additional support for a certain transfer syntax using the
/// main transfer syntax registry.
///
/// This macro does actually "run" anything, so place it outside of a
/// function body at the root of the crate.
///
/// Without the `inventory-registry` feature, this request is ignored.
macro_rules! submit_transfer_syntax {
($ts: expr) => {
// ignore request
};
}
/// Description regarding the encoding and decoding requirements of a transfer
/// syntax. This is also used as a means to describe whether pixel data is
/// encapsulated and whether this implementation supports it.
#[derive(Debug, Clone, PartialEq)]
pub enum Codec<A> {
/// No codec is given, nor is it required.
None,
/// Custom encoding and decoding of the entire data set is required, but
/// not supported. This could be used by a stub of
/// _Deflated Explicit VR Little Endian_, for example.
Unsupported,
/// Custom encoding and decoding of the pixel data set is required, but
/// not supported. The program should still be able to parse DICOM
/// data sets and fetch the pixel data in its encapsulated form.
EncapsulatedPixelData,
/// A pixel data encapsulation codec is required and provided for reading
/// and writing pixel data.
PixelData(A),
/// A full, custom data set codec is required and provided.
Dataset(A),
}
/// An alias for a transfer syntax specifier with no pixel data encapsulation
/// nor data set deflating.
pub type AdapterFreeTransferSyntax = TransferSyntax<NeverAdapter>;
/// An adapter of byte read and write streams.
pub trait DataRWAdapter<R, W> {
type Reader: Read;
type Writer: Write;
/// Adapt a byte reader.
fn adapt_reader(&self, reader: R) -> Self::Reader
where
R: Read;
/// Adapt a byte writer.
fn adapt_writer(&self, writer: W) -> Self::Writer
where
W: Write;
}
pub type DynDataRWAdapter = Box<
dyn DataRWAdapter<
Box<dyn Read>,
Box<dyn Write>,
Reader = Box<dyn Read>,
Writer = Box<dyn Write>,
> + Send
+ Sync,
>;
impl<'a, T, R, W> DataRWAdapter<R, W> for &'a T
where
T: DataRWAdapter<R, W>,
R: Read,
W: Write,
{
type Reader = <T as DataRWAdapter<R, W>>::Reader;
type Writer = <T as DataRWAdapter<R, W>>::Writer;
/// Adapt a byte reader.
fn adapt_reader(&self, reader: R) -> Self::Reader
where
R: Read,
{
(**self).adapt_reader(reader)
}
/// Adapt a byte writer.
fn adapt_writer(&self, writer: W) -> Self::Writer
where
W: Write,
{
(**self).adapt_writer(writer)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum NeverAdapter {}
impl<R, W> DataRWAdapter<R, W> for NeverAdapter {
type Reader = Box<dyn Read>;
type Writer = Box<dyn Write>;
fn adapt_reader(&self, _reader: R) -> Self::Reader
where
R: Read,
{
unreachable!()
}
fn adapt_writer(&self, _writer: W) -> Self::Writer
where
W: Write,
{
unreachable!()
}
}
impl<A> TransferSyntax<A> {
pub const fn new(
uid: &'static str,
name: &'static str,
byte_order: Endianness,
explicit_vr: bool,
codec: Codec<A>,
) -> Self {
TransferSyntax {
uid,
name,
byte_order,
explicit_vr,
codec,
}
}
/// Obtain this transfer syntax' unique identifier.
pub const fn uid(&self) -> &'static str {
self.uid
}
/// Obtain the name of this transfer syntax.
pub const fn name(&self) -> &'static str {
self.name
}
/// Obtain this transfer syntax' expected endianness.
pub const fn endianness(&self) -> Endianness {
self.byte_order
}
/// Obtain this transfer syntax' codec specification.
pub fn codec(&self) -> &Codec<A> {
&self.codec
}
/// Check whether this transfer syntax specifier provides a complete
/// implementation.
pub fn fully_supported(&self) -> bool {
match self.codec {
Codec::None | Codec::Dataset(_) | Codec::PixelData(_) => true,
_ => false,
}
}
/// Check whether reading and writing of data sets is unsupported.
/// If this is `true`, encoding and decoding will not be available.
pub fn unsupported(&self) -> bool {
match self.codec {
Codec::Unsupported => true,
_ => false,
}
}
/// Check whether reading and writing the pixel data is unsupported.
/// If this is `true`, encoding and decoding of the data set will still
/// be possible, but the pixel data will only be available in its
/// encapsulated form.
pub fn unsupported_pixel_encapsulation(&self) -> bool {
match self.codec {
Codec::Unsupported | Codec::EncapsulatedPixelData => true,
_ => false,
}
}
/// Retrieve the appropriate data element decoder for this transfer syntax.
/// Can yield none if decoding is not supported.
///
/// The resulting decoder does not consider pixel data encapsulation or
/// data set compression rules. This means that the consumer of this method
/// needs to adapt the reader before using the decoder.
pub fn decoder<'s>(&self) -> Option<DynDecoder<dyn Read + 's>> {
self.decoder_for()
}
/// Retrieve the appropriate data element decoder for this transfer syntax
/// and given reader type (this method is not object safe).
/// Can yield none if decoding is not supported.
///
/// The resulting decoder does not consider pixel data encapsulation or
/// data set compression rules. This means that the consumer of this method
/// needs to adapt the reader before using the decoder.
pub fn decoder_for<S>(&self) -> Option<DynDecoder<S>>
where
Self: Sized,
S: ?Sized + Read,
{
match (self.byte_order, self.explicit_vr) {
(Endianness::Little, false) => Some(Box::new(
implicit_le::ImplicitVRLittleEndianDecoder::default(),
)),
(Endianness::Little, true) => Some(Box::new(
explicit_le::ExplicitVRLittleEndianDecoder::default(),
)),
(Endianness::Big, true) => {
Some(Box::new(explicit_be::ExplicitVRBigEndianDecoder::default()))
}
_ => None,
}
}
/// Retrieve the appropriate data element encoder for this transfer syntax.
/// Can yield none if encoding is not supported. The resulting encoder does not
/// consider pixel data encapsulation or data set compression rules.
pub fn encoder(&self) -> Option<DynEncoder<dyn Write>> {
self.encoder_for()
}
/// Retrieve the appropriate data element encoder for this transfer syntax
/// and the given writer type (this method is not object safe).
/// Can yield none if encoding is not supported. The resulting encoder does not
/// consider pixel data encapsulation or data set compression rules.
pub fn encoder_for<W>(&self) -> Option<DynEncoder<W>>
where
Self: Sized,
W: ?Sized + Write,
{
match (self.byte_order, self.explicit_vr) {
(Endianness::Little, false) => Some(Box::new(
implicit_le::ImplicitVRLittleEndianEncoder::default(),
)),
(Endianness::Little, true) => Some(Box::new(
explicit_le::ExplicitVRLittleEndianEncoder::default(),
)),
(Endianness::Big, true) => {
Some(Box::new(explicit_be::ExplicitVRBigEndianEncoder::default()))
}
_ => None,
}
}
/// Obtain a dynamic basic decoder, based on this transfer syntax' expected endianness.
pub fn basic_decoder(&self) -> BasicDecoder {
BasicDecoder::from(self.endianness())
}
/// Type-erase the pixel data or data set codec.
pub fn erased(self) -> TransferSyntax
where
A: Send + Sync + 'static,
A: DataRWAdapter<
Box<dyn Read>,
Box<dyn Write>,
Reader = Box<dyn Read>,
Writer = Box<dyn Write>,
>,
{
let codec = match self.codec {
Codec::Dataset(a) => Codec::Dataset(Box::new(a) as DynDataRWAdapter),
Codec::PixelData(a) => Codec::PixelData(Box::new(a) as DynDataRWAdapter),
Codec::EncapsulatedPixelData => Codec::EncapsulatedPixelData,
Codec::Unsupported => Codec::Unsupported,
Codec::None => Codec::None,
};
TransferSyntax {
uid: self.uid,
name: self.name,
byte_order: self.byte_order,
explicit_vr: self.explicit_vr,
codec,
}
}
}
| 32.758065 | 91 | 0.633022 |
081a52cf4aac828f48d82b06c91ca88a9b855e1e | 15,693 | use crate::util::ShortHash;
use proc_macro2::{Ident, Span};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::PathBuf;
use crate::ast;
use crate::Diagnostic;
pub struct EncodeResult {
pub custom_section: Vec<u8>,
pub included_files: Vec<PathBuf>,
}
pub fn encode(program: &ast::Program) -> Result<EncodeResult, Diagnostic> {
let mut e = Encoder::new();
let i = Interner::new();
shared_program(program, &i)?.encode(&mut e);
let custom_section = e.finish();
let included_files = i
.files
.borrow()
.values()
.map(|p| &p.path)
.cloned()
.collect();
Ok(EncodeResult {
custom_section,
included_files,
})
}
struct Interner {
bump: bumpalo::Bump,
files: RefCell<HashMap<String, LocalFile>>,
root: PathBuf,
crate_name: String,
has_package_json: Cell<bool>,
}
struct LocalFile {
path: PathBuf,
definition: Span,
new_identifier: String,
}
impl Interner {
fn new() -> Interner {
Interner {
bump: bumpalo::Bump::new(),
files: RefCell::new(HashMap::new()),
root: env::var_os("CARGO_MANIFEST_DIR").unwrap().into(),
crate_name: env::var("CARGO_PKG_NAME").unwrap(),
has_package_json: Cell::new(false),
}
}
fn intern(&self, s: &Ident) -> &str {
self.intern_str(&s.to_string())
}
fn intern_str(&self, s: &str) -> &str {
// NB: eventually this could be used to intern `s` to only allocate one
// copy, but for now let's just "transmute" `s` to have the same
// lifetime as this struct itself (which is our main goal here)
self.bump.alloc_str(s)
}
/// Given an import to a local module `id` this generates a unique module id
/// to assign to the contents of `id`.
///
/// Note that repeated invocations of this function will be memoized, so the
/// same `id` will always return the same resulting unique `id`.
fn resolve_import_module(&self, id: &str, span: Span) -> Result<&str, Diagnostic> {
let mut files = self.files.borrow_mut();
if let Some(file) = files.get(id) {
return Ok(self.intern_str(&file.new_identifier));
}
self.check_for_package_json();
let path = if id.starts_with("/") {
self.root.join(&id[1..])
} else if id.starts_with("./") || id.starts_with("../") {
let msg = "relative module paths aren't supported yet";
return Err(Diagnostic::span_error(span, msg));
} else {
return Ok(self.intern_str(&id));
};
// Generate a unique ID which is somewhat readable as well, so mix in
// the crate name, hash to make it unique, and then the original path.
let new_identifier = format!("{}{}", self.unique_crate_identifier(), id);
let file = LocalFile {
path,
definition: span,
new_identifier,
};
files.insert(id.to_string(), file);
drop(files);
self.resolve_import_module(id, span)
}
fn unique_crate_identifier(&self) -> String {
format!("{}-{}", self.crate_name, ShortHash(0))
}
fn check_for_package_json(&self) {
if self.has_package_json.get() {
return;
}
let path = self.root.join("package.json");
if path.exists() {
self.has_package_json.set(true);
}
}
}
fn shared_program<'a>(
prog: &'a ast::Program,
intern: &'a Interner,
) -> Result<Program<'a>, Diagnostic> {
Ok(Program {
exports: prog
.exports
.iter()
.map(|a| shared_export(a, intern))
.collect::<Result<Vec<_>, _>>()?,
structs: prog
.structs
.iter()
.map(|a| shared_struct(a, intern))
.collect(),
enums: prog.enums.iter().map(|a| shared_enum(a, intern)).collect(),
imports: prog
.imports
.iter()
.map(|a| shared_import(a, intern))
.collect::<Result<Vec<_>, _>>()?,
typescript_custom_sections: prog
.typescript_custom_sections
.iter()
.map(|x| -> &'a str { &x })
.collect(),
local_modules: intern
.files
.borrow()
.values()
.map(|file| {
fs::read_to_string(&file.path)
.map(|s| LocalModule {
identifier: intern.intern_str(&file.new_identifier),
contents: intern.intern_str(&s),
})
.map_err(|e| {
let msg = format!("failed to read file `{}`: {}", file.path.display(), e);
Diagnostic::span_error(file.definition, msg)
})
})
.collect::<Result<Vec<_>, _>>()?,
inline_js: prog
.inline_js
.iter()
.map(|js| intern.intern_str(js))
.collect(),
unique_crate_identifier: intern.intern_str(&intern.unique_crate_identifier()),
package_json: if intern.has_package_json.get() {
Some(intern.intern_str(intern.root.join("package.json").to_str().unwrap()))
} else {
None
},
})
}
fn shared_export<'a>(
export: &'a ast::Export,
intern: &'a Interner,
) -> Result<Export<'a>, Diagnostic> {
let consumed = match export.method_self {
Some(ast::MethodSelf::ByValue) => true,
_ => false,
};
let method_kind = from_ast_method_kind(&export.function, intern, &export.method_kind)?;
Ok(Export {
class: export.js_class.as_ref().map(|s| &**s),
comments: export.comments.iter().map(|s| &**s).collect(),
consumed,
function: shared_function(&export.function, intern),
method_kind,
start: export.start,
unstable_api: export.unstable_api,
})
}
fn shared_function<'a>(func: &'a ast::Function, _intern: &'a Interner) -> Function<'a> {
let arg_names = func
.arguments
.iter()
.enumerate()
.map(|(idx, arg)| {
if let syn::Pat::Ident(x) = &*arg.pat {
return x.ident.to_string();
}
format!("arg{}", idx)
})
.collect::<Vec<_>>();
Function {
arg_names,
name: &func.name,
}
}
fn shared_enum<'a>(e: &'a ast::Enum, intern: &'a Interner) -> Enum<'a> {
Enum {
name: intern.intern(&e.name),
variants: e
.variants
.iter()
.map(|v| shared_variant(v, intern))
.collect(),
comments: e.comments.iter().map(|s| &**s).collect(),
}
}
fn shared_variant<'a>(v: &'a ast::Variant, intern: &'a Interner) -> EnumVariant<'a> {
EnumVariant {
name: intern.intern(&v.name),
value: v.value,
}
}
fn shared_import<'a>(i: &'a ast::Import, intern: &'a Interner) -> Result<Import<'a>, Diagnostic> {
Ok(Import {
module: match &i.module {
ast::ImportModule::Named(m, span) => {
ImportModule::Named(intern.resolve_import_module(m, *span)?)
}
ast::ImportModule::RawNamed(m, _span) => ImportModule::RawNamed(intern.intern_str(m)),
ast::ImportModule::Inline(idx, _) => ImportModule::Inline(*idx as u32),
ast::ImportModule::None => ImportModule::None,
},
js_namespace: i.js_namespace.as_ref().map(|s| intern.intern(s)),
kind: shared_import_kind(&i.kind, intern)?,
})
}
fn shared_import_kind<'a>(
i: &'a ast::ImportKind,
intern: &'a Interner,
) -> Result<ImportKind<'a>, Diagnostic> {
Ok(match i {
ast::ImportKind::Function(f) => ImportKind::Function(shared_import_function(f, intern)?),
ast::ImportKind::Static(f) => ImportKind::Static(shared_import_static(f, intern)),
ast::ImportKind::Type(f) => ImportKind::Type(shared_import_type(f, intern)),
ast::ImportKind::Enum(f) => ImportKind::Enum(shared_import_enum(f, intern)),
})
}
fn shared_import_function<'a>(
i: &'a ast::ImportFunction,
intern: &'a Interner,
) -> Result<ImportFunction<'a>, Diagnostic> {
let method = match &i.kind {
ast::ImportFunctionKind::Method { class, kind, .. } => {
let kind = from_ast_method_kind(&i.function, intern, kind)?;
Some(MethodData { class, kind })
}
ast::ImportFunctionKind::Normal => None,
};
Ok(ImportFunction {
shim: intern.intern(&i.shim),
catch: i.catch,
method,
assert_no_shim: i.assert_no_shim,
structural: i.structural,
function: shared_function(&i.function, intern),
variadic: i.variadic,
})
}
fn shared_import_static<'a>(i: &'a ast::ImportStatic, intern: &'a Interner) -> ImportStatic<'a> {
ImportStatic {
name: &i.js_name,
shim: intern.intern(&i.shim),
}
}
fn shared_import_type<'a>(i: &'a ast::ImportType, intern: &'a Interner) -> ImportType<'a> {
ImportType {
name: &i.js_name,
instanceof_shim: &i.instanceof_shim,
vendor_prefixes: i.vendor_prefixes.iter().map(|x| intern.intern(x)).collect(),
}
}
fn shared_import_enum<'a>(_i: &'a ast::ImportEnum, _intern: &'a Interner) -> ImportEnum {
ImportEnum {}
}
fn shared_struct<'a>(s: &'a ast::Struct, intern: &'a Interner) -> Struct<'a> {
Struct {
name: &s.js_name,
fields: s
.fields
.iter()
.map(|s| shared_struct_field(s, intern))
.collect(),
comments: s.comments.iter().map(|s| &**s).collect(),
is_inspectable: s.is_inspectable,
}
}
fn shared_struct_field<'a>(s: &'a ast::StructField, intern: &'a Interner) -> StructField<'a> {
StructField {
name: match &s.name {
syn::Member::Named(ident) => intern.intern(ident),
syn::Member::Unnamed(index) => intern.intern_str(&index.index.to_string()),
},
readonly: s.readonly,
comments: s.comments.iter().map(|s| &**s).collect(),
}
}
trait Encode {
fn encode(&self, dst: &mut Encoder);
}
struct Encoder {
dst: Vec<u8>,
}
impl Encoder {
fn new() -> Encoder {
Encoder {
dst: vec![0, 0, 0, 0],
}
}
fn finish(mut self) -> Vec<u8> {
let len = self.dst.len() - 4;
self.dst[0] = (len >> 0) as u8;
self.dst[1] = (len >> 8) as u8;
self.dst[2] = (len >> 16) as u8;
self.dst[3] = (len >> 24) as u8;
self.dst
}
fn byte(&mut self, byte: u8) {
self.dst.push(byte);
}
}
impl Encode for bool {
fn encode(&self, dst: &mut Encoder) {
dst.byte(*self as u8);
}
}
impl Encode for u32 {
fn encode(&self, dst: &mut Encoder) {
let mut val = *self;
while (val >> 7) != 0 {
dst.byte((val as u8) | 0x80);
val >>= 7;
}
assert_eq!(val >> 7, 0);
dst.byte(val as u8);
}
}
impl Encode for usize {
fn encode(&self, dst: &mut Encoder) {
assert!(*self <= u32::max_value() as usize);
(*self as u32).encode(dst);
}
}
impl<'a> Encode for &'a [u8] {
fn encode(&self, dst: &mut Encoder) {
self.len().encode(dst);
dst.dst.extend_from_slice(*self);
}
}
impl<'a> Encode for &'a str {
fn encode(&self, dst: &mut Encoder) {
self.as_bytes().encode(dst);
}
}
impl<'a> Encode for String {
fn encode(&self, dst: &mut Encoder) {
self.as_bytes().encode(dst);
}
}
impl<T: Encode> Encode for Vec<T> {
fn encode(&self, dst: &mut Encoder) {
self.len().encode(dst);
for item in self {
item.encode(dst);
}
}
}
impl<T: Encode> Encode for Option<T> {
fn encode(&self, dst: &mut Encoder) {
match self {
None => dst.byte(0),
Some(val) => {
dst.byte(1);
val.encode(dst)
}
}
}
}
macro_rules! encode_struct {
($name:ident ($($lt:tt)*) $($field:ident: $ty:ty,)*) => {
struct $name $($lt)* {
$($field: $ty,)*
}
impl $($lt)* Encode for $name $($lt)* {
fn encode(&self, _dst: &mut Encoder) {
$(self.$field.encode(_dst);)*
}
}
}
}
macro_rules! encode_enum {
($name:ident ($($lt:tt)*) $($fields:tt)*) => (
enum $name $($lt)* { $($fields)* }
impl$($lt)* Encode for $name $($lt)* {
fn encode(&self, dst: &mut Encoder) {
use self::$name::*;
encode_enum!(@arms self dst (0) () $($fields)*)
}
}
);
(@arms $me:ident $dst:ident ($cnt:expr) ($($arms:tt)*)) => (
encode_enum!(@expr match $me { $($arms)* })
);
(@arms $me:ident $dst:ident ($cnt:expr) ($($arms:tt)*) $name:ident, $($rest:tt)*) => (
encode_enum!(
@arms
$me
$dst
($cnt+1)
($($arms)* $name => $dst.byte($cnt),)
$($rest)*
)
);
(@arms $me:ident $dst:ident ($cnt:expr) ($($arms:tt)*) $name:ident($t:ty), $($rest:tt)*) => (
encode_enum!(
@arms
$me
$dst
($cnt+1)
($($arms)* $name(val) => { $dst.byte($cnt); val.encode($dst) })
$($rest)*
)
);
(@expr $e:expr) => ($e);
}
macro_rules! encode_api {
() => ();
(struct $name:ident<'a> { $($fields:tt)* } $($rest:tt)*) => (
encode_struct!($name (<'a>) $($fields)*);
encode_api!($($rest)*);
);
(struct $name:ident { $($fields:tt)* } $($rest:tt)*) => (
encode_struct!($name () $($fields)*);
encode_api!($($rest)*);
);
(enum $name:ident<'a> { $($variants:tt)* } $($rest:tt)*) => (
encode_enum!($name (<'a>) $($variants)*);
encode_api!($($rest)*);
);
(enum $name:ident { $($variants:tt)* } $($rest:tt)*) => (
encode_enum!($name () $($variants)*);
encode_api!($($rest)*);
);
}
wasm_bindgen_shared::shared_api!(encode_api);
fn from_ast_method_kind<'a>(
function: &'a ast::Function,
intern: &'a Interner,
method_kind: &'a ast::MethodKind,
) -> Result<MethodKind<'a>, Diagnostic> {
Ok(match method_kind {
ast::MethodKind::Constructor => MethodKind::Constructor,
ast::MethodKind::Operation(ast::Operation { is_static, kind }) => {
let is_static = *is_static;
let kind = match kind {
ast::OperationKind::Getter(g) => {
let g = g.as_ref().map(|g| intern.intern(g));
OperationKind::Getter(g.unwrap_or_else(|| function.infer_getter_property()))
}
ast::OperationKind::Regular => OperationKind::Regular,
ast::OperationKind::Setter(s) => {
let s = s.as_ref().map(|s| intern.intern(s));
OperationKind::Setter(match s {
Some(s) => s,
None => intern.intern_str(&function.infer_setter_property()?),
})
}
ast::OperationKind::IndexingGetter => OperationKind::IndexingGetter,
ast::OperationKind::IndexingSetter => OperationKind::IndexingSetter,
ast::OperationKind::IndexingDeleter => OperationKind::IndexingDeleter,
};
MethodKind::Operation(Operation { is_static, kind })
}
})
}
| 29.891429 | 98 | 0.524438 |
38f2068a0dbb9164d8107fea8f82fad4d901fd88 | 62 | use minitrace::trace;
#[trace(a, b)]
fn f() {}
fn main() {}
| 8.857143 | 21 | 0.532258 |
e6ac34c23c0e53f6013f12097814f18205012b9b | 11,979 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//! The central type in Apache Arrow are arrays, represented
//! by the [`Array` trait](crate::array::Array).
//! An array represents a known-length sequence of values all
//! having the same type.
//!
//! Internally, those values are represented by one or several
//! [buffers](crate::buffer::Buffer), the number and meaning
//! of which depend on the array’s data type, as documented in
//! [the Arrow data layout specification](https://arrow.apache.org/docs/format/Columnar.html).
//! For example, the type `Int16Array` represents an Apache
//! Arrow array of 16-bit integers.
//!
//! Those buffers consist of the value data itself and an
//! optional [bitmap buffer](crate::bitmap::Bitmap) that
//! indicates which array entries are null values.
//! The bitmap buffer can be entirely omitted if the array is
//! known to have zero null values.
//!
//! There are concrete implementations of this trait for each
//! data type, that help you access individual values of the
//! array.
//!
//! # Building an Array
//!
//! Arrow's `Arrays` are immutable, but there is the trait
//! [`ArrayBuilder`](crate::array::ArrayBuilder)
//! that helps you with constructing new `Arrays`. As with the
//! `Array` trait, there are builder implementations for all
//! concrete array types.
//!
//! # Example
//! ```
//! extern crate arrow;
//!
//! use arrow::array::Int16Array;
//!
//! // Create a new builder with a capacity of 100
//! let mut builder = Int16Array::builder(100);
//!
//! // Append a single primitive value
//! builder.append_value(1).unwrap();
//!
//! // Append a null value
//! builder.append_null().unwrap();
//!
//! // Append a slice of primitive values
//! builder.append_slice(&[2, 3, 4]).unwrap();
//!
//! // Build the array
//! let array = builder.finish();
//!
//! assert_eq!(
//! 5,
//! array.len(),
//! "The array has 5 values, counting the null value"
//! );
//!
//! assert_eq!(2, array.value(2), "Get the value with index 2");
//!
//! assert_eq!(
//! &array.values()[3..5],
//! &[3, 4],
//! "Get slice of len 2 starting at idx 3"
//! )
//! ```
#[allow(clippy::module_inception)]
mod array;
mod array_binary;
mod array_boolean;
mod array_dictionary;
mod array_list;
mod array_primitive;
mod array_string;
mod array_struct;
mod array_union;
mod builder;
mod cast;
mod data;
mod equal;
mod equal_json;
mod ffi;
mod iterator;
mod null;
mod ord;
mod raw_pointer;
mod transform;
use crate::datatypes::*;
// --------------------- Array & ArrayData ---------------------
pub use self::array::Array;
pub use self::array::ArrayRef;
pub use self::data::ArrayData;
pub use self::data::ArrayDataBuilder;
pub use self::data::ArrayDataRef;
pub use self::array_binary::BinaryArray;
pub use self::array_binary::DecimalArray;
pub use self::array_binary::FixedSizeBinaryArray;
pub use self::array_binary::LargeBinaryArray;
pub use self::array_boolean::BooleanArray;
pub use self::array_dictionary::DictionaryArray;
pub use self::array_list::FixedSizeListArray;
pub use self::array_list::LargeListArray;
pub use self::array_list::ListArray;
pub use self::array_primitive::PrimitiveArray;
pub use self::array_string::LargeStringArray;
pub use self::array_string::StringArray;
pub use self::array_struct::StructArray;
pub use self::array_union::UnionArray;
pub use self::null::NullArray;
pub use self::array::make_array;
pub use self::array::new_empty_array;
pub use self::array::new_null_array;
pub type Int8Array = PrimitiveArray<Int8Type>;
pub type Int16Array = PrimitiveArray<Int16Type>;
pub type Int32Array = PrimitiveArray<Int32Type>;
pub type Int64Array = PrimitiveArray<Int64Type>;
pub type UInt8Array = PrimitiveArray<UInt8Type>;
pub type UInt16Array = PrimitiveArray<UInt16Type>;
pub type UInt32Array = PrimitiveArray<UInt32Type>;
pub type UInt64Array = PrimitiveArray<UInt64Type>;
pub type Float32Array = PrimitiveArray<Float32Type>;
pub type Float64Array = PrimitiveArray<Float64Type>;
pub type Int8DictionaryArray = DictionaryArray<Int8Type>;
pub type Int16DictionaryArray = DictionaryArray<Int16Type>;
pub type Int32DictionaryArray = DictionaryArray<Int32Type>;
pub type Int64DictionaryArray = DictionaryArray<Int64Type>;
pub type UInt8DictionaryArray = DictionaryArray<UInt8Type>;
pub type UInt16DictionaryArray = DictionaryArray<UInt16Type>;
pub type UInt32DictionaryArray = DictionaryArray<UInt32Type>;
pub type UInt64DictionaryArray = DictionaryArray<UInt64Type>;
pub type Timestamp32Array = PrimitiveArray<Timestamp32Type>;
pub type TimestampSecondArray = PrimitiveArray<TimestampSecondType>;
pub type TimestampMillisecondArray = PrimitiveArray<TimestampMillisecondType>;
pub type TimestampMicrosecondArray = PrimitiveArray<TimestampMicrosecondType>;
pub type TimestampNanosecondArray = PrimitiveArray<TimestampNanosecondType>;
pub type Date16Array = PrimitiveArray<Date16Type>;
pub type Date32Array = PrimitiveArray<Date32Type>;
pub type Date64Array = PrimitiveArray<Date64Type>;
pub type Time32SecondArray = PrimitiveArray<Time32SecondType>;
pub type Time32MillisecondArray = PrimitiveArray<Time32MillisecondType>;
pub type Time64MicrosecondArray = PrimitiveArray<Time64MicrosecondType>;
pub type Time64NanosecondArray = PrimitiveArray<Time64NanosecondType>;
pub type IntervalYearMonthArray = PrimitiveArray<IntervalYearMonthType>;
pub type IntervalDayTimeArray = PrimitiveArray<IntervalDayTimeType>;
pub type DurationSecondArray = PrimitiveArray<DurationSecondType>;
pub type DurationMillisecondArray = PrimitiveArray<DurationMillisecondType>;
pub type DurationMicrosecondArray = PrimitiveArray<DurationMicrosecondType>;
pub type DurationNanosecondArray = PrimitiveArray<DurationNanosecondType>;
pub use self::array_binary::BinaryOffsetSizeTrait;
pub use self::array_binary::GenericBinaryArray;
pub use self::array_list::GenericListArray;
pub use self::array_list::OffsetSizeTrait;
pub use self::array_string::GenericStringArray;
pub use self::array_string::StringOffsetSizeTrait;
// --------------------- Array Builder ---------------------
pub use self::builder::BooleanBufferBuilder;
pub use self::builder::BufferBuilder;
pub type Int8BufferBuilder = BufferBuilder<i8>;
pub type Int16BufferBuilder = BufferBuilder<i16>;
pub type Int32BufferBuilder = BufferBuilder<i32>;
pub type Int64BufferBuilder = BufferBuilder<i64>;
pub type UInt8BufferBuilder = BufferBuilder<u8>;
pub type UInt16BufferBuilder = BufferBuilder<u16>;
pub type UInt32BufferBuilder = BufferBuilder<u32>;
pub type UInt64BufferBuilder = BufferBuilder<u64>;
pub type Float32BufferBuilder = BufferBuilder<f32>;
pub type Float64BufferBuilder = BufferBuilder<f64>;
pub type TimestampSecondBufferBuilder = BufferBuilder<TimestampSecondType>;
pub type TimestampMillisecondBufferBuilder = BufferBuilder<TimestampMillisecondType>;
pub type TimestampMicrosecondBufferBuilder = BufferBuilder<TimestampMicrosecondType>;
pub type TimestampNanosecondBufferBuilder = BufferBuilder<TimestampNanosecondType>;
pub type Date16BufferBuilder = BufferBuilder<Date16Type>;
pub type Date32BufferBuilder = BufferBuilder<Date32Type>;
pub type Date64BufferBuilder = BufferBuilder<Date64Type>;
pub type Time32SecondBufferBuilder = BufferBuilder<Time32SecondType>;
pub type Time32MillisecondBufferBuilder = BufferBuilder<Time32MillisecondType>;
pub type Time64MicrosecondBufferBuilder = BufferBuilder<Time64MicrosecondType>;
pub type Time64NanosecondBufferBuilder = BufferBuilder<Time64NanosecondType>;
pub type IntervalYearMonthBufferBuilder = BufferBuilder<IntervalYearMonthType>;
pub type IntervalDayTimeBufferBuilder = BufferBuilder<IntervalDayTimeType>;
pub type DurationSecondBufferBuilder = BufferBuilder<DurationSecondType>;
pub type DurationMillisecondBufferBuilder = BufferBuilder<DurationMillisecondType>;
pub type DurationMicrosecondBufferBuilder = BufferBuilder<DurationMicrosecondType>;
pub type DurationNanosecondBufferBuilder = BufferBuilder<DurationNanosecondType>;
pub use self::builder::ArrayBuilder;
pub use self::builder::BinaryBuilder;
pub use self::builder::BooleanBuilder;
pub use self::builder::DecimalBuilder;
pub use self::builder::FixedSizeBinaryBuilder;
pub use self::builder::FixedSizeListBuilder;
pub use self::builder::GenericStringBuilder;
pub use self::builder::LargeBinaryBuilder;
pub use self::builder::LargeListBuilder;
pub use self::builder::LargeStringBuilder;
pub use self::builder::ListBuilder;
pub use self::builder::PrimitiveBuilder;
pub use self::builder::PrimitiveDictionaryBuilder;
pub use self::builder::StringBuilder;
pub use self::builder::StringDictionaryBuilder;
pub use self::builder::StructBuilder;
pub use self::builder::UnionBuilder;
pub type Int8Builder = PrimitiveBuilder<Int8Type>;
pub type Int16Builder = PrimitiveBuilder<Int16Type>;
pub type Int32Builder = PrimitiveBuilder<Int32Type>;
pub type Int64Builder = PrimitiveBuilder<Int64Type>;
pub type UInt8Builder = PrimitiveBuilder<UInt8Type>;
pub type UInt16Builder = PrimitiveBuilder<UInt16Type>;
pub type UInt32Builder = PrimitiveBuilder<UInt32Type>;
pub type UInt64Builder = PrimitiveBuilder<UInt64Type>;
pub type Float32Builder = PrimitiveBuilder<Float32Type>;
pub type Float64Builder = PrimitiveBuilder<Float64Type>;
pub type TimestampSecondBuilder = PrimitiveBuilder<TimestampSecondType>;
pub type TimestampMillisecondBuilder = PrimitiveBuilder<TimestampMillisecondType>;
pub type TimestampMicrosecondBuilder = PrimitiveBuilder<TimestampMicrosecondType>;
pub type TimestampNanosecondBuilder = PrimitiveBuilder<TimestampNanosecondType>;
pub type Date16Builder = PrimitiveBuilder<Date16Type>;
pub type Date32Builder = PrimitiveBuilder<Date32Type>;
pub type Date64Builder = PrimitiveBuilder<Date64Type>;
pub type Time32SecondBuilder = PrimitiveBuilder<Time32SecondType>;
pub type Time32MillisecondBuilder = PrimitiveBuilder<Time32MillisecondType>;
pub type Time64MicrosecondBuilder = PrimitiveBuilder<Time64MicrosecondType>;
pub type Time64NanosecondBuilder = PrimitiveBuilder<Time64NanosecondType>;
pub type IntervalYearMonthBuilder = PrimitiveBuilder<IntervalYearMonthType>;
pub type IntervalDayTimeBuilder = PrimitiveBuilder<IntervalDayTimeType>;
pub type DurationSecondBuilder = PrimitiveBuilder<DurationSecondType>;
pub type DurationMillisecondBuilder = PrimitiveBuilder<DurationMillisecondType>;
pub type DurationMicrosecondBuilder = PrimitiveBuilder<DurationMicrosecondType>;
pub type DurationNanosecondBuilder = PrimitiveBuilder<DurationNanosecondType>;
pub use self::transform::{Capacities, MutableArrayData};
// --------------------- Array Iterator ---------------------
pub use self::iterator::*;
// --------------------- Array Equality ---------------------
pub use self::equal_json::JsonEqual;
// --------------------- Array's values comparison ---------------------
pub use self::ord::{build_compare, DynComparator};
// --------------------- Array downcast helper functions ---------------------
pub use self::cast::{
as_boolean_array, as_dictionary_array, as_generic_list_array, as_large_list_array,
as_largestring_array, as_list_array, as_null_array, as_primitive_array,
as_string_array, as_struct_array,
};
// ------------------------------ C Data Interface ---------------------------
pub use self::array::make_array_from_raw;
| 41.59375 | 94 | 0.77736 |
dee02331f891e388ac339dde81b9fbd54b15ae0d | 22 | pub enum Prototype { } | 22 | 22 | 0.727273 |
eb95733eab778e3a0cf625ad5afdd9b3795112a9 | 6,605 | use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::ast::CellPath;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::Category;
use nu_protocol::{
Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"str contains"
}
fn signature(&self) -> Signature {
Signature::build("str contains")
.required("pattern", SyntaxShape::String, "the pattern to find")
.rest(
"rest",
SyntaxShape::CellPath,
"optionally check if string contains pattern by column paths",
)
.switch("insensitive", "search is case insensitive", Some('i'))
.category(Category::Strings)
}
fn usage(&self) -> &str {
"Checks if string contains pattern"
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
operate(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Check if string contains pattern",
example: "'my_library.rb' | str contains '.rb'",
result: Some(Value::Bool {
val: true,
span: Span::test_data(),
}),
},
Example {
description: "Check if string contains pattern case insensitive",
example: "'my_library.rb' | str contains -i '.RB'",
result: Some(Value::Bool {
val: true,
span: Span::test_data(),
}),
},
Example {
description: "Check if string contains pattern in a table",
example: " [[ColA ColB]; [test 100]] | str contains 'e' ColA",
result: Some(Value::List {
vals: vec![Value::Record {
cols: vec!["ColA".to_string(), "ColB".to_string()],
vals: vec![
Value::Bool {
val: true,
span: Span::test_data(),
},
Value::test_int(100),
],
span: Span::test_data(),
}],
span: Span::test_data(),
}),
},
Example {
description: "Check if string contains pattern in a table",
example: " [[ColA ColB]; [test 100]] | str contains -i 'E' ColA",
result: Some(Value::List {
vals: vec![Value::Record {
cols: vec!["ColA".to_string(), "ColB".to_string()],
vals: vec![
Value::Bool {
val: true,
span: Span::test_data(),
},
Value::test_int(100),
],
span: Span::test_data(),
}],
span: Span::test_data(),
}),
},
Example {
description: "Check if string contains pattern in a table",
example: " [[ColA ColB]; [test hello]] | str contains 'e' ColA ColB",
result: Some(Value::List {
vals: vec![Value::Record {
cols: vec!["ColA".to_string(), "ColB".to_string()],
vals: vec![
Value::Bool {
val: true,
span: Span::test_data(),
},
Value::Bool {
val: true,
span: Span::test_data(),
},
],
span: Span::test_data(),
}],
span: Span::test_data(),
}),
},
Example {
description: "Check if string contains pattern",
example: "'hello' | str contains 'banana'",
result: Some(Value::Bool {
val: false,
span: Span::test_data(),
}),
},
]
}
}
fn operate(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let pattern: Spanned<String> = call.req(engine_state, stack, 0)?;
let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
let case_insensitive = call.has_flag("insensitive");
input.map(
move |v| {
if column_paths.is_empty() {
action(&v, case_insensitive, &pattern.item, head)
} else {
let mut ret = v;
for path in &column_paths {
let p = pattern.item.clone();
let r = ret.update_cell_path(
&path.members,
Box::new(move |old| action(old, case_insensitive, &p, head)),
);
if let Err(error) = r {
return Value::Error { error };
}
}
ret
}
},
engine_state.ctrlc.clone(),
)
}
fn action(input: &Value, case_insensitive: bool, pattern: &str, head: Span) -> Value {
match input {
Value::String { val, .. } => Value::Bool {
val: match case_insensitive {
true => val.to_lowercase().contains(pattern.to_lowercase().as_str()),
false => val.contains(pattern),
},
span: head,
},
other => Value::Error {
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with strings.",
other.get_type()
),
head,
),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}
| 33.527919 | 86 | 0.42483 |
261d892a69dea0efebb8a04988918749333befa1 | 2,601 | #![feature(intrinsics, lang_items, no_core, fundamental)]
#![no_core]
#![allow(unused_variables)]
fn fibonacci_recursive(n: i32) -> i32 {
if n == 0 || n == 1 {
n
} else {
fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
}
}
fn fibonacci_iterative(n: i32) -> i32 {
let mut current = 0;
let mut next = 1;
let mut iterator = 0;
loop {
if iterator == n {
break;
}
let tmp = current + next;
current = next;
next = tmp;
iterator += 1;
}
current
}
// Unusual example just to test trait methods
trait Fibonacci {
fn fibonacci(&self) -> Self;
}
impl Fibonacci for i32 {
fn fibonacci(&self) -> i32 {
fibonacci_iterative(*self)
}
}
#[lang = "panic"]
fn panic() -> ! {
loop {}
}
macro_rules! panic {
() => (
panic!("explicit panic")
);
($msg:expr) => ({
$crate::panic()
});
}
macro_rules! assert {
($cond:expr) => (
if !$cond {
panic!(concat!("assertion failed: ", stringify!($cond)))
}
);
}
fn main() {
let result = fibonacci_recursive(10);
assert!(result == 55);
let result = fibonacci_iterative(25);
assert!(result == 75025);
let result = fibonacci_recursive(25);
assert!(result == 75025);
// trait example
let nth = 20;
let result = nth.fibonacci();
assert!(result == 6765);
}
#[lang = "sized"]
#[fundamental]
pub trait Sized {}
#[lang = "copy"]
pub trait Copy: Clone {}
pub trait Clone: Sized {}
#[lang = "eq"]
pub trait PartialEq<Rhs: ?Sized = Self> {
fn eq(&self, other: &Rhs) -> bool;
#[inline]
fn ne(&self, other: &Rhs) -> bool {
!self.eq(other)
}
}
impl PartialEq for i32 {
#[inline]
fn eq(&self, other: &i32) -> bool {
(*self) == (*other)
}
#[inline]
fn ne(&self, other: &i32) -> bool {
(*self) != (*other)
}
}
#[lang = "add"]
pub trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
impl Add for i32 {
type Output = i32;
fn add(self, rhs: i32) -> Self::Output {
self + rhs
}
}
#[lang = "sub"]
pub trait Sub<RHS = Self> {
type Output;
fn sub(self, rhs: RHS) -> Self::Output;
}
impl Sub for i32 {
type Output = i32;
fn sub(self, rhs: i32) -> Self::Output {
self - rhs
}
}
#[lang = "add_assign"]
pub trait AddAssign<Rhs = Self> {
fn add_assign(&mut self, Rhs);
}
impl AddAssign for i32 {
#[inline]
fn add_assign(&mut self, other: i32) {
*self += other
}
}
| 17.456376 | 68 | 0.529796 |
5d5b95a059d5cc4821d0fdac5ba672bf357e121e | 16,909 | // Copyright 2018-2020 argmin developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://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.
//! * [Hager-Zhang line search](struct.HagerZhangLineSearch.html)
//!
//! TODO: Not all stopping criteria implemented
//!
//! # Reference
//!
//! William W. Hager and Hongchao Zhang. "A new conjugate gradient method with guaranteed descent
//! and an efficient line search." SIAM J. Optim. 16(1), 2006, 170-192.
//! DOI: https://doi.org/10.1137/030601880
use crate::prelude::*;
#[cfg(feature = "serde1")]
use serde::{Deserialize, Serialize};
use std::default::Default;
type Triplet = (f64, f64, f64);
/// The Hager-Zhang line search is a method to find a step length which obeys the strong Wolfe
/// conditions.
///
/// [Example](https://github.com/argmin-rs/argmin/blob/master/examples/hagerzhang.rs)
///
/// # References
///
/// [0] William W. Hager and Hongchao Zhang. "A new conjugate gradient method with guaranteed
/// descent and an efficient line search." SIAM J. Optim. 16(1), 2006, 170-192.
/// DOI: https://doi.org/10.1137/030601880
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Clone)]
pub struct HagerZhangLineSearch<P> {
/// delta: (0, 0.5), used in the Wolve conditions
delta: f64,
/// sigma: [delta, 1), used in the Wolfe conditions
sigma: f64,
/// epsilon: [0, infinity), used in the approximate Wolfe termination
epsilon: f64,
/// epsilon_k
epsilon_k: f64,
/// theta: (0, 1), used in the update rules when the potential intervals [a, c] or [c, b]
/// viloate the opposite slope condition
theta: f64,
/// gamma: (0, 1), determines when a bisection step is performed
gamma: f64,
/// eta: (0, infinity), used in the lower bound for beta_k^N
eta: f64,
/// initial a
a_x_init: f64,
/// a
a_x: f64,
/// phi(a)
a_f: f64,
/// phi'(a)
a_g: f64,
/// initial b
b_x_init: f64,
/// b
b_x: f64,
/// phi(b)
b_f: f64,
/// phi'(b)
b_g: f64,
/// initial c
c_x_init: f64,
/// c
c_x: f64,
/// phi(c)
c_f: f64,
/// phi'(c)
c_g: f64,
/// best x
best_x: f64,
/// best function value
best_f: f64,
/// best slope
best_g: f64,
/// Search direction (builder)
search_direction_b: Option<P>,
/// initial parameter vector
init_param: P,
/// initial cost
finit: f64,
/// initial gradient (builder)
init_grad: P,
/// Search direction (builder)
search_direction: P,
/// Search direction in 1D
dginit: f64,
}
impl<P: Default> HagerZhangLineSearch<P> {
/// Constructor
pub fn new() -> Self {
HagerZhangLineSearch {
delta: 0.1,
sigma: 0.9,
epsilon: 1e-6,
epsilon_k: std::f64::NAN,
theta: 0.5,
gamma: 0.66,
eta: 0.01,
a_x_init: std::f64::EPSILON,
a_x: std::f64::NAN,
a_f: std::f64::NAN,
a_g: std::f64::NAN,
b_x_init: 100.0,
b_x: std::f64::NAN,
b_f: std::f64::NAN,
b_g: std::f64::NAN,
c_x_init: 1.0,
c_x: std::f64::NAN,
c_f: std::f64::NAN,
c_g: std::f64::NAN,
best_x: 0.0,
best_f: std::f64::INFINITY,
best_g: std::f64::NAN,
search_direction_b: None,
init_param: P::default(),
init_grad: P::default(),
search_direction: P::default(),
dginit: std::f64::NAN,
finit: std::f64::INFINITY,
}
}
}
impl<P> HagerZhangLineSearch<P>
where
P: Clone
+ SerializeAlias
+ DeserializeOwnedAlias
+ Default
+ ArgminScaledAdd<P, f64, P>
+ ArgminDot<P, f64>,
{
/// set delta
pub fn delta(mut self, delta: f64) -> Result<Self, Error> {
if delta <= 0.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: delta must be > 0.0.".to_string(),
}
.into());
}
if delta >= 1.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: delta must be < 1.0.".to_string(),
}
.into());
}
self.delta = delta;
Ok(self)
}
/// set sigma
pub fn sigma(mut self, sigma: f64) -> Result<Self, Error> {
if sigma < self.delta {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: sigma must be >= delta.".to_string(),
}
.into());
}
if sigma >= 1.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: sigma must be < 1.0.".to_string(),
}
.into());
}
self.sigma = sigma;
Ok(self)
}
/// set epsilon
pub fn epsilon(mut self, epsilon: f64) -> Result<Self, Error> {
if epsilon < 0.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: epsilon must be >= 0.0.".to_string(),
}
.into());
}
self.epsilon = epsilon;
Ok(self)
}
/// set theta
pub fn theta(mut self, theta: f64) -> Result<Self, Error> {
if theta <= 0.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: theta must be > 0.0.".to_string(),
}
.into());
}
if theta >= 1.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: theta must be < 1.0.".to_string(),
}
.into());
}
self.theta = theta;
Ok(self)
}
/// set gamma
pub fn gamma(mut self, gamma: f64) -> Result<Self, Error> {
if gamma <= 0.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: gamma must be > 0.0.".to_string(),
}
.into());
}
if gamma >= 1.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: gamma must be < 1.0.".to_string(),
}
.into());
}
self.gamma = gamma;
Ok(self)
}
/// set eta
pub fn eta(mut self, eta: f64) -> Result<Self, Error> {
if eta <= 0.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: eta must be > 0.0.".to_string(),
}
.into());
}
self.eta = eta;
Ok(self)
}
/// set alpha limits
pub fn alpha(mut self, alpha_min: f64, alpha_max: f64) -> Result<Self, Error> {
if alpha_min < 0.0 {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: alpha_min must be >= 0.0.".to_string(),
}
.into());
}
if alpha_max <= alpha_min {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: alpha_min must be smaller than alpha_max.".to_string(),
}
.into());
}
self.a_x_init = alpha_min;
self.b_x_init = alpha_max;
Ok(self)
}
fn update<O: ArgminOp<Param = P, Output = f64>>(
&mut self,
op: &mut OpWrapper<O>,
(a_x, a_f, a_g): Triplet,
(b_x, b_f, b_g): Triplet,
(c_x, c_f, c_g): Triplet,
) -> Result<(Triplet, Triplet), Error> {
// U0
if c_x <= a_x || c_x >= b_x {
// nothing changes.
return Ok(((a_x, a_f, a_g), (b_x, b_f, b_g)));
}
// U1
if c_g >= 0.0 {
return Ok(((a_x, a_f, a_g), (c_x, c_f, c_g)));
}
// U2
if c_g < 0.0 && c_f <= self.finit + self.epsilon_k {
return Ok(((c_x, c_f, c_g), (b_x, b_f, b_g)));
}
// U3
if c_g < 0.0 && c_f > self.finit + self.epsilon_k {
let mut ah_x = a_x;
let mut ah_f = a_f;
let mut ah_g = a_g;
let mut bh_x = c_x;
loop {
let d_x = (1.0 - self.theta) * ah_x + self.theta * bh_x;
let d_f = self.calc(op, d_x)?;
let d_g = self.calc_grad(op, d_x)?;
if d_g >= 0.0 {
return Ok(((ah_x, ah_f, ah_g), (d_x, d_f, d_g)));
}
if d_g < 0.0 && d_f <= self.finit + self.epsilon_k {
ah_x = d_x;
ah_f = d_f;
ah_g = d_g;
}
if d_g < 0.0 && d_f > self.finit + self.epsilon_k {
bh_x = d_x;
}
}
}
// return Ok(((a_x, a_f, a_g), (b_x, b_f, b_g)));
Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: Reached unreachable point in `update` method.".to_string(),
}
.into())
}
/// secant step
fn secant(&self, a_x: f64, a_g: f64, b_x: f64, b_g: f64) -> f64 {
(a_x * b_g - b_x * a_g) / (b_g - a_g)
}
/// double secant step
fn secant2<O: ArgminOp<Param = P, Output = f64>>(
&mut self,
op: &mut OpWrapper<O>,
(a_x, a_f, a_g): Triplet,
(b_x, b_f, b_g): Triplet,
) -> Result<(Triplet, Triplet), Error> {
// S1
let c_x = self.secant(a_x, a_g, b_x, b_g);
let c_f = self.calc(op, c_x)?;
let c_g = self.calc_grad(op, c_x)?;
let mut c_bar_x: f64 = 0.0;
let ((aa_x, aa_f, aa_g), (bb_x, bb_f, bb_g)) =
self.update(op, (a_x, a_f, a_g), (b_x, b_f, b_g), (c_x, c_f, c_g))?;
// S2
if (c_x - bb_x).abs() < std::f64::EPSILON {
c_bar_x = self.secant(b_x, b_g, bb_x, bb_g);
}
// S3
if (c_x - aa_x).abs() < std::f64::EPSILON {
c_bar_x = self.secant(a_x, a_g, aa_x, aa_g);
}
// S4
if (c_x - aa_x).abs() < std::f64::EPSILON || (c_x - bb_x).abs() < std::f64::EPSILON {
let c_bar_f = self.calc(op, c_bar_x)?;
let c_bar_g = self.calc_grad(op, c_bar_x)?;
let (a_bar, b_bar) = self.update(
op,
(aa_x, aa_f, aa_g),
(bb_x, bb_f, bb_g),
(c_bar_x, c_bar_f, c_bar_g),
)?;
Ok((a_bar, b_bar))
} else {
Ok(((aa_x, aa_f, aa_g), (bb_x, bb_f, bb_g)))
}
}
fn calc<O: ArgminOp<Param = P, Output = f64>>(
&mut self,
op: &mut OpWrapper<O>,
alpha: f64,
) -> Result<f64, Error> {
let tmp = self.init_param.scaled_add(&alpha, &self.search_direction);
op.apply(&tmp)
}
fn calc_grad<O: ArgminOp<Param = P, Output = f64>>(
&mut self,
op: &mut OpWrapper<O>,
alpha: f64,
) -> Result<f64, Error> {
let tmp = self.init_param.scaled_add(&alpha, &self.search_direction);
let grad = op.gradient(&tmp)?;
Ok(self.search_direction.dot(&grad))
}
fn set_best(&mut self) {
if self.a_f < self.b_f && self.a_f < self.c_f {
self.best_x = self.a_x;
self.best_f = self.a_f;
self.best_g = self.a_g;
}
if self.b_f < self.a_f && self.b_f < self.c_f {
self.best_x = self.b_x;
self.best_f = self.b_f;
self.best_g = self.b_g;
}
if self.c_f < self.a_f && self.c_f < self.b_f {
self.best_x = self.c_x;
self.best_f = self.c_f;
self.best_g = self.c_g;
}
}
}
impl<P: Default> Default for HagerZhangLineSearch<P> {
fn default() -> Self {
HagerZhangLineSearch::new()
}
}
impl<P> ArgminLineSearch<P> for HagerZhangLineSearch<P>
where
P: Clone
+ SerializeAlias
+ DeserializeOwnedAlias
+ Default
+ ArgminSub<P, P>
+ ArgminDot<P, f64>
+ ArgminScaledAdd<P, f64, P>,
{
/// Set search direction
fn set_search_direction(&mut self, search_direction: P) {
self.search_direction_b = Some(search_direction);
}
/// Set initial alpha value
fn set_init_alpha(&mut self, alpha: f64) -> Result<(), Error> {
self.c_x_init = alpha;
Ok(())
}
}
impl<P, O> Solver<O> for HagerZhangLineSearch<P>
where
O: ArgminOp<Param = P, Output = f64>,
P: Clone
+ SerializeAlias
+ DeserializeOwnedAlias
+ Default
+ ArgminSub<P, P>
+ ArgminDot<P, f64>
+ ArgminScaledAdd<P, f64, P>,
{
const NAME: &'static str = "Hager-Zhang Line search";
fn init(
&mut self,
op: &mut OpWrapper<O>,
state: &IterState<O>,
) -> Result<Option<ArgminIterData<O>>, Error> {
if self.sigma < self.delta {
return Err(ArgminError::InvalidParameter {
text: "HagerZhangLineSearch: sigma must be >= delta.".to_string(),
}
.into());
}
self.search_direction = check_param!(
self.search_direction_b,
"HagerZhangLineSearch: Search direction not initialized. Call `set_search_direction`."
);
self.init_param = state.get_param();
let cost = state.get_cost();
self.finit = if cost == std::f64::INFINITY {
op.apply(&self.init_param)?
} else {
cost
};
self.init_grad = state.get_grad().unwrap_or(op.gradient(&self.init_param)?);
self.a_x = self.a_x_init;
self.b_x = self.b_x_init;
self.c_x = self.c_x_init;
let at = self.a_x;
self.a_f = self.calc(op, at)?;
self.a_g = self.calc_grad(op, at)?;
let bt = self.b_x;
self.b_f = self.calc(op, bt)?;
self.b_g = self.calc_grad(op, bt)?;
let ct = self.c_x;
self.c_f = self.calc(op, ct)?;
self.c_g = self.calc_grad(op, ct)?;
self.epsilon_k = self.epsilon * self.finit.abs();
self.dginit = self.init_grad.dot(&self.search_direction);
self.set_best();
let new_param = self
.init_param
.scaled_add(&self.best_x, &self.search_direction);
let best_f = self.best_f;
Ok(Some(ArgminIterData::new().param(new_param).cost(best_f)))
}
fn next_iter(
&mut self,
op: &mut OpWrapper<O>,
_state: &IterState<O>,
) -> Result<ArgminIterData<O>, Error> {
// L1
let aa = (self.a_x, self.a_f, self.a_g);
let bb = (self.b_x, self.b_f, self.b_g);
let ((mut at_x, mut at_f, mut at_g), (mut bt_x, mut bt_f, mut bt_g)) =
self.secant2(op, aa, bb)?;
// L2
if bt_x - at_x > self.gamma * (self.b_x - self.a_x) {
let c_x = (at_x + bt_x) / 2.0;
let tmp = self.init_param.scaled_add(&c_x, &self.search_direction);
let c_f = op.apply(&tmp)?;
let grad = op.gradient(&tmp)?;
let c_g = self.search_direction.dot(&grad);
let ((an_x, an_f, an_g), (bn_x, bn_f, bn_g)) =
self.update(op, (at_x, at_f, at_g), (bt_x, bt_f, bt_g), (c_x, c_f, c_g))?;
at_x = an_x;
at_f = an_f;
at_g = an_g;
bt_x = bn_x;
bt_f = bn_f;
bt_g = bn_g;
}
// L3
self.a_x = at_x;
self.a_f = at_f;
self.a_g = at_g;
self.b_x = bt_x;
self.b_f = bt_f;
self.b_g = bt_g;
self.set_best();
let new_param = self
.init_param
.scaled_add(&self.best_x, &self.search_direction);
Ok(ArgminIterData::new().param(new_param).cost(self.best_f))
}
fn terminate(&mut self, _state: &IterState<O>) -> TerminationReason {
if self.best_f - self.finit < self.delta * self.best_x * self.dginit {
return TerminationReason::LineSearchConditionMet;
}
if self.best_g > self.sigma * self.dginit {
return TerminationReason::LineSearchConditionMet;
}
if (2.0 * self.delta - 1.0) * self.dginit >= self.best_g
&& self.best_g >= self.sigma * self.dginit
&& self.best_f <= self.finit + self.epsilon_k
{
return TerminationReason::LineSearchConditionMet;
}
TerminationReason::NotTerminated
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_trait_impl;
use crate::MinimalNoOperator;
test_trait_impl!(hagerzhang, HagerZhangLineSearch<MinimalNoOperator>);
}
| 30.033748 | 100 | 0.517003 |
d606e7a15fc391dd39d6df79cfa7274623d9ab10 | 11,497 | #![feature(plugin, inclusive_range_syntax, custom_attribute)]
use std::collections::*;
use std::rc::Rc;
static STATIC: [usize; 4] = [0, 1, 8, 16];
const CONST: [usize; 4] = [0, 1, 8, 16];
#[warn(clippy)]
fn for_loop_over_option_and_result() {
let option = Some(1);
let result = option.ok_or("x not found");
let v = vec![0, 1, 2];
// check FOR_LOOP_OVER_OPTION lint
#[clippy(author)]for x in option {
println!("{}", x);
}
// check FOR_LOOP_OVER_RESULT lint
for x in result {
println!("{}", x);
}
for x in option.ok_or("x not found") {
println!("{}", x);
}
// make sure LOOP_OVER_NEXT lint takes precedence when next() is the last call
// in the chain
for x in v.iter().next() {
println!("{}", x);
}
// make sure we lint when next() is not the last call in the chain
for x in v.iter().next().and(Some(0)) {
println!("{}", x);
}
for x in v.iter().next().ok_or("x not found") {
println!("{}", x);
}
// check for false positives
// for loop false positive
for x in v {
println!("{}", x);
}
// while let false positive for Option
while let Some(x) = option {
println!("{}", x);
break;
}
// while let false positive for Result
while let Ok(x) = result {
println!("{}", x);
break;
}
}
struct Unrelated(Vec<u8>);
impl Unrelated {
fn next(&self) -> std::slice::Iter<u8> {
self.0.iter()
}
fn iter(&self) -> std::slice::Iter<u8> {
self.0.iter()
}
}
#[warn(needless_range_loop, explicit_iter_loop, explicit_into_iter_loop, iter_next_loop, reverse_range_loop,
explicit_counter_loop, for_kv_map)]
#[warn(unused_collect)]
#[allow(linkedlist, shadow_unrelated, unnecessary_mut_passed, cyclomatic_complexity, similar_names)]
#[allow(many_single_char_names, unused_variables)]
fn main() {
const MAX_LEN: usize = 42;
let mut vec = vec![1, 2, 3, 4];
let vec2 = vec![1, 2, 3, 4];
for i in 0..vec.len() {
println!("{}", vec[i]);
}
for i in 0..vec.len() {
let i = 42; // make a different `i`
println!("{}", vec[i]); // ok, not the `i` of the for-loop
}
for i in 0..vec.len() {
let _ = vec[i];
}
// ICE #746
for j in 0..4 {
println!("{:?}", STATIC[j]);
}
for j in 0..4 {
println!("{:?}", CONST[j]);
}
for i in 0..vec.len() {
println!("{} {}", vec[i], i);
}
for i in 0..vec.len() {
// not an error, indexing more than one variable
println!("{} {}", vec[i], vec2[i]);
}
for i in 0..vec.len() {
println!("{}", vec2[i]);
}
for i in 5..vec.len() {
println!("{}", vec[i]);
}
for i in 0..MAX_LEN {
println!("{}", vec[i]);
}
for i in 0..=MAX_LEN {
println!("{}", vec[i]);
}
for i in 5..10 {
println!("{}", vec[i]);
}
for i in 5..=10 {
println!("{}", vec[i]);
}
for i in 5..vec.len() {
println!("{} {}", vec[i], i);
}
for i in 5..10 {
println!("{} {}", vec[i], i);
}
for i in 10..0 {
println!("{}", i);
}
for i in 10..=0 {
println!("{}", i);
}
for i in MAX_LEN..0 {
println!("{}", i);
}
for i in 5..5 {
println!("{}", i);
}
for i in 5..=5 {
// not an error, this is the range with only one element “5”
println!("{}", i);
}
for i in 0..10 {
// not an error, the start index is less than the end index
println!("{}", i);
}
for i in -10..0 {
// not an error
println!("{}", i);
}
for i in (10..0).map(|x| x * 2) {
// not an error, it can't be known what arbitrary methods do to a range
println!("{}", i);
}
// testing that the empty range lint folds constants
for i in 10..5 + 4 {
println!("{}", i);
}
for i in (5 + 2)..(3 - 1) {
println!("{}", i);
}
for i in (5 + 2)..(8 - 1) {
println!("{}", i);
}
for i in (2 * 2)..(2 * 3) {
// no error, 4..6 is fine
println!("{}", i);
}
let x = 42;
for i in x..10 {
// no error, not constant-foldable
println!("{}", i);
}
// See #601
for i in 0..10 {
// no error, id_col does not exist outside the loop
let mut id_col = vec![0f64; 10];
id_col[i] = 1f64;
}
for _v in vec.iter() {}
for _v in vec.iter_mut() {}
let out_vec = vec![1, 2, 3];
for _v in out_vec.into_iter() {}
let array = [1, 2, 3];
for _v in array.into_iter() {}
for _v in &vec {} // these are fine
for _v in &mut vec {} // these are fine
for _v in [1, 2, 3].iter() {}
for _v in (&mut [1, 2, 3]).iter() {} // no error
for _v in [0; 32].iter() {}
for _v in [0; 33].iter() {} // no error
let ll: LinkedList<()> = LinkedList::new();
for _v in ll.iter() {}
let vd: VecDeque<()> = VecDeque::new();
for _v in vd.iter() {}
let bh: BinaryHeap<()> = BinaryHeap::new();
for _v in bh.iter() {}
let hm: HashMap<(), ()> = HashMap::new();
for _v in hm.iter() {}
let bt: BTreeMap<(), ()> = BTreeMap::new();
for _v in bt.iter() {}
let hs: HashSet<()> = HashSet::new();
for _v in hs.iter() {}
let bs: BTreeSet<()> = BTreeSet::new();
for _v in bs.iter() {}
for _v in vec.iter().next() {}
let u = Unrelated(vec![]);
for _v in u.next() {} // no error
for _v in u.iter() {} // no error
let mut out = vec![];
vec.iter().cloned().map(|x| out.push(x)).collect::<Vec<_>>();
let _y = vec.iter().cloned().map(|x| out.push(x)).collect::<Vec<_>>(); // this is fine
// Loop with explicit counter variable
let mut _index = 0;
for _v in &vec {
_index += 1
}
let mut _index = 1;
_index = 0;
for _v in &vec {
_index += 1
}
// Potential false positives
let mut _index = 0;
_index = 1;
for _v in &vec {
_index += 1
}
let mut _index = 0;
_index += 1;
for _v in &vec {
_index += 1
}
let mut _index = 0;
if true {
_index = 1
}
for _v in &vec {
_index += 1
}
let mut _index = 0;
let mut _index = 1;
for _v in &vec {
_index += 1
}
let mut _index = 0;
for _v in &vec {
_index += 1;
_index += 1
}
let mut _index = 0;
for _v in &vec {
_index *= 2;
_index += 1
}
let mut _index = 0;
for _v in &vec {
_index = 1;
_index += 1
}
let mut _index = 0;
for _v in &vec {
let mut _index = 0;
_index += 1
}
let mut _index = 0;
for _v in &vec {
_index += 1;
_index = 0;
}
let mut _index = 0;
for _v in &vec {
for _x in 0..1 {
_index += 1;
}
_index += 1
}
let mut _index = 0;
for x in &vec {
if *x == 1 {
_index += 1
}
}
let mut _index = 0;
if true {
_index = 1
};
for _v in &vec {
_index += 1
}
let mut _index = 1;
if false {
_index = 0
};
for _v in &vec {
_index += 1
}
let mut index = 0;
{
let mut _x = &mut index;
}
for _v in &vec {
_index += 1
}
let mut index = 0;
for _v in &vec {
index += 1
}
println!("index: {}", index);
for_loop_over_option_and_result();
let m: HashMap<u64, u64> = HashMap::new();
for (_, v) in &m {
let _v = v;
}
let m: Rc<HashMap<u64, u64>> = Rc::new(HashMap::new());
for (_, v) in &*m {
let _v = v;
// Here the `*` is not actually necesarry, but the test tests that we don't
// suggest
// `in *m.values()` as we used to
}
let mut m: HashMap<u64, u64> = HashMap::new();
for (_, v) in &mut m {
let _v = v;
}
let m: &mut HashMap<u64, u64> = &mut HashMap::new();
for (_, v) in &mut *m {
let _v = v;
}
let m: HashMap<u64, u64> = HashMap::new();
let rm = &m;
for (k, _value) in rm {
let _k = k;
}
test_for_kv_map();
fn f<T>(_: &T, _: &T) -> bool {
unimplemented!()
}
fn g<T>(_: &mut [T], _: usize, _: usize) {
unimplemented!()
}
for i in 1..vec.len() {
if f(&vec[i - 1], &vec[i]) {
g(&mut vec, i - 1, i);
}
}
for mid in 1..vec.len() {
let (_, _) = vec.split_at(mid);
}
}
#[allow(used_underscore_binding)]
fn test_for_kv_map() {
let m: HashMap<u64, u64> = HashMap::new();
// No error, _value is actually used
for (k, _value) in &m {
let _ = _value;
let _k = k;
}
}
#[allow(dead_code)]
fn partition<T: PartialOrd + Send>(v: &mut [T]) -> usize {
let pivot = v.len() - 1;
let mut i = 0;
for j in 0..pivot {
if v[j] <= v[pivot] {
v.swap(i, j);
i += 1;
}
}
v.swap(i, pivot);
i
}
const LOOP_OFFSET: usize = 5000;
#[warn(needless_range_loop)]
pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) {
// plain manual memcpy
for i in 0..src.len() {
dst[i] = src[i];
}
// dst offset memcpy
for i in 0..src.len() {
dst[i + 10] = src[i];
}
// src offset memcpy
for i in 0..src.len() {
dst[i] = src[i + 10];
}
// src offset memcpy
for i in 11..src.len() {
dst[i] = src[i - 10];
}
// overwrite entire dst
for i in 0..dst.len() {
dst[i] = src[i];
}
// manual copy with branch - can't easily convert to memcpy!
for i in 0..src.len() {
dst[i] = src[i];
if dst[i] > 5 {
break;
}
}
// multiple copies - suggest two memcpy statements
for i in 10..256 {
dst[i] = src[i - 5];
dst2[i + 500] = src[i]
}
// this is a reversal - the copy lint shouldn't be triggered
for i in 10..LOOP_OFFSET {
dst[i + LOOP_OFFSET] = src[LOOP_OFFSET - i];
}
let some_var = 5;
// Offset in variable
for i in 10..LOOP_OFFSET {
dst[i + LOOP_OFFSET] = src[i - some_var];
}
// Non continuous copy - don't trigger lint
for i in 0..10 {
dst[i + i] = src[i];
}
let src_vec = vec![1, 2, 3, 4, 5];
let mut dst_vec = vec![0, 0, 0, 0, 0];
// make sure vectors are supported
for i in 0..src_vec.len() {
dst_vec[i] = src_vec[i];
}
// lint should not trigger when either
// source or destination type is not
// slice-like, like DummyStruct
struct DummyStruct(i32);
impl ::std::ops::Index<usize> for DummyStruct {
type Output = i32;
fn index(&self, _: usize) -> &i32 {
&self.0
}
}
let src = DummyStruct(5);
let mut dst_vec = vec![0; 10];
for i in 0..10 {
dst_vec[i] = src[i];
}
}
#[warn(needless_range_loop)]
pub fn manual_clone(src: &[String], dst: &mut [String]) {
for i in 0..src.len() {
dst[i] = src[i].clone();
}
}
#[warn(needless_range_loop)]
pub fn manual_copy_same_destination(dst: &mut [i32], d: usize, s: usize) {
// Same source and destination - don't trigger lint
for i in 0..dst.len() {
dst[d + i] = dst[s + i];
}
}
| 20.567084 | 108 | 0.47856 |
38159fca57f64aa995ee5a4f01eb1f3d1fb911d4 | 961 | //! Helix endpoints regarding clips
//!
//! # Examples
//!
//! ```rust,no_run
//! # use twitch_api2::helix::{HelixClient, clips::GetClipsRequest};
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
//! let client = HelixClient::new();
//! # let _: &HelixClient<twitch_api2::DummyHttpClient> = &client;
//! # let token = twitch_oauth2::AccessToken::new("validtoken".to_string());
//! # let token = twitch_oauth2::UserToken::from_existing(&client, token, None, None).await?;
//! let req = GetClipsRequest::builder()
//! .game_id(Some("1234".into()))
//! .first(100) // max 100, 20 if left unspecified
//! .build();
//!
//! println!("{:?}", &client.req_get(req, &token).await?.data.get(0));
//! # Ok(())
//! # }
//! ```
use crate::{
helix::{self, Request},
types,
};
use serde::{Deserialize, Serialize};
pub mod get_clips;
#[doc(inline)]
pub use get_clips::{Clip, GetClipsRequest};
| 30.03125 | 93 | 0.612903 |
9c63997ce2f9586d7abe866a40679e9a21ee8bfe | 621 | use crate::abi::Endian;
use crate::spec::{LinkerFlavor, Target, TargetOptions};
pub fn target() -> Target {
let mut base = super::vxworks_base::opts();
base.cpu = "ppc64".to_string();
base.pre_link_args.entry(LinkerFlavor::Gcc).or_default().push("-m64".to_string());
base.max_atomic_width = Some(64);
Target {
llvm_target: "powerpc64-unknown-linux-gnu".to_string(),
pointer_width: 64,
data_layout: "E-m:e-i64:64-n32:64-S128-v256:256:256-v512:512:512".to_string(),
arch: "powerpc64".to_string(),
options: TargetOptions { endian: Endian::Big, ..base },
}
}
| 34.5 | 86 | 0.645733 |
7203d7951a0cfc9774b94cb141672ada4a30f6d9 | 1,796 | use cgisf_lib::cgisf;
use rand::seq::SliceRandom;
use serde::Deserialize;
use serde_json::from_str;
use include_dir::{include_dir, Dir};
use rand::Rng;
use std::error::Error;
static LANG_DIR: Dir = include_dir!("src/lang");
#[allow(dead_code)]
#[derive(Deserialize, Clone, Debug)]
pub struct Language {
name: String,
size: u32,
words: Vec<String>,
}
impl Language {
pub fn new(file_name: String) -> Self {
read_language_from_file(format!("{}.json", file_name)).unwrap()
}
pub fn get_random_sentence(&self, num: usize) -> (Vec<String>, usize) {
let rng = &mut rand::thread_rng();
let mut vec = Vec::new();
let mut word_count = 0;
for i in 0..num {
let mut s = cgisf(
rng.gen_range(1..3),
rng.gen_range(1..3),
rng.gen_range(1..5),
rng.gen_bool(0.5),
rng.gen_range(1..3),
rng.gen_bool(0.5),
);
word_count += &s.matches(' ').count();
// gets the word count of the sentence.
if i == num - 1 {
s.pop();
}
vec.push(s);
}
(vec, word_count)
}
pub fn get_random(&self, num: usize) -> Vec<String> {
let mut rng = &mut rand::thread_rng();
self.words.choose_multiple(&mut rng, num).cloned().collect()
}
}
fn read_language_from_file(file_name: String) -> Result<Language, Box<dyn Error>> {
let file = LANG_DIR
.get_file(file_name)
.expect("Language file not found");
let file_as_str = file
.contents_utf8()
.expect("Unable to interpret file as a string");
let lang = from_str(file_as_str).expect("Unable to deserialize language json");
Ok(lang)
}
| 26.411765 | 83 | 0.558463 |
9bf0382312e989ece3f4ee28215ff56e9e5f0361 | 29,773 | use crate::fmt;
use crate::hash::Hash;
/// An unbounded range (`..`).
///
/// `RangeFull` is primarily used as a [slicing index], its shorthand is `..`.
/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
///
/// # Examples
///
/// The `..` syntax is a `RangeFull`:
///
/// ```
/// assert_eq!((..), std::ops::RangeFull);
/// ```
///
/// It does not have an [`IntoIterator`] implementation, so you can't use it in
/// a `for` loop directly. This won't compile:
///
/// ```compile_fail,E0277
/// for i in .. {
/// // ...
/// }
/// ```
///
/// Used as a [slicing index], `RangeFull` produces the full array as a slice.
///
/// ```
/// let arr = [0, 1, 2, 3, 4];
/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); // This is the `RangeFull`
/// assert_eq!(arr[ .. 3], [0, 1, 2 ]);
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]);
/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]);
/// assert_eq!(arr[1.. 3], [ 1, 2 ]);
/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]);
/// ```
///
/// [slicing index]: crate::slice::SliceIndex
#[lang = "RangeFull"]
#[doc(alias = "..")]
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RangeFull;
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for RangeFull {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "..")
}
}
/// A (half-open) range bounded inclusively below and exclusively above
/// (`start..end`).
///
/// The range `start..end` contains all values with `start <= x < end`.
/// It is empty if `start >= end`.
///
/// # Examples
///
/// The `start..end` syntax is a `Range`:
///
/// ```
/// assert_eq!((3..5), std::ops::Range { start: 3, end: 5 });
/// assert_eq!(3 + 4 + 5, (3..6).sum());
/// ```
///
/// ```
/// let arr = [0, 1, 2, 3, 4];
/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
/// assert_eq!(arr[ .. 3], [0, 1, 2 ]);
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]);
/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]);
/// assert_eq!(arr[1.. 3], [ 1, 2 ]); // This is a `Range`
/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]);
/// ```
#[lang = "Range"]
#[doc(alias = "..")]
#[derive(Clone, Default, PartialEq, Eq, Hash)] // not Copy -- see #27186
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Range<Idx> {
/// The lower bound of the range (inclusive).
#[stable(feature = "rust1", since = "1.0.0")]
pub start: Idx,
/// The upper bound of the range (exclusive).
#[stable(feature = "rust1", since = "1.0.0")]
pub end: Idx,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.start.fmt(fmt)?;
write!(fmt, "..")?;
self.end.fmt(fmt)?;
Ok(())
}
}
impl<Idx: PartialOrd<Idx>> Range<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// assert!(!(3..5).contains(&2));
/// assert!( (3..5).contains(&3));
/// assert!( (3..5).contains(&4));
/// assert!(!(3..5).contains(&5));
///
/// assert!(!(3..3).contains(&3));
/// assert!(!(3..2).contains(&3));
///
/// assert!( (0.0..1.0).contains(&0.5));
/// assert!(!(0.0..1.0).contains(&f32::NAN));
/// assert!(!(0.0..f32::NAN).contains(&0.5));
/// assert!(!(f32::NAN..1.0).contains(&0.5));
/// ```
#[stable(feature = "range_contains", since = "1.35.0")]
pub fn contains<U>(&self, item: &U) -> bool
where
Idx: PartialOrd<U>,
U: ?Sized + PartialOrd<Idx>,
{
<Self as RangeBounds<Idx>>::contains(self, item)
}
/// Returns `true` if the range contains no items.
///
/// # Examples
///
/// ```
/// assert!(!(3..5).is_empty());
/// assert!( (3..3).is_empty());
/// assert!( (3..2).is_empty());
/// ```
///
/// The range is empty if either side is incomparable:
///
/// ```
/// assert!(!(3.0..5.0).is_empty());
/// assert!( (3.0..f32::NAN).is_empty());
/// assert!( (f32::NAN..5.0).is_empty());
/// ```
#[stable(feature = "range_is_empty", since = "1.47.0")]
pub fn is_empty(&self) -> bool {
!(self.start < self.end)
}
}
/// A range only bounded inclusively below (`start..`).
///
/// The `RangeFrom` `start..` contains all values with `x >= start`.
///
/// *Note*: Overflow in the [`Iterator`] implementation (when the contained
/// data type reaches its numerical limit) is allowed to panic, wrap, or
/// saturate. This behavior is defined by the implementation of the [`Step`]
/// trait. For primitive integers, this follows the normal rules, and respects
/// the overflow checks profile (panic in debug, wrap in release). Note also
/// that overflow happens earlier than you might assume: the overflow happens
/// in the call to `next` that yields the maximum value, as the range must be
/// set to a state to yield the next value.
///
/// [`Step`]: crate::iter::Step
///
/// # Examples
///
/// The `start..` syntax is a `RangeFrom`:
///
/// ```
/// assert_eq!((2..), std::ops::RangeFrom { start: 2 });
/// assert_eq!(2 + 3 + 4, (2..).take(3).sum());
/// ```
///
/// ```
/// let arr = [0, 1, 2, 3, 4];
/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
/// assert_eq!(arr[ .. 3], [0, 1, 2 ]);
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]);
/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]); // This is a `RangeFrom`
/// assert_eq!(arr[1.. 3], [ 1, 2 ]);
/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]);
/// ```
#[lang = "RangeFrom"]
#[doc(alias = "..")]
#[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RangeFrom<Idx> {
/// The lower bound of the range (inclusive).
#[stable(feature = "rust1", since = "1.0.0")]
pub start: Idx,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.start.fmt(fmt)?;
write!(fmt, "..")?;
Ok(())
}
}
impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// assert!(!(3..).contains(&2));
/// assert!( (3..).contains(&3));
/// assert!( (3..).contains(&1_000_000_000));
///
/// assert!( (0.0..).contains(&0.5));
/// assert!(!(0.0..).contains(&f32::NAN));
/// assert!(!(f32::NAN..).contains(&0.5));
/// ```
#[stable(feature = "range_contains", since = "1.35.0")]
pub fn contains<U>(&self, item: &U) -> bool
where
Idx: PartialOrd<U>,
U: ?Sized + PartialOrd<Idx>,
{
<Self as RangeBounds<Idx>>::contains(self, item)
}
}
/// A range only bounded exclusively above (`..end`).
///
/// The `RangeTo` `..end` contains all values with `x < end`.
/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
///
/// # Examples
///
/// The `..end` syntax is a `RangeTo`:
///
/// ```
/// assert_eq!((..5), std::ops::RangeTo { end: 5 });
/// ```
///
/// It does not have an [`IntoIterator`] implementation, so you can't use it in
/// a `for` loop directly. This won't compile:
///
/// ```compile_fail,E0277
/// // error[E0277]: the trait bound `std::ops::RangeTo<{integer}>:
/// // std::iter::Iterator` is not satisfied
/// for i in ..5 {
/// // ...
/// }
/// ```
///
/// When used as a [slicing index], `RangeTo` produces a slice of all array
/// elements before the index indicated by `end`.
///
/// ```
/// let arr = [0, 1, 2, 3, 4];
/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
/// assert_eq!(arr[ .. 3], [0, 1, 2 ]); // This is a `RangeTo`
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]);
/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]);
/// assert_eq!(arr[1.. 3], [ 1, 2 ]);
/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]);
/// ```
///
/// [slicing index]: crate::slice::SliceIndex
#[lang = "RangeTo"]
#[doc(alias = "..")]
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RangeTo<Idx> {
/// The upper bound of the range (exclusive).
#[stable(feature = "rust1", since = "1.0.0")]
pub end: Idx,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "..")?;
self.end.fmt(fmt)?;
Ok(())
}
}
impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// assert!( (..5).contains(&-1_000_000_000));
/// assert!( (..5).contains(&4));
/// assert!(!(..5).contains(&5));
///
/// assert!( (..1.0).contains(&0.5));
/// assert!(!(..1.0).contains(&f32::NAN));
/// assert!(!(..f32::NAN).contains(&0.5));
/// ```
#[stable(feature = "range_contains", since = "1.35.0")]
pub fn contains<U>(&self, item: &U) -> bool
where
Idx: PartialOrd<U>,
U: ?Sized + PartialOrd<Idx>,
{
<Self as RangeBounds<Idx>>::contains(self, item)
}
}
/// A range bounded inclusively below and above (`start..=end`).
///
/// The `RangeInclusive` `start..=end` contains all values with `x >= start`
/// and `x <= end`. It is empty unless `start <= end`.
///
/// This iterator is [fused], but the specific values of `start` and `end` after
/// iteration has finished are **unspecified** other than that [`.is_empty()`]
/// will return `true` once no more values will be produced.
///
/// [fused]: crate::iter::FusedIterator
/// [`.is_empty()`]: RangeInclusive::is_empty
///
/// # Examples
///
/// The `start..=end` syntax is a `RangeInclusive`:
///
/// ```
/// assert_eq!((3..=5), std::ops::RangeInclusive::new(3, 5));
/// assert_eq!(3 + 4 + 5, (3..=5).sum());
/// ```
///
/// ```
/// let arr = [0, 1, 2, 3, 4];
/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
/// assert_eq!(arr[ .. 3], [0, 1, 2 ]);
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]);
/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]);
/// assert_eq!(arr[1.. 3], [ 1, 2 ]);
/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]); // This is a `RangeInclusive`
/// ```
#[lang = "RangeInclusive"]
#[doc(alias = "..=")]
#[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
#[stable(feature = "inclusive_range", since = "1.26.0")]
pub struct RangeInclusive<Idx> {
// Note that the fields here are not public to allow changing the
// representation in the future; in particular, while we could plausibly
// expose start/end, modifying them without changing (future/current)
// private fields may lead to incorrect behavior, so we don't want to
// support that mode.
pub(crate) start: Idx,
pub(crate) end: Idx,
// This field is:
// - `false` upon construction
// - `false` when iteration has yielded an element and the iterator is not exhausted
// - `true` when iteration has been used to exhaust the iterator
//
// This is required to support PartialEq and Hash without a PartialOrd bound or specialization.
pub(crate) exhausted: bool,
}
impl<Idx> RangeInclusive<Idx> {
/// Creates a new inclusive range. Equivalent to writing `start..=end`.
///
/// # Examples
///
/// ```
/// use std::ops::RangeInclusive;
///
/// assert_eq!(3..=5, RangeInclusive::new(3, 5));
/// ```
#[lang = "range_inclusive_new"]
#[stable(feature = "inclusive_range_methods", since = "1.27.0")]
#[inline]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_range_new", since = "1.32.0")]
pub const fn new(start: Idx, end: Idx) -> Self {
Self { start, end, exhausted: false }
}
/// Returns the lower bound of the range (inclusive).
///
/// When using an inclusive range for iteration, the values of `start()` and
/// [`end()`] are unspecified after the iteration ended. To determine
/// whether the inclusive range is empty, use the [`is_empty()`] method
/// instead of comparing `start() > end()`.
///
/// Note: the value returned by this method is unspecified after the range
/// has been iterated to exhaustion.
///
/// [`end()`]: RangeInclusive::end
/// [`is_empty()`]: RangeInclusive::is_empty
///
/// # Examples
///
/// ```
/// assert_eq!((3..=5).start(), &3);
/// ```
#[stable(feature = "inclusive_range_methods", since = "1.27.0")]
#[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
#[inline]
pub const fn start(&self) -> &Idx {
&self.start
}
/// Returns the upper bound of the range (inclusive).
///
/// When using an inclusive range for iteration, the values of [`start()`]
/// and `end()` are unspecified after the iteration ended. To determine
/// whether the inclusive range is empty, use the [`is_empty()`] method
/// instead of comparing `start() > end()`.
///
/// Note: the value returned by this method is unspecified after the range
/// has been iterated to exhaustion.
///
/// [`start()`]: RangeInclusive::start
/// [`is_empty()`]: RangeInclusive::is_empty
///
/// # Examples
///
/// ```
/// assert_eq!((3..=5).end(), &5);
/// ```
#[stable(feature = "inclusive_range_methods", since = "1.27.0")]
#[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
#[inline]
pub const fn end(&self) -> &Idx {
&self.end
}
/// Destructures the `RangeInclusive` into (lower bound, upper (inclusive) bound).
///
/// Note: the value returned by this method is unspecified after the range
/// has been iterated to exhaustion.
///
/// # Examples
///
/// ```
/// assert_eq!((3..=5).into_inner(), (3, 5));
/// ```
#[stable(feature = "inclusive_range_methods", since = "1.27.0")]
#[inline]
pub fn into_inner(self) -> (Idx, Idx) {
(self.start, self.end)
}
}
impl RangeInclusive<usize> {
/// Converts to an exclusive `Range` for `SliceIndex` implementations.
/// The caller is responsible for dealing with `end == usize::MAX`.
#[inline]
pub(crate) fn into_slice_range(self) -> Range<usize> {
// If we're not exhausted, we want to simply slice `start..end + 1`.
// If we are exhausted, then slicing with `end + 1..end + 1` gives us an
// empty range that is still subject to bounds-checks for that endpoint.
let exclusive_end = self.end + 1;
let start = if self.exhausted { exclusive_end } else { self.start };
start..exclusive_end
}
}
#[stable(feature = "inclusive_range", since = "1.26.0")]
impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.start.fmt(fmt)?;
write!(fmt, "..=")?;
self.end.fmt(fmt)?;
if self.exhausted {
write!(fmt, " (exhausted)")?;
}
Ok(())
}
}
impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// assert!(!(3..=5).contains(&2));
/// assert!( (3..=5).contains(&3));
/// assert!( (3..=5).contains(&4));
/// assert!( (3..=5).contains(&5));
/// assert!(!(3..=5).contains(&6));
///
/// assert!( (3..=3).contains(&3));
/// assert!(!(3..=2).contains(&3));
///
/// assert!( (0.0..=1.0).contains(&1.0));
/// assert!(!(0.0..=1.0).contains(&f32::NAN));
/// assert!(!(0.0..=f32::NAN).contains(&0.0));
/// assert!(!(f32::NAN..=1.0).contains(&1.0));
/// ```
///
/// This method always returns `false` after iteration has finished:
///
/// ```
/// let mut r = 3..=5;
/// assert!(r.contains(&3) && r.contains(&5));
/// for _ in r.by_ref() {}
/// // Precise field values are unspecified here
/// assert!(!r.contains(&3) && !r.contains(&5));
/// ```
#[stable(feature = "range_contains", since = "1.35.0")]
pub fn contains<U>(&self, item: &U) -> bool
where
Idx: PartialOrd<U>,
U: ?Sized + PartialOrd<Idx>,
{
<Self as RangeBounds<Idx>>::contains(self, item)
}
/// Returns `true` if the range contains no items.
///
/// # Examples
///
/// ```
/// assert!(!(3..=5).is_empty());
/// assert!(!(3..=3).is_empty());
/// assert!( (3..=2).is_empty());
/// ```
///
/// The range is empty if either side is incomparable:
///
/// ```
/// assert!(!(3.0..=5.0).is_empty());
/// assert!( (3.0..=f32::NAN).is_empty());
/// assert!( (f32::NAN..=5.0).is_empty());
/// ```
///
/// This method returns `true` after iteration has finished:
///
/// ```
/// let mut r = 3..=5;
/// for _ in r.by_ref() {}
/// // Precise field values are unspecified here
/// assert!(r.is_empty());
/// ```
#[stable(feature = "range_is_empty", since = "1.47.0")]
#[inline]
pub fn is_empty(&self) -> bool {
self.exhausted || !(self.start <= self.end)
}
}
/// A range only bounded inclusively above (`..=end`).
///
/// The `RangeToInclusive` `..=end` contains all values with `x <= end`.
/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
///
/// # Examples
///
/// The `..=end` syntax is a `RangeToInclusive`:
///
/// ```
/// assert_eq!((..=5), std::ops::RangeToInclusive{ end: 5 });
/// ```
///
/// It does not have an [`IntoIterator`] implementation, so you can't use it in a
/// `for` loop directly. This won't compile:
///
/// ```compile_fail,E0277
/// // error[E0277]: the trait bound `std::ops::RangeToInclusive<{integer}>:
/// // std::iter::Iterator` is not satisfied
/// for i in ..=5 {
/// // ...
/// }
/// ```
///
/// When used as a [slicing index], `RangeToInclusive` produces a slice of all
/// array elements up to and including the index indicated by `end`.
///
/// ```
/// let arr = [0, 1, 2, 3, 4];
/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
/// assert_eq!(arr[ .. 3], [0, 1, 2 ]);
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); // This is a `RangeToInclusive`
/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]);
/// assert_eq!(arr[1.. 3], [ 1, 2 ]);
/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]);
/// ```
///
/// [slicing index]: crate::slice::SliceIndex
#[lang = "RangeToInclusive"]
#[doc(alias = "..=")]
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[stable(feature = "inclusive_range", since = "1.26.0")]
pub struct RangeToInclusive<Idx> {
/// The upper bound of the range (inclusive)
#[stable(feature = "inclusive_range", since = "1.26.0")]
pub end: Idx,
}
#[stable(feature = "inclusive_range", since = "1.26.0")]
impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "..=")?;
self.end.fmt(fmt)?;
Ok(())
}
}
impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// assert!( (..=5).contains(&-1_000_000_000));
/// assert!( (..=5).contains(&5));
/// assert!(!(..=5).contains(&6));
///
/// assert!( (..=1.0).contains(&1.0));
/// assert!(!(..=1.0).contains(&f32::NAN));
/// assert!(!(..=f32::NAN).contains(&0.5));
/// ```
#[stable(feature = "range_contains", since = "1.35.0")]
pub fn contains<U>(&self, item: &U) -> bool
where
Idx: PartialOrd<U>,
U: ?Sized + PartialOrd<Idx>,
{
<Self as RangeBounds<Idx>>::contains(self, item)
}
}
// RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
// because underflow would be possible with (..0).into()
/// An endpoint of a range of keys.
///
/// # Examples
///
/// `Bound`s are range endpoints:
///
/// ```
/// use std::ops::Bound::*;
/// use std::ops::RangeBounds;
///
/// assert_eq!((..100).start_bound(), Unbounded);
/// assert_eq!((1..12).start_bound(), Included(&1));
/// assert_eq!((1..12).end_bound(), Excluded(&12));
/// ```
///
/// Using a tuple of `Bound`s as an argument to [`BTreeMap::range`].
/// Note that in most cases, it's better to use range syntax (`1..5`) instead.
///
/// ```
/// use std::collections::BTreeMap;
/// use std::ops::Bound::{Excluded, Included, Unbounded};
///
/// let mut map = BTreeMap::new();
/// map.insert(3, "a");
/// map.insert(5, "b");
/// map.insert(8, "c");
///
/// for (key, value) in map.range((Excluded(3), Included(8))) {
/// println!("{}: {}", key, value);
/// }
///
/// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next());
/// ```
///
/// [`BTreeMap::range`]: ../../std/collections/btree_map/struct.BTreeMap.html#method.range
#[stable(feature = "collections_bound", since = "1.17.0")]
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum Bound<T> {
/// An inclusive bound.
#[stable(feature = "collections_bound", since = "1.17.0")]
Included(#[stable(feature = "collections_bound", since = "1.17.0")] T),
/// An exclusive bound.
#[stable(feature = "collections_bound", since = "1.17.0")]
Excluded(#[stable(feature = "collections_bound", since = "1.17.0")] T),
/// An infinite endpoint. Indicates that there is no bound in this direction.
#[stable(feature = "collections_bound", since = "1.17.0")]
Unbounded,
}
impl<T> Bound<T> {
/// Converts from `&Bound<T>` to `Bound<&T>`.
#[inline]
#[unstable(feature = "bound_as_ref", issue = "80996")]
pub fn as_ref(&self) -> Bound<&T> {
match *self {
Included(ref x) => Included(x),
Excluded(ref x) => Excluded(x),
Unbounded => Unbounded,
}
}
/// Converts from `&mut Bound<T>` to `Bound<&mut T>`.
#[inline]
#[unstable(feature = "bound_as_ref", issue = "80996")]
pub fn as_mut(&mut self) -> Bound<&mut T> {
match *self {
Included(ref mut x) => Included(x),
Excluded(ref mut x) => Excluded(x),
Unbounded => Unbounded,
}
}
/// Maps a `Bound<T>` to a `Bound<U>` by applying a function to the contained value (including
/// both `Included` and `Excluded`), returning a `Bound` of the same kind.
///
/// # Examples
///
/// ```
/// #![feature(bound_map)]
/// use std::ops::Bound::*;
///
/// let bound_string = Included("Hello, World!");
///
/// assert_eq!(bound_string.map(|s| s.len()), Included(13));
/// ```
///
/// ```
/// #![feature(bound_map)]
/// use std::ops::Bound;
/// use Bound::*;
///
/// let unbounded_string: Bound<String> = Unbounded;
///
/// assert_eq!(unbounded_string.map(|s| s.len()), Unbounded);
/// ```
#[inline]
#[unstable(feature = "bound_map", issue = "86026")]
pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Bound<U> {
match self {
Unbounded => Unbounded,
Included(x) => Included(f(x)),
Excluded(x) => Excluded(f(x)),
}
}
}
impl<T: Clone> Bound<&T> {
/// Map a `Bound<&T>` to a `Bound<T>` by cloning the contents of the bound.
///
/// # Examples
///
/// ```
/// use std::ops::Bound::*;
/// use std::ops::RangeBounds;
///
/// assert_eq!((1..12).start_bound(), Included(&1));
/// assert_eq!((1..12).start_bound().cloned(), Included(1));
/// ```
#[stable(feature = "bound_cloned", since = "1.55.0")]
pub fn cloned(self) -> Bound<T> {
match self {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(x) => Bound::Included(x.clone()),
Bound::Excluded(x) => Bound::Excluded(x.clone()),
}
}
}
/// `RangeBounds` is implemented by Rust's built-in range types, produced
/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
#[stable(feature = "collections_range", since = "1.28.0")]
pub trait RangeBounds<T: ?Sized> {
/// Start index bound.
///
/// Returns the start value as a `Bound`.
///
/// # Examples
///
/// ```
/// # fn main() {
/// use std::ops::Bound::*;
/// use std::ops::RangeBounds;
///
/// assert_eq!((..10).start_bound(), Unbounded);
/// assert_eq!((3..10).start_bound(), Included(&3));
/// # }
/// ```
#[stable(feature = "collections_range", since = "1.28.0")]
fn start_bound(&self) -> Bound<&T>;
/// End index bound.
///
/// Returns the end value as a `Bound`.
///
/// # Examples
///
/// ```
/// # fn main() {
/// use std::ops::Bound::*;
/// use std::ops::RangeBounds;
///
/// assert_eq!((3..).end_bound(), Unbounded);
/// assert_eq!((3..10).end_bound(), Excluded(&10));
/// # }
/// ```
#[stable(feature = "collections_range", since = "1.28.0")]
fn end_bound(&self) -> Bound<&T>;
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// assert!( (3..5).contains(&4));
/// assert!(!(3..5).contains(&2));
///
/// assert!( (0.0..1.0).contains(&0.5));
/// assert!(!(0.0..1.0).contains(&f32::NAN));
/// assert!(!(0.0..f32::NAN).contains(&0.5));
/// assert!(!(f32::NAN..1.0).contains(&0.5));
#[stable(feature = "range_contains", since = "1.35.0")]
fn contains<U>(&self, item: &U) -> bool
where
T: PartialOrd<U>,
U: ?Sized + PartialOrd<T>,
{
(match self.start_bound() {
Included(ref start) => *start <= item,
Excluded(ref start) => *start < item,
Unbounded => true,
}) && (match self.end_bound() {
Included(ref end) => item <= *end,
Excluded(ref end) => item < *end,
Unbounded => true,
})
}
}
use self::Bound::{Excluded, Included, Unbounded};
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T: ?Sized> RangeBounds<T> for RangeFull {
fn start_bound(&self) -> Bound<&T> {
Unbounded
}
fn end_bound(&self) -> Bound<&T> {
Unbounded
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeFrom<T> {
fn start_bound(&self) -> Bound<&T> {
Included(&self.start)
}
fn end_bound(&self) -> Bound<&T> {
Unbounded
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeTo<T> {
fn start_bound(&self) -> Bound<&T> {
Unbounded
}
fn end_bound(&self) -> Bound<&T> {
Excluded(&self.end)
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for Range<T> {
fn start_bound(&self) -> Bound<&T> {
Included(&self.start)
}
fn end_bound(&self) -> Bound<&T> {
Excluded(&self.end)
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeInclusive<T> {
fn start_bound(&self) -> Bound<&T> {
Included(&self.start)
}
fn end_bound(&self) -> Bound<&T> {
if self.exhausted {
// When the iterator is exhausted, we usually have start == end,
// but we want the range to appear empty, containing nothing.
Excluded(&self.end)
} else {
Included(&self.end)
}
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeToInclusive<T> {
fn start_bound(&self) -> Bound<&T> {
Unbounded
}
fn end_bound(&self) -> Bound<&T> {
Included(&self.end)
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for (Bound<T>, Bound<T>) {
fn start_bound(&self) -> Bound<&T> {
match *self {
(Included(ref start), _) => Included(start),
(Excluded(ref start), _) => Excluded(start),
(Unbounded, _) => Unbounded,
}
}
fn end_bound(&self) -> Bound<&T> {
match *self {
(_, Included(ref end)) => Included(end),
(_, Excluded(ref end)) => Excluded(end),
(_, Unbounded) => Unbounded,
}
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<'a, T: ?Sized + 'a> RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
fn start_bound(&self) -> Bound<&T> {
self.0
}
fn end_bound(&self) -> Bound<&T> {
self.1
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeFrom<&T> {
fn start_bound(&self) -> Bound<&T> {
Included(self.start)
}
fn end_bound(&self) -> Bound<&T> {
Unbounded
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeTo<&T> {
fn start_bound(&self) -> Bound<&T> {
Unbounded
}
fn end_bound(&self) -> Bound<&T> {
Excluded(self.end)
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for Range<&T> {
fn start_bound(&self) -> Bound<&T> {
Included(self.start)
}
fn end_bound(&self) -> Bound<&T> {
Excluded(self.end)
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeInclusive<&T> {
fn start_bound(&self) -> Bound<&T> {
Included(self.start)
}
fn end_bound(&self) -> Bound<&T> {
Included(self.end)
}
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeToInclusive<&T> {
fn start_bound(&self) -> Bound<&T> {
Unbounded
}
fn end_bound(&self) -> Bound<&T> {
Included(self.end)
}
}
| 30.599178 | 99 | 0.534242 |
bf1b18e2fd2f584cf6ab3ccddf834ebb2a466a9d | 14,725 | /* diosix hypervisor code for handling hardware interrupts and software exceptions
*
* (c) Chris Williams, 2019-2021.
*
* See LICENSE for usage and copying.
*/
use super::scheduler;
use super::capsule;
use super::pcore;
use super::hardware;
use super::service;
use super::error::Cause;
/* platform-specific code must implement all this */
use platform;
use platform::irq::{IRQContext, IRQType, IRQCause, IRQSeverity, IRQ};
use platform::cpu::PrivilegeMode;
use platform::instructions::{self, EmulationResult};
use platform::syscalls;
use platform::timer;
/* hypervisor_irq_handler
entry point for hardware interrupts and software exceptions, collectively known as IRQs.
call down into platform-specific handlers
=> context = platform-specific context of the IRQ, which may be modified depending
on the IRQ raised.
*/
#[no_mangle]
pub extern "C" fn hypervisor_irq_handler(mut context: IRQContext)
{
/* if dispatch() returns an IRQ context then we need to handle it here
at the high level. if it returns None, the platform-specific code handled it.
note: the platform library should take care of hardware specfic things like
catching illegal instructions that can be fixed up and handled transparently */
if let Some(irq) = platform::irq::dispatch(context)
{
match irq.irq_type
{
IRQType::Exception => exception(irq, &mut context),
IRQType::Interrupt => interrupt(irq, &mut context),
};
}
}
/* handle software exception */
fn exception(irq: IRQ, context: &mut IRQContext)
{
match (irq.severity, irq.privilege_mode, irq.cause)
{
/* catch illegal instructions we may be able to emulate */
(_, PrivilegeMode::User, IRQCause::IllegalInstruction) |
(_, PrivilegeMode::Supervisor, IRQCause::IllegalInstruction) =>
{
match instructions::emulate(irq.privilege_mode, context)
{
EmulationResult::Success => (), /* nothing more to do, return */
EmulationResult::Yield =>
{
/* instruction was some kind of sleep or pause operation.
try to find something else to run in the meantime */
scheduler::ping();
},
/* if we can't handle the instruction,
kill the capsule and force a context switch.
TODO: is killing the whole capsule a little extreme? */
_ => fatal_exception(&irq)
}
},
/* catch environment calls from supervisor mode */
(_, PrivilegeMode::Supervisor, IRQCause::SupervisorEnvironmentCall) =>
{
/* determine what we need to do from the platform code's decoding */
if let Some(action) = syscalls::handler(context)
{
match action
{
syscalls::Action::Yield => scheduler::ping(),
syscalls::Action::Terminate => if let Err(_e) = capsule::destroy_current()
{
hvalert!("BUG: Failed to terminate currently running capsule ({:?})", _e);
syscalls::failed(context, syscalls::ActionResult::Failed);
}
else
{
/* find something else to run, this virtual core is dead */
scheduler::ping();
},
syscalls::Action::Restart => if let Err(_e) = capsule::restart_current()
{
hvalert!("BUG: Failed to restart currently running capsule ({:?})", _e);
syscalls::failed(context, syscalls::ActionResult::Failed);
}
else
{
/* find something else to run, this virtual core is being replaced */
scheduler::ping();
},
syscalls::Action::TimerIRQAt(target) =>
{
/* mark this virtual core as awaiting a timer IRQ and
schedule a timer interrupt in anticipation */
pcore::PhysicalCore::set_virtualcore_timer_target(Some(target));
hardware::scheduler_timer_at(target);
},
/* output a character to the user from this capsule
when a console_write capsule calls this, it writes to the console.
when a non-console_write capsule calls this, it writes to its console buffer */
syscalls::Action::OutputChar(character) => if let Err(_) = capsule::putc(character)
{
syscalls::failed(context, syscalls::ActionResult::Failed);
},
/* get a character from the user for this capsule
when a console_read capsule calls this, it reads from the console.
when a non-console_read capsule calls this, it reads from its console buffer */
syscalls::Action::InputChar => match capsule::getc()
{
/* Linux expects getc()'s value (a character value, or -1 for none available) in
the error field of the RISC-V SBI and not in the value field. FIXME: Non-portable.
Ref: https://github.com/torvalds/linux/blob/master/arch/riscv/kernel/sbi.c#L92 */
Ok(c) => syscalls::result_as_error(context, c as usize),
Err(Cause::CapsuleBufferEmpty) => syscalls::result_as_error(context, usize::MAX), /* -1 == nothing to read */
Err(_) => syscalls::failed(context, syscalls::ActionResult::Failed)
},
/* write a character to the given capsule's console buffer.
only console_write capsules can call this */
syscalls::Action::ConsoleBufferWriteChar(character, capsule_id) => match capsule::console_putc(character, capsule_id)
{
Ok(_) => (),
Err(e) => syscalls::failed(context, match e
{
Cause::CapsuleBadPermissions => syscalls::ActionResult::Denied,
_ => syscalls::ActionResult::Failed
})
},
/* get the next available character from any capsule's console buffer
only console_read capsules can call this */
syscalls::Action::ConsoleBufferReadChar => match capsule::console_getc()
{
Ok((character, capsule_id)) => syscalls::result_1extra(context, character as usize, capsule_id),
Err(Cause::CapsuleBufferEmpty) => syscalls::result(context, usize::MAX), /* -1 == nothing to read */
Err(e) => syscalls::failed(context, match e
{
Cause::CapsuleBadPermissions => syscalls::ActionResult::Denied,
_ => syscalls::ActionResult::Failed
})
},
/* get the next available character from the hypervisor's console/log buffer
only console_read capsules can call this */
syscalls::Action::HypervisorBufferReadChar => match capsule::hypervisor_getc()
{
Ok(character) => syscalls::result(context, character as usize),
Err(Cause::CapsuleBufferEmpty) => syscalls::result(context, usize::MAX), /* -1 == nothing to read */
Err(e) => syscalls::failed(context, match e
{
Cause::CapsuleBadPermissions => syscalls::ActionResult::Denied,
_ => syscalls::ActionResult::Failed
})
},
/* currently running capsule wants to register itself as a service so it can receive
and proces requests from other capsules */
syscalls::Action::RegisterService(stype_nr) => if let Some(cid) = pcore::PhysicalCore::get_capsule_id()
{
match service::usize_to_service_type(stype_nr)
{
Ok(stype) => match service::register(stype, cid)
{
Ok(_) => (),
Err(e) => syscalls::failed(context, match e
{
Cause::CapsuleBadPermissions => syscalls::ActionResult::Denied,
_ => syscalls::ActionResult::Failed
})
},
Err(e) => syscalls::failed(context, match e
{
Cause::ServiceNotFound => syscalls::ActionResult::BadParams,
_ => syscalls::ActionResult::Failed
})
}
}
else
{
/* how is this possible? can't find capsule running on this physical core
but we're going to try returning to it anyway? */
syscalls::failed(context, syscalls::ActionResult::Failed);
},
_ => if let Some(c) = pcore::PhysicalCore::get_capsule_id()
{
hvalert!("Capsule {}: Unhandled syscall: {:x?} at 0x{:x}", c, action, irq.pc);
}
else
{
hvdebug!("Unhandled syscall: {:x?} at 0x{:x} in unknown capsule", action, irq.pc);
}
}
}
},
/* catch everything else, halting if fatal */
(severity, privilege, cause) =>
{
/* if an unhandled fatal exception reaches us here from the supervisor or user mode,
kill the capsule. if the hypervisor can't handle its own fatal exception, give up */
match privilege
{
PrivilegeMode::Supervisor | PrivilegeMode::User => if severity == IRQSeverity::Fatal
{
/* TODO: is it wise to blow away the whole capsule for a user exception?
the supervisor should really catch its user-level faults */
fatal_exception(&irq);
},
PrivilegeMode::Machine =>
{
if severity == IRQSeverity::Fatal
{
hvalert!("Halting physical CPU core for {:?} at 0x{:x}, stack 0x{:x} integrity {:?}",
cause, irq.pc, irq.sp, pcore::PhysicalCore::integrity_check());
debughousekeeper!(); // flush the debug output
loop {}
}
}
}
}
}
}
/* handle hardware interrupt */
fn interrupt(irq: IRQ, _: &mut IRQContext)
{
match irq.cause
{
IRQCause::MachineTimer =>
{
/* make a scheduling decision and raise any supervior-level timer IRQs*/
scheduler::ping();
check_supervisor_timer_irq();
},
_ => hvdebug!("Unhandled hardware interrupt: {:?}", irq.cause)
}
/* clear the interrupt condition */
platform::irq::acknowledge(irq);
}
/* is the virtual core we're about to run awaiting a timer IRQ?
if so, and if its timer target value has been passed, generate a pending timer IRQ */
fn check_supervisor_timer_irq()
{
if let Some(target) = pcore::PhysicalCore::get_virtualcore_timer_target()
{
match (hardware::scheduler_get_timer_now(), hardware::scheduler_get_timer_frequency())
{
(Some(time), Some(freq)) =>
{
let current = time.to_exact(freq);
if current >= target.to_exact(freq)
{
/* create a pending timer IRQ for the supervisor kernel and clear the target */
timer::trigger_supervisor_irq();
pcore::PhysicalCore::set_virtualcore_timer_target(None);
}
},
(_, _) => ()
}
}
}
/* kill the running capsule, alert the user, and then find something else to run.
if the capsule is important enough to auto-restart-on-crash, try to revive it */
fn fatal_exception(irq: &IRQ)
{
hvalert!("Terminating running capsule {} for {:?} at 0x{:x}, stack 0x{:x}",
match pcore::PhysicalCore::this().get_virtualcore_id()
{
Some(id) => format!("{}.{}", id.capsuleid, id.vcoreid),
None => format!("[unknown!]")
}, irq.cause, irq.pc, irq.sp);
let mut terminate = false; // when true, destroy the current capsule
let mut reschedule = false; // when true, we must find another vcore to run
match capsule::is_current_autorestart()
{
Some(true) =>
{
hvalert!("Restarting capsule due to auto-restart-on-crash flag");
if let Err(err) = capsule::restart_current()
{
hvalert!("Can't restart capsule ({:?}), letting it die instead", err);
terminate = true;
}
else
{
/* the current vcore is no longer running due to restart */
reschedule = true;
}
},
Some(false) => terminate = true,
None =>
{
hvalert!("BUG: fatal_exception() can't find the running capsule to kill");
return;
},
}
if terminate == true
{
match capsule::destroy_current()
{
Err(e) => hvalert!("BUG: Failed to kill running capsule ({:?})", e),
_ =>
{
hvdebug!("Terminated running capsule");
/* the current vcore is no longer running due to restart */
reschedule = true;
}
}
}
if reschedule == true
{
/* force a context switch to find another virtual core to run
because this virtual core no longer exists */
scheduler::ping();
}
} | 43.308824 | 137 | 0.511715 |
0a848f0dd51263032e78a39e6a61e4f43cf98798 | 1,093 | //! File reading utilities.
use std::fs;
pub fn read_or_die(path: &str) -> Vec<u8> {
match fs::read(path) {
Ok(src) => src,
Err(e) => {
match e.kind() {
std::io::ErrorKind::NotFound => {
eprintln!("No such file: {}", path);
}
std::io::ErrorKind::PermissionDenied => {
eprintln!("Permission denied when reading file: {}", path);
}
_ => {
eprintln!("Could not read file: {} (error {:?})", path, e.kind());
}
};
std::process::exit(1);
}
}
}
/// Do these bytes look like a binary (non-textual) format?
pub fn is_probably_binary(bytes: &[u8]) -> bool {
// If more than 20 of the first 1,000 characters are not valid
// UTF-8, we assume it's binary.
let num_replaced = String::from_utf8_lossy(bytes)
.to_string()
.chars()
.take(1000)
.filter(|c| *c == std::char::REPLACEMENT_CHARACTER)
.count();
num_replaced > 20
}
| 29.540541 | 86 | 0.482159 |
6278030eb171f6a6a3d1332fee0f752d67efb8d8 | 1,116 | use anyhow::Error;
use serde_json::json;
mod common;
use common::models::profile::profile_create::CreateProfile;
use common::models::profile::profile_patch::PatchProfile;
use crate::common::framework::Framework;
#[tokio::test]
async fn token_post_valid() -> Result<(), Error> {
let framework = Framework::new().await;
// Register
let profile = CreateProfile::new();
framework
.create_profile(&profile)
.await?;
// Fetch Token
// FIXME: Maybe use a builder here to create a token request body instead, shouldn't necessarily be testing by
// passing in raw JSON bodies, try and make this more approachable?
let token_request_body = json!({
"lifespan": 60,
"attributes": {
"profile": {
"update": true
}
}
});
let token_response = framework
.request_token(&profile.email, &profile.password, token_request_body)
.await?;
let token_authorization = token_response.body["token"]
.as_str()
.unwrap();
assert!(!token_authorization.is_empty());
Ok(())
}
| 25.363636 | 114 | 0.628136 |
22b560966bb91016f1fc065c5576d83560688319 | 1,603 | #[doc = "Reader of register SLEEPSTATE"]
pub type R = crate::R<u32, super::SLEEPSTATE>;
#[doc = "Reflects the sleep state during automatic collision resolution. Set to IDLE by a GOIDLE task. Set to SLEEP_A when a valid SLEEP_REQ frame is received or by a GOSLEEP task.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SLEEPSTATE_A {
#[doc = "0: State is IDLE."]
IDLE = 0,
#[doc = "1: State is SLEEP_A."]
SLEEPA = 1,
}
impl From<SLEEPSTATE_A> for bool {
#[inline(always)]
fn from(variant: SLEEPSTATE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SLEEPSTATE`"]
pub type SLEEPSTATE_R = crate::R<bool, SLEEPSTATE_A>;
impl SLEEPSTATE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SLEEPSTATE_A {
match self.bits {
false => SLEEPSTATE_A::IDLE,
true => SLEEPSTATE_A::SLEEPA,
}
}
#[doc = "Checks if the value of the field is `IDLE`"]
#[inline(always)]
pub fn is_idle(&self) -> bool {
*self == SLEEPSTATE_A::IDLE
}
#[doc = "Checks if the value of the field is `SLEEPA`"]
#[inline(always)]
pub fn is_sleep_a(&self) -> bool {
*self == SLEEPSTATE_A::SLEEPA
}
}
impl R {
#[doc = "Bit 0 - Reflects the sleep state during automatic collision resolution. Set to IDLE by a GOIDLE task. Set to SLEEP_A when a valid SLEEP_REQ frame is received or by a GOSLEEP task."]
#[inline(always)]
pub fn sleepstate(&self) -> SLEEPSTATE_R {
SLEEPSTATE_R::new((self.bits & 0x01) != 0)
}
}
| 34.847826 | 203 | 0.625702 |
abd19775227e8a7155b4b10cd0469e35a302baa4 | 76 | #![no_main]
#[macro_use]
mod macros;
roundtrip_unsigned!(u64, leb128_u64);
| 12.666667 | 37 | 0.736842 |
f9f04095016418661adaec37c4c5da204aa75054 | 1,850 | use super::*;
use crate::SqlResult;
use connector::mutaction::NestedCreateNode;
use prisma_models::*;
use prisma_query::ast::*;
use std::sync::Arc;
impl NestedActions for NestedCreateNode {
fn relation_field(&self) -> RelationFieldRef {
self.relation_field.clone()
}
fn relation(&self) -> RelationRef {
self.relation_field().relation()
}
fn required_check(&self, parent_id: &GraphqlId) -> SqlResult<Option<(Select, ResultCheck)>> {
if self.top_is_create {
return Ok(None);
}
let p = Arc::clone(&self.relation_field);
let c = p.related_field();
match (p.is_list, p.is_required, c.is_list, c.is_required) {
(false, true, false, true) => Err(self.relation_violation()),
(false, true, false, false) => Ok(None),
(false, false, false, true) => Ok(Some(self.check_for_old_child(parent_id))),
(false, false, false, false) => Ok(None),
(true, false, false, true) => Ok(None),
(true, false, false, false) => Ok(None),
(false, true, true, false) => Ok(None),
(false, false, true, false) => Ok(None),
(true, false, true, false) => Ok(None),
_ => unreachable!(),
}
}
fn parent_removal(&self, parent_id: &GraphqlId) -> Option<Query> {
if self.top_is_create {
return None;
}
let p = self.relation_field.clone();
let c = p.related_field();
match (p.is_list, c.is_list) {
(false, false) => Some(self.removal_by_parent(parent_id)),
(true, false) => None,
(false, true) => Some(self.removal_by_parent(parent_id)),
(true, true) => None,
}
}
fn child_removal(&self, _: &GraphqlId) -> Option<Query> {
None
}
}
| 31.355932 | 97 | 0.558919 |
61f87263a4c538a2162124dae6aa6bd2679d60b5 | 159 | /*!
Storage and set types for your collision meshes and shapes.
*/
mod components;
mod set;
pub use components::ColliderComponent;
pub use set::ColliderSet;
| 15.9 | 59 | 0.761006 |
5d035003404848fccb8921145947e75d7d70749c | 2,301 | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::{Arc, Mutex};
use crate::config::CoprReadPoolConfig;
use crate::storage::kv::{destroy_tls_engine, set_tls_engine};
use crate::storage::{Engine, FlowStatsReporter};
use tikv_util::yatp_pool::{Config, DefaultTicker, FuturePool, PoolTicker, YatpPoolBuilder};
use super::metrics::*;
#[derive(Clone)]
struct FuturePoolTicker<R: FlowStatsReporter> {
pub reporter: R,
}
impl<R: FlowStatsReporter> PoolTicker for FuturePoolTicker<R> {
fn on_tick(&mut self) {
tls_flush(&self.reporter);
}
}
pub fn build_read_pool<E: Engine, R: FlowStatsReporter>(
config: &CoprReadPoolConfig,
reporter: R,
engine: E,
) -> Vec<FuturePool> {
let names = vec!["cop-low", "cop-normal", "cop-high"];
let configs: Vec<Config> = config.to_yatp_pool_configs();
assert_eq!(configs.len(), 3);
configs
.into_iter()
.zip(names)
.map(|(config, name)| {
let reporter = reporter.clone();
let engine = Arc::new(Mutex::new(engine.clone()));
YatpPoolBuilder::new(FuturePoolTicker { reporter })
.config(config)
.name_prefix(name)
.after_start(move || set_tls_engine(engine.lock().unwrap().clone()))
.before_stop(move || unsafe {
// Safety: we call `set_` and `destroy_` with the same engine type.
destroy_tls_engine::<E>();
})
.build_future_pool()
})
.collect()
}
pub fn build_read_pool_for_test<E: Engine>(
config: &CoprReadPoolConfig,
engine: E,
) -> Vec<FuturePool> {
let configs: Vec<Config> = config.to_yatp_pool_configs();
assert_eq!(configs.len(), 3);
configs
.into_iter()
.map(|config| {
let engine = Arc::new(Mutex::new(engine.clone()));
YatpPoolBuilder::new(DefaultTicker::default())
.config(config)
.after_start(move || set_tls_engine(engine.lock().unwrap().clone()))
// Safety: we call `set_` and `destroy_` with the same engine type.
.before_stop(|| unsafe { destroy_tls_engine::<E>() })
.build_future_pool()
})
.collect()
}
| 32.408451 | 91 | 0.59322 |
c19fd1757792f4a2f795e4fb4b525dc6f5cfcde0 | 36,065 | #[doc = "Register `APB2LPENR` reader"]
pub struct R(crate::R<APB2LPENR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<APB2LPENR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<APB2LPENR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<APB2LPENR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `APB2LPENR` writer"]
pub struct W(crate::W<APB2LPENR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<APB2LPENR_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<APB2LPENR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<APB2LPENR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "TIM1 clock enable during Sleep mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIM1LPEN_A {
#[doc = "0: Selected module is disabled during Sleep mode"]
DISABLEDINSLEEP = 0,
#[doc = "1: Selected module is enabled during Sleep mode"]
ENABLEDINSLEEP = 1,
}
impl From<TIM1LPEN_A> for bool {
#[inline(always)]
fn from(variant: TIM1LPEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `TIM1LPEN` reader - TIM1 clock enable during Sleep mode"]
pub struct TIM1LPEN_R(crate::FieldReader<bool, TIM1LPEN_A>);
impl TIM1LPEN_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TIM1LPEN_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIM1LPEN_A {
match self.bits {
false => TIM1LPEN_A::DISABLEDINSLEEP,
true => TIM1LPEN_A::ENABLEDINSLEEP,
}
}
#[doc = "Checks if the value of the field is `DISABLEDINSLEEP`"]
#[inline(always)]
pub fn is_disabled_in_sleep(&self) -> bool {
**self == TIM1LPEN_A::DISABLEDINSLEEP
}
#[doc = "Checks if the value of the field is `ENABLEDINSLEEP`"]
#[inline(always)]
pub fn is_enabled_in_sleep(&self) -> bool {
**self == TIM1LPEN_A::ENABLEDINSLEEP
}
}
impl core::ops::Deref for TIM1LPEN_R {
type Target = crate::FieldReader<bool, TIM1LPEN_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TIM1LPEN` writer - TIM1 clock enable during Sleep mode"]
pub struct TIM1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> TIM1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM1LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(TIM1LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(TIM1LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
#[doc = "TIM8 clock enable during Sleep mode"]
pub type TIM8LPEN_A = TIM1LPEN_A;
#[doc = "Field `TIM8LPEN` reader - TIM8 clock enable during Sleep mode"]
pub type TIM8LPEN_R = TIM1LPEN_R;
#[doc = "Field `TIM8LPEN` writer - TIM8 clock enable during Sleep mode"]
pub struct TIM8LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> TIM8LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM8LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(TIM8LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(TIM8LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1);
self.w
}
}
#[doc = "USART1 clock enable during Sleep mode"]
pub type USART1LPEN_A = TIM1LPEN_A;
#[doc = "Field `USART1LPEN` reader - USART1 clock enable during Sleep mode"]
pub type USART1LPEN_R = TIM1LPEN_R;
#[doc = "Field `USART1LPEN` writer - USART1 clock enable during Sleep mode"]
pub struct USART1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> USART1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USART1LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4);
self.w
}
}
#[doc = "USART6 clock enable during Sleep mode"]
pub type USART6LPEN_A = TIM1LPEN_A;
#[doc = "Field `USART6LPEN` reader - USART6 clock enable during Sleep mode"]
pub type USART6LPEN_R = TIM1LPEN_R;
#[doc = "Field `USART6LPEN` writer - USART6 clock enable during Sleep mode"]
pub struct USART6LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> USART6LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USART6LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(USART6LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(USART6LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5);
self.w
}
}
#[doc = "ADC1 clock enable during Sleep mode"]
pub type ADC1LPEN_A = TIM1LPEN_A;
#[doc = "Field `ADC1LPEN` reader - ADC1 clock enable during Sleep mode"]
pub type ADC1LPEN_R = TIM1LPEN_R;
#[doc = "Field `ADC1LPEN` writer - ADC1 clock enable during Sleep mode"]
pub struct ADC1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> ADC1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ADC1LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(ADC1LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(ADC1LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u32 & 0x01) << 8);
self.w
}
}
#[doc = "ADC2 clock enable during Sleep mode"]
pub type ADC2LPEN_A = TIM1LPEN_A;
#[doc = "Field `ADC2LPEN` reader - ADC2 clock enable during Sleep mode"]
pub type ADC2LPEN_R = TIM1LPEN_R;
#[doc = "Field `ADC2LPEN` writer - ADC2 clock enable during Sleep mode"]
pub struct ADC2LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> ADC2LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ADC2LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(ADC2LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(ADC2LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | ((value as u32 & 0x01) << 9);
self.w
}
}
#[doc = "ADC 3 clock enable during Sleep mode"]
pub type ADC3LPEN_A = TIM1LPEN_A;
#[doc = "Field `ADC3LPEN` reader - ADC 3 clock enable during Sleep mode"]
pub type ADC3LPEN_R = TIM1LPEN_R;
#[doc = "Field `ADC3LPEN` writer - ADC 3 clock enable during Sleep mode"]
pub struct ADC3LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> ADC3LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ADC3LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(ADC3LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(ADC3LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | ((value as u32 & 0x01) << 10);
self.w
}
}
#[doc = "SDIO clock enable during Sleep mode"]
pub type SDIOLPEN_A = TIM1LPEN_A;
#[doc = "Field `SDIOLPEN` reader - SDIO clock enable during Sleep mode"]
pub type SDIOLPEN_R = TIM1LPEN_R;
#[doc = "Field `SDIOLPEN` writer - SDIO clock enable during Sleep mode"]
pub struct SDIOLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SDIOLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SDIOLPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(SDIOLPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(SDIOLPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | ((value as u32 & 0x01) << 11);
self.w
}
}
#[doc = "SPI 1 clock enable during Sleep mode"]
pub type SPI1LPEN_A = TIM1LPEN_A;
#[doc = "Field `SPI1LPEN` reader - SPI 1 clock enable during Sleep mode"]
pub type SPI1LPEN_R = TIM1LPEN_R;
#[doc = "Field `SPI1LPEN` writer - SPI 1 clock enable during Sleep mode"]
pub struct SPI1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SPI1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI1LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(SPI1LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(SPI1LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | ((value as u32 & 0x01) << 12);
self.w
}
}
#[doc = "SPI 4 clock enable during Sleep mode"]
pub type SPI4LPEN_A = TIM1LPEN_A;
#[doc = "Field `SPI4LPEN` reader - SPI 4 clock enable during Sleep mode"]
pub type SPI4LPEN_R = TIM1LPEN_R;
#[doc = "Field `SPI4LPEN` writer - SPI 4 clock enable during Sleep mode"]
pub struct SPI4LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SPI4LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI4LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(SPI4LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(SPI4LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | ((value as u32 & 0x01) << 13);
self.w
}
}
#[doc = "System configuration controller clock enable during Sleep mode"]
pub type SYSCFGLPEN_A = TIM1LPEN_A;
#[doc = "Field `SYSCFGLPEN` reader - System configuration controller clock enable during Sleep mode"]
pub type SYSCFGLPEN_R = TIM1LPEN_R;
#[doc = "Field `SYSCFGLPEN` writer - System configuration controller clock enable during Sleep mode"]
pub struct SYSCFGLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SYSCFGLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SYSCFGLPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | ((value as u32 & 0x01) << 14);
self.w
}
}
#[doc = "TIM9 clock enable during sleep mode"]
pub type TIM9LPEN_A = TIM1LPEN_A;
#[doc = "Field `TIM9LPEN` reader - TIM9 clock enable during sleep mode"]
pub type TIM9LPEN_R = TIM1LPEN_R;
#[doc = "Field `TIM9LPEN` writer - TIM9 clock enable during sleep mode"]
pub struct TIM9LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> TIM9LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM9LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(TIM9LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(TIM9LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | ((value as u32 & 0x01) << 16);
self.w
}
}
#[doc = "TIM10 clock enable during Sleep mode"]
pub type TIM10LPEN_A = TIM1LPEN_A;
#[doc = "Field `TIM10LPEN` reader - TIM10 clock enable during Sleep mode"]
pub type TIM10LPEN_R = TIM1LPEN_R;
#[doc = "Field `TIM10LPEN` writer - TIM10 clock enable during Sleep mode"]
pub struct TIM10LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> TIM10LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM10LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(TIM10LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(TIM10LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | ((value as u32 & 0x01) << 17);
self.w
}
}
#[doc = "TIM11 clock enable during Sleep mode"]
pub type TIM11LPEN_A = TIM1LPEN_A;
#[doc = "Field `TIM11LPEN` reader - TIM11 clock enable during Sleep mode"]
pub type TIM11LPEN_R = TIM1LPEN_R;
#[doc = "Field `TIM11LPEN` writer - TIM11 clock enable during Sleep mode"]
pub struct TIM11LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> TIM11LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM11LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(TIM11LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(TIM11LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | ((value as u32 & 0x01) << 18);
self.w
}
}
#[doc = "SPI 5 clock enable during Sleep mode"]
pub type SPI5LPEN_A = TIM1LPEN_A;
#[doc = "Field `SPI5LPEN` reader - SPI 5 clock enable during Sleep mode"]
pub type SPI5LPEN_R = TIM1LPEN_R;
#[doc = "Field `SPI5LPEN` writer - SPI 5 clock enable during Sleep mode"]
pub struct SPI5LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SPI5LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI5LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(SPI5LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(SPI5LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | ((value as u32 & 0x01) << 20);
self.w
}
}
#[doc = "SPI 6 clock enable during Sleep mode"]
pub type SPI6LPEN_A = TIM1LPEN_A;
#[doc = "Field `SPI6LPEN` reader - SPI 6 clock enable during Sleep mode"]
pub type SPI6LPEN_R = TIM1LPEN_R;
#[doc = "Field `SPI6LPEN` writer - SPI 6 clock enable during Sleep mode"]
pub struct SPI6LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SPI6LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI6LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(SPI6LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(SPI6LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | ((value as u32 & 0x01) << 21);
self.w
}
}
#[doc = "SAI1 clock enable"]
pub type SAI1LPEN_A = TIM1LPEN_A;
#[doc = "Field `SAI1LPEN` reader - SAI1 clock enable"]
pub type SAI1LPEN_R = TIM1LPEN_R;
#[doc = "Field `SAI1LPEN` writer - SAI1 clock enable"]
pub struct SAI1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SAI1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SAI1LPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(SAI1LPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(SAI1LPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | ((value as u32 & 0x01) << 22);
self.w
}
}
#[doc = "LTDC clock enable"]
pub type LTDCLPEN_A = TIM1LPEN_A;
#[doc = "Field `LTDCLPEN` reader - LTDC clock enable"]
pub type LTDCLPEN_R = TIM1LPEN_R;
#[doc = "Field `LTDCLPEN` writer - LTDC clock enable"]
pub struct LTDCLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> LTDCLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LTDCLPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(LTDCLPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(LTDCLPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | ((value as u32 & 0x01) << 26);
self.w
}
}
#[doc = "DSI clocks enable during Sleep mode"]
pub type DSILPEN_A = TIM1LPEN_A;
#[doc = "Field `DSILPEN` reader - DSI clocks enable during Sleep mode"]
pub type DSILPEN_R = TIM1LPEN_R;
#[doc = "Field `DSILPEN` writer - DSI clocks enable during Sleep mode"]
pub struct DSILPEN_W<'a> {
w: &'a mut W,
}
impl<'a> DSILPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DSILPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut W {
self.variant(DSILPEN_A::DISABLEDINSLEEP)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut W {
self.variant(DSILPEN_A::ENABLEDINSLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | ((value as u32 & 0x01) << 27);
self.w
}
}
impl R {
#[doc = "Bit 0 - TIM1 clock enable during Sleep mode"]
#[inline(always)]
pub fn tim1lpen(&self) -> TIM1LPEN_R {
TIM1LPEN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - TIM8 clock enable during Sleep mode"]
#[inline(always)]
pub fn tim8lpen(&self) -> TIM8LPEN_R {
TIM8LPEN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 4 - USART1 clock enable during Sleep mode"]
#[inline(always)]
pub fn usart1lpen(&self) -> USART1LPEN_R {
USART1LPEN_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - USART6 clock enable during Sleep mode"]
#[inline(always)]
pub fn usart6lpen(&self) -> USART6LPEN_R {
USART6LPEN_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 8 - ADC1 clock enable during Sleep mode"]
#[inline(always)]
pub fn adc1lpen(&self) -> ADC1LPEN_R {
ADC1LPEN_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - ADC2 clock enable during Sleep mode"]
#[inline(always)]
pub fn adc2lpen(&self) -> ADC2LPEN_R {
ADC2LPEN_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - ADC 3 clock enable during Sleep mode"]
#[inline(always)]
pub fn adc3lpen(&self) -> ADC3LPEN_R {
ADC3LPEN_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - SDIO clock enable during Sleep mode"]
#[inline(always)]
pub fn sdiolpen(&self) -> SDIOLPEN_R {
SDIOLPEN_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - SPI 1 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi1lpen(&self) -> SPI1LPEN_R {
SPI1LPEN_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - SPI 4 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi4lpen(&self) -> SPI4LPEN_R {
SPI4LPEN_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - System configuration controller clock enable during Sleep mode"]
#[inline(always)]
pub fn syscfglpen(&self) -> SYSCFGLPEN_R {
SYSCFGLPEN_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 16 - TIM9 clock enable during sleep mode"]
#[inline(always)]
pub fn tim9lpen(&self) -> TIM9LPEN_R {
TIM9LPEN_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - TIM10 clock enable during Sleep mode"]
#[inline(always)]
pub fn tim10lpen(&self) -> TIM10LPEN_R {
TIM10LPEN_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - TIM11 clock enable during Sleep mode"]
#[inline(always)]
pub fn tim11lpen(&self) -> TIM11LPEN_R {
TIM11LPEN_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 20 - SPI 5 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi5lpen(&self) -> SPI5LPEN_R {
SPI5LPEN_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - SPI 6 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi6lpen(&self) -> SPI6LPEN_R {
SPI6LPEN_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - SAI1 clock enable"]
#[inline(always)]
pub fn sai1lpen(&self) -> SAI1LPEN_R {
SAI1LPEN_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 26 - LTDC clock enable"]
#[inline(always)]
pub fn ltdclpen(&self) -> LTDCLPEN_R {
LTDCLPEN_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - DSI clocks enable during Sleep mode"]
#[inline(always)]
pub fn dsilpen(&self) -> DSILPEN_R {
DSILPEN_R::new(((self.bits >> 27) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM1 clock enable during Sleep mode"]
#[inline(always)]
pub fn tim1lpen(&mut self) -> TIM1LPEN_W {
TIM1LPEN_W { w: self }
}
#[doc = "Bit 1 - TIM8 clock enable during Sleep mode"]
#[inline(always)]
pub fn tim8lpen(&mut self) -> TIM8LPEN_W {
TIM8LPEN_W { w: self }
}
#[doc = "Bit 4 - USART1 clock enable during Sleep mode"]
#[inline(always)]
pub fn usart1lpen(&mut self) -> USART1LPEN_W {
USART1LPEN_W { w: self }
}
#[doc = "Bit 5 - USART6 clock enable during Sleep mode"]
#[inline(always)]
pub fn usart6lpen(&mut self) -> USART6LPEN_W {
USART6LPEN_W { w: self }
}
#[doc = "Bit 8 - ADC1 clock enable during Sleep mode"]
#[inline(always)]
pub fn adc1lpen(&mut self) -> ADC1LPEN_W {
ADC1LPEN_W { w: self }
}
#[doc = "Bit 9 - ADC2 clock enable during Sleep mode"]
#[inline(always)]
pub fn adc2lpen(&mut self) -> ADC2LPEN_W {
ADC2LPEN_W { w: self }
}
#[doc = "Bit 10 - ADC 3 clock enable during Sleep mode"]
#[inline(always)]
pub fn adc3lpen(&mut self) -> ADC3LPEN_W {
ADC3LPEN_W { w: self }
}
#[doc = "Bit 11 - SDIO clock enable during Sleep mode"]
#[inline(always)]
pub fn sdiolpen(&mut self) -> SDIOLPEN_W {
SDIOLPEN_W { w: self }
}
#[doc = "Bit 12 - SPI 1 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi1lpen(&mut self) -> SPI1LPEN_W {
SPI1LPEN_W { w: self }
}
#[doc = "Bit 13 - SPI 4 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi4lpen(&mut self) -> SPI4LPEN_W {
SPI4LPEN_W { w: self }
}
#[doc = "Bit 14 - System configuration controller clock enable during Sleep mode"]
#[inline(always)]
pub fn syscfglpen(&mut self) -> SYSCFGLPEN_W {
SYSCFGLPEN_W { w: self }
}
#[doc = "Bit 16 - TIM9 clock enable during sleep mode"]
#[inline(always)]
pub fn tim9lpen(&mut self) -> TIM9LPEN_W {
TIM9LPEN_W { w: self }
}
#[doc = "Bit 17 - TIM10 clock enable during Sleep mode"]
#[inline(always)]
pub fn tim10lpen(&mut self) -> TIM10LPEN_W {
TIM10LPEN_W { w: self }
}
#[doc = "Bit 18 - TIM11 clock enable during Sleep mode"]
#[inline(always)]
pub fn tim11lpen(&mut self) -> TIM11LPEN_W {
TIM11LPEN_W { w: self }
}
#[doc = "Bit 20 - SPI 5 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi5lpen(&mut self) -> SPI5LPEN_W {
SPI5LPEN_W { w: self }
}
#[doc = "Bit 21 - SPI 6 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi6lpen(&mut self) -> SPI6LPEN_W {
SPI6LPEN_W { w: self }
}
#[doc = "Bit 22 - SAI1 clock enable"]
#[inline(always)]
pub fn sai1lpen(&mut self) -> SAI1LPEN_W {
SAI1LPEN_W { w: self }
}
#[doc = "Bit 26 - LTDC clock enable"]
#[inline(always)]
pub fn ltdclpen(&mut self) -> LTDCLPEN_W {
LTDCLPEN_W { w: self }
}
#[doc = "Bit 27 - DSI clocks enable during Sleep mode"]
#[inline(always)]
pub fn dsilpen(&mut self) -> DSILPEN_W {
DSILPEN_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 = "APB2 peripheral clock enabled in low power mode register\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 [apb2lpenr](index.html) module"]
pub struct APB2LPENR_SPEC;
impl crate::RegisterSpec for APB2LPENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [apb2lpenr::R](R) reader structure"]
impl crate::Readable for APB2LPENR_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [apb2lpenr::W](W) writer structure"]
impl crate::Writable for APB2LPENR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets APB2LPENR to value 0x0007_5f33"]
impl crate::Resettable for APB2LPENR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x0007_5f33
}
}
| 33.424467 | 446 | 0.592846 |
2696bb1eb26ffc3419eafd7a2e979e3d5f2a990b | 1,197 | use crate::fd::AsFd;
use crate::imp;
use crate::io::{self, OwnedFd};
pub use imp::time::types::{Itimerspec, TimerfdClockId, TimerfdFlags, TimerfdTimerFlags};
/// `timerfd_create(clockid, flags)`—Create a timer.
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man7.org/linux/man-pages/man2/timerfd_create.2.html
#[inline]
pub fn timerfd_create(clockid: TimerfdClockId, flags: TimerfdFlags) -> io::Result<OwnedFd> {
imp::time::syscalls::timerfd_create(clockid, flags)
}
/// `timerfd_settime(clockid, flags, new_value)`—Set the time on a timer.
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man7.org/linux/man-pages/man2/timerfd_settime.2.html
#[inline]
pub fn timerfd_settime<Fd: AsFd>(
fd: &Fd,
flags: TimerfdTimerFlags,
new_value: &Itimerspec,
) -> io::Result<Itimerspec> {
imp::time::syscalls::timerfd_settime(fd.as_fd(), flags, new_value)
}
/// `timerfd_gettime(clockid, flags)`—Query a timer.
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man7.org/linux/man-pages/man2/timerfd_gettime.2.html
#[inline]
pub fn timerfd_gettime<Fd: AsFd>(fd: &Fd) -> io::Result<Itimerspec> {
imp::time::syscalls::timerfd_gettime(fd.as_fd())
}
| 27.837209 | 92 | 0.675856 |
0a93119a037d2be43a67a1a3c7191d75dc537c84 | 143 | pub mod ast;
pub mod parser;
use super::lexer::*;
use super::source::*;
use super::visitor::*;
pub use self::ast::*;
pub use self::parser::*; | 15.888889 | 24 | 0.643357 |
de229ded463f68570f5ed0a71866e9dbec44548a | 645 | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
let _foo = Vec::new();
//~^ ERROR type annotations needed [E0282]
//~| NOTE cannot infer type for `T`
//~| NOTE consider giving `_foo` a type
}
| 35.833333 | 69 | 0.700775 |
1a16302af5e5e42542018abf5c5713eabab5d8f0 | 722 | #![cfg(feature = "async-traits")]
use crate::{UnixListener, UnixStream};
use futures_core::stream::Stream;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
/// Stream of listeners
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Incoming {
inner: UnixListener,
}
impl Incoming {
pub(crate) fn new(listener: UnixListener) -> Incoming {
Incoming { inner: listener }
}
}
impl Stream for Incoming {
type Item = io::Result<UnixStream>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let (socket, _) = ready!(Pin::new(&mut self.inner).poll_accept(cx))?;
Poll::Ready(Some(Ok(socket)))
}
}
| 24.066667 | 94 | 0.642659 |
23731178f5296a83c6e7ff21db515ca44533313a | 27,074 | use super::{ClapChain, EthereumOpts, Wallet};
use crate::{
cmd::cast::find_block::FindBlockArgs,
utils::{parse_ether_value, parse_u256},
};
use clap::{Parser, Subcommand, ValueHint};
use ethers::types::{Address, BlockId, BlockNumber, NameOrAddress, H256, U256};
use std::{path::PathBuf, str::FromStr};
#[derive(Debug, Subcommand)]
#[clap(
about = "Perform Ethereum RPC calls from the comfort of your command line.",
after_help = "Find more information in the book: http://book.getfoundry.sh/reference/cast/cast.html"
)]
pub enum Subcommands {
#[clap(name = "--max-int")]
#[clap(about = "Get the maximum i256 value.")]
MaxInt,
#[clap(name = "--min-int")]
#[clap(about = "Get the minimum i256 value.")]
MinInt,
#[clap(name = "--max-uint")]
#[clap(about = "Get the maximum u256 value.")]
MaxUint,
#[clap(name = "--address-zero", about = "Get zero address")]
AddressZero,
#[clap(name = "--hash-zero", about = "Get zero hash")]
HashZero,
#[clap(aliases = &["--from-ascii"])]
#[clap(name = "--from-utf8")]
#[clap(about = "Convert UTF8 text to hex.")]
FromUtf8 { text: Option<String> },
#[clap(name = "--to-hex")]
#[clap(about = "Convert an integer to hex.")]
ToHex { decimal: Option<String> },
#[clap(name = "--concat-hex")]
#[clap(about = "Concatencate hex strings.")]
ConcatHex { data: Vec<String> },
#[clap(name = "--from-bin")]
#[clap(about = "Convert binary data into hex data.")]
FromBin,
#[clap(name = "--to-hexdata")]
#[clap(
about = "Normalize the input to lowercase, 0x-prefixed hex. See --help for more info.",
long_about = r#"Normalize the input to lowercase, 0x-prefixed hex.
The input can be:
- mixed case hex with or without 0x prefix
- 0x prefixed hex, concatenated with a ':'
- an absolute path to file
- @tag, where the tag is defined in an environment variable"#
)]
ToHexdata { input: Option<String> },
#[clap(aliases = &["--to-checksum"])] // Compatibility with dapptools' cast
#[clap(name = "--to-checksum-address")]
#[clap(about = "Convert an address to a checksummed format (EIP-55).")]
ToCheckSumAddress { address: Option<Address> },
#[clap(name = "--to-ascii")]
#[clap(about = "Convert hex data to an ASCII string.")]
ToAscii { hexdata: Option<String> },
#[clap(name = "--from-fix")]
#[clap(about = "Convert a fixed point number into an integer.")]
FromFix {
decimals: Option<u128>,
#[clap(allow_hyphen_values = true)] // negative values not yet supported internally
value: Option<String>,
},
#[clap(name = "--to-bytes32")]
#[clap(about = "Right-pads hex data to 32 bytes.")]
ToBytes32 { bytes: Option<String> },
#[clap(name = "--to-dec")]
#[clap(about = "Convert hex value into a decimal number.")]
ToDec { hexvalue: Option<String> },
#[clap(name = "--to-fix")]
#[clap(about = "Convert an integer into a fixed point number.")]
ToFix {
decimals: Option<u128>,
#[clap(allow_hyphen_values = true)] // negative values not yet supported internally
value: Option<String>,
},
#[clap(name = "--to-uint256")]
#[clap(about = "Convert a number to a hex-encoded uint256.")]
ToUint256 { value: Option<String> },
#[clap(name = "--to-int256")]
#[clap(about = "Convert a number to a hex-encoded int256.")]
ToInt256 { value: Option<String> },
#[clap(name = "--to-unit")]
#[clap(
about = "Convert an ETH amount into another unit (ether, gwei or wei).",
long_about = r#"Convert an ETH amount into another unit (ether, gwei or wei).\
Examples:
- 1ether wei
- "1 ether" wei
- 1ether
- 1 gwei
- 1gwei ether"#
)]
ToUnit {
value: Option<String>,
#[clap(help = "The unit to convert to (ether, gwei, wei).", default_value = "wei")]
unit: String,
},
#[clap(name = "--to-wei")]
#[clap(about = "Convert an ETH amount to wei. Consider using --to-unit.")]
ToWei {
#[clap(allow_hyphen_values = true)] // negative values not yet supported internally
value: Option<String>,
unit: Option<String>,
},
#[clap(name = "--from-wei")]
#[clap(about = "Convert wei into an ETH amount. Consider using --to-unit.")]
FromWei {
#[clap(allow_hyphen_values = true)] // negative values not yet supported internally
value: Option<String>,
unit: Option<String>,
},
#[clap(name = "access-list")]
#[clap(about = "Create an access list for a transaction.")]
AccessList {
#[clap(help = "The destination of the transaction.", parse(try_from_str = parse_name_or_address))]
address: NameOrAddress,
#[clap(help = "The signature of the function to call.")]
sig: String,
#[clap(help = "The arguments of the function to call.")]
args: Vec<String>,
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: Option<BlockId>,
#[clap(flatten)]
// TODO: We only need RPC URL + etherscan stuff from this struct
eth: EthereumOpts,
#[clap(long = "json", short = 'j', help_heading = "DISPLAY OPTIONS")]
to_json: bool,
},
#[clap(name = "block")]
#[clap(about = "Get information about a block.")]
Block {
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: BlockId,
#[clap(long, env = "CAST_FULL_BLOCK")]
full: bool,
#[clap(long, short, help = "If specified, only get the given field of the block.")]
field: Option<String>,
#[clap(long = "json", short = 'j', help_heading = "DISPLAY OPTIONS")]
to_json: bool,
#[clap(long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "block-number")]
#[clap(about = "Get the latest block number.")]
BlockNumber {
#[clap(long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "call")]
#[clap(about = "Perform a call on an account without publishing a transaction.")]
Call {
#[clap(help = "the address you want to query", parse(try_from_str = parse_name_or_address))]
address: NameOrAddress,
sig: String,
args: Vec<String>,
#[clap(long, short, help = "the block you want to query, can also be earliest/latest/pending", parse(try_from_str = parse_block_id))]
block: Option<BlockId>,
#[clap(flatten)]
eth: EthereumOpts,
},
#[clap(about = "ABI-encode a function with arguments.")]
Calldata {
#[clap(
help = "The function signature.",
long_help = "The function signature in the form <name>(<types...>)"
)]
sig: String,
#[clap(allow_hyphen_values = true)]
args: Vec<String>,
},
#[clap(name = "chain")]
#[clap(about = "Get the symbolic name of the current chain.")]
Chain {
#[clap(long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "chain-id")]
#[clap(about = "Get the Ethereum chain ID.")]
ChainId {
#[clap(long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "client")]
#[clap(about = "Get the current client version.")]
Client {
#[clap(long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "compute-address")]
#[clap(about = "Compute the contract address from a given nonce and deployer address.")]
ComputeAddress {
#[clap(long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
#[clap(help = "The deployer address.")]
address: String,
#[clap(long, help = "The nonce of the deployer address.", parse(try_from_str = parse_u256))]
nonce: Option<U256>,
},
#[clap(name = "namehash")]
#[clap(about = "Calculate the ENS namehash of a name.")]
Namehash { name: String },
#[clap(name = "tx")]
#[clap(about = "Get information about a transaction.")]
Tx {
hash: String,
field: Option<String>,
#[clap(long = "json", short = 'j', help_heading = "DISPLAY OPTIONS")]
to_json: bool,
#[clap(long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "receipt")]
#[clap(about = "Get the transaction receipt for a transaction.")]
Receipt {
#[clap(value_name = "TX_HASH")]
hash: String,
field: Option<String>,
#[clap(
short,
long,
help = "The number of confirmations until the receipt is fetched",
default_value = "1"
)]
confirmations: usize,
#[clap(long, env = "CAST_ASYNC")]
cast_async: bool,
#[clap(long = "json", short = 'j', help_heading = "DISPLAY OPTIONS")]
to_json: bool,
#[clap(long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "send")]
#[clap(about = "Sign and publish a transaction.")]
SendTx {
#[clap(
help = "The destination of the transaction.",
parse(try_from_str = parse_name_or_address)
)]
to: NameOrAddress,
#[clap(help = "The signature of the function to call.")]
sig: Option<String>,
#[clap(help = "The arguments of the function to call.")]
args: Vec<String>,
#[clap(long, help = "Gas limit for the transaction.", parse(try_from_str = parse_u256))]
gas: Option<U256>,
#[clap(
long = "gas-price",
help = "Gas price for legacy transactions, or max fee per gas for EIP1559 transactions.",
env = "ETH_GAS_PRICE",
parse(try_from_str = parse_ether_value)
)]
gas_price: Option<U256>,
#[clap(
long,
help = "Ether to send in the transaction.",
long_help = r#"Ether to send in the transaction, either specified in wei, or as a string with a unit type.
Examples: 1ether, 10gwei, 0.01ether"#,
parse(try_from_str = parse_ether_value)
)]
value: Option<U256>,
#[clap(long, help = "nonce for the transaction", parse(try_from_str = parse_u256))]
nonce: Option<U256>,
#[clap(long, env = "CAST_ASYNC")]
cast_async: bool,
#[clap(flatten)]
eth: EthereumOpts,
#[clap(
long,
help = "Send a legacy transaction instead of an EIP1559 transaction.",
long_help = r#"Send a legacy transaction instead of an EIP1559 transaction.
This is automatically enabled for common networks without EIP1559."#
)]
legacy: bool,
#[clap(
short,
long,
help = "The number of confirmations until the receipt is fetched.",
default_value = "1"
)]
confirmations: usize,
#[clap(long = "json", short = 'j', help_heading = "DISPLAY OPTIONS")]
to_json: bool,
#[clap(
long = "resend",
help = "Reuse the latest nonce for the sender account.",
conflicts_with = "nonce"
)]
resend: bool,
},
#[clap(name = "publish")]
#[clap(about = "Publish a raw transaction to the network.")]
PublishTx {
#[clap(help = "The raw transaction", value_name = "RAW_TX")]
raw_tx: String,
#[clap(long, env = "CAST_ASYNC")]
cast_async: bool,
// FIXME: We only need the RPC URL and `--flashbots` options from this.
#[clap(flatten)]
eth: EthereumOpts,
},
#[clap(name = "estimate")]
#[clap(about = "Estimate the gas cost of a transaction.")]
Estimate {
#[clap(help = "The destination of the transaction.", parse(try_from_str = parse_name_or_address))]
to: NameOrAddress,
#[clap(help = "The signature of the function to call.")]
sig: String,
#[clap(help = "The arguments of the function to call.")]
args: Vec<String>,
#[clap(
long,
help = "Ether to send in the transaction.",
long_help = r#"Ether to send in the transaction, either specified in wei, or as a string with a unit type.
Examples: 1ether, 10gwei, 0.01ether"#,
parse(try_from_str = parse_ether_value)
)]
value: Option<U256>,
#[clap(flatten)]
// TODO: We only need RPC URL and Etherscan API key here.
eth: EthereumOpts,
},
#[clap(name = "--calldata-decode")]
#[clap(about = "Decode ABI-encoded input data.")]
CalldataDecode {
#[clap(help = "The function signature in the format `<name>(<in-types>)(<out-types>)`.")]
sig: String,
#[clap(help = "The ABI-encoded calldata.")]
calldata: String,
},
#[clap(name = "--abi-decode")]
#[clap(
about = "Decode ABI-encoded input or output data",
long_about = r#"Decode ABI-encoded input or output data.
Defaults to decoding output data. To decode input data pass --input or use cast --calldata-decode."#
)]
AbiDecode {
#[clap(help = "The function signature in the format `<name>(<in-types>)(<out-types>)`.")]
sig: String,
#[clap(help = "The ABI-encoded calldata.")]
calldata: String,
#[clap(long, short, help = "Decode input data.")]
input: bool,
},
#[clap(name = "abi-encode")]
#[clap(about = "ABI encode the given function argument, excluding the selector.")]
AbiEncode {
#[clap(help = "The function signature.")]
sig: String,
#[clap(help = "The arguments of the function.")]
#[clap(allow_hyphen_values = true)]
args: Vec<String>,
},
#[clap(name = "index")]
#[clap(about = "Compute the storage slot for an entry in a mapping.")]
Index {
#[clap(help = "The mapping key type.")]
key_type: String,
#[clap(help = "The mapping value type.")]
value_type: String,
#[clap(help = "The mapping key.")]
key: String,
#[clap(help = "The storage slot of the mapping.")]
slot_number: String,
},
#[clap(name = "4byte")]
#[clap(about = "Get the function signatures for the given selector from 4byte.directory.")]
FourByte {
#[clap(help = "The function selector.")]
selector: String,
},
#[clap(name = "4byte-decode")]
#[clap(about = "Decode ABI-encoded calldata using 4byte.directory.")]
FourByteDecode {
#[clap(help = "The ABI-encoded calldata.")]
calldata: String,
#[clap(
long,
help = "The index of the resolved signature to use.",
long_help = r#"The index of the resolved signature to use.
4byte.directory can have multiple possible signatures for a given selector.
The index can also be earliest or latest."#
)]
id: Option<String>,
},
#[clap(name = "4byte-event")]
#[clap(about = "Get the event signature for a given topic 0 from 4byte.directory.")]
FourByteEvent {
#[clap(help = "Topic 0", value_name = "TOPIC_0")]
topic: String,
},
#[clap(name = "pretty-calldata")]
#[clap(
about = "Pretty print calldata.",
long_about = r#"Pretty print calldata.
Tries to decode the calldata using 4byte.directory unless --offline is passed."#
)]
PrettyCalldata {
#[clap(help = "The calldata.")]
calldata: String,
#[clap(long, short, help = "Skip the 4byte directory lookup.")]
offline: bool,
},
#[clap(name = "age")]
#[clap(about = "Get the timestamp of a block.")]
Age {
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: Option<BlockId>,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "balance")]
#[clap(about = "Get the balance of an account in wei.")]
Balance {
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: Option<BlockId>,
#[clap(help = "The account you want to query", parse(try_from_str = parse_name_or_address))]
who: NameOrAddress,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "basefee")]
#[clap(about = "Get the basefee of a block.")]
BaseFee {
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: Option<BlockId>,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "code")]
#[clap(about = "Get the bytecode of a contract.")]
Code {
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: Option<BlockId>,
#[clap(help = "The contract address.", parse(try_from_str = parse_name_or_address))]
who: NameOrAddress,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "gas-price")]
#[clap(about = "Get the current gas price.")]
GasPrice {
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "keccak")]
#[clap(about = "Hash arbitrary data using keccak-256.")]
Keccak { data: String },
#[clap(name = "resolve-name")]
#[clap(about = "Perform an ENS lookup.")]
ResolveName {
#[clap(help = "The name to lookup.")]
who: Option<String>,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
#[clap(long, short, help = "Perform a reverse lookup to verify that the name is correct.")]
verify: bool,
},
#[clap(name = "lookup-address")]
#[clap(about = "Perform an ENS reverse lookup.")]
LookupAddress {
#[clap(help = "The account to perform the lookup for.")]
who: Option<Address>,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
#[clap(
long,
short,
help = "Perform a normal lookup to verify that the address is correct."
)]
verify: bool,
},
#[clap(name = "storage", about = "Get the raw value of a contract's storage slot.")]
Storage {
#[clap(help = "The contract address.", parse(try_from_str = parse_name_or_address))]
address: NameOrAddress,
#[clap(help = "The storage slot number (hex or decimal)", parse(try_from_str = parse_slot))]
slot: H256,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: Option<BlockId>,
},
#[clap(name = "proof", about = "Generate a storage proof for a given storage slot.")]
Proof {
#[clap(help = "The contract address.", parse(try_from_str = parse_name_or_address))]
address: NameOrAddress,
#[clap(help = "The storage slot numbers (hex or decimal).", parse(try_from_str = parse_slot))]
slots: Vec<H256>,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: Option<BlockId>,
},
#[clap(name = "nonce")]
#[clap(about = "Get the nonce for an account.")]
Nonce {
#[clap(
long,
short = 'B',
help = "The block height you want to query at.",
long_help = "The block height you want to query at. Can also be the tags earliest, latest, or pending.",
parse(try_from_str = parse_block_id)
)]
block: Option<BlockId>,
#[clap(help = "The address you want to get the nonce for.", parse(try_from_str = parse_name_or_address))]
who: NameOrAddress,
#[clap(short, long, env = "ETH_RPC_URL")]
rpc_url: Option<String>,
},
#[clap(name = "etherscan-source")]
#[clap(about = "Get the source code of a contract from Etherscan.")]
EtherscanSource {
#[clap(flatten)]
chain: ClapChain,
#[clap(help = "The contract's address.")]
address: String,
#[clap(short, help = "The output directory to expand source tree into.", value_hint = ValueHint::DirPath)]
directory: Option<PathBuf>,
#[clap(long, env = "ETHERSCAN_API_KEY")]
etherscan_api_key: Option<String>,
},
#[clap(name = "wallet", about = "Wallet management utilities.")]
Wallet {
#[clap(subcommand)]
command: WalletSubcommands,
},
#[clap(
name = "interface",
about = "Generate a Solidity interface from a given ABI.",
long_about = "Generate a Solidity interface from a given ABI. Currently does not support ABI encoder v2."
)]
Interface {
#[clap(
help = "The contract address, or the path to an ABI file.",
long_help = r#"The contract address, or the path to an ABI file.
If an address is specified, then the ABI is fetched from Etherscan."#
)]
path_or_address: String,
#[clap(long, short, default_value = "^0.8.10", help = "Solidity pragma version.")]
pragma: String,
#[clap(
short,
help = "The path to the output file.",
long_help = "The path to the output file. If not specified, the interface will be output to stdout."
)]
output_location: Option<PathBuf>,
#[clap(long, short, env = "ETHERSCAN_API_KEY", help = "etherscan API key")]
etherscan_api_key: Option<String>,
#[clap(flatten)]
chain: ClapChain,
},
#[clap(name = "sig", about = "Get the selector for a function.")]
Sig {
#[clap(help = "The function signature, e.g. transfer(address,uint256).")]
sig: String,
},
#[clap(name = "find-block", about = "Get the block number closest to the provided timestamp.")]
FindBlock(FindBlockArgs),
#[clap(about = "Generate shell completions script")]
Completions {
#[clap(arg_enum)]
shell: clap_complete::Shell,
},
}
#[derive(Debug, Parser)]
pub enum WalletSubcommands {
#[clap(name = "new", about = "Create a new random keypair.")]
New {
#[clap(help = "If provided, then keypair will be written to an encrypted JSON keystore.")]
path: Option<String>,
#[clap(
long,
short,
help = "Triggers a hidden password prompt for the JSON keystore.",
conflicts_with = "unsafe-password",
requires = "path"
)]
password: bool,
#[clap(
long,
help = "Password for the JSON keystore in cleartext. This is UNSAFE to use and we recommend using the --password.",
requires = "path",
env = "CAST_PASSWORD"
)]
unsafe_password: Option<String>,
},
#[clap(name = "vanity", about = "Generate a vanity address.")]
Vanity {
#[clap(
long,
help = "Prefix for the vanity address.",
required_unless_present = "ends-with"
)]
starts_with: Option<String>,
#[clap(long, help = "Suffix for the vanity address.")]
ends_with: Option<String>,
#[clap(
long,
help = "Generate a vanity contract address created by the generated keypair with the specified nonce."
)]
nonce: Option<u64>, /* 2^64-1 is max possible nonce per https://eips.ethereum.org/EIPS/eip-2681 */
},
#[clap(name = "address", about = "Convert a private key to an address.")]
Address {
#[clap(flatten)]
wallet: Wallet,
},
#[clap(name = "sign", about = "Sign a message.")]
Sign {
#[clap(help = "message to sign")]
message: String,
#[clap(flatten)]
wallet: Wallet,
},
#[clap(name = "verify", about = "Verify the signature of a message.")]
Verify {
#[clap(help = "The original message.")]
message: String,
#[clap(help = "The signature to verify.")]
signature: String,
#[clap(long, short, help = "The address of the message signer.")]
address: String,
},
}
pub fn parse_name_or_address(s: &str) -> eyre::Result<NameOrAddress> {
Ok(if s.starts_with("0x") {
NameOrAddress::Address(s.parse::<Address>()?)
} else {
NameOrAddress::Name(s.into())
})
}
pub fn parse_block_id(s: &str) -> eyre::Result<BlockId> {
Ok(match s {
"earliest" => BlockId::Number(BlockNumber::Earliest),
"latest" => BlockId::Number(BlockNumber::Latest),
"pending" => BlockId::Number(BlockNumber::Pending),
s if s.starts_with("0x") => BlockId::Hash(H256::from_str(s)?),
s => BlockId::Number(BlockNumber::Number(u64::from_str(s)?.into())),
})
}
fn parse_slot(s: &str) -> eyre::Result<H256> {
Ok(if s.starts_with("0x") {
let padded = format!("{:0>64}", s.strip_prefix("0x").unwrap());
H256::from_str(&padded)?
} else {
H256::from_low_u64_be(u64::from_str(s)?)
})
}
#[derive(Debug, Parser)]
#[clap(name = "cast", version = crate::utils::VERSION_MESSAGE)]
pub struct Opts {
#[clap(subcommand)]
pub sub: Subcommands,
}
| 37.498615 | 141 | 0.573687 |
33cd12117f8437406e1d62f13578fc9a0e27da73 | 234 | use lazy_static::lazy_static;
lazy_static! {
static ref BUILD_VERSION: String =
format!("{}-{}", env!("CARGO_PKG_VERSION"), env!("VERGEN_SHA_SHORT"));
}
pub fn build_version() -> String {
BUILD_VERSION.to_string()
}
| 21.272727 | 78 | 0.662393 |
1619384096bc1e1748c45a27a24262e84f1fc347 | 357 | use bevy_ecs::prelude::*;
use bevy_ecs::query::WorldQuery;
#[derive(Component)]
struct Foo;
#[derive(WorldQuery)]
struct MutableUnmarked {
a: &'static mut Foo,
}
#[derive(WorldQuery)]
#[world_query(mutable)]
struct MutableMarked {
a: &'static mut Foo,
}
#[derive(WorldQuery)]
struct NestedMutableUnmarked {
a: MutableMarked,
}
fn main() {}
| 14.875 | 32 | 0.691877 |
29ec3b1fc33f517cda5f7360f3a3d57aee7024ff | 5,574 | use super::{Tracker, TrackerId, TrackerRegistration, TrackerRegistry};
use hashbrown::hash_map::Entry;
use hashbrown::HashMap;
use std::hash::Hash;
use tracing::info;
/// A wrapper around a TrackerRegistry that automatically retains a history
#[derive(Debug)]
pub struct TrackerRegistryWithHistory<T> {
registry: TrackerRegistry<T>,
history: SizeLimitedHashMap<TrackerId, Tracker<T>>,
}
impl<T: std::fmt::Debug> TrackerRegistryWithHistory<T> {
pub fn new(capacity: usize) -> Self {
Self {
history: SizeLimitedHashMap::new(capacity),
registry: TrackerRegistry::new(),
}
}
/// Register a new tracker in the registry
pub fn register(&mut self, metadata: T) -> (Tracker<T>, TrackerRegistration) {
self.registry.register(metadata)
}
/// Get the tracker associated with a given id
pub fn get(&self, id: TrackerId) -> Option<Tracker<T>> {
match self.history.get(&id) {
Some(x) => Some(x.clone()),
None => self.registry.get(id),
}
}
/// Returns a list of trackers, including those that are no longer running
pub fn tracked(&self) -> Vec<Tracker<T>> {
let mut tracked = self.registry.tracked();
tracked.extend(self.history.values().cloned());
tracked
}
/// Returns a list of active trackers
pub fn running(&self) -> Vec<Tracker<T>> {
self.registry.running()
}
/// Reclaims jobs into the historical archive
pub fn reclaim(&mut self) {
for job in self.registry.reclaim() {
info!(?job, "job finished");
self.history.push(job.id(), job)
}
}
}
/// A size limited hashmap that maintains a finite number
/// of key value pairs providing O(1) key lookups
///
/// Inserts over the capacity will overwrite previous values
#[derive(Debug)]
struct SizeLimitedHashMap<K, V> {
values: HashMap<K, V>,
ring: Vec<K>,
start_idx: usize,
capacity: usize,
}
impl<K: Copy + Hash + Eq + Ord, V> SizeLimitedHashMap<K, V> {
pub fn new(capacity: usize) -> Self {
Self {
values: HashMap::with_capacity(capacity),
ring: Vec::with_capacity(capacity),
start_idx: 0,
capacity,
}
}
/// Get the value associated with a specific key
pub fn get(&self, key: &K) -> Option<&V> {
self.values.get(key)
}
/// Returns an iterator to all values stored within the ring buffer
///
/// Note: the order is not guaranteed
pub fn values(&self) -> impl Iterator<Item = &V> + '_ {
self.values.values()
}
/// Push a new value into the ring buffer
///
/// If a value with the given key already exists, it will replace the value
/// Otherwise it will add the key and value to the buffer
///
/// If there is insufficient capacity it will drop the oldest key value pair
/// from the buffer
pub fn push(&mut self, key: K, value: V) {
if let Entry::Occupied(occupied) = self.values.entry(key) {
// If already exists - replace existing value
occupied.replace_entry(value);
return;
}
if self.ring.len() < self.capacity {
// Still populating the ring
assert_eq!(self.start_idx, 0);
self.ring.push(key);
self.values.insert(key, value);
return;
}
// Need to swap something out of the ring
let mut old = key;
std::mem::swap(&mut self.ring[self.start_idx], &mut old);
self.start_idx += 1;
if self.start_idx == self.capacity {
self.start_idx = 0;
}
self.values.remove(&old);
self.values.insert(key, value);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hashmap() {
let expect = |ring: &SizeLimitedHashMap<i32, i32>, expected: &[i32]| {
let mut values: Vec<_> = ring.values().cloned().collect();
values.sort_unstable();
assert_eq!(&values, expected);
};
let mut ring = SizeLimitedHashMap::new(5);
for i in 0..=4 {
ring.push(i, i);
}
expect(&ring, &[0, 1, 2, 3, 4]);
// Expect rollover
ring.push(5, 5);
expect(&ring, &[1, 2, 3, 4, 5]);
for i in 6..=9 {
ring.push(i, i);
}
expect(&ring, &[5, 6, 7, 8, 9]);
for i in 10..=52 {
ring.push(i + 10, i);
}
expect(&ring, &[48, 49, 50, 51, 52]);
assert_eq!(*ring.get(&60).unwrap(), 50);
}
#[test]
fn test_tracker_archive() {
let compare = |expected_ids: &[TrackerId], archive: &TrackerRegistryWithHistory<i32>| {
let mut collected: Vec<_> = archive.history.values().map(|x| x.id()).collect();
collected.sort();
assert_eq!(&collected, expected_ids);
};
let mut archive = TrackerRegistryWithHistory::new(4);
for i in 0..=3 {
archive.register(i);
}
archive.reclaim();
compare(
&[TrackerId(0), TrackerId(1), TrackerId(2), TrackerId(3)],
&archive,
);
for i in 4..=7 {
archive.register(i);
}
compare(
&[TrackerId(0), TrackerId(1), TrackerId(2), TrackerId(3)],
&archive,
);
archive.reclaim();
compare(
&[TrackerId(4), TrackerId(5), TrackerId(6), TrackerId(7)],
&archive,
);
}
}
| 27.731343 | 95 | 0.554718 |
91939cef6f6b4ed83936a5564ee5055c7620d8f4 | 78,559 | #![cfg(any(feature = "bpf_c", feature = "bpf_rust"))]
#[macro_use]
extern crate solana_bpf_loader_program;
use itertools::izip;
use solana_bpf_loader_program::{
create_vm,
serialization::{deserialize_parameters, serialize_parameters},
syscalls::register_syscalls,
ThisInstructionMeter,
};
use solana_cli_output::display::println_transaction;
use solana_rbpf::vm::{Config, Executable, Tracer};
use solana_runtime::{
bank::{Bank, ExecuteTimings, NonceRollbackInfo, TransactionBalancesSet, TransactionResults},
bank_client::BankClient,
genesis_utils::{create_genesis_config, GenesisConfigInfo},
loader_utils::{
load_buffer_account, load_program, load_upgradeable_program, set_upgrade_authority,
upgrade_program,
},
};
use solana_sdk::{
account::AccountSharedData,
bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable,
client::SyncClient,
clock::{DEFAULT_SLOTS_PER_EPOCH, MAX_PROCESSING_AGE},
entrypoint::{MAX_PERMITTED_DATA_INCREASE, SUCCESS},
feature_set::ristretto_mul_syscall_enabled,
instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError},
keyed_account::KeyedAccount,
message::Message,
process_instruction::{InvokeContext, MockInvokeContext},
pubkey::Pubkey,
signature::{keypair_from_seed, Keypair, Signer},
system_instruction,
sysvar::{clock, fees, rent, slot_hashes, stake_history},
transaction::{Transaction, TransactionError},
};
use solana_transaction_status::{
token_balances::collect_token_balances, ConfirmedTransaction, InnerInstructions,
TransactionStatusMeta, TransactionWithStatusMeta, UiTransactionEncoding,
};
use std::{cell::RefCell, collections::HashMap, env, fs::File, io::Read, path::PathBuf, sync::Arc};
/// BPF program file extension
const PLATFORM_FILE_EXTENSION_BPF: &str = "so";
/// Create a BPF program file name
fn create_bpf_path(name: &str) -> PathBuf {
let mut pathbuf = {
let current_exe = env::current_exe().unwrap();
PathBuf::from(current_exe.parent().unwrap().parent().unwrap())
};
pathbuf.push("bpf/");
pathbuf.push(name);
pathbuf.set_extension(PLATFORM_FILE_EXTENSION_BPF);
pathbuf
}
fn load_bpf_program(
bank_client: &BankClient,
loader_id: &Pubkey,
payer_keypair: &Keypair,
name: &str,
) -> Pubkey {
let elf = read_bpf_program(name);
load_program(bank_client, payer_keypair, loader_id, elf)
}
fn read_bpf_program(name: &str) -> Vec<u8> {
let path = create_bpf_path(name);
let mut file = File::open(&path).unwrap_or_else(|err| {
panic!("Failed to open {}: {}", path.display(), err);
});
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
elf
}
#[cfg(feature = "bpf_rust")]
fn write_bpf_program(
bank_client: &BankClient,
loader_id: &Pubkey,
payer_keypair: &Keypair,
program_keypair: &Keypair,
elf: &[u8],
) {
use solana_sdk::loader_instruction;
let chunk_size = 256; // Size of chunk just needs to fit into tx
let mut offset = 0;
for chunk in elf.chunks(chunk_size) {
let instruction =
loader_instruction::write(&program_keypair.pubkey(), loader_id, offset, chunk.to_vec());
let message = Message::new(&[instruction], Some(&payer_keypair.pubkey()));
bank_client
.send_and_confirm_message(&[payer_keypair, &program_keypair], message)
.unwrap();
offset += chunk_size as u32;
}
}
fn load_upgradeable_bpf_program(
bank_client: &BankClient,
payer_keypair: &Keypair,
buffer_keypair: &Keypair,
executable_keypair: &Keypair,
authority_keypair: &Keypair,
name: &str,
) {
let path = create_bpf_path(name);
let mut file = File::open(&path).unwrap_or_else(|err| {
panic!("Failed to open {}: {}", path.display(), err);
});
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
load_upgradeable_program(
bank_client,
payer_keypair,
buffer_keypair,
executable_keypair,
authority_keypair,
elf,
);
}
fn load_upgradeable_buffer(
bank_client: &BankClient,
payer_keypair: &Keypair,
buffer_keypair: &Keypair,
buffer_authority_keypair: &Keypair,
name: &str,
) {
let path = create_bpf_path(name);
let mut file = File::open(&path).unwrap_or_else(|err| {
panic!("Failed to open {}: {}", path.display(), err);
});
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
load_buffer_account(
bank_client,
payer_keypair,
&buffer_keypair,
buffer_authority_keypair,
&elf,
);
}
fn upgrade_bpf_program(
bank_client: &BankClient,
payer_keypair: &Keypair,
buffer_keypair: &Keypair,
executable_pubkey: &Pubkey,
authority_keypair: &Keypair,
name: &str,
) {
load_upgradeable_buffer(
bank_client,
payer_keypair,
buffer_keypair,
authority_keypair,
name,
);
upgrade_program(
bank_client,
payer_keypair,
executable_pubkey,
&buffer_keypair.pubkey(),
&authority_keypair,
&payer_keypair.pubkey(),
);
}
fn run_program(
name: &str,
program_id: &Pubkey,
parameter_accounts: &[KeyedAccount],
instruction_data: &[u8],
) -> Result<u64, InstructionError> {
let path = create_bpf_path(name);
let mut file = File::open(path).unwrap();
let mut data = vec![];
file.read_to_end(&mut data).unwrap();
let loader_id = bpf_loader::id();
let mut invoke_context = MockInvokeContext::default();
let parameter_bytes = serialize_parameters(
&bpf_loader::id(),
program_id,
parameter_accounts,
&instruction_data,
)
.unwrap();
let compute_meter = invoke_context.get_compute_meter();
let mut instruction_meter = ThisInstructionMeter { compute_meter };
let config = Config {
max_call_depth: 20,
stack_frame_size: 4096,
enable_instruction_meter: true,
enable_instruction_tracing: true,
};
let mut executable = Executable::from_elf(&data, None, config).unwrap();
executable.set_syscall_registry(register_syscalls(&mut invoke_context).unwrap());
executable.jit_compile().unwrap();
let mut instruction_count = 0;
let mut tracer = None;
for i in 0..2 {
let mut parameter_bytes = parameter_bytes.clone();
let mut vm = create_vm(
&loader_id,
executable.as_ref(),
&mut parameter_bytes,
parameter_accounts,
&mut invoke_context,
)
.unwrap();
let result = if i == 0 {
vm.execute_program_interpreted(&mut instruction_meter)
} else {
vm.execute_program_jit(&mut instruction_meter)
};
assert_eq!(SUCCESS, result.unwrap());
deserialize_parameters(
&bpf_loader::id(),
parameter_accounts,
¶meter_bytes,
true,
)
.unwrap();
if i == 1 {
assert_eq!(instruction_count, vm.get_total_instruction_count());
}
instruction_count = vm.get_total_instruction_count();
if config.enable_instruction_tracing {
if i == 1 {
if !Tracer::compare(tracer.as_ref().unwrap(), vm.get_tracer()) {
let mut tracer_display = String::new();
tracer
.as_ref()
.unwrap()
.write(&mut tracer_display, vm.get_program())
.unwrap();
println!("TRACE (interpreted): {}", tracer_display);
let mut tracer_display = String::new();
vm.get_tracer()
.write(&mut tracer_display, vm.get_program())
.unwrap();
println!("TRACE (jit): {}", tracer_display);
assert!(false);
}
}
tracer = Some(vm.get_tracer().clone());
}
}
Ok(instruction_count)
}
fn process_transaction_and_record_inner(
bank: &Bank,
tx: Transaction,
) -> (Result<(), TransactionError>, Vec<Vec<CompiledInstruction>>) {
let signature = tx.signatures.get(0).unwrap().clone();
let txs = vec![tx];
let tx_batch = bank.prepare_batch(&txs, None);
let (mut results, _, mut inner, _transaction_logs) = bank.load_execute_and_commit_transactions(
&tx_batch,
MAX_PROCESSING_AGE,
false,
true,
false,
&mut ExecuteTimings::default(),
);
let inner_instructions = if inner.is_empty() {
Some(vec![vec![]])
} else {
inner.swap_remove(0)
};
let result = results
.fee_collection_results
.swap_remove(0)
.and_then(|_| bank.get_signature_status(&signature).unwrap());
(
result,
inner_instructions.expect("cpi recording should be enabled"),
)
}
fn execute_transactions(bank: &Bank, txs: &[Transaction]) -> Vec<ConfirmedTransaction> {
let batch = bank.prepare_batch(txs, None);
let mut timings = ExecuteTimings::default();
let mut mint_decimals = HashMap::new();
let tx_pre_token_balances = collect_token_balances(&bank, &batch, &mut mint_decimals);
let (
TransactionResults {
execution_results, ..
},
TransactionBalancesSet {
pre_balances,
post_balances,
..
},
mut inner_instructions,
mut transaction_logs,
) = bank.load_execute_and_commit_transactions(
&batch,
std::usize::MAX,
true,
true,
true,
&mut timings,
);
let tx_post_token_balances = collect_token_balances(&bank, &batch, &mut mint_decimals);
for _ in 0..(txs.len() - transaction_logs.len()) {
transaction_logs.push(vec![]);
}
for _ in 0..(txs.len() - inner_instructions.len()) {
inner_instructions.push(None);
}
izip!(
txs.iter(),
execution_results.into_iter(),
inner_instructions.into_iter(),
pre_balances.into_iter(),
post_balances.into_iter(),
tx_pre_token_balances.into_iter(),
tx_post_token_balances.into_iter(),
transaction_logs.into_iter(),
)
.map(
|(
tx,
(execute_result, nonce_rollback),
inner_instructions,
pre_balances,
post_balances,
pre_token_balances,
post_token_balances,
log_messages,
)| {
let fee_calculator = nonce_rollback
.map(|nonce_rollback| nonce_rollback.fee_calculator())
.unwrap_or_else(|| bank.get_fee_calculator(&tx.message().recent_blockhash))
.expect("FeeCalculator must exist");
let fee = fee_calculator.calculate_fee(tx.message());
let inner_instructions = inner_instructions.map(|inner_instructions| {
inner_instructions
.into_iter()
.enumerate()
.map(|(index, instructions)| InnerInstructions {
index: index as u8,
instructions,
})
.filter(|i| !i.instructions.is_empty())
.collect()
});
let tx_status_meta = TransactionStatusMeta {
status: execute_result,
fee,
pre_balances,
post_balances,
pre_token_balances: Some(pre_token_balances),
post_token_balances: Some(post_token_balances),
inner_instructions,
log_messages: Some(log_messages),
};
ConfirmedTransaction {
slot: bank.slot(),
transaction: TransactionWithStatusMeta {
transaction: tx.clone(),
meta: Some(tx_status_meta),
},
block_time: None,
}
},
)
.collect()
}
fn print_confirmed_tx(name: &str, confirmed_tx: ConfirmedTransaction) {
let block_time = confirmed_tx.block_time;
let tx = confirmed_tx.transaction.transaction.clone();
let encoded = confirmed_tx.encode(UiTransactionEncoding::JsonParsed);
println!("EXECUTE {} (slot {})", name, encoded.slot);
println_transaction(&tx, &encoded.transaction.meta, " ", None, block_time);
}
#[test]
#[cfg(any(feature = "bpf_c", feature = "bpf_rust"))]
fn test_program_bpf_sanity() {
solana_logger::setup();
let mut programs = Vec::new();
#[cfg(feature = "bpf_c")]
{
programs.extend_from_slice(&[
("alloc", true),
("bpf_to_bpf", true),
("multiple_static", true),
("noop", true),
("noop++", true),
("panic", false),
("relative_call", true),
("sanity", true),
("sanity++", true),
("sha256", true),
("struct_pass", true),
("struct_ret", true),
]);
}
#[cfg(feature = "bpf_rust")]
{
programs.extend_from_slice(&[
("solana_bpf_rust_128bit", true),
("solana_bpf_rust_alloc", true),
("solana_bpf_rust_custom_heap", true),
("solana_bpf_rust_dep_crate", true),
("solana_bpf_rust_external_spend", false),
("solana_bpf_rust_iter", true),
("solana_bpf_rust_many_args", true),
("solana_bpf_rust_mem", true),
("solana_bpf_rust_noop", true),
("solana_bpf_rust_panic", false),
("solana_bpf_rust_param_passing", true),
("solana_bpf_rust_rand", true),
("solana_bpf_rust_ristretto", true),
("solana_bpf_rust_sanity", true),
("solana_bpf_rust_sha256", true),
("solana_bpf_rust_sysval", true),
]);
}
for program in programs.iter() {
println!("Test program: {:?}", program.0);
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
// Create bank with a specific slot, used by solana_bpf_rust_sysvar test
let bank = Bank::new_from_parent(&bank, &Pubkey::default(), DEFAULT_SLOTS_PER_EPOCH + 1);
let bank_client = BankClient::new(bank);
// Call user program
let program_id =
load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.0);
let account_metas = vec![
AccountMeta::new(mint_keypair.pubkey(), true),
AccountMeta::new(Keypair::new().pubkey(), false),
AccountMeta::new(clock::id(), false),
AccountMeta::new(fees::id(), false),
AccountMeta::new(slot_hashes::id(), false),
AccountMeta::new(stake_history::id(), false),
AccountMeta::new(rent::id(), false),
];
let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
if program.1 {
assert!(result.is_ok());
} else {
assert!(result.is_err());
}
}
}
#[test]
#[cfg(any(feature = "bpf_c", feature = "bpf_rust"))]
fn test_program_bpf_loader_deprecated() {
solana_logger::setup();
let mut programs = Vec::new();
#[cfg(feature = "bpf_c")]
{
programs.extend_from_slice(&[("deprecated_loader")]);
}
#[cfg(feature = "bpf_rust")]
{
programs.extend_from_slice(&[("solana_bpf_rust_deprecated_loader")]);
}
for program in programs.iter() {
println!("Test program: {:?}", program);
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_deprecated_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
let program_id = load_bpf_program(
&bank_client,
&bpf_loader_deprecated::id(),
&mint_keypair,
program,
);
let account_metas = vec![AccountMeta::new(mint_keypair.pubkey(), true)];
let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert!(result.is_ok());
}
}
#[test]
fn test_program_bpf_duplicate_accounts() {
solana_logger::setup();
let mut programs = Vec::new();
#[cfg(feature = "bpf_c")]
{
programs.extend_from_slice(&[("dup_accounts")]);
}
#[cfg(feature = "bpf_rust")]
{
programs.extend_from_slice(&[("solana_bpf_rust_dup_accounts")]);
}
for program in programs.iter() {
println!("Test program: {:?}", program);
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program);
let payee_account = AccountSharedData::new(10, 1, &program_id);
let payee_pubkey = solana_sdk::pubkey::new_rand();
bank.store_account(&payee_pubkey, &payee_account);
let account = AccountSharedData::new(10, 1, &program_id);
let pubkey = solana_sdk::pubkey::new_rand();
let account_metas = vec![
AccountMeta::new(mint_keypair.pubkey(), true),
AccountMeta::new(payee_pubkey, false),
AccountMeta::new(pubkey, false),
AccountMeta::new(pubkey, false),
];
bank.store_account(&pubkey, &account);
let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let data = bank_client.get_account_data(&pubkey).unwrap().unwrap();
assert!(result.is_ok());
assert_eq!(data[0], 1);
bank.store_account(&pubkey, &account);
let instruction = Instruction::new_with_bytes(program_id, &[2], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let data = bank_client.get_account_data(&pubkey).unwrap().unwrap();
assert!(result.is_ok());
assert_eq!(data[0], 2);
bank.store_account(&pubkey, &account);
let instruction = Instruction::new_with_bytes(program_id, &[3], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let data = bank_client.get_account_data(&pubkey).unwrap().unwrap();
assert!(result.is_ok());
assert_eq!(data[0], 3);
bank.store_account(&pubkey, &account);
let instruction = Instruction::new_with_bytes(program_id, &[4], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let lamports = bank_client.get_balance(&pubkey).unwrap();
assert!(result.is_ok());
assert_eq!(lamports, 11);
bank.store_account(&pubkey, &account);
let instruction = Instruction::new_with_bytes(program_id, &[5], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let lamports = bank_client.get_balance(&pubkey).unwrap();
assert!(result.is_ok());
assert_eq!(lamports, 12);
bank.store_account(&pubkey, &account);
let instruction = Instruction::new_with_bytes(program_id, &[6], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let lamports = bank_client.get_balance(&pubkey).unwrap();
assert!(result.is_ok());
assert_eq!(lamports, 13);
let keypair = Keypair::new();
let pubkey = keypair.pubkey();
let account_metas = vec![
AccountMeta::new(mint_keypair.pubkey(), true),
AccountMeta::new(payee_pubkey, false),
AccountMeta::new(pubkey, false),
AccountMeta::new_readonly(pubkey, true),
AccountMeta::new_readonly(program_id, false),
];
bank.store_account(&pubkey, &account);
let instruction = Instruction::new_with_bytes(program_id, &[7], account_metas.clone());
let message = Message::new(&[instruction], Some(&mint_keypair.pubkey()));
let result = bank_client.send_and_confirm_message(&[&mint_keypair, &keypair], message);
assert!(result.is_ok());
}
}
#[test]
fn test_program_bpf_error_handling() {
solana_logger::setup();
let mut programs = Vec::new();
#[cfg(feature = "bpf_c")]
{
programs.extend_from_slice(&[("error_handling")]);
}
#[cfg(feature = "bpf_rust")]
{
programs.extend_from_slice(&[("solana_bpf_rust_error_handling")]);
}
for program in programs.iter() {
println!("Test program: {:?}", program);
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
let program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program);
let account_metas = vec![AccountMeta::new(mint_keypair.pubkey(), true)];
let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert!(result.is_ok());
let instruction = Instruction::new_with_bytes(program_id, &[2], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::InvalidAccountData)
);
let instruction = Instruction::new_with_bytes(program_id, &[3], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(0))
);
let instruction = Instruction::new_with_bytes(program_id, &[4], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(42))
);
let instruction = Instruction::new_with_bytes(program_id, &[5], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let result = result.unwrap_err().unwrap();
if TransactionError::InstructionError(0, InstructionError::InvalidInstructionData) != result
{
assert_eq!(
result,
TransactionError::InstructionError(0, InstructionError::InvalidError)
);
}
let instruction = Instruction::new_with_bytes(program_id, &[6], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let result = result.unwrap_err().unwrap();
if TransactionError::InstructionError(0, InstructionError::InvalidInstructionData) != result
{
assert_eq!(
result,
TransactionError::InstructionError(0, InstructionError::InvalidError)
);
}
let instruction = Instruction::new_with_bytes(program_id, &[7], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
let result = result.unwrap_err().unwrap();
if TransactionError::InstructionError(0, InstructionError::InvalidInstructionData) != result
{
assert_eq!(
result,
TransactionError::InstructionError(0, InstructionError::AccountBorrowFailed)
);
}
let instruction = Instruction::new_with_bytes(program_id, &[8], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::InvalidInstructionData)
);
let instruction = Instruction::new_with_bytes(program_id, &[9], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::MaxSeedLengthExceeded)
);
}
}
#[test]
fn test_program_bpf_invoke_sanity() {
solana_logger::setup();
const TEST_SUCCESS: u8 = 1;
const TEST_PRIVILEGE_ESCALATION_SIGNER: u8 = 2;
const TEST_PRIVILEGE_ESCALATION_WRITABLE: u8 = 3;
const TEST_PPROGRAM_NOT_EXECUTABLE: u8 = 4;
const TEST_EMPTY_ACCOUNTS_SLICE: u8 = 5;
const TEST_CAP_SEEDS: u8 = 6;
const TEST_CAP_SIGNERS: u8 = 7;
const TEST_ALLOC_ACCESS_VIOLATION: u8 = 8;
const TEST_INSTRUCTION_DATA_TOO_LARGE: u8 = 9;
const TEST_INSTRUCTION_META_TOO_LARGE: u8 = 10;
const TEST_RETURN_ERROR: u8 = 11;
const TEST_PRIVILEGE_DEESCALATION_ESCALATION_SIGNER: u8 = 12;
const TEST_PRIVILEGE_DEESCALATION_ESCALATION_WRITABLE: u8 = 13;
#[allow(dead_code)]
#[derive(Debug)]
enum Languages {
C,
Rust,
}
let mut programs = Vec::new();
#[cfg(feature = "bpf_c")]
{
programs.push((Languages::C, "invoke", "invoked", "noop"));
}
#[cfg(feature = "bpf_rust")]
{
programs.push((
Languages::Rust,
"solana_bpf_rust_invoke",
"solana_bpf_rust_invoked",
"solana_bpf_rust_noop",
));
}
for program in programs.iter() {
println!("Test program: {:?}", program);
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let invoke_program_id =
load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.1);
let invoked_program_id =
load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.2);
let noop_program_id =
load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.3);
let argument_keypair = Keypair::new();
let account = AccountSharedData::new(42, 100, &invoke_program_id);
bank.store_account(&argument_keypair.pubkey(), &account);
let invoked_argument_keypair = Keypair::new();
let account = AccountSharedData::new(10, 10, &invoked_program_id);
bank.store_account(&invoked_argument_keypair.pubkey(), &account);
let from_keypair = Keypair::new();
let account = AccountSharedData::new(84, 0, &solana_sdk::system_program::id());
bank.store_account(&from_keypair.pubkey(), &account);
let (derived_key1, bump_seed1) =
Pubkey::find_program_address(&[b"You pass butter"], &invoke_program_id);
let (derived_key2, bump_seed2) =
Pubkey::find_program_address(&[b"Lil'", b"Bits"], &invoked_program_id);
let (derived_key3, bump_seed3) =
Pubkey::find_program_address(&[derived_key2.as_ref()], &invoked_program_id);
let mint_pubkey = mint_keypair.pubkey();
let account_metas = vec![
AccountMeta::new(mint_pubkey, true),
AccountMeta::new(argument_keypair.pubkey(), true),
AccountMeta::new_readonly(invoked_program_id, false),
AccountMeta::new(invoked_argument_keypair.pubkey(), true),
AccountMeta::new_readonly(invoked_program_id, false),
AccountMeta::new(argument_keypair.pubkey(), true),
AccountMeta::new(derived_key1, false),
AccountMeta::new(derived_key2, false),
AccountMeta::new_readonly(derived_key3, false),
AccountMeta::new_readonly(solana_sdk::system_program::id(), false),
AccountMeta::new(from_keypair.pubkey(), true),
];
// success cases
let instruction = Instruction::new_with_bytes(
invoke_program_id,
&[TEST_SUCCESS, bump_seed1, bump_seed2, bump_seed3],
account_metas.clone(),
);
let noop_instruction = Instruction::new_with_bytes(noop_program_id, &[], vec![]);
let message = Message::new(&[instruction, noop_instruction], Some(&mint_pubkey));
let tx = Transaction::new(
&[
&mint_keypair,
&argument_keypair,
&invoked_argument_keypair,
&from_keypair,
],
message.clone(),
bank.last_blockhash(),
);
let (result, inner_instructions) = process_transaction_and_record_inner(&bank, tx);
assert!(result.is_ok());
let invoked_programs: Vec<Pubkey> = inner_instructions[0]
.iter()
.map(|ix| message.account_keys[ix.program_id_index as usize].clone())
.collect();
let expected_invoked_programs = match program.0 {
Languages::C => vec![
solana_sdk::system_program::id(),
solana_sdk::system_program::id(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
],
Languages::Rust => vec![
solana_sdk::system_program::id(),
solana_sdk::system_program::id(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
invoked_program_id.clone(),
],
};
assert_eq!(invoked_programs.len(), expected_invoked_programs.len());
assert_eq!(invoked_programs, expected_invoked_programs);
let no_invoked_programs: Vec<Pubkey> = inner_instructions[1]
.iter()
.map(|ix| message.account_keys[ix.program_id_index as usize].clone())
.collect();
assert_eq!(no_invoked_programs.len(), 0);
// failure cases
let do_invoke_failure_test_local =
|test: u8, expected_error: TransactionError, expected_invoked_programs: &[Pubkey]| {
println!("Running failure test #{:?}", test);
let instruction_data = &[test, bump_seed1, bump_seed2, bump_seed3];
let signers = vec![
&mint_keypair,
&argument_keypair,
&invoked_argument_keypair,
&from_keypair,
];
let instruction = Instruction::new_with_bytes(
invoke_program_id,
instruction_data,
account_metas.clone(),
);
let message = Message::new(&[instruction], Some(&mint_pubkey));
let tx = Transaction::new(&signers, message.clone(), bank.last_blockhash());
let (result, inner_instructions) = process_transaction_and_record_inner(&bank, tx);
let invoked_programs: Vec<Pubkey> = inner_instructions[0]
.iter()
.map(|ix| message.account_keys[ix.program_id_index as usize].clone())
.collect();
assert_eq!(result.unwrap_err(), expected_error);
assert_eq!(invoked_programs, expected_invoked_programs);
};
do_invoke_failure_test_local(
TEST_PRIVILEGE_ESCALATION_SIGNER,
TransactionError::InstructionError(0, InstructionError::PrivilegeEscalation),
&[invoked_program_id.clone()],
);
do_invoke_failure_test_local(
TEST_PRIVILEGE_ESCALATION_WRITABLE,
TransactionError::InstructionError(0, InstructionError::PrivilegeEscalation),
&[invoked_program_id.clone()],
);
do_invoke_failure_test_local(
TEST_PPROGRAM_NOT_EXECUTABLE,
TransactionError::InstructionError(0, InstructionError::AccountNotExecutable),
&[],
);
do_invoke_failure_test_local(
TEST_EMPTY_ACCOUNTS_SLICE,
TransactionError::InstructionError(0, InstructionError::MissingAccount),
&[],
);
do_invoke_failure_test_local(
TEST_CAP_SEEDS,
TransactionError::InstructionError(0, InstructionError::MaxSeedLengthExceeded),
&[],
);
do_invoke_failure_test_local(
TEST_CAP_SIGNERS,
TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete),
&[],
);
do_invoke_failure_test_local(
TEST_INSTRUCTION_DATA_TOO_LARGE,
TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete),
&[],
);
do_invoke_failure_test_local(
TEST_INSTRUCTION_META_TOO_LARGE,
TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete),
&[],
);
do_invoke_failure_test_local(
TEST_RETURN_ERROR,
TransactionError::InstructionError(0, InstructionError::Custom(42)),
&[invoked_program_id.clone()],
);
do_invoke_failure_test_local(
TEST_PRIVILEGE_DEESCALATION_ESCALATION_SIGNER,
TransactionError::InstructionError(0, InstructionError::PrivilegeEscalation),
&[invoked_program_id.clone()],
);
do_invoke_failure_test_local(
TEST_PRIVILEGE_DEESCALATION_ESCALATION_WRITABLE,
TransactionError::InstructionError(0, InstructionError::PrivilegeEscalation),
&[invoked_program_id.clone()],
);
// Check resulting state
assert_eq!(43, bank.get_balance(&derived_key1));
let account = bank.get_account(&derived_key1).unwrap();
assert_eq!(invoke_program_id, account.owner);
assert_eq!(
MAX_PERMITTED_DATA_INCREASE,
bank.get_account(&derived_key1).unwrap().data.len()
);
for i in 0..20 {
assert_eq!(i as u8, account.data[i]);
}
// Attempt to realloc into unauthorized address space
let account = AccountSharedData::new(84, 0, &solana_sdk::system_program::id());
bank.store_account(&from_keypair.pubkey(), &account);
bank.store_account(&derived_key1, &AccountSharedData::default());
let instruction = Instruction::new_with_bytes(
invoke_program_id,
&[
TEST_ALLOC_ACCESS_VIOLATION,
bump_seed1,
bump_seed2,
bump_seed3,
],
account_metas.clone(),
);
let message = Message::new(&[instruction], Some(&mint_pubkey));
let tx = Transaction::new(
&[
&mint_keypair,
&argument_keypair,
&invoked_argument_keypair,
&from_keypair,
],
message.clone(),
bank.last_blockhash(),
);
let (result, inner_instructions) = process_transaction_and_record_inner(&bank, tx);
let invoked_programs: Vec<Pubkey> = inner_instructions[0]
.iter()
.map(|ix| message.account_keys[ix.program_id_index as usize].clone())
.collect();
assert_eq!(invoked_programs, vec![solana_sdk::system_program::id()]);
assert_eq!(
result.unwrap_err(),
TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete)
);
}
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_program_id_spoofing() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let malicious_swap_pubkey = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_spoof1",
);
let malicious_system_pubkey = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_spoof1_system",
);
let from_pubkey = Pubkey::new_unique();
let account = AccountSharedData::new(10, 0, &solana_sdk::system_program::id());
bank.store_account(&from_pubkey, &account);
let to_pubkey = Pubkey::new_unique();
let account = AccountSharedData::new(0, 0, &solana_sdk::system_program::id());
bank.store_account(&to_pubkey, &account);
let account_metas = vec![
AccountMeta::new_readonly(solana_sdk::system_program::id(), false),
AccountMeta::new_readonly(malicious_system_pubkey, false),
AccountMeta::new(from_pubkey, false),
AccountMeta::new(to_pubkey, false),
];
let instruction =
Instruction::new_with_bytes(malicious_swap_pubkey, &[], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::MissingRequiredSignature)
);
assert_eq!(10, bank.get_balance(&from_pubkey));
assert_eq!(0, bank.get_balance(&to_pubkey));
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_caller_has_access_to_cpi_program() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let caller_pubkey = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_caller_access",
);
let caller2_pubkey = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_caller_access",
);
let account_metas = vec![
AccountMeta::new_readonly(caller_pubkey, false),
AccountMeta::new_readonly(caller2_pubkey, false),
];
let instruction = Instruction::new_with_bytes(caller_pubkey, &[1], account_metas.clone());
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::MissingAccount)
);
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_ro_modify() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let program_pubkey = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_ro_modify",
);
let test_keypair = Keypair::new();
let account = AccountSharedData::new(10, 0, &solana_sdk::system_program::id());
bank.store_account(&test_keypair.pubkey(), &account);
let account_metas = vec![
AccountMeta::new_readonly(solana_sdk::system_program::id(), false),
AccountMeta::new(test_keypair.pubkey(), true),
];
let instruction = Instruction::new_with_bytes(program_pubkey, &[1], account_metas.clone());
let message = Message::new(&[instruction], Some(&mint_keypair.pubkey()));
let result = bank_client.send_and_confirm_message(&[&mint_keypair, &test_keypair], message);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete)
);
let instruction = Instruction::new_with_bytes(program_pubkey, &[3], account_metas.clone());
let message = Message::new(&[instruction], Some(&mint_keypair.pubkey()));
let result = bank_client.send_and_confirm_message(&[&mint_keypair, &test_keypair], message);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete)
);
let instruction = Instruction::new_with_bytes(program_pubkey, &[4], account_metas.clone());
let message = Message::new(&[instruction], Some(&mint_keypair.pubkey()));
let result = bank_client.send_and_confirm_message(&[&mint_keypair, &test_keypair], message);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete)
);
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_call_depth() {
use solana_sdk::process_instruction::BpfComputeBudget;
solana_logger::setup();
println!("Test program: solana_bpf_rust_call_depth");
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
let program_id = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_call_depth",
);
let instruction = Instruction::new_with_bincode(
program_id,
&(BpfComputeBudget::default().max_call_depth - 1),
vec![],
);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert!(result.is_ok());
let instruction = Instruction::new_with_bincode(
program_id,
&BpfComputeBudget::default().max_call_depth,
vec![],
);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert!(result.is_err());
}
#[test]
fn assert_instruction_count() {
solana_logger::setup();
let mut programs = Vec::new();
#[cfg(feature = "bpf_c")]
{
programs.extend_from_slice(&[
("bpf_to_bpf", 13),
("multiple_static", 8),
("noop", 45),
("relative_call", 10),
("sanity", 176),
("sanity++", 177),
("struct_pass", 8),
("struct_ret", 22),
]);
}
#[cfg(feature = "bpf_rust")]
{
programs.extend_from_slice(&[
("solana_bpf_rust_128bit", 581),
("solana_bpf_rust_alloc", 8941),
("solana_bpf_rust_dep_crate", 2),
("solana_bpf_rust_external_spend", 505),
("solana_bpf_rust_iter", 724),
("solana_bpf_rust_many_args", 237),
("solana_bpf_rust_noop", 479),
("solana_bpf_rust_param_passing", 54),
("solana_bpf_rust_ristretto", 19275),
("solana_bpf_rust_sanity", 956),
]);
}
for program in programs.iter() {
println!("Test program: {:?}", program.0);
let program_id = solana_sdk::pubkey::new_rand();
let key = solana_sdk::pubkey::new_rand();
let mut account = RefCell::new(AccountSharedData::default());
let parameter_accounts = vec![KeyedAccount::new(&key, false, &mut account)];
let count = run_program(program.0, &program_id, ¶meter_accounts[..], &[]).unwrap();
println!(" {} : {:?} ({:?})", program.0, count, program.1,);
assert!(count <= program.1);
}
}
#[cfg(any(feature = "bpf_rust"))]
#[test]
fn test_program_bpf_instruction_introspection() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50_000);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let program_id = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_instruction_introspection",
);
// Passing transaction
let account_metas = vec![AccountMeta::new_readonly(
solana_sdk::sysvar::instructions::id(),
false,
)];
let instruction0 = Instruction::new_with_bytes(program_id, &[0u8, 0u8], account_metas.clone());
let instruction1 = Instruction::new_with_bytes(program_id, &[0u8, 1u8], account_metas.clone());
let instruction2 = Instruction::new_with_bytes(program_id, &[0u8, 2u8], account_metas);
let message = Message::new(
&[instruction0, instruction1, instruction2],
Some(&mint_keypair.pubkey()),
);
let result = bank_client.send_and_confirm_message(&[&mint_keypair], message);
assert!(result.is_ok());
// writable special instructions11111 key, should not be allowed
let account_metas = vec![AccountMeta::new(
solana_sdk::sysvar::instructions::id(),
false,
)];
let instruction = Instruction::new_with_bytes(program_id, &[0], account_metas);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InvalidAccountIndex
);
// No accounts, should error
let instruction = Instruction::new_with_bytes(program_id, &[0], vec![]);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert!(result.is_err());
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(
0,
solana_sdk::instruction::InstructionError::NotEnoughAccountKeys
)
);
assert!(bank
.get_account(&solana_sdk::sysvar::instructions::id())
.is_none());
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_test_use_latest_executor() {
use solana_sdk::{loader_instruction, system_instruction};
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
let panic_id = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_panic",
);
let program_keypair = Keypair::new();
// Write the panic program into the program account
let elf = read_bpf_program("solana_bpf_rust_panic");
let message = Message::new(
&[system_instruction::create_account(
&mint_keypair.pubkey(),
&program_keypair.pubkey(),
1,
elf.len() as u64 * 2,
&bpf_loader::id(),
)],
Some(&mint_keypair.pubkey()),
);
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair, &program_keypair], message)
.is_ok());
write_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
&program_keypair,
&elf,
);
// Finalize the panic program, but fail the tx
let message = Message::new(
&[
loader_instruction::finalize(&program_keypair.pubkey(), &bpf_loader::id()),
Instruction::new_with_bytes(panic_id, &[0], vec![]),
],
Some(&mint_keypair.pubkey()),
);
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair, &program_keypair], message)
.is_err());
// Write the noop program into the same program account
let elf = read_bpf_program("solana_bpf_rust_noop");
write_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
&program_keypair,
&elf,
);
// Finalize the noop program
let message = Message::new(
&[loader_instruction::finalize(
&program_keypair.pubkey(),
&bpf_loader::id(),
)],
Some(&mint_keypair.pubkey()),
);
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair, &program_keypair], message)
.is_ok());
// Call the noop program, should get noop not panic
let message = Message::new(
&[Instruction::new_with_bytes(
program_keypair.pubkey(),
&[0],
vec![],
)],
Some(&mint_keypair.pubkey()),
);
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair], message)
.is_ok());
}
#[ignore] // Invoking BPF loaders from CPI not allowed
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_test_use_latest_executor2() {
use solana_sdk::{loader_instruction, system_instruction};
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
let invoke_and_error = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_invoke_and_error",
);
let invoke_and_ok = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_invoke_and_ok",
);
let program_keypair = Keypair::new();
// Write the panic program into the program account
let elf = read_bpf_program("solana_bpf_rust_panic");
let message = Message::new(
&[system_instruction::create_account(
&mint_keypair.pubkey(),
&program_keypair.pubkey(),
1,
elf.len() as u64 * 2,
&bpf_loader::id(),
)],
Some(&mint_keypair.pubkey()),
);
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair, &program_keypair], message)
.is_ok());
write_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
&program_keypair,
&elf,
);
// - invoke finalize and return error, swallow error
let mut instruction =
loader_instruction::finalize(&program_keypair.pubkey(), &bpf_loader::id());
instruction.accounts.insert(
0,
AccountMeta {
is_signer: false,
is_writable: false,
pubkey: instruction.program_id,
},
);
instruction.program_id = invoke_and_ok;
instruction.accounts.insert(
0,
AccountMeta {
is_signer: false,
is_writable: false,
pubkey: invoke_and_error,
},
);
let message = Message::new(&[instruction], Some(&mint_keypair.pubkey()));
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair, &program_keypair], message)
.is_ok());
// invoke program, verify not found
let message = Message::new(
&[Instruction::new_with_bytes(
program_keypair.pubkey(),
&[0],
vec![],
)],
Some(&mint_keypair.pubkey()),
);
assert_eq!(
bank_client
.send_and_confirm_message(&[&mint_keypair], message)
.unwrap_err()
.unwrap(),
TransactionError::InvalidProgramForExecution
);
// Write the noop program into the same program account
let elf = read_bpf_program("solana_bpf_rust_noop");
write_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
&program_keypair,
&elf,
);
// Finalize the noop program
let message = Message::new(
&[loader_instruction::finalize(
&program_keypair.pubkey(),
&bpf_loader::id(),
)],
Some(&mint_keypair.pubkey()),
);
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair, &program_keypair], message)
.is_ok());
// Call the program, should get noop, not panic
let message = Message::new(
&[Instruction::new_with_bytes(
program_keypair.pubkey(),
&[0],
vec![],
)],
Some(&mint_keypair.pubkey()),
);
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair], message)
.is_ok());
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_upgrade() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
// Deploy upgrade program
let buffer_keypair = Keypair::new();
let program_keypair = Keypair::new();
let program_id = program_keypair.pubkey();
let authority_keypair = Keypair::new();
load_upgradeable_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_keypair,
&authority_keypair,
"solana_bpf_rust_upgradeable",
);
let mut instruction = Instruction::new_with_bytes(
program_id,
&[0],
vec![
AccountMeta::new(program_id.clone(), false),
AccountMeta::new(clock::id(), false),
AccountMeta::new(fees::id(), false),
],
);
// Call upgrade program
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone());
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(42))
);
// Upgrade program
let buffer_keypair = Keypair::new();
upgrade_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_id,
&authority_keypair,
"solana_bpf_rust_upgraded",
);
// Call upgraded program
instruction.data[0] += 1;
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone());
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(43))
);
// Set a new authority
let new_authority_keypair = Keypair::new();
set_upgrade_authority(
&bank_client,
&mint_keypair,
&program_id,
&authority_keypair,
Some(&new_authority_keypair.pubkey()),
);
// Upgrade back to the original program
let buffer_keypair = Keypair::new();
upgrade_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_id,
&new_authority_keypair,
"solana_bpf_rust_upgradeable",
);
// Call original program
instruction.data[0] += 1;
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(42))
);
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_upgrade_and_invoke_in_same_tx() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
// Deploy upgrade program
let buffer_keypair = Keypair::new();
let program_keypair = Keypair::new();
let program_id = program_keypair.pubkey();
let authority_keypair = Keypair::new();
load_upgradeable_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_keypair,
&authority_keypair,
"solana_bpf_rust_noop",
);
let invoke_instruction = Instruction::new_with_bytes(
program_id,
&[0],
vec![
AccountMeta::new(program_id.clone(), false),
AccountMeta::new(clock::id(), false),
AccountMeta::new(fees::id(), false),
],
);
// Call upgradeable program
let result =
bank_client.send_and_confirm_instruction(&mint_keypair, invoke_instruction.clone());
assert!(result.is_ok());
// Prepare for upgrade
let buffer_keypair = Keypair::new();
load_upgradeable_buffer(
&bank_client,
&mint_keypair,
&buffer_keypair,
&authority_keypair,
"solana_bpf_rust_panic",
);
// Invoke, then upgrade the program, and then invoke again in same tx
let message = Message::new(
&[
invoke_instruction.clone(),
bpf_loader_upgradeable::upgrade(
&program_id,
&buffer_keypair.pubkey(),
&authority_keypair.pubkey(),
&mint_keypair.pubkey(),
),
invoke_instruction,
],
Some(&mint_keypair.pubkey()),
);
let tx = Transaction::new(
&[&mint_keypair, &authority_keypair],
message.clone(),
bank.last_blockhash(),
);
let (result, _) = process_transaction_and_record_inner(&bank, tx);
assert_eq!(
result.unwrap_err(),
TransactionError::InstructionError(2, InstructionError::ProgramFailedToComplete)
);
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_invoke_upgradeable_via_cpi() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
let invoke_and_return = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_invoke_and_return",
);
// Deploy upgradeable program
let buffer_keypair = Keypair::new();
let program_keypair = Keypair::new();
let program_id = program_keypair.pubkey();
let authority_keypair = Keypair::new();
load_upgradeable_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_keypair,
&authority_keypair,
"solana_bpf_rust_upgradeable",
);
let mut instruction = Instruction::new_with_bytes(
invoke_and_return,
&[0],
vec![
AccountMeta::new(program_id, false),
AccountMeta::new(program_id, false),
AccountMeta::new(clock::id(), false),
AccountMeta::new(fees::id(), false),
],
);
// Call invoker program to invoke the upgradeable program
instruction.data[0] += 1;
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone());
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(42))
);
// Upgrade program
let buffer_keypair = Keypair::new();
upgrade_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_id,
&authority_keypair,
"solana_bpf_rust_upgraded",
);
// Call the upgraded program
instruction.data[0] += 1;
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone());
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(43))
);
// Set a new authority
let new_authority_keypair = Keypair::new();
set_upgrade_authority(
&bank_client,
&mint_keypair,
&program_id,
&authority_keypair,
Some(&new_authority_keypair.pubkey()),
);
// Upgrade back to the original program
let buffer_keypair = Keypair::new();
upgrade_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_id,
&new_authority_keypair,
"solana_bpf_rust_upgradeable",
);
// Call original program
instruction.data[0] += 1;
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone());
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(42))
);
}
#[test]
#[cfg(any(feature = "bpf_c", feature = "bpf_rust"))]
fn test_program_bpf_disguised_as_bpf_loader() {
solana_logger::setup();
let mut programs = Vec::new();
#[cfg(feature = "bpf_c")]
{
programs.extend_from_slice(&[("noop")]);
}
#[cfg(feature = "bpf_rust")]
{
programs.extend_from_slice(&[("solana_bpf_rust_noop")]);
}
for program in programs.iter() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_deprecated_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
let program_id = load_bpf_program(
&bank_client,
&bpf_loader_deprecated::id(),
&mint_keypair,
program,
);
let account_metas = vec![AccountMeta::new_readonly(program_id, false)];
let instruction =
Instruction::new_with_bytes(bpf_loader_deprecated::id(), &[1], account_metas);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::IncorrectProgramId)
);
}
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_upgrade_via_cpi() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!();
bank.add_builtin(&name, id, entrypoint);
let bank_client = BankClient::new(bank);
let invoke_and_return = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_invoke_and_return",
);
// Deploy upgradeable program
let buffer_keypair = Keypair::new();
let program_keypair = Keypair::new();
let program_id = program_keypair.pubkey();
let authority_keypair = Keypair::new();
load_upgradeable_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_keypair,
&authority_keypair,
"solana_bpf_rust_upgradeable",
);
let mut instruction = Instruction::new_with_bytes(
invoke_and_return,
&[0],
vec![
AccountMeta::new(program_id, false),
AccountMeta::new(program_id, false),
AccountMeta::new(clock::id(), false),
AccountMeta::new(fees::id(), false),
],
);
// Call the upgraded program
instruction.data[0] += 1;
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone());
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(42))
);
// Load the buffer account
let path = create_bpf_path("solana_bpf_rust_upgraded");
let mut file = File::open(&path).unwrap_or_else(|err| {
panic!("Failed to open {}: {}", path.display(), err);
});
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
let buffer_keypair = Keypair::new();
load_buffer_account(
&bank_client,
&mint_keypair,
&buffer_keypair,
&authority_keypair,
&elf,
);
// Upgrade program via CPI
let mut upgrade_instruction = bpf_loader_upgradeable::upgrade(
&program_id,
&buffer_keypair.pubkey(),
&authority_keypair.pubkey(),
&mint_keypair.pubkey(),
);
upgrade_instruction.program_id = invoke_and_return;
upgrade_instruction
.accounts
.insert(0, AccountMeta::new(bpf_loader_upgradeable::id(), false));
let message = Message::new(&[upgrade_instruction], Some(&mint_keypair.pubkey()));
bank_client
.send_and_confirm_message(&[&mint_keypair, &authority_keypair], message)
.unwrap();
// Call the upgraded program
instruction.data[0] += 1;
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone());
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::Custom(43))
);
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_upgrade_self_via_cpi() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let noop_program_id = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_noop",
);
// Deploy upgradeable program
let buffer_keypair = Keypair::new();
let program_keypair = Keypair::new();
let program_id = program_keypair.pubkey();
let authority_keypair = Keypair::new();
load_upgradeable_bpf_program(
&bank_client,
&mint_keypair,
&buffer_keypair,
&program_keypair,
&authority_keypair,
"solana_bpf_rust_invoke_and_return",
);
let mut invoke_instruction = Instruction::new_with_bytes(
program_id,
&[0],
vec![
AccountMeta::new(noop_program_id, false),
AccountMeta::new(noop_program_id, false),
AccountMeta::new(clock::id(), false),
AccountMeta::new(fees::id(), false),
],
);
// Call the upgraded program
invoke_instruction.data[0] += 1;
let result =
bank_client.send_and_confirm_instruction(&mint_keypair, invoke_instruction.clone());
assert!(result.is_ok());
// Prepare for upgrade
let buffer_keypair = Keypair::new();
load_upgradeable_buffer(
&bank_client,
&mint_keypair,
&buffer_keypair,
&authority_keypair,
"solana_bpf_rust_panic",
);
// Invoke, then upgrade the program, and then invoke again in same tx
let message = Message::new(
&[
invoke_instruction.clone(),
bpf_loader_upgradeable::upgrade(
&program_id,
&buffer_keypair.pubkey(),
&authority_keypair.pubkey(),
&mint_keypair.pubkey(),
),
invoke_instruction,
],
Some(&mint_keypair.pubkey()),
);
let tx = Transaction::new(
&[&mint_keypair, &authority_keypair],
message.clone(),
bank.last_blockhash(),
);
let (result, _) = process_transaction_and_record_inner(&bank, tx);
assert_eq!(
result.unwrap_err(),
TransactionError::InstructionError(2, InstructionError::ProgramFailedToComplete)
);
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_upgradeable_locks() {
fn setup_program_upgradeable_locks(
payer_keypair: &Keypair,
buffer_keypair: &Keypair,
program_keypair: &Keypair,
) -> (Arc<Bank>, Transaction, Transaction) {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(2_000_000_000);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
load_upgradeable_bpf_program(
&bank_client,
&mint_keypair,
buffer_keypair,
program_keypair,
payer_keypair,
"solana_bpf_rust_panic",
);
// Load the buffer account
let path = create_bpf_path("solana_bpf_rust_noop");
let mut file = File::open(&path).unwrap_or_else(|err| {
panic!("Failed to open {}: {}", path.display(), err);
});
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
load_buffer_account(
&bank_client,
&mint_keypair,
buffer_keypair,
&payer_keypair,
&elf,
);
bank_client
.send_and_confirm_instruction(
&mint_keypair,
system_instruction::transfer(
&mint_keypair.pubkey(),
&payer_keypair.pubkey(),
1_000_000_000,
),
)
.unwrap();
let invoke_tx = Transaction::new(
&[payer_keypair],
Message::new(
&[Instruction::new_with_bytes(
program_keypair.pubkey(),
&[0; 0],
vec![],
)],
Some(&payer_keypair.pubkey()),
),
bank.last_blockhash(),
);
let upgrade_tx = Transaction::new(
&[payer_keypair],
Message::new(
&[bpf_loader_upgradeable::upgrade(
&program_keypair.pubkey(),
&buffer_keypair.pubkey(),
&payer_keypair.pubkey(),
&payer_keypair.pubkey(),
)],
Some(&payer_keypair.pubkey()),
),
bank.last_blockhash(),
);
(bank, invoke_tx, upgrade_tx)
}
let payer_keypair = keypair_from_seed(&[56u8; 32]).unwrap();
let buffer_keypair = keypair_from_seed(&[11; 32]).unwrap();
let program_keypair = keypair_from_seed(&[77u8; 32]).unwrap();
let results1 = {
let (bank, invoke_tx, upgrade_tx) =
setup_program_upgradeable_locks(&payer_keypair, &buffer_keypair, &program_keypair);
execute_transactions(&bank, &[upgrade_tx, invoke_tx])
};
let results2 = {
let (bank, invoke_tx, upgrade_tx) =
setup_program_upgradeable_locks(&payer_keypair, &buffer_keypair, &program_keypair);
execute_transactions(&bank, &[invoke_tx, upgrade_tx])
};
if false {
println!("upgrade and invoke");
for result in &results1 {
print_confirmed_tx("result", result.clone());
}
println!("invoke and upgrade");
for result in &results2 {
print_confirmed_tx("result", result.clone());
}
}
if let Some(ref meta) = results1[0].transaction.meta {
assert_eq!(meta.status, Ok(()));
} else {
panic!("no meta");
}
if let Some(ref meta) = results1[1].transaction.meta {
assert_eq!(meta.status, Err(TransactionError::AccountInUse));
} else {
panic!("no meta");
}
if let Some(ref meta) = results2[0].transaction.meta {
assert_eq!(
meta.status,
Err(TransactionError::InstructionError(
0,
InstructionError::ProgramFailedToComplete
))
);
} else {
panic!("no meta");
}
if let Some(ref meta) = results2[1].transaction.meta {
assert_eq!(meta.status, Err(TransactionError::AccountInUse));
} else {
panic!("no meta");
}
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_syscall_feature_activation() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
bank.deactivate_feature(&ristretto_mul_syscall_enabled::id());
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let program_id = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_noop",
);
let instruction = Instruction::new_with_bytes(program_id, &[0], vec![]);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
assert!(result.is_ok());
let mut bank = Bank::new_from_parent(&bank, &Pubkey::default(), 1);
bank.activate_feature(&ristretto_mul_syscall_enabled::id());
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let instruction = Instruction::new_with_bytes(program_id, &[1], vec![]);
let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
println!("result: {:?}", result);
assert!(result.is_ok());
}
#[cfg(feature = "bpf_rust")]
#[test]
fn test_program_bpf_finalize() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let program_pubkey = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_finalize",
);
let noop_keypair = Keypair::new();
// Write the noop program into the same program account
let elf = read_bpf_program("solana_bpf_rust_noop");
let message = Message::new(
&[system_instruction::create_account(
&mint_keypair.pubkey(),
&noop_keypair.pubkey(),
1,
elf.len() as u64 * 2,
&bpf_loader::id(),
)],
Some(&mint_keypair.pubkey()),
);
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair, &noop_keypair], message)
.is_ok());
write_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
&noop_keypair,
&elf,
);
let account_metas = vec![
AccountMeta::new(noop_keypair.pubkey(), true),
AccountMeta::new_readonly(bpf_loader::id(), false),
AccountMeta::new(rent::id(), false),
];
let instruction = Instruction::new_with_bytes(program_pubkey, &[], account_metas.clone());
let message = Message::new(&[instruction], Some(&mint_keypair.pubkey()));
let result = bank_client.send_and_confirm_message(&[&mint_keypair, &noop_keypair], message);
assert_eq!(
result.unwrap_err().unwrap(),
TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete)
);
}
| 33.861638 | 100 | 0.612202 |
bb383deef89f0152222c9b0fd9dc6858edc504b3 | 268 | #![no_main]
use libfuzzer_sys::fuzz_target;
use milagro_bls::PublicKey;
fuzz_target!(|data: &[u8]| {
if let Ok(pk) = PublicKey::from_bytes(data) {
let data_round_trip = pk.as_bytes();
assert_eq!(data.to_vec(), data_round_trip.to_vec());
}
});
| 24.363636 | 60 | 0.649254 |
18517bd2430a990a0fd1f8d73b47c820e0b85ae3 | 2,287 | use serde::{de::DeserializeOwned, Serialize};
use crate::{
bot::Bot,
requests::{HasPayload, Payload, Request, ResponseResult},
RequestError,
};
/// A ready-to-send Telegram request whose payload is sent using [JSON].
///
/// [JSON]: https://core.telegram.org/bots/api#making-requests
#[must_use = "Requests are lazy and do nothing unless sent"]
pub struct JsonRequest<P> {
bot: Bot,
payload: P,
}
impl<P> JsonRequest<P> {
pub const fn new(bot: Bot, payload: P) -> Self {
Self { bot, payload }
}
}
impl<P> Request for JsonRequest<P>
where
// FIXME(waffle):
// this is required on stable because of
// https://github.com/rust-lang/rust/issues/76882
// when it's resolved or `type_alias_impl_trait` feature
// stabilized, we should remove 'static restriction
//
// (though critically, currently we have no
// non-'static payloads)
P: 'static,
P: Payload + Serialize,
P::Output: DeserializeOwned,
{
type Err = RequestError;
type Send = Send<P>;
type SendRef = SendRef<P>;
fn send(self) -> Self::Send {
Send::new(self)
}
fn send_ref(&self) -> Self::SendRef {
SendRef::new(self)
}
}
impl<P> HasPayload for JsonRequest<P>
where
P: Payload,
{
type Payload = P;
fn payload_mut(&mut self) -> &mut Self::Payload {
&mut self.payload
}
fn payload_ref(&self) -> &Self::Payload {
&self.payload
}
}
impl<P: Payload + Serialize> core::ops::Deref for JsonRequest<P> {
type Target = P;
fn deref(&self) -> &Self::Target {
self.payload_ref()
}
}
impl<P: Payload + Serialize> core::ops::DerefMut for JsonRequest<P> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.payload_mut()
}
}
req_future! {
def: |it: JsonRequest<U>| {
it.bot.execute_json(&it.payload)
}
pub Send<U> (inner0) -> ResponseResult<U::Output>
where
U: 'static,
U: Payload + Serialize,
U::Output: DeserializeOwned,
}
req_future! {
def: |it: &JsonRequest<U>| {
it.bot.execute_json(&it.payload)
}
pub SendRef<U> (inner1) -> ResponseResult<U::Output>
where
U: 'static,
U: Payload + Serialize,
U::Output: DeserializeOwned,
}
| 22.643564 | 72 | 0.602536 |
9b8e3fa2dc376543fb97572ef3b21141bfdbbb17 | 7,351 | use crate::{
err::*,
interface::{Config, Interface},
mem::Mem,
obj::Object,
state::State,
text::Text,
};
pub struct Screen {
v: u8,
font: u16,
width: usize,
}
impl Screen {
pub fn status<I: Interface>(
&self,
mem: &Mem,
text: &Text,
state: &mut State,
obj: &Object,
interface: &mut I,
) -> Result<(), Error> {
let mut name = obj.name(mem, text, state.get_var(mem, 0x10)?)?;
if name.chars().count() > self.width {
let mut last_word = 0;
let mut last_char = 0;
for (n, (i, char)) in name.char_indices().enumerate() {
last_char = i;
if n + 1 >= self.width {
break;
}
if char == ' ' {
last_word = i;
}
}
if last_word == 0 {
name.truncate(last_char);
} else {
name.truncate(last_word + 1);
}
name.push('…');
}
if name.len() + 9 > self.width {
interface.status(&format!("{:1$}", name, self.width));
return Ok(());
}
let score = if self.v == 3 && mem[1] & 0x02 != 0 {
let hours = state.get_var(mem, 0x11)?;
if hours < 12 {
format!("{:02}:{:02} AM", hours, state.get_var(mem, 0x12)?)
} else {
format!("{:02}:{:02} PM", hours - 12, state.get_var(mem, 0x12)?)
}
} else {
format!(
"{}/{}",
state.get_var(mem, 0x11)? as i16,
state.get_var(mem, 0x12)? as i16
)
};
let status = format!("{:2$} {:8}", name, score, self.width - 9);
interface.status(&status);
Ok(())
}
pub fn font<I: Interface>(&mut self, interface: &mut I, font: u16) -> u16 {
if font == 0 {
return self.font;
}
if interface.window_font(font) {
let old = self.font;
self.font = font;
return old;
}
0
}
pub fn color<I: Interface>(
&self,
interface: &mut I,
foreground: u16,
background: u16,
) -> Result<(), Error> {
let foreground = get_true(foreground)?;
let background = get_true(background)?;
interface.window_color(foreground, background);
Ok(())
}
pub fn true_color<I: Interface>(&self, interface: &mut I, foreground: u16, background: u16) {
interface.window_color(foreground, background);
}
pub fn style<I: Interface>(&self, interface: &mut I, style: u16) {
interface.window_style(style);
}
pub fn window<I: Interface>(&self, interface: &mut I, window: u16) {
interface.window_set(window);
}
pub fn buffer<I: Interface>(&self, interface: &mut I, mode: u16) {
interface.window_buffer(mode);
}
pub fn split_window<I: Interface>(&self, interface: &mut I, height: u16) {
interface.window_split(height);
}
pub fn set_cursor<I: Interface>(&self, interface: &mut I, line: u16, column: u16) {
interface.window_cursor_set(line, column);
}
pub fn get_cursor<I: Interface>(&self, interface: &mut I) -> (u16, u16) {
interface.window_cursor_get()
}
pub fn erase_window<I: Interface>(&self, interface: &mut I, window: u16) {
interface.window_erase(window);
}
pub fn erase_line<I: Interface>(&self, interface: &mut I) {
interface.window_line();
}
}
fn get_true(color: u16) -> Result<u16, Error> {
Ok(match color {
0 => 0xfffe,
1 => 0xffff,
2 => 0x0000,
3 => 0x001D,
4 => 0x0340,
5 => 0x03BD,
6 => 0x59A0,
7 => 0x7C1F,
8 => 0x77A0,
9 => 0x7FFF,
_ => return error(Cause::BadColor, (color, 0)),
})
}
pub fn init(mem: &Mem, config: &Config) -> Screen {
Screen {
v: mem[0],
font: 1,
width: config.screen.0 as usize,
}
}
#[cfg(test)]
struct Output(String);
#[cfg(test)]
impl Interface for Output {
fn status(&mut self, str: &str) {
self.0 = str.to_string();
}
fn window_font(&mut self, font: u16) -> bool {
font == 1 || font == 4
}
}
#[cfg(test)]
use crate::{header, interface, mem, obj, state, text};
#[test]
fn test() {
let mut data = mem::default();
data[0x00] = 0x03;
data[0x0b] = 0x46;
data[0x0d] = 0x40;
data[0x0f] = 0x46;
data.extend(vec![0; 0x4c]);
data.extend(vec![
0x8d, 0x05, 0x11, 0xaa, 0x46, 0x34, 0x00, 0x9c, 0x52, 0xf1, 0xa4, 0xa5,
]);
let mut mem = mem::new(data).unwrap();
let header = header::init_test(&mut mem);
let text = text::init(&mem, &header).unwrap();
let mut state = state::init(&mem);
let mut screen = init(&mem, &interface::DEFAULT);
let obj = obj::init(&mem);
let mut output = Output(String::new());
assert_eq!(screen.font(&mut output, 0), 1);
assert_eq!(screen.font(&mut output, 4), 1);
assert_eq!(screen.font(&mut output, 2), 0);
assert_eq!(screen.font(&mut output, 0), 4);
assert_eq!(screen.font(&mut output, 3), 0);
assert_eq!(screen.font(&mut output, 1), 4);
state.set_var(&mut mem, 0x10, 1).unwrap();
screen.width = 4;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hel…");
screen.width = 6;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello…");
screen.width = 7;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello …");
screen.width = 10;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello … ");
screen.width = 11;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello World");
screen.width = 19;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello World ");
screen.width = 20;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello World 0/0 ");
state.set_var(&mut mem, 0x11, -99i16 as u16).unwrap();
state.set_var(&mut mem, 0x12, 9999).unwrap();
screen.width = 21;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello World -99/9999");
let flags = mem.loadb(0x01).unwrap();
mem.storeb(0x01, flags | 0x02).unwrap();
state.set_var(&mut mem, 0x11, 1).unwrap();
state.set_var(&mut mem, 0x12, 5).unwrap();
screen.width = 22;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello World 01:05 AM");
state.set_var(&mut mem, 0x11, 22).unwrap();
state.set_var(&mut mem, 0x12, 30).unwrap();
screen.width = 23;
screen
.status(&mem, &text, &mut state, &obj, &mut output)
.unwrap();
assert_eq!(&output.0, "Hello World 10:30 PM");
}
| 27.844697 | 97 | 0.518705 |
4be7420e33c17246f9f633b61fd5fdd8a447b6aa | 454 | fn main() {
1 + Some(1); //~ ERROR cannot add `Option<{integer}>` to `{integer}`
2 as usize - Some(1); //~ ERROR cannot subtract `Option<{integer}>` from `usize`
3 * (); //~ ERROR cannot multiply `{integer}` by `()`
4 / ""; //~ ERROR cannot divide `{integer}` by `&str`
5 < String::new(); //~ ERROR can't compare `{integer}` with `String`
6 == Ok(1); //~ ERROR can't compare `{integer}` with `std::result::Result<{integer}, _>`
}
| 50.444444 | 92 | 0.568282 |
bf5ec06d74837826f81e0c5ee678564c6b75f944 | 5,202 | // TryFrom is a simple and safe type conversion that may fail in a controlled way under some circumstances.
// Basically, this is the same as From. The main difference is that this should return a Result type
// instead of the target type itself.
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.TryFrom.html
use std::convert::{TryFrom, TryInto};
#[derive(Debug, PartialEq)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
// Your task is to complete this implementation
// and return an Ok result of inner type Color.
// You need to create an implementation for a tuple of three integers,
// an array of three integers and a slice of integers.
//
// Note that the implementation for tuple and array will be checked at compile time,
// but the slice implementation needs to check the slice length!
// Also note that correct RGB color values must be integers in the 0..=255 range.
// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = String;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
let [red, green, blue] = arr;
for c in [red, green, blue].iter() {
if *c > 256 || *c < 0 {
return Err(String::from("Err"));
}
}
Ok(Color {
red: red as u8,
blue: blue as u8,
green: green as u8,
})
}
}
// Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {
type Error = String;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
let (red, green, blue) = tuple;
Color::try_from([red, green, blue])
}
}
// Slice implementation
impl TryFrom<&[i16]> for Color {
type Error = String;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if let [red, green, blue] = slice {
for c in [red, green, blue].iter() {
if *c > &256 || *c < &0 {
return Err(String::from("Err"));
}
}
Ok(Color {
red: *red as u8,
blue: *blue as u8,
green: *green as u8,
})
} else {
Err(String::from("Err"))
}
}
}
fn main() {
// Use the `from` function
let c1 = Color::try_from((183, 65, 14));
println!("{:?}", c1);
// Since From is implemented for Color, we should be able to use Into
let c2: Result<Color, _> = [183, 65, 14].try_into();
println!("{:?}", c2);
let v = vec![183, 65, 14];
// With slice we should use `from` function
let c3 = Color::try_from(&v[..]);
println!("{:?}", c3);
// or take slice within round brackets and use Into
let c4: Result<Color, _> = (&v[..]).try_into();
println!("{:?}", c4);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tuple_out_of_range_positive() {
assert!(Color::try_from((256, 1000, 10000)).is_err());
}
#[test]
fn test_tuple_out_of_range_negative() {
assert!(Color::try_from((-1, -10, -256)).is_err());
}
#[test]
fn test_tuple_sum() {
assert!(Color::try_from((-1, 255, 255)).is_err());
}
#[test]
fn test_tuple_correct() {
let c: Result<Color, String> = (183, 65, 14).try_into();
assert_eq!(
c,
Ok(Color {
red: 183,
green: 65,
blue: 14
})
);
}
#[test]
fn test_array_out_of_range_positive() {
let c: Result<Color, String> = [1000, 10000, 256].try_into();
assert!(c.is_err());
}
#[test]
fn test_array_out_of_range_negative() {
let c: Result<Color, String> = [-10, -256, -1].try_into();
assert!(c.is_err());
}
#[test]
fn test_array_sum() {
let c: Result<Color, String> = [-1, 255, 255].try_into();
assert!(c.is_err());
}
#[test]
fn test_array_correct() {
let c: Result<Color, String> = [183, 65, 14].try_into();
assert_eq!(
c,
Ok(Color {
red: 183,
green: 65,
blue: 14
})
);
}
#[test]
fn test_slice_out_of_range_positive() {
let arr = [10000, 256, 1000];
assert!(Color::try_from(&arr[..]).is_err());
}
#[test]
fn test_slice_out_of_range_negative() {
let arr = [-256, -1, -10];
assert!(Color::try_from(&arr[..]).is_err());
}
#[test]
fn test_slice_sum() {
let arr = [-1, 255, 255];
assert!(Color::try_from(&arr[..]).is_err());
}
#[test]
fn test_slice_correct() {
let v = vec![183, 65, 14];
let c: Result<Color, String> = Color::try_from(&v[..]);
assert_eq!(
c,
Ok(Color {
red: 183,
green: 65,
blue: 14
})
);
}
#[test]
fn test_slice_excess_length() {
let v = vec![0, 0, 0, 0];
assert!(Color::try_from(&v[..]).is_err());
}
#[test]
fn test_slice_insufficient_length() {
let v = vec![0, 0];
assert!(Color::try_from(&v[..]).is_err());
}
}
| 28.42623 | 107 | 0.518839 |
e575f052c8adfd89ddf8656efaf8461f5ee1f54e | 721 | #![feature(plugin_registrar)]
#![feature(box_syntax, rustc_private)]
extern crate syntax;
extern crate syntax_pos;
// Load rustc as a plugin to get macros
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate docstrings;
extern crate ispell;
extern crate markdown;
mod helpers;
mod doc_params_mismatch;
mod spelling_error;
use doc_params_mismatch::DocParamsMismatch;
use spelling_error::SpellingError;
use rustc::lint::LateLintPassObject;
use rustc_plugin::Registry;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_late_lint_pass(box DocParamsMismatch as LateLintPassObject);
reg.register_late_lint_pass(box SpellingError::new() as LateLintPassObject);
}
| 22.53125 | 80 | 0.801664 |
4b6bdade86e845749082c5ceca84d87e53f13f5e | 3,027 | // Copyright (c) 2021 Shreepad Shukla
// SPDX-License-Identifier: MIT
use day15_1::graph::Graph;
use std::fs;
pub fn calculate_least_risk_path(file_path: &String) -> u32 {
println!("Loading data from file:{}", file_path);
let contents = fs::read_to_string(file_path).expect(&format!(
"Something went wrong reading the file {}",
file_path
));
let mut grid: [[u32; 502]; 502] = [[u32::MAX; 502]; 502];
load_grid(&mut grid, contents);
let mut graph = Graph::new();
load_graph(&mut graph, &grid);
graph.shortest_path_weight(1, 250000).unwrap()
}
fn load_graph(graph: &mut Graph, grid: &[[u32; 502]; 502]) {
for row_no in 1..=500 {
for col_no in 1..=500 {
let multiplier = 500;
let from_node_id = col_no + (row_no - 1) * multiplier;
// check above
let above_weight: u32 = grid[row_no - 1][col_no];
if above_weight != u32::MAX {
graph.add_edge(
from_node_id,
col_no + (row_no - 2) * multiplier,
above_weight,
);
}
// check below
let below_weight: u32 = grid[row_no + 1][col_no];
if below_weight != u32::MAX {
graph.add_edge(from_node_id, col_no + (row_no) * multiplier, below_weight);
}
// check right
let right_weight: u32 = grid[row_no][col_no + 1];
if right_weight != u32::MAX {
graph.add_edge(
from_node_id,
col_no + 1 + (row_no - 1) * multiplier,
right_weight,
);
}
// check left
let left_weight: u32 = grid[row_no][col_no - 1];
if left_weight != u32::MAX {
graph.add_edge(
from_node_id,
col_no - 1 + (row_no - 1) * multiplier,
left_weight,
);
}
}
}
}
fn load_grid(grid: &mut [[u32; 502]; 502], contents: String) {
for (row_no, line_str) in contents.lines().enumerate() {
for (col_no, digit_chr) in line_str.chars().enumerate() {
let digit: u32 = digit_chr.to_digit(10).unwrap().try_into().unwrap();
// Fill all 25 frames with given digit
for frame_row in 0..5 {
for frame_col in 0..5 {
let point_row_no = row_no + 1 + (frame_row * 100);
let point_col_no = col_no + 1 + (frame_col * 100);
let point_digit = ((digit + frame_row as u32 + frame_col as u32 - 1) % 9) + 1;
grid[point_row_no][point_col_no] = point_digit;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn day15_2_works() {
let result = calculate_least_risk_path(&String::from("../resources/day15-1-input.txt"));
assert_eq!(result, 3022);
}
}
| 29.970297 | 98 | 0.503799 |
db861abc9f98d46519a601953a486fed7321e9ba | 4,639 | // Copyright 2020-2021 the Deno authors. All rights reserved. MIT license.
use super::{Context, LintRule, DUMMY_NODE};
use crate::ProgramRef;
use swc_ecmascript::ast::ClassMethod;
use swc_ecmascript::ast::FnDecl;
use swc_ecmascript::ast::FnExpr;
use swc_ecmascript::ast::Function;
use swc_ecmascript::ast::MethodProp;
use swc_ecmascript::ast::PrivateMethod;
use swc_ecmascript::ast::YieldExpr;
use swc_ecmascript::visit::noop_visit_type;
use swc_ecmascript::visit::Node;
use swc_ecmascript::visit::Visit;
pub struct RequireYield;
const CODE: &str = "require-yield";
const MESSAGE: &str = "Generator function has no `yield`";
impl LintRule for RequireYield {
fn new() -> Box<Self> {
Box::new(RequireYield)
}
fn tags(&self) -> &'static [&'static str] {
&["recommended"]
}
fn code(&self) -> &'static str {
CODE
}
fn lint_program<'view>(
&self,
context: &mut Context<'view>,
program: ProgramRef<'view>,
) {
let mut visitor = RequireYieldVisitor::new(context);
match program {
ProgramRef::Module(m) => visitor.visit_module(m, &DUMMY_NODE),
ProgramRef::Script(s) => visitor.visit_script(s, &DUMMY_NODE),
}
}
#[cfg(feature = "docs")]
fn docs(&self) -> &'static str {
include_str!("../../docs/rules/require_yield.md")
}
}
struct RequireYieldVisitor<'c, 'view> {
context: &'c mut Context<'view>,
yield_stack: Vec<u32>,
}
impl<'c, 'view> RequireYieldVisitor<'c, 'view> {
fn new(context: &'c mut Context<'view>) -> Self {
Self {
context,
yield_stack: vec![],
}
}
fn enter_function(&mut self, function: &Function) {
if function.is_generator {
self.yield_stack.push(0);
}
}
fn exit_function(&mut self, function: &Function) {
if function.is_generator {
let yield_count = self.yield_stack.pop().unwrap();
// Verify that `yield` was called only if function body
// is non-empty
if let Some(body) = &function.body {
if !body.stmts.is_empty() && yield_count == 0 {
self.context.add_diagnostic(function.span, CODE, MESSAGE);
}
}
}
}
}
impl<'c, 'view> Visit for RequireYieldVisitor<'c, 'view> {
noop_visit_type!();
fn visit_yield_expr(&mut self, _yield_expr: &YieldExpr, _parent: &dyn Node) {
if let Some(last) = self.yield_stack.last_mut() {
*last += 1;
}
}
fn visit_fn_decl(&mut self, fn_decl: &FnDecl, parent: &dyn Node) {
self.enter_function(&fn_decl.function);
swc_ecmascript::visit::visit_fn_decl(self, fn_decl, parent);
self.exit_function(&fn_decl.function);
}
fn visit_fn_expr(&mut self, fn_expr: &FnExpr, parent: &dyn Node) {
self.enter_function(&fn_expr.function);
swc_ecmascript::visit::visit_fn_expr(self, fn_expr, parent);
self.exit_function(&fn_expr.function);
}
fn visit_class_method(
&mut self,
class_method: &ClassMethod,
parent: &dyn Node,
) {
self.enter_function(&class_method.function);
swc_ecmascript::visit::visit_class_method(self, class_method, parent);
self.exit_function(&class_method.function);
}
fn visit_private_method(
&mut self,
private_method: &PrivateMethod,
parent: &dyn Node,
) {
self.enter_function(&private_method.function);
swc_ecmascript::visit::visit_private_method(self, private_method, parent);
self.exit_function(&private_method.function);
}
fn visit_method_prop(&mut self, method_prop: &MethodProp, parent: &dyn Node) {
self.enter_function(&method_prop.function);
swc_ecmascript::visit::visit_method_prop(self, method_prop, parent);
self.exit_function(&method_prop.function);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn require_yield_valid() {
assert_lint_ok! {
RequireYield,
r#"
function foo() {}
function* bar() {
yield "bar";
}
function* emptyBar() {}
class Fizz {
*fizz() {
yield "fizz";
}
*#buzz() {
yield "buzz";
}
}
const obj = {
*foo() {
yield "foo";
}
};
"#,
};
}
#[test]
fn require_yield_invalid() {
assert_lint_err! {
RequireYield,
r#"function* bar() { return "bar"; }"#: [{ col: 0, message: MESSAGE }],
r#"(function* foo() { return "foo"; })();"#: [{ col: 1, message: MESSAGE }],
r#"function* nested() { function* gen() { yield "gen"; } }"#: [{ col: 0, message: MESSAGE }],
r#"const obj = { *foo() { return "foo"; } };"#: [{ col: 14, message: MESSAGE }],
r#"
class Fizz {
*fizz() {
return "fizz";
}
*#buzz() {
return "buzz";
}
}
"#: [{ line: 3, col: 2, message: MESSAGE }, { line: 7, col: 2, message: MESSAGE }],
}
}
}
| 24.544974 | 99 | 0.633542 |
714f8b9feab59cf15207d6975f2fa0fa513da45d | 10,116 | //! Twitch API helpers.
use crate::{oauth2, prelude::*};
use bytes::Bytes;
use chrono::{DateTime, Utc};
use hashbrown::HashMap;
use reqwest::{
header,
r#async::{Chunk, Client, Decoder},
Method, StatusCode, Url,
};
use std::mem;
const V3_URL: &'static str = "https://www.googleapis.com/youtube/v3";
const GET_VIDEO_INFO_URL: &'static str = "https://www.youtube.com/get_video_info";
/// API integration.
#[derive(Clone, Debug)]
pub struct YouTube {
client: Client,
v3_url: Url,
get_video_info_url: Url,
pub token: oauth2::SyncToken,
}
impl YouTube {
/// Create a new API integration.
pub fn new(token: oauth2::SyncToken) -> Result<YouTube, failure::Error> {
Ok(YouTube {
client: Client::new(),
v3_url: str::parse::<Url>(V3_URL)?,
get_video_info_url: str::parse::<Url>(GET_VIDEO_INFO_URL)?,
token,
})
}
/// Build request against v3 URL.
fn v3(&self, method: Method, path: &[&str]) -> RequestBuilder {
let mut url = self.v3_url.clone();
{
let mut url_path = url.path_segments_mut().expect("bad base");
url_path.extend(path);
}
RequestBuilder {
token: self.token.clone(),
client: self.client.clone(),
url,
method,
headers: Vec::new(),
body: None,
}
}
/// Update the channel information.
pub fn videos_by_id(
&self,
video_id: String,
part: String,
) -> impl Future<Output = Result<Option<Video>, failure::Error>> {
let req = self
.v3(Method::GET, &["videos"])
.query_param("part", part.as_str())
.query_param("id", video_id.as_str())
.json::<Videos>();
async move { Ok(req.await?.and_then(|v| v.items.into_iter().next())) }
}
/// Search YouTube.
pub fn search(&self, q: String) -> impl Future<Output = Result<SearchResults, failure::Error>> {
let req = self
.v3(Method::GET, &["search"])
.query_param("part", "snippet")
.query_param("q", q.as_str())
.json::<SearchResults>();
async move {
match req.await? {
Some(result) => Ok(result),
None => failure::bail!("got empty response"),
}
}
}
/// Get video info of a video.
pub async fn get_video_info(
&self,
video_id: String,
) -> Result<Option<VideoInfo>, failure::Error> {
let mut url = self.get_video_info_url.clone();
url.query_pairs_mut()
.append_pair("video_id", video_id.as_str());
let request = RequestBuilder {
token: self.token.clone(),
client: self.client.clone(),
url,
method: Method::GET,
headers: Vec::new(),
body: None,
};
let body = request.raw().await?;
let body = match body {
Some(body) => body,
None => return Ok(None),
};
let result: RawVideoInfo = serde_urlencoded::from_bytes(&body)?;
let result = result.into_decoded()?;
Ok(Some(result))
}
}
struct RequestBuilder {
token: oauth2::SyncToken,
client: Client,
url: Url,
method: Method,
headers: Vec<(header::HeaderName, String)>,
body: Option<Bytes>,
}
impl RequestBuilder {
/// Execute the request, providing the raw body as a response.
pub async fn raw(self) -> Result<Option<Chunk>, failure::Error> {
let access_token = self.token.read()?.access_token().to_string();
let mut req = self.client.request(self.method, self.url);
if let Some(body) = self.body {
req = req.body(body);
}
for (key, value) in self.headers {
req = req.header(key, value);
}
req = req.header(header::ACCEPT, "application/json");
let req = req.header(header::AUTHORIZATION, format!("Bearer {}", access_token));
let mut res = req.send().compat().await?;
let status = res.status();
if status == StatusCode::UNAUTHORIZED {
self.token.force_refresh()?;
}
if status == StatusCode::NOT_FOUND {
return Ok(None);
}
let body = mem::replace(res.body_mut(), Decoder::empty());
let body = body.compat().try_concat().await?;
if !status.is_success() {
failure::bail!(
"bad response: {}: {}",
status,
String::from_utf8_lossy(&body)
);
}
if log::log_enabled!(log::Level::Trace) {
let response = String::from_utf8_lossy(body.as_ref());
log::trace!("response: {}", response);
}
Ok(Some(body))
}
/// Execute the request expecting a JSON response.
pub async fn json<T>(self) -> Result<Option<T>, failure::Error>
where
T: serde::de::DeserializeOwned,
{
let body = self.raw().await?;
let body = match body {
Some(body) => body,
None => return Ok(None),
};
serde_json::from_slice(body.as_ref()).map_err(Into::into)
}
/// Add a query parameter.
pub fn query_param(mut self, key: &str, value: &str) -> Self {
self.url.query_pairs_mut().append_pair(key, value);
self
}
}
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub struct Empty {}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PageInfo {
pub total_results: u32,
pub results_per_page: u32,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Videos {
pub kind: String,
pub etag: String,
pub page_info: PageInfo,
#[serde(default)]
pub items: Vec<Video>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum Kind {
#[serde(rename = "youtube#channel")]
Channel,
#[serde(rename = "youtube#video")]
Video,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Id {
pub kind: Kind,
pub video_id: Option<String>,
pub channel_id: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchResult {
pub kind: String,
pub etag: String,
pub id: Id,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchResults {
pub kind: String,
pub etag: String,
pub next_page_token: Option<String>,
pub region_code: Option<String>,
pub page_info: PageInfo,
#[serde(default)]
pub items: Vec<SearchResult>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Thumbnail {
pub url: String,
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Snippet {
#[serde(default)]
pub published_at: Option<DateTime<Utc>>,
pub channel_id: String,
pub title: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub thumbnails: HashMap<String, Thumbnail>,
#[serde(default)]
pub channel_title: Option<String>,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub category_id: Option<String>,
#[serde(default)]
pub live_broadcast_content: Option<String>,
#[serde(default)]
pub default_language: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ContentDetails {
#[serde(default)]
pub published_at: Option<DateTime<Utc>>,
pub duration: String,
#[serde(default)]
pub dimension: Option<String>,
#[serde(default)]
pub definition: Option<String>,
pub caption: Option<String>,
#[serde(default)]
pub licensed_content: bool,
#[serde(default)]
pub projection: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Video {
pub kind: String,
pub etag: String,
pub id: String,
#[serde(default)]
pub snippet: Option<Snippet>,
#[serde(default)]
pub content_details: Option<ContentDetails>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct RawVideoInfo {
pub author: String,
pub video_id: String,
pub status: String,
pub title: String,
#[serde(default)]
pub thumbnail_url: Option<String>,
pub url_encoded_fmt_stream_map: String,
#[serde(default)]
pub view_count: Option<usize>,
#[serde(default)]
pub adaptive_fmts: Option<String>,
#[serde(default)]
pub hlsvp: Option<String>,
#[serde(default)]
pub player_response: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AudioConfig {
pub loudness_db: f32,
pub perceptual_loudness_db: f32,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlayerConfig {
#[serde(default)]
pub audio_config: Option<AudioConfig>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlayerResponse {
#[serde(default)]
pub player_config: Option<PlayerConfig>,
}
#[derive(Debug, Clone)]
pub struct VideoInfo {
pub player_response: Option<PlayerResponse>,
}
impl RawVideoInfo {
/// Convert into a decoded version.
pub fn into_decoded(self) -> Result<VideoInfo, failure::Error> {
let player_response = match self.player_response.as_ref() {
Some(player_response) => Some(serde_json::from_str(player_response)?),
None => None,
};
Ok(VideoInfo { player_response })
}
}
| 27.340541 | 100 | 0.601226 |
f7558f8ba450ad730af91e5696c931f287e60b3f | 1,064 | pub fn solve() {
println!("Day 3");
let input_lines = adventlib::read_input_lines("day03input.txt");
let input_width = input_lines
.first()
.map(|line| line.len())
.expect("We must have input");
let tree_count = count_on_slope((3, 1), &input_lines, input_width);
println!("Output (part 1): {}", tree_count);
let all_slopes: Vec<(usize, usize)> = vec![(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)];
let product: usize = all_slopes
.iter()
.map(|&slope| count_on_slope(slope, &input_lines, input_width))
.product();
println!("Output (part 2): {}", product);
}
fn count_on_slope(slope: (usize, usize), map: &Vec<String>, map_width: usize) -> usize {
let mut x = 0;
let mut y = 0;
let (dx, dy) = slope;
let mut tree_count = 0;
while y < map.len() {
match map.get(y).and_then(|line| line.chars().nth(x % map_width)) {
Some('#') => tree_count += 1,
_ => (),
};
x += dx;
y += dy;
}
return tree_count;
}
| 25.333333 | 88 | 0.534774 |
031642e79077be1f117340c02c20284c6a7d46bc | 1,733 | use clarity::Uint256;
use std::time::Duration;
pub const TIMEOUT: Duration = Duration::from_secs(60);
pub fn one_eth() -> f64 {
1000000000000000000f64
}
pub fn one_atom() -> f64 {
1000000f64
}
/// TODO revisit this for higher precision while
/// still representing the number to the user as a float
/// this takes a number like 0.37 eth and turns it into wei
/// or any erc20 with arbitrary decimals
pub fn fraction_to_exponent(num: f64, exponent: u8) -> Uint256 {
let mut res = num;
// in order to avoid floating point rounding issues we
// multiply only by 10 each time. this reduces the rounding
// errors enough to be ignored
for _ in 0..exponent {
res *= 10f64
}
(res as u128).into()
}
pub fn print_eth(input: Uint256) -> String {
let float: f64 = input.to_string().parse().unwrap();
let res = float / one_eth();
format!("{}", res)
}
pub fn print_atom(input: Uint256) -> String {
let float: f64 = input.to_string().parse().unwrap();
let res = float / one_atom();
format!("{}", res)
}
#[test]
fn even_f32_rounding() {
let one_eth: Uint256 = 1000000000000000000u128.into();
let one_point_five_eth: Uint256 = 1500000000000000000u128.into();
let one_point_one_five_eth: Uint256 = 1150000000000000000u128.into();
let a_high_precision_number: Uint256 = 1150100000000000000u128.into();
let res = fraction_to_exponent(1f64, 18);
assert_eq!(one_eth, res);
let res = fraction_to_exponent(1.5f64, 18);
assert_eq!(one_point_five_eth, res);
let res = fraction_to_exponent(1.15f64, 18);
assert_eq!(one_point_one_five_eth, res);
let res = fraction_to_exponent(1.1501f64, 18);
assert_eq!(a_high_precision_number, res);
}
| 30.946429 | 74 | 0.686093 |
d946d4d856ea78eb9c481dca13abb315d81c00cb | 6,062 | use casper_engine_test_support::{
ExecuteRequestBuilder, InMemoryWasmTestBuilder, DEFAULT_ACCOUNT_ADDR,
DEFAULT_RUN_GENESIS_REQUEST,
};
use casper_types::{runtime_args, Key, RuntimeArgs};
const CONTRACT_COUNTER_DEFINE: &str = "counter_define.wasm";
const CONTRACT_NAME: &str = "counter_package_hash";
const COUNTER_VALUE_UREF: &str = "counter";
const ENTRYPOINT_COUNTER: &str = "counter";
const ENTRYPOINT_SESSION: &str = "session";
const COUNTER_CONTRACT_HASH_KEY_NAME: &str = "counter_contract_hash";
const ARG_COUNTER_METHOD: &str = "method";
const METHOD_INC: &str = "inc";
#[ignore]
#[test]
fn should_run_counter_example_contract() {
let mut builder = InMemoryWasmTestBuilder::default();
let exec_request_1 = ExecuteRequestBuilder::standard(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_COUNTER_DEFINE,
RuntimeArgs::new(),
)
.build();
builder
.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST)
.exec(exec_request_1)
.expect_success()
.commit();
let account = builder
.query(None, Key::Account(*DEFAULT_ACCOUNT_ADDR), &[])
.expect("should query account")
.as_account()
.expect("should be account")
.clone();
let counter_contract_hash_key = *account
.named_keys()
.get(COUNTER_CONTRACT_HASH_KEY_NAME)
.expect("should have counter contract hash key");
let exec_request_2 = ExecuteRequestBuilder::versioned_contract_call_by_name(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_NAME,
None,
ENTRYPOINT_SESSION,
runtime_args! { COUNTER_CONTRACT_HASH_KEY_NAME => counter_contract_hash_key },
)
.build();
builder.exec(exec_request_2).expect_success().commit();
let value: i32 = builder
.query(
None,
counter_contract_hash_key,
&[COUNTER_VALUE_UREF.to_string()],
)
.expect("should have counter value")
.as_cl_value()
.expect("should be CLValue")
.clone()
.into_t()
.expect("should cast CLValue to integer");
assert_eq!(value, 1);
let exec_request_3 = ExecuteRequestBuilder::versioned_contract_call_by_name(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_NAME,
None,
ENTRYPOINT_SESSION,
runtime_args! { COUNTER_CONTRACT_HASH_KEY_NAME => counter_contract_hash_key },
)
.build();
builder.exec(exec_request_3).expect_success().commit();
let value: i32 = builder
.query(
None,
counter_contract_hash_key,
&[COUNTER_VALUE_UREF.to_string()],
)
.expect("should have counter value")
.as_cl_value()
.expect("should be CLValue")
.clone()
.into_t()
.expect("should cast CLValue to integer");
assert_eq!(value, 2);
}
#[ignore]
#[test]
fn should_default_contract_hash_arg() {
let mut builder = InMemoryWasmTestBuilder::default();
// This test runs a contract that's after every call extends the same key with
// more data
let exec_request_1 = ExecuteRequestBuilder::standard(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_COUNTER_DEFINE,
RuntimeArgs::new(),
)
.build();
builder
.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST)
.exec(exec_request_1)
.expect_success()
.commit();
let exec_request_2 = ExecuteRequestBuilder::versioned_contract_call_by_name(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_NAME,
None,
ENTRYPOINT_SESSION,
RuntimeArgs::new(),
)
.build();
builder.exec(exec_request_2).expect_success().commit();
let value: i32 = {
let counter_contract_hash_key = *builder
.query(None, Key::Account(*DEFAULT_ACCOUNT_ADDR), &[])
.expect("should query account")
.as_account()
.expect("should be account")
.clone()
.named_keys()
.get(COUNTER_CONTRACT_HASH_KEY_NAME)
.expect("should have counter contract hash key");
builder
.query(
None,
counter_contract_hash_key,
&[COUNTER_VALUE_UREF.to_string()],
)
.expect("should have counter value")
.as_cl_value()
.expect("should be CLValue")
.clone()
.into_t()
.expect("should cast CLValue to integer")
};
assert_eq!(value, 1);
}
#[ignore]
#[test]
fn should_call_counter_contract_directly() {
let mut builder = InMemoryWasmTestBuilder::default();
let exec_request_1 = ExecuteRequestBuilder::standard(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_COUNTER_DEFINE,
RuntimeArgs::new(),
)
.build();
builder
.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST)
.exec(exec_request_1)
.expect_success()
.commit();
let exec_request_2 = ExecuteRequestBuilder::versioned_contract_call_by_name(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_NAME,
None,
ENTRYPOINT_COUNTER,
runtime_args! { ARG_COUNTER_METHOD => METHOD_INC },
)
.build();
builder.exec(exec_request_2).expect_success().commit();
let value: i32 = {
let counter_contract_hash_key = *builder
.query(None, Key::Account(*DEFAULT_ACCOUNT_ADDR), &[])
.expect("should query account")
.as_account()
.expect("should be account")
.clone()
.named_keys()
.get(COUNTER_CONTRACT_HASH_KEY_NAME)
.expect("should have counter contract hash key");
builder
.query(
None,
counter_contract_hash_key,
&[COUNTER_VALUE_UREF.to_string()],
)
.expect("should have counter value")
.as_cl_value()
.expect("should be CLValue")
.clone()
.into_t()
.expect("should cast CLValue to integer")
};
assert_eq!(value, 1);
}
| 28.327103 | 86 | 0.611514 |
916b921f853ab108c7a538d8a6df54fea0cbc3ea | 495 | //
// Copyright © 2020 Haim Gelfenbeyn
// This code is licensed under MIT license (see LICENSE.txt for details)
//
use rusb::UsbContext;
pub fn device2str<T: UsbContext>(device: rusb::Device<T>) -> Option<String> {
device
.device_descriptor()
.map(|device_desc| format!("{:04x}:{:04x}", device_desc.vendor_id(), device_desc.product_id()))
.ok()
}
pub trait UsbCallback {
fn device_added(&self, device_id: &str);
fn device_removed(&self, device_id: &str);
}
| 27.5 | 103 | 0.662626 |
f76dc055fbde0c9f3edbf3f40e921ec63cc10f2b | 14,845 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This file defines ledger store APIs that are related to the main ledger accumulator, from the
//! root(LedgerInfo) to leaf(TransactionInfo).
use crate::{
change_set::ChangeSet,
errors::LibraDbError,
schema::{
epoch_by_version::EpochByVersionSchema, ledger_info::LedgerInfoSchema,
transaction_accumulator::TransactionAccumulatorSchema,
transaction_info::TransactionInfoSchema,
},
};
use accumulator::{HashReader, MerkleAccumulator};
use anyhow::{ensure, format_err, Result};
use arc_swap::ArcSwap;
use itertools::Itertools;
use libra_crypto::{
hash::{CryptoHash, TransactionAccumulatorHasher},
HashValue,
};
use libra_types::{
ledger_info::LedgerInfoWithSignatures,
on_chain_config::ValidatorSet,
proof::{
definition::LeafCount, position::Position, AccumulatorConsistencyProof,
TransactionAccumulatorProof, TransactionAccumulatorRangeProof,
},
transaction::{TransactionInfo, Version},
};
use schemadb::{ReadOptions, SchemaIterator, DB};
use std::{ops::Deref, sync::Arc};
use storage_interface::{StartupInfo, TreeState};
pub(crate) struct LedgerStore {
db: Arc<DB>,
/// We almost always need the latest ledger info and signatures to serve read requests, so we
/// cache it in memory in order to avoid reading DB and deserializing the object frequently. It
/// should be updated every time new ledger info and signatures are persisted.
latest_ledger_info: ArcSwap<Option<LedgerInfoWithSignatures>>,
}
impl LedgerStore {
pub fn new(db: Arc<DB>) -> Self {
// Upon restart, read the latest ledger info and signatures and cache them in memory.
let ledger_info = {
let mut iter = db
.iter::<LedgerInfoSchema>(ReadOptions::default())
.expect("Constructing iterator should work.");
iter.seek_to_last().expect("Unable to seek to last entry!");
iter.next()
.transpose()
.expect("Reading latest ledger info from DB should work.")
.map(|kv| kv.1)
};
Self {
db,
latest_ledger_info: ArcSwap::from(Arc::new(ledger_info)),
}
}
pub fn get_epoch(&self, version: Version) -> Result<u64> {
let mut iter = self
.db
.iter::<EpochByVersionSchema>(ReadOptions::default())?;
// Search for the end of the previous epoch.
iter.seek_for_prev(&version)?;
let (epoch_end_version, epoch) = match iter.next().transpose()? {
Some(x) => x,
None => {
// There should be a genesis LedgerInfo at version 0 (genesis only consists of one
// transaction), so this normally doesn't happen. However this part of
// implementation doesn't need to rely on this assumption.
return Ok(0);
}
};
ensure!(
epoch_end_version <= version,
"DB corruption: looking for epoch for version {}, got epoch {} ends at version {}",
version,
epoch,
epoch_end_version
);
// If the obtained epoch ended before the given version, return epoch+1, otherwise
// the given version is exactly the last version of the found epoch.
Ok(if epoch_end_version < version {
epoch + 1
} else {
epoch
})
}
/// Returns the ledger infos reflecting epoch bumps with their 2f+1 signatures in
/// [`start_epoch`, `end_epoch`). If there is no more than `limit` results, this function
/// returns all of them, otherwise the first `limit` results are returned and a flag
/// (when true) will be used to indicate the fact that there is more.
pub fn get_first_n_epoch_change_ledger_infos(
&self,
start_epoch: u64,
end_epoch: u64,
limit: usize,
) -> Result<(Vec<LedgerInfoWithSignatures>, bool)> {
let mut iter = self.db.iter::<LedgerInfoSchema>(ReadOptions::default())?;
iter.seek(&start_epoch)?;
let mut results = Vec::new();
for res in iter {
let (epoch, ledger_info_with_sigs) = res?;
debug_assert_eq!(epoch, ledger_info_with_sigs.ledger_info().epoch());
if epoch >= end_epoch {
break;
}
if results.len() >= limit {
return Ok((results, true));
}
ensure!(
ledger_info_with_sigs
.ledger_info()
.next_validator_set()
.is_some(),
"DB corruption: the last ledger info of epoch {} is missing next validator set",
epoch,
);
results.push(ledger_info_with_sigs);
}
Ok((results, false))
}
pub fn get_latest_ledger_info_option(&self) -> Option<LedgerInfoWithSignatures> {
let ledger_info_ptr = self.latest_ledger_info.load();
let ledger_info: &Option<_> = ledger_info_ptr.deref();
ledger_info.clone()
}
pub fn get_latest_ledger_info(&self) -> Result<LedgerInfoWithSignatures> {
self.get_latest_ledger_info_option()
.ok_or_else(|| LibraDbError::NotFound(String::from("Genesis LedgerInfo")).into())
}
pub fn set_latest_ledger_info(&self, ledger_info_with_sigs: LedgerInfoWithSignatures) {
self.latest_ledger_info
.store(Arc::new(Some(ledger_info_with_sigs)));
}
fn get_validator_set(&self, epoch: u64) -> Result<ValidatorSet> {
ensure!(epoch > 0, "ValidatorSet only queryable for epoch >= 1.",);
let ledger_info_with_sigs =
self.db
.get::<LedgerInfoSchema>(&(epoch - 1))?
.ok_or_else(|| {
LibraDbError::NotFound(format!("Last LedgerInfo of epoch {}", epoch - 1))
})?;
let latest_validator_set = ledger_info_with_sigs
.ledger_info()
.next_validator_set()
.ok_or_else(|| {
format_err!("Last LedgerInfo in epoch must carry next_validator_set.")
})?;
Ok(latest_validator_set.clone())
}
pub fn get_tree_state(
&self,
num_transactions: LeafCount,
transaction_info: TransactionInfo,
) -> Result<TreeState> {
Ok(TreeState::new(
num_transactions,
Accumulator::get_frozen_subtree_hashes(self, num_transactions)?,
transaction_info.state_root_hash(),
))
}
pub fn get_startup_info(&self) -> Result<Option<StartupInfo>> {
// Get the latest ledger info. Return None if not bootstrapped.
let latest_ledger_info = match self.get_latest_ledger_info_option() {
Some(x) => x,
None => return Ok(None),
};
let latest_validator_set_if_not_in_li =
match latest_ledger_info.ledger_info().next_validator_set() {
Some(_) => None,
// If the latest LedgerInfo doesn't carry a validator set, we look for the previous
// LedgerInfo which should always carry a validator set.
None => Some(self.get_validator_set(latest_ledger_info.ledger_info().epoch())?),
};
let li_version = latest_ledger_info.ledger_info().version();
let (latest_version, latest_txn_info) = self.get_latest_transaction_info()?;
assert!(latest_version >= li_version);
let (commited_tree_state, synced_tree_state) = if latest_version == li_version {
(
self.get_tree_state(latest_version + 1, latest_txn_info)?,
None,
)
} else {
let commited_txn_info = self.get_transaction_info(li_version)?;
(
self.get_tree_state(li_version + 1, commited_txn_info)?,
Some(self.get_tree_state(latest_version + 1, latest_txn_info)?),
)
};
Ok(Some(StartupInfo::new(
latest_ledger_info,
latest_validator_set_if_not_in_li,
commited_tree_state,
synced_tree_state,
)))
}
/// Get transaction info given `version`
pub fn get_transaction_info(&self, version: Version) -> Result<TransactionInfo> {
self.db
.get::<TransactionInfoSchema>(&version)?
.ok_or_else(|| format_err!("No TransactionInfo at version {}", version))
}
pub fn get_latest_transaction_info_option(&self) -> Result<Option<(Version, TransactionInfo)>> {
let mut iter = self
.db
.iter::<TransactionInfoSchema>(ReadOptions::default())?;
iter.seek_to_last()?;
iter.next().transpose()
}
/// Get latest transaction info together with its version. Note that during node syncing, this
/// version can be greater than what's in the latest LedgerInfo.
pub fn get_latest_transaction_info(&self) -> Result<(Version, TransactionInfo)> {
self.get_latest_transaction_info_option()?
.ok_or_else(|| LibraDbError::NotFound(String::from("Genesis TransactionInfo.")).into())
}
/// Gets an iterator that yields `num_transaction_infos` transaction infos starting from
/// `start_version`.
pub fn get_transaction_info_iter(
&self,
start_version: Version,
num_transaction_infos: u64,
) -> Result<TransactionInfoIter> {
let mut iter = self
.db
.iter::<TransactionInfoSchema>(ReadOptions::default())?;
iter.seek(&start_version)?;
Ok(TransactionInfoIter {
inner: iter,
expected_next_version: start_version,
end_version: start_version
.checked_add(num_transaction_infos)
.ok_or_else(|| format_err!("Too many transaction infos requested."))?,
})
}
/// Get transaction info at `version` with proof towards root of ledger at `ledger_version`.
pub fn get_transaction_info_with_proof(
&self,
version: Version,
ledger_version: Version,
) -> Result<(TransactionInfo, TransactionAccumulatorProof)> {
Ok((
self.get_transaction_info(version)?,
self.get_transaction_proof(version, ledger_version)?,
))
}
/// Get proof for transaction at `version` towards root of ledger at `ledger_version`.
pub fn get_transaction_proof(
&self,
version: Version,
ledger_version: Version,
) -> Result<TransactionAccumulatorProof> {
Accumulator::get_proof(self, ledger_version + 1 /* num_leaves */, version)
}
/// Get proof for `num_txns` consecutive transactions starting from `start_version` towards
/// root of ledger at `ledger_version`.
pub fn get_transaction_range_proof(
&self,
start_version: Option<Version>,
num_txns: u64,
ledger_version: Version,
) -> Result<TransactionAccumulatorRangeProof> {
Accumulator::get_range_proof(
self,
ledger_version + 1, /* num_leaves */
start_version,
num_txns,
)
}
/// Gets proof that shows the ledger at `ledger_version` is consistent with the ledger at
/// `client_known_version`.
pub fn get_consistency_proof(
&self,
client_known_version: Version,
ledger_version: Version,
) -> Result<AccumulatorConsistencyProof> {
Accumulator::get_consistency_proof(self, ledger_version + 1, client_known_version + 1)
}
/// Write `txn_infos` to `batch`. Assigned `first_version` to the the version number of the
/// first transaction, and so on.
pub fn put_transaction_infos(
&self,
first_version: u64,
txn_infos: &[TransactionInfo],
cs: &mut ChangeSet,
) -> Result<HashValue> {
// write txn_info
(first_version..first_version + txn_infos.len() as u64)
.zip_eq(txn_infos.iter())
.map(|(version, txn_info)| cs.batch.put::<TransactionInfoSchema>(&version, txn_info))
.collect::<Result<()>>()?;
// write hash of txn_info into the accumulator
let txn_hashes: Vec<HashValue> = txn_infos.iter().map(TransactionInfo::hash).collect();
let (root_hash, writes) = Accumulator::append(
self,
first_version, /* num_existing_leaves */
&txn_hashes,
)?;
writes
.iter()
.map(|(pos, hash)| cs.batch.put::<TransactionAccumulatorSchema>(pos, hash))
.collect::<Result<()>>()?;
Ok(root_hash)
}
/// Write `ledger_info` to `cs`.
pub fn put_ledger_info(
&self,
ledger_info_with_sigs: &LedgerInfoWithSignatures,
cs: &mut ChangeSet,
) -> Result<()> {
let ledger_info = ledger_info_with_sigs.ledger_info();
if ledger_info.next_validator_set().is_some() {
// This is the last version of the current epoch, update the epoch by version index.
cs.batch
.put::<EpochByVersionSchema>(&ledger_info.version(), &ledger_info.epoch())?;
}
cs.batch.put::<LedgerInfoSchema>(
&ledger_info_with_sigs.ledger_info().epoch(),
ledger_info_with_sigs,
)
}
}
type Accumulator = MerkleAccumulator<LedgerStore, TransactionAccumulatorHasher>;
impl HashReader for LedgerStore {
fn get(&self, position: Position) -> Result<HashValue> {
self.db
.get::<TransactionAccumulatorSchema>(&position)?
.ok_or_else(|| format_err!("{} does not exist.", position))
}
}
pub struct TransactionInfoIter<'a> {
inner: SchemaIterator<'a, TransactionInfoSchema>,
expected_next_version: Version,
end_version: Version,
}
impl<'a> TransactionInfoIter<'a> {
fn next_impl(&mut self) -> Result<Option<TransactionInfo>> {
if self.expected_next_version >= self.end_version {
return Ok(None);
}
let ret = match self.inner.next().transpose()? {
Some((version, transaction_info)) => {
ensure!(
version == self.expected_next_version,
"Transaction info versions are not consecutive.",
);
self.expected_next_version += 1;
Some(transaction_info)
}
_ => None,
};
Ok(ret)
}
}
impl<'a> Iterator for TransactionInfoIter<'a> {
type Item = Result<TransactionInfo>;
fn next(&mut self) -> Option<Self::Item> {
self.next_impl().transpose()
}
}
#[cfg(test)]
mod ledger_info_test;
#[cfg(test)]
mod transaction_info_test;
| 36.384804 | 100 | 0.608757 |
f42689714045bf1215f15b605552751519538674 | 66,023 | // Copyright 2018 sqlparser-rs contributors. All rights reserved.
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// This file is derived from the sqlparser-rs project, available at
// https://github.com/andygrove/sqlparser-rs. It was incorporated
// directly into Materialize on December 21, 2019.
//
// 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 in the LICENSE file at the
// root of this repository, or online at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt;
use crate::ast::display::{self, AstDisplay, AstFormatter};
use crate::ast::{
AstInfo, ColumnDef, CreateConnector, CreateSinkConnector, CreateSourceConnector,
CreateSourceFormat, Envelope, Expr, Format, Ident, KeyConstraint, Query, SourceIncludeMetadata,
TableAlias, TableConstraint, TableWithJoins, UnresolvedDatabaseName, UnresolvedObjectName,
UnresolvedSchemaName, Value,
};
/// A top-level statement (SELECT, INSERT, CREATE, etc.)
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Statement<T: AstInfo> {
Select(SelectStatement<T>),
Insert(InsertStatement<T>),
Copy(CopyStatement<T>),
Update(UpdateStatement<T>),
Delete(DeleteStatement<T>),
CreateConnector(CreateConnectorStatement<T>),
CreateDatabase(CreateDatabaseStatement),
CreateSchema(CreateSchemaStatement),
CreateSource(CreateSourceStatement<T>),
CreateSink(CreateSinkStatement<T>),
CreateView(CreateViewStatement<T>),
CreateViews(CreateViewsStatement<T>),
CreateTable(CreateTableStatement<T>),
CreateIndex(CreateIndexStatement<T>),
CreateType(CreateTypeStatement<T>),
CreateRole(CreateRoleStatement),
CreateCluster(CreateClusterStatement<T>),
CreateClusterReplica(CreateClusterReplicaStatement<T>),
CreateSecret(CreateSecretStatement<T>),
AlterObjectRename(AlterObjectRenameStatement<T>),
AlterIndex(AlterIndexStatement<T>),
AlterSecret(AlterSecretStatement<T>),
Discard(DiscardStatement),
DropDatabase(DropDatabaseStatement<T>),
DropSchema(DropSchemaStatement<T>),
DropObjects(DropObjectsStatement<T>),
DropRoles(DropRolesStatement),
DropClusters(DropClustersStatement),
DropClusterReplicas(DropClusterReplicasStatement),
SetVariable(SetVariableStatement),
ShowDatabases(ShowDatabasesStatement<T>),
ShowSchemas(ShowSchemasStatement<T>),
ShowObjects(ShowObjectsStatement<T>),
ShowIndexes(ShowIndexesStatement<T>),
ShowColumns(ShowColumnsStatement<T>),
ShowCreateView(ShowCreateViewStatement<T>),
ShowCreateSource(ShowCreateSourceStatement<T>),
ShowCreateTable(ShowCreateTableStatement<T>),
ShowCreateSink(ShowCreateSinkStatement<T>),
ShowCreateIndex(ShowCreateIndexStatement<T>),
ShowCreateConnector(ShowCreateConnectorStatement<T>),
ShowVariable(ShowVariableStatement),
StartTransaction(StartTransactionStatement),
SetTransaction(SetTransactionStatement),
Commit(CommitStatement),
Rollback(RollbackStatement),
Tail(TailStatement<T>),
Explain(ExplainStatement<T>),
Declare(DeclareStatement<T>),
Fetch(FetchStatement<T>),
Close(CloseStatement),
Prepare(PrepareStatement<T>),
Execute(ExecuteStatement<T>),
Deallocate(DeallocateStatement),
Raise(RaiseStatement),
}
impl<T: AstInfo> AstDisplay for Statement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
Statement::Select(stmt) => f.write_node(stmt),
Statement::Insert(stmt) => f.write_node(stmt),
Statement::Copy(stmt) => f.write_node(stmt),
Statement::Update(stmt) => f.write_node(stmt),
Statement::Delete(stmt) => f.write_node(stmt),
Statement::CreateConnector(stmt) => f.write_node(stmt),
Statement::CreateDatabase(stmt) => f.write_node(stmt),
Statement::CreateSchema(stmt) => f.write_node(stmt),
Statement::CreateSource(stmt) => f.write_node(stmt),
Statement::CreateSink(stmt) => f.write_node(stmt),
Statement::CreateView(stmt) => f.write_node(stmt),
Statement::CreateViews(stmt) => f.write_node(stmt),
Statement::CreateTable(stmt) => f.write_node(stmt),
Statement::CreateIndex(stmt) => f.write_node(stmt),
Statement::CreateRole(stmt) => f.write_node(stmt),
Statement::CreateSecret(stmt) => f.write_node(stmt),
Statement::CreateType(stmt) => f.write_node(stmt),
Statement::CreateCluster(stmt) => f.write_node(stmt),
Statement::CreateClusterReplica(stmt) => f.write_node(stmt),
Statement::AlterObjectRename(stmt) => f.write_node(stmt),
Statement::AlterIndex(stmt) => f.write_node(stmt),
Statement::AlterSecret(stmt) => f.write_node(stmt),
Statement::Discard(stmt) => f.write_node(stmt),
Statement::DropDatabase(stmt) => f.write_node(stmt),
Statement::DropSchema(stmt) => f.write_node(stmt),
Statement::DropObjects(stmt) => f.write_node(stmt),
Statement::DropRoles(stmt) => f.write_node(stmt),
Statement::DropClusters(stmt) => f.write_node(stmt),
Statement::DropClusterReplicas(stmt) => f.write_node(stmt),
Statement::SetVariable(stmt) => f.write_node(stmt),
Statement::ShowDatabases(stmt) => f.write_node(stmt),
Statement::ShowSchemas(stmt) => f.write_node(stmt),
Statement::ShowObjects(stmt) => f.write_node(stmt),
Statement::ShowIndexes(stmt) => f.write_node(stmt),
Statement::ShowColumns(stmt) => f.write_node(stmt),
Statement::ShowCreateView(stmt) => f.write_node(stmt),
Statement::ShowCreateSource(stmt) => f.write_node(stmt),
Statement::ShowCreateTable(stmt) => f.write_node(stmt),
Statement::ShowCreateSink(stmt) => f.write_node(stmt),
Statement::ShowCreateIndex(stmt) => f.write_node(stmt),
Statement::ShowCreateConnector(stmt) => f.write_node(stmt),
Statement::ShowVariable(stmt) => f.write_node(stmt),
Statement::StartTransaction(stmt) => f.write_node(stmt),
Statement::SetTransaction(stmt) => f.write_node(stmt),
Statement::Commit(stmt) => f.write_node(stmt),
Statement::Rollback(stmt) => f.write_node(stmt),
Statement::Tail(stmt) => f.write_node(stmt),
Statement::Explain(stmt) => f.write_node(stmt),
Statement::Declare(stmt) => f.write_node(stmt),
Statement::Close(stmt) => f.write_node(stmt),
Statement::Fetch(stmt) => f.write_node(stmt),
Statement::Prepare(stmt) => f.write_node(stmt),
Statement::Execute(stmt) => f.write_node(stmt),
Statement::Deallocate(stmt) => f.write_node(stmt),
Statement::Raise(stmt) => f.write_node(stmt),
}
}
}
impl_display_t!(Statement);
/// `SELECT`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SelectStatement<T: AstInfo> {
pub query: Query<T>,
pub as_of: Option<AsOf<T>>,
}
impl<T: AstInfo> AstDisplay for SelectStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_node(&self.query);
if let Some(as_of) = &self.as_of {
f.write_str(" ");
f.write_node(as_of);
}
}
}
impl_display_t!(SelectStatement);
/// `INSERT`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InsertStatement<T: AstInfo> {
/// TABLE
pub table_name: T::ObjectName,
/// COLUMNS
pub columns: Vec<Ident>,
/// A SQL query that specifies what to insert.
pub source: InsertSource<T>,
}
impl<T: AstInfo> AstDisplay for InsertStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("INSERT INTO ");
f.write_node(&self.table_name);
if !self.columns.is_empty() {
f.write_str(" (");
f.write_node(&display::comma_separated(&self.columns));
f.write_str(")");
}
f.write_str(" ");
f.write_node(&self.source);
}
}
impl_display_t!(InsertStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CopyRelation<T: AstInfo> {
Table {
name: T::ObjectName,
columns: Vec<Ident>,
},
Select(SelectStatement<T>),
Tail(TailStatement<T>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CopyDirection {
To,
From,
}
impl AstDisplay for CopyDirection {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str(match self {
CopyDirection::To => "TO",
CopyDirection::From => "FROM",
})
}
}
impl_display!(CopyDirection);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CopyTarget {
Stdin,
Stdout,
}
impl AstDisplay for CopyTarget {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str(match self {
CopyTarget::Stdin => "STDIN",
CopyTarget::Stdout => "STDOUT",
})
}
}
impl_display!(CopyTarget);
/// `COPY`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CopyStatement<T: AstInfo> {
/// RELATION
pub relation: CopyRelation<T>,
/// DIRECTION
pub direction: CopyDirection,
// TARGET
pub target: CopyTarget,
// OPTIONS
pub options: Vec<WithOption<T>>,
}
impl<T: AstInfo> AstDisplay for CopyStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("COPY ");
match &self.relation {
CopyRelation::Table { name, columns } => {
f.write_node(name);
if !columns.is_empty() {
f.write_str("(");
f.write_node(&display::comma_separated(&columns));
f.write_str(")");
}
}
CopyRelation::Select(query) => {
f.write_str("(");
f.write_node(query);
f.write_str(")");
}
CopyRelation::Tail(query) => {
f.write_str("(");
f.write_node(query);
f.write_str(")");
}
};
f.write_str(" ");
f.write_node(&self.direction);
f.write_str(" ");
f.write_node(&self.target);
if !self.options.is_empty() {
f.write_str(" WITH (");
f.write_node(&display::comma_separated(&self.options));
f.write_str(")");
}
}
}
impl_display_t!(CopyStatement);
/// `UPDATE`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UpdateStatement<T: AstInfo> {
/// `FROM`
pub table_name: T::ObjectName,
/// Column assignments
pub assignments: Vec<Assignment<T>>,
/// WHERE
pub selection: Option<Expr<T>>,
}
impl<T: AstInfo> AstDisplay for UpdateStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("UPDATE ");
f.write_node(&self.table_name);
if !self.assignments.is_empty() {
f.write_str(" SET ");
f.write_node(&display::comma_separated(&self.assignments));
}
if let Some(selection) = &self.selection {
f.write_str(" WHERE ");
f.write_node(selection);
}
}
}
impl_display_t!(UpdateStatement);
/// `DELETE`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DeleteStatement<T: AstInfo> {
/// `FROM`
pub table_name: T::ObjectName,
/// `AS`
pub alias: Option<TableAlias>,
/// `USING`
pub using: Vec<TableWithJoins<T>>,
/// `WHERE`
pub selection: Option<Expr<T>>,
}
impl<T: AstInfo> AstDisplay for DeleteStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DELETE FROM ");
f.write_node(&self.table_name);
if let Some(alias) = &self.alias {
f.write_str(" AS ");
f.write_node(alias);
}
if !self.using.is_empty() {
f.write_str(" USING ");
f.write_node(&display::comma_separated(&self.using));
}
if let Some(selection) = &self.selection {
f.write_str(" WHERE ");
f.write_node(selection);
}
}
}
impl_display_t!(DeleteStatement);
/// `CREATE DATABASE`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateDatabaseStatement {
pub name: UnresolvedDatabaseName,
pub if_not_exists: bool,
}
impl AstDisplay for CreateDatabaseStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE DATABASE ");
if self.if_not_exists {
f.write_str("IF NOT EXISTS ");
}
f.write_node(&self.name);
}
}
impl_display!(CreateDatabaseStatement);
/// `CREATE SCHEMA`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateSchemaStatement {
pub name: UnresolvedSchemaName,
pub if_not_exists: bool,
}
impl AstDisplay for CreateSchemaStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE SCHEMA ");
if self.if_not_exists {
f.write_str("IF NOT EXISTS ");
}
f.write_node(&self.name);
}
}
impl_display!(CreateSchemaStatement);
/// `CREATE CONNECTOR`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateConnectorStatement<T: AstInfo> {
pub name: UnresolvedObjectName,
pub connector: CreateConnector<T>,
pub if_not_exists: bool,
}
impl<T: AstInfo> AstDisplay for CreateConnectorStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE CONNECTOR ");
if self.if_not_exists {
f.write_str("IF NOT EXISTS ");
}
f.write_node(&self.name);
f.write_str(" FOR ");
self.connector.fmt(f)
}
}
impl_display_t!(CreateConnectorStatement);
/// `CREATE SOURCE`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateSourceStatement<T: AstInfo> {
pub name: UnresolvedObjectName,
pub col_names: Vec<Ident>,
pub connector: CreateSourceConnector<T>,
pub with_options: Vec<WithOption<T>>,
pub include_metadata: Vec<SourceIncludeMetadata>,
pub format: CreateSourceFormat<T>,
pub envelope: Option<Envelope>,
pub if_not_exists: bool,
pub materialized: bool,
pub key_constraint: Option<KeyConstraint>,
}
impl<T: AstInfo> AstDisplay for CreateSourceStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE ");
if self.materialized {
f.write_str("MATERIALIZED ");
}
f.write_str("SOURCE ");
if self.if_not_exists {
f.write_str("IF NOT EXISTS ");
}
f.write_node(&self.name);
f.write_str(" ");
if !self.col_names.is_empty() {
f.write_str("(");
f.write_node(&display::comma_separated(&self.col_names));
if self.key_constraint.is_some() {
f.write_str(", ");
f.write_node(self.key_constraint.as_ref().unwrap());
}
f.write_str(") ");
} else if self.key_constraint.is_some() {
f.write_str("(");
f.write_node(self.key_constraint.as_ref().unwrap());
f.write_str(") ")
}
f.write_str("FROM ");
f.write_node(&self.connector);
if !self.with_options.is_empty() {
f.write_str(" WITH (");
f.write_node(&display::comma_separated(&self.with_options));
f.write_str(")");
}
f.write_node(&self.format);
if !self.include_metadata.is_empty() {
f.write_str(" INCLUDE ");
f.write_node(&display::comma_separated(&self.include_metadata));
}
match &self.envelope {
None => (),
Some(Envelope::None) => (),
Some(envelope) => {
f.write_str(" ENVELOPE ");
f.write_node(envelope);
}
}
}
}
impl_display_t!(CreateSourceStatement);
/// `CREATE SINK`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateSinkStatement<T: AstInfo> {
pub name: UnresolvedObjectName,
pub in_cluster: Option<T::ClusterName>,
pub from: T::ObjectName,
pub connector: CreateSinkConnector<T>,
pub with_options: Vec<WithOption<T>>,
pub format: Option<Format<T>>,
pub envelope: Option<Envelope>,
pub with_snapshot: bool,
pub as_of: Option<AsOf<T>>,
pub if_not_exists: bool,
}
impl<T: AstInfo> AstDisplay for CreateSinkStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE SINK ");
if self.if_not_exists {
f.write_str("IF NOT EXISTS ");
}
f.write_node(&self.name);
if let Some(cluster) = &self.in_cluster {
f.write_str(" IN CLUSTER ");
f.write_node(cluster);
}
f.write_str(" FROM ");
f.write_node(&self.from);
f.write_str(" INTO ");
f.write_node(&self.connector);
if !self.with_options.is_empty() {
f.write_str(" WITH (");
f.write_node(&display::comma_separated(&self.with_options));
f.write_str(")");
}
if let Some(format) = &self.format {
f.write_str(" FORMAT ");
f.write_node(format);
}
if let Some(envelope) = &self.envelope {
f.write_str(" ENVELOPE ");
f.write_node(envelope);
}
if self.with_snapshot {
f.write_str(" WITH SNAPSHOT");
} else {
f.write_str(" WITHOUT SNAPSHOT");
}
if let Some(as_of) = &self.as_of {
f.write_str(" ");
f.write_node(as_of);
}
}
}
impl_display_t!(CreateSinkStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ViewDefinition<T: AstInfo> {
/// View name
pub name: UnresolvedObjectName,
pub columns: Vec<Ident>,
pub with_options: Vec<WithOption<T>>,
pub query: Query<T>,
}
impl<T: AstInfo> AstDisplay for ViewDefinition<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_node(&self.name);
if !self.with_options.is_empty() {
f.write_str(" WITH (");
f.write_node(&display::comma_separated(&self.with_options));
f.write_str(")");
}
if !self.columns.is_empty() {
f.write_str(" (");
f.write_node(&display::comma_separated(&self.columns));
f.write_str(")");
}
f.write_str(" AS ");
f.write_node(&self.query);
}
}
impl_display_t!(ViewDefinition);
/// `CREATE VIEW`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateViewStatement<T: AstInfo> {
pub if_exists: IfExistsBehavior,
pub temporary: bool,
pub materialized: bool,
pub definition: ViewDefinition<T>,
}
impl<T: AstInfo> AstDisplay for CreateViewStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE");
if self.if_exists == IfExistsBehavior::Replace {
f.write_str(" OR REPLACE");
}
if self.temporary {
f.write_str(" TEMPORARY");
}
if self.materialized {
f.write_str(" MATERIALIZED");
}
f.write_str(" VIEW");
if self.if_exists == IfExistsBehavior::Skip {
f.write_str(" IF NOT EXISTS");
}
f.write_str(" ");
f.write_node(&self.definition);
}
}
impl_display_t!(CreateViewStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateViewsSourceTarget {
pub name: UnresolvedObjectName,
pub alias: Option<UnresolvedObjectName>,
}
impl AstDisplay for CreateViewsSourceTarget {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_node(&self.name);
if let Some(alias) = &self.alias {
f.write_str(" AS ");
f.write_node(alias);
}
}
}
impl_display!(CreateViewsSourceTarget);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CreateViewsDefinitions<T: AstInfo> {
Source {
name: T::ObjectName,
targets: Option<Vec<CreateViewsSourceTarget>>,
},
Literal(Vec<ViewDefinition<T>>),
}
impl<T: AstInfo> AstDisplay for CreateViewsDefinitions<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
Self::Source { name, targets } => {
f.write_str(" FROM SOURCE ");
f.write_node(name);
if let Some(targets) = targets {
f.write_str(" (");
f.write_node(&display::comma_separated(&targets));
f.write_str(")");
}
}
Self::Literal(defs) => {
let mut delim = " ";
for def in defs {
f.write_str(delim);
delim = ", ";
f.write_str('(');
f.write_node(def);
f.write_str(')');
}
}
}
}
}
impl_display_t!(CreateViewsDefinitions);
/// `CREATE VIEWS`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateViewsStatement<T: AstInfo> {
pub if_exists: IfExistsBehavior,
pub temporary: bool,
pub materialized: bool,
pub definitions: CreateViewsDefinitions<T>,
}
impl<T: AstInfo> AstDisplay for CreateViewsStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE");
if self.if_exists == IfExistsBehavior::Replace {
f.write_str(" OR REPLACE");
}
if self.temporary {
f.write_str(" TEMPORARY");
}
if self.materialized {
f.write_str(" MATERIALIZED");
}
f.write_str(" VIEWS");
if self.if_exists == IfExistsBehavior::Skip {
f.write_str(" IF NOT EXISTS");
}
f.write_node(&self.definitions);
}
}
impl_display_t!(CreateViewsStatement);
/// `CREATE TABLE`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateTableStatement<T: AstInfo> {
/// Table name
pub name: UnresolvedObjectName,
/// Optional schema
pub columns: Vec<ColumnDef<T>>,
pub constraints: Vec<TableConstraint<T>>,
pub with_options: Vec<WithOption<T>>,
pub if_not_exists: bool,
pub temporary: bool,
}
impl<T: AstInfo> AstDisplay for CreateTableStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE ");
if self.temporary {
f.write_str("TEMPORARY ");
}
f.write_str("TABLE ");
if self.if_not_exists {
f.write_str("IF NOT EXISTS ");
}
f.write_node(&self.name);
f.write_str(" (");
f.write_node(&display::comma_separated(&self.columns));
if !self.constraints.is_empty() {
f.write_str(", ");
f.write_node(&display::comma_separated(&self.constraints));
}
f.write_str(")");
if !self.with_options.is_empty() {
f.write_str(" WITH (");
f.write_node(&display::comma_separated(&self.with_options));
f.write_str(")");
}
}
}
impl_display_t!(CreateTableStatement);
/// `CREATE INDEX`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateIndexStatement<T: AstInfo> {
/// Optional index name.
pub name: Option<Ident>,
pub in_cluster: Option<T::ClusterName>,
/// `ON` table or view name
pub on_name: T::ObjectName,
/// Expressions that form part of the index key. If not included, the
/// key_parts will be inferred from the named object.
pub key_parts: Option<Vec<Expr<T>>>,
pub with_options: Vec<WithOption<T>>,
pub if_not_exists: bool,
}
impl<T: AstInfo> AstDisplay for CreateIndexStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE ");
if self.key_parts.is_none() {
f.write_str("DEFAULT ");
}
f.write_str("INDEX ");
if self.if_not_exists {
f.write_str("IF NOT EXISTS ");
}
if let Some(name) = &self.name {
f.write_node(name);
f.write_str(" ");
}
if let Some(cluster) = &self.in_cluster {
f.write_str("IN CLUSTER ");
f.write_node(cluster);
f.write_str(" ");
}
f.write_str("ON ");
f.write_node(&self.on_name);
if let Some(key_parts) = &self.key_parts {
f.write_str(" (");
f.write_node(&display::comma_separated(key_parts));
f.write_str(")");
}
if !self.with_options.is_empty() {
f.write_str(" WITH (");
f.write_node(&display::comma_separated(&self.with_options));
f.write_str(")");
}
}
}
impl_display_t!(CreateIndexStatement);
/// A `CREATE ROLE` statement.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateRoleStatement {
/// Whether this was actually a `CREATE USER` statement.
pub is_user: bool,
/// The specified role.
pub name: Ident,
/// Any options that were attached, in the order they were presented.
pub options: Vec<CreateRoleOption>,
}
impl AstDisplay for CreateRoleStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE ");
if self.is_user {
f.write_str("USER ");
} else {
f.write_str("ROLE ");
}
f.write_node(&self.name);
for option in &self.options {
f.write_str(" ");
option.fmt(f)
}
}
}
impl_display!(CreateRoleStatement);
/// Options that can be attached to [`CreateRoleStatement`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CreateRoleOption {
/// The `SUPERUSER` option.
SuperUser,
/// The `NOSUPERUSER` option.
NoSuperUser,
/// The `LOGIN` option.
Login,
/// The `NOLOGIN` option.
NoLogin,
}
impl AstDisplay for CreateRoleOption {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
CreateRoleOption::SuperUser => f.write_str("SUPERUSER"),
CreateRoleOption::NoSuperUser => f.write_str("NOSUPERUSER"),
CreateRoleOption::Login => f.write_str("LOGIN"),
CreateRoleOption::NoLogin => f.write_str("NOLOGIN"),
}
}
}
impl_display!(CreateRoleOption);
/// A `CREATE SECRET` statement.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateSecretStatement<T: AstInfo> {
pub name: UnresolvedObjectName,
pub if_not_exists: bool,
pub value: Expr<T>,
}
impl<T: AstInfo> AstDisplay for CreateSecretStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE SECRET ");
if self.if_not_exists {
f.write_str("IF NOT EXISTS ");
}
f.write_node(&self.name);
f.write_str(" AS ");
f.write_node(&self.value);
}
}
impl_display_t!(CreateSecretStatement);
/// `CREATE TYPE ..`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateTypeStatement<T: AstInfo> {
/// Name of the created type.
pub name: UnresolvedObjectName,
/// The new type's "base type".
pub as_type: CreateTypeAs<T>,
}
impl<T: AstInfo> AstDisplay for CreateTypeStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE TYPE ");
f.write_node(&self.name);
f.write_str(" AS ");
match &self.as_type {
CreateTypeAs::List { with_options } | CreateTypeAs::Map { with_options } => {
f.write_str(&self.as_type);
f.write_str("( ");
if !with_options.is_empty() {
f.write_node(&display::comma_separated(&with_options));
}
f.write_str(" )");
}
CreateTypeAs::Record { column_defs } => {
f.write_str("( ");
if !column_defs.is_empty() {
f.write_node(&display::comma_separated(&column_defs));
}
f.write_str(" )");
}
};
}
}
impl_display_t!(CreateTypeStatement);
/// `CREATE CLUSTER ..`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateClusterStatement<T: AstInfo> {
/// Name of the created cluster.
pub name: Ident,
/// The comma-separated options.
pub options: Vec<ClusterOption<T>>,
/// Replicas to create alongside the cluster.
pub replicas: Vec<ReplicaDefinition<T>>,
}
impl<T: AstInfo> AstDisplay for CreateClusterStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE CLUSTER ");
f.write_node(&self.name);
if !self.replicas.is_empty() {
f.write_str(" ");
let replica_defs = self
.replicas
.iter()
.map(|ReplicaDefinition { name, options }| {
let options =
itertools::join(options.iter().map(|o| o.to_ast_string_stable()), ", ");
format!("REPLICA {name} ({options})")
})
.collect::<Vec<_>>();
f.write_str(itertools::join(replica_defs, ", "));
}
if !self.options.is_empty() {
f.write_str(" ");
f.write_node(&display::comma_separated(&self.options));
}
}
}
impl_display_t!(CreateClusterStatement);
/// An option in a `CREATE CLUSTER` statement.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ClusterOption<T: AstInfo> {
/// The `INTROSPECTION GRANULARITY [[=] <interval>] option.
IntrospectionGranularity(WithOptionValue<T>),
/// The `INTROSPECTION DEBUGGING [[=] <enabled>] option.
IntrospectionDebugging(WithOptionValue<T>),
}
impl<T: AstInfo> AstDisplay for ClusterOption<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
ClusterOption::IntrospectionGranularity(granularity) => {
f.write_str("INTROSPECTION GRANULARITY ");
f.write_node(granularity);
}
ClusterOption::IntrospectionDebugging(debugging) => {
f.write_str("INTROSPECTION DEBUGGING ");
f.write_node(debugging);
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ReplicaDefinition<T: AstInfo> {
/// Name of the created replica.
pub name: Ident,
/// The comma-separated options.
pub options: Vec<ReplicaOption<T>>,
}
/// `CREATE CLUSTER REPLICA ..`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateClusterReplicaStatement<T: AstInfo> {
/// Name of the replica's cluster.
pub of_cluster: Ident,
/// The replica's definition.
pub definition: ReplicaDefinition<T>,
}
impl<T: AstInfo> AstDisplay for CreateClusterReplicaStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CREATE CLUSTER REPLICA ");
f.write_node(&self.of_cluster);
f.write_str(".");
f.write_node(&self.definition.name);
if !self.definition.options.is_empty() {
f.write_str(" ");
f.write_node(&display::comma_separated(&self.definition.options));
}
}
}
impl_display_t!(CreateClusterReplicaStatement);
/// An option in a `CREATE CLUSTER` statement.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ReplicaOption<T: AstInfo> {
/// The `REMOTE <cluster> (<host> [, <host> ...])` option.
Remote {
/// The hosts.
hosts: Vec<WithOptionValue<T>>,
},
/// The `SIZE [[=] <size>]` option.
Size(WithOptionValue<T>),
/// The `AVAILABILITY ZONE [[=] <size>]` option.
AvailabilityZone(WithOptionValue<T>),
}
impl<T: AstInfo> AstDisplay for ReplicaOption<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
ReplicaOption::Remote { hosts } => {
f.write_str("REMOTE (");
f.write_node(&display::comma_separated(hosts));
f.write_str(")");
}
ReplicaOption::Size(size) => {
f.write_str("SIZE ");
f.write_node(size);
}
ReplicaOption::AvailabilityZone(az) => {
f.write_str("AVAILABILITY ZONE ");
f.write_node(az);
}
}
}
}
/// `CREATE TYPE .. AS <TYPE>`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CreateTypeAs<T: AstInfo> {
List { with_options: Vec<WithOption<T>> },
Map { with_options: Vec<WithOption<T>> },
Record { column_defs: Vec<ColumnDef<T>> },
}
impl<T: AstInfo> AstDisplay for CreateTypeAs<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
CreateTypeAs::List { .. } => f.write_str("LIST "),
CreateTypeAs::Map { .. } => f.write_str("MAP "),
CreateTypeAs::Record { .. } => f.write_str("RECORD "),
}
}
}
impl_display_t!(CreateTypeAs);
/// `ALTER <OBJECT> ... RENAME TO`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AlterObjectRenameStatement<T: AstInfo> {
pub object_type: ObjectType,
pub if_exists: bool,
pub name: T::ObjectName,
pub to_item_name: Ident,
}
impl<T: AstInfo> AstDisplay for AlterObjectRenameStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("ALTER ");
f.write_node(&self.object_type);
f.write_str(" ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&self.name);
f.write_str(" RENAME TO ");
f.write_node(&self.to_item_name);
}
}
impl_display_t!(AlterObjectRenameStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AlterIndexAction<T: AstInfo> {
SetOptions(Vec<WithOption<T>>),
ResetOptions(Vec<Ident>),
}
/// `ALTER INDEX ... {RESET, SET}`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AlterIndexStatement<T: AstInfo> {
pub index_name: T::ObjectName,
pub if_exists: bool,
pub action: AlterIndexAction<T>,
}
impl<T: AstInfo> AstDisplay for AlterIndexStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("ALTER INDEX ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&self.index_name);
f.write_str(" ");
match &self.action {
AlterIndexAction::SetOptions(options) => {
f.write_str("SET (");
f.write_node(&display::comma_separated(&options));
f.write_str(")");
}
AlterIndexAction::ResetOptions(options) => {
f.write_str("RESET (");
f.write_node(&display::comma_separated(&options));
f.write_str(")");
}
}
}
}
impl_display_t!(AlterIndexStatement);
/// `ALTER SECRET ... AS`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AlterSecretStatement<T: AstInfo> {
pub name: T::ObjectName,
pub if_exists: bool,
pub value: Expr<T>,
}
impl<T: AstInfo> AstDisplay for AlterSecretStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("ALTER SECRET ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&self.name);
f.write_str(" AS ");
f.write_node(&self.value);
}
}
impl_display_t!(AlterSecretStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DiscardStatement {
pub target: DiscardTarget,
}
impl AstDisplay for DiscardStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DISCARD ");
f.write_node(&self.target);
}
}
impl_display!(DiscardStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DiscardTarget {
Plans,
Sequences,
Temp,
All,
}
impl AstDisplay for DiscardTarget {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
DiscardTarget::Plans => f.write_str("PLANS"),
DiscardTarget::Sequences => f.write_str("SEQUENCES"),
DiscardTarget::Temp => f.write_str("TEMP"),
DiscardTarget::All => f.write_str("ALL"),
}
}
}
impl_display!(DiscardTarget);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropDatabaseStatement<T: AstInfo> {
pub name: T::DatabaseName,
pub if_exists: bool,
pub restrict: bool,
}
impl<T: AstInfo> AstDisplay for DropDatabaseStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DROP DATABASE ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&self.name);
if self.restrict {
f.write_str(" RESTRICT");
}
}
}
impl_display_t!(DropDatabaseStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropSchemaStatement<T: AstInfo> {
pub name: T::SchemaName,
pub if_exists: bool,
pub cascade: bool,
}
impl<T: AstInfo> AstDisplay for DropSchemaStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DROP SCHEMA ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&self.name);
if self.cascade {
f.write_str(" CASCADE");
}
}
}
impl_display_t!(DropSchemaStatement);
/// `DROP`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropObjectsStatement<T: AstInfo> {
/// If this was constructed as `DROP MATERIALIZED <type>`
pub materialized: bool,
/// The type of the object to drop: TABLE, VIEW, etc.
pub object_type: ObjectType,
/// An optional `IF EXISTS` clause. (Non-standard.)
pub if_exists: bool,
/// One or more objects to drop. (ANSI SQL requires exactly one.)
pub names: Vec<T::ObjectName>,
/// Whether `CASCADE` was specified. This will be `false` when
/// `RESTRICT` or no drop behavior at all was specified.
pub cascade: bool,
}
impl<T: AstInfo> AstDisplay for DropObjectsStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DROP ");
f.write_node(&self.object_type);
f.write_str(" ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&display::comma_separated(&self.names));
if self.cascade {
f.write_str(" CASCADE");
}
}
}
impl_display_t!(DropObjectsStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropRolesStatement {
/// An optional `IF EXISTS` clause. (Non-standard.)
pub if_exists: bool,
/// One or more objects to drop. (ANSI SQL requires exactly one.)
pub names: Vec<UnresolvedObjectName>,
}
impl AstDisplay for DropRolesStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DROP ROLE ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&display::comma_separated(&self.names));
}
}
impl_display!(DropRolesStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropClustersStatement {
/// An optional `IF EXISTS` clause. (Non-standard.)
pub if_exists: bool,
/// One or more objects to drop. (ANSI SQL requires exactly one.)
pub names: Vec<UnresolvedObjectName>,
/// Whether `CASCADE` was specified. This will be `false` when
/// `RESTRICT` or no drop behavior at all was specified.
pub cascade: bool,
}
impl AstDisplay for DropClustersStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DROP CLUSTER ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&display::comma_separated(&self.names));
if self.cascade {
f.write_str(" CASCADE");
}
}
}
impl_display!(DropClustersStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct QualifiedReplica {
pub cluster: Ident,
pub replica: Ident,
}
impl AstDisplay for QualifiedReplica {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_node(&self.cluster);
f.write_str(".");
f.write_node(&self.replica);
}
}
impl_display!(QualifiedReplica);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropClusterReplicasStatement {
/// An optional `IF EXISTS` clause. (Non-standard.)
pub if_exists: bool,
/// One or more objects to drop. (ANSI SQL requires exactly one.)
pub names: Vec<QualifiedReplica>,
}
impl AstDisplay for DropClusterReplicasStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DROP CLUSTER REPLICA ");
if self.if_exists {
f.write_str("IF EXISTS ");
}
f.write_node(&display::comma_separated(&self.names));
}
}
impl_display!(DropClusterReplicasStatement);
/// `SET <variable>`
///
/// Note: this is not a standard SQL statement, but it is supported by at
/// least MySQL and PostgreSQL. Not all MySQL-specific syntactic forms are
/// supported yet.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SetVariableStatement {
pub local: bool,
pub variable: Ident,
pub value: SetVariableValue,
}
impl AstDisplay for SetVariableStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SET ");
if self.local {
f.write_str("LOCAL ");
}
f.write_node(&self.variable);
f.write_str(" = ");
f.write_node(&self.value);
}
}
impl_display!(SetVariableStatement);
/// `SHOW <variable>`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowVariableStatement {
pub variable: Ident,
}
impl AstDisplay for ShowVariableStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW ");
f.write_node(&self.variable);
}
}
impl_display!(ShowVariableStatement);
/// `SHOW DATABASES`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowDatabasesStatement<T: AstInfo> {
pub filter: Option<ShowStatementFilter<T>>,
}
impl<T: AstInfo> AstDisplay for ShowDatabasesStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW DATABASES");
if let Some(filter) = &self.filter {
f.write_str(" ");
f.write_node(filter);
}
}
}
impl_display_t!(ShowDatabasesStatement);
/// `SHOW SCHEMAS`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowSchemasStatement<T: AstInfo> {
pub from: Option<T::DatabaseName>,
pub extended: bool,
pub full: bool,
pub filter: Option<ShowStatementFilter<T>>,
}
impl<T: AstInfo> AstDisplay for ShowSchemasStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW");
if self.extended {
f.write_str(" EXTENDED");
}
if self.full {
f.write_str(" FULL");
}
f.write_str(" SCHEMAS");
if let Some(from) = &self.from {
f.write_str(" FROM ");
f.write_node(from);
}
if let Some(filter) = &self.filter {
f.write_str(" ");
f.write_node(filter);
}
}
}
impl_display_t!(ShowSchemasStatement);
/// `SHOW <object>S`
///
/// ```sql
/// SHOW TABLES;
/// SHOW SOURCES;
/// SHOW VIEWS;
/// SHOW SINKS;
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowObjectsStatement<T: AstInfo> {
pub object_type: ObjectType,
pub from: Option<T::SchemaName>,
pub in_cluster: Option<T::ClusterName>,
pub extended: bool,
pub full: bool,
pub materialized: bool,
pub filter: Option<ShowStatementFilter<T>>,
}
impl<T: AstInfo> AstDisplay for ShowObjectsStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW");
if self.extended {
f.write_str(" EXTENDED");
}
if self.full {
f.write_str(" FULL");
}
if self.materialized {
f.write_str(" MATERIALIZED");
}
f.write_str(" ");
f.write_str(match &self.object_type {
ObjectType::Table => "TABLES",
ObjectType::View => "VIEWS",
ObjectType::Source => "SOURCES",
ObjectType::Sink => "SINKS",
ObjectType::Type => "TYPES",
ObjectType::Role => "ROLES",
ObjectType::Cluster => "CLUSTERS",
ObjectType::ClusterReplica => "CLUSTER REPLICAS",
ObjectType::Object => "OBJECTS",
ObjectType::Secret => "SECRETS",
ObjectType::Connector => "CONNECTORS",
ObjectType::Index => unreachable!(),
});
if let Some(from) = &self.from {
f.write_str(" FROM ");
f.write_node(from);
}
if let Some(filter) = &self.filter {
f.write_str(" ");
f.write_node(filter);
}
}
}
impl_display_t!(ShowObjectsStatement);
/// `SHOW INDEX|INDEXES|KEYS`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowIndexesStatement<T: AstInfo> {
pub table_name: Option<T::ObjectName>,
pub in_cluster: Option<T::ClusterName>,
pub extended: bool,
pub filter: Option<ShowStatementFilter<T>>,
}
impl<T: AstInfo> AstDisplay for ShowIndexesStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW ");
if self.extended {
f.write_str("EXTENDED ");
}
f.write_str("INDEXES ");
if let Some(table_name) = &self.table_name {
f.write_str("FROM ");
f.write_node(table_name);
}
if let Some(in_cluster) = &self.in_cluster {
f.write_str("IN CLUSTER ");
f.write_node(in_cluster);
}
if let Some(filter) = &self.filter {
f.write_str(" ");
f.write_node(filter);
}
}
}
impl_display_t!(ShowIndexesStatement);
/// `SHOW COLUMNS`
///
/// Note: this is a MySQL-specific statement.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowColumnsStatement<T: AstInfo> {
pub extended: bool,
pub full: bool,
pub table_name: T::ObjectName,
pub filter: Option<ShowStatementFilter<T>>,
}
impl<T: AstInfo> AstDisplay for ShowColumnsStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW ");
if self.extended {
f.write_str("EXTENDED ");
}
if self.full {
f.write_str("FULL ");
}
f.write_str("COLUMNS FROM ");
f.write_node(&self.table_name);
if let Some(filter) = &self.filter {
f.write_str(" ");
f.write_node(filter);
}
}
}
impl_display_t!(ShowColumnsStatement);
/// `SHOW CREATE VIEW <view>`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowCreateViewStatement<T: AstInfo> {
pub view_name: T::ObjectName,
}
impl<T: AstInfo> AstDisplay for ShowCreateViewStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW CREATE VIEW ");
f.write_node(&self.view_name);
}
}
impl_display_t!(ShowCreateViewStatement);
/// `SHOW CREATE SOURCE <source>`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowCreateSourceStatement<T: AstInfo> {
pub source_name: T::ObjectName,
}
impl<T: AstInfo> AstDisplay for ShowCreateSourceStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW CREATE SOURCE ");
f.write_node(&self.source_name);
}
}
impl_display_t!(ShowCreateSourceStatement);
/// `SHOW CREATE TABLE <table>`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowCreateTableStatement<T: AstInfo> {
pub table_name: T::ObjectName,
}
impl<T: AstInfo> AstDisplay for ShowCreateTableStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW CREATE TABLE ");
f.write_node(&self.table_name);
}
}
impl_display_t!(ShowCreateTableStatement);
/// `SHOW CREATE SINK <sink>`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowCreateSinkStatement<T: AstInfo> {
pub sink_name: T::ObjectName,
}
impl<T: AstInfo> AstDisplay for ShowCreateSinkStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW CREATE SINK ");
f.write_node(&self.sink_name);
}
}
impl_display_t!(ShowCreateSinkStatement);
/// `SHOW CREATE INDEX <index>`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowCreateIndexStatement<T: AstInfo> {
pub index_name: T::ObjectName,
}
impl<T: AstInfo> AstDisplay for ShowCreateIndexStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW CREATE INDEX ");
f.write_node(&self.index_name);
}
}
impl_display_t!(ShowCreateIndexStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShowCreateConnectorStatement<T: AstInfo> {
pub connector_name: T::ObjectName,
}
impl<T: AstInfo> AstDisplay for ShowCreateConnectorStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SHOW CREATE CONNECTOR ");
f.write_node(&self.connector_name);
}
}
/// `{ BEGIN [ TRANSACTION | WORK ] | START TRANSACTION } ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StartTransactionStatement {
pub modes: Vec<TransactionMode>,
}
impl AstDisplay for StartTransactionStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("START TRANSACTION");
if !self.modes.is_empty() {
f.write_str(" ");
f.write_node(&display::comma_separated(&self.modes));
}
}
}
impl_display!(StartTransactionStatement);
/// `SET TRANSACTION ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SetTransactionStatement {
pub modes: Vec<TransactionMode>,
}
impl AstDisplay for SetTransactionStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("SET TRANSACTION");
if !self.modes.is_empty() {
f.write_str(" ");
f.write_node(&display::comma_separated(&self.modes));
}
}
}
impl_display!(SetTransactionStatement);
/// `COMMIT [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ]`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CommitStatement {
pub chain: bool,
}
impl AstDisplay for CommitStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("COMMIT");
if self.chain {
f.write_str(" AND CHAIN");
}
}
}
impl_display!(CommitStatement);
/// `ROLLBACK [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ]`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RollbackStatement {
pub chain: bool,
}
impl AstDisplay for RollbackStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("ROLLBACK");
if self.chain {
f.write_str(" AND CHAIN");
}
}
}
impl_display!(RollbackStatement);
/// `TAIL`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TailStatement<T: AstInfo> {
pub relation: TailRelation<T>,
pub options: Vec<WithOption<T>>,
pub as_of: Option<AsOf<T>>,
}
impl<T: AstInfo> AstDisplay for TailStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("TAIL ");
f.write_node(&self.relation);
if !self.options.is_empty() {
f.write_str(" WITH (");
f.write_node(&display::comma_separated(&self.options));
f.write_str(")");
}
if let Some(as_of) = &self.as_of {
f.write_str(" ");
f.write_node(as_of);
}
}
}
impl_display_t!(TailStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TailRelation<T: AstInfo> {
Name(T::ObjectName),
Query(Query<T>),
}
impl<T: AstInfo> AstDisplay for TailRelation<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
TailRelation::Name(name) => f.write_node(name),
TailRelation::Query(query) => {
f.write_str("(");
f.write_node(query);
f.write_str(")");
}
}
}
}
impl_display_t!(TailRelation);
/// `EXPLAIN ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExplainStatement<T: AstInfo> {
pub stage: ExplainStage,
pub explainee: Explainee<T>,
pub options: ExplainOptions,
}
impl<T: AstInfo> AstDisplay for ExplainStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("EXPLAIN ");
if self.options.timing {
f.write_str("(TIMING ");
f.write_str(self.options.timing);
f.write_str(") ");
}
if self.options.typed {
f.write_str("TYPED ");
}
f.write_node(&self.stage);
f.write_str(" FOR ");
f.write_node(&self.explainee);
}
}
impl_display_t!(ExplainStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InsertSource<T: AstInfo> {
Query(Query<T>),
DefaultValues,
}
impl<T: AstInfo> AstDisplay for InsertSource<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
InsertSource::Query(query) => f.write_node(query),
InsertSource::DefaultValues => f.write_str("DEFAULT VALUES"),
}
}
}
impl_display_t!(InsertSource);
#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
pub enum ObjectType {
Table,
View,
Source,
Sink,
Index,
Type,
Role,
Cluster,
ClusterReplica,
Object,
Secret,
Connector,
}
impl AstDisplay for ObjectType {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str(match self {
ObjectType::Table => "TABLE",
ObjectType::View => "VIEW",
ObjectType::Source => "SOURCE",
ObjectType::Sink => "SINK",
ObjectType::Index => "INDEX",
ObjectType::Type => "TYPE",
ObjectType::Role => "ROLE",
ObjectType::Cluster => "CLUSTER",
ObjectType::ClusterReplica => "CLUSTER REPLICA",
ObjectType::Object => "OBJECT",
ObjectType::Secret => "SECRET",
ObjectType::Connector => "CONNECTOR",
})
}
}
impl_display!(ObjectType);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ShowStatementFilter<T: AstInfo> {
Like(String),
Where(Expr<T>),
}
impl<T: AstInfo> AstDisplay for ShowStatementFilter<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
use ShowStatementFilter::*;
match self {
Like(pattern) => {
f.write_str("LIKE '");
f.write_node(&display::escape_single_quote_string(pattern));
f.write_str("'");
}
Where(expr) => {
f.write_str("WHERE ");
f.write_node(expr);
}
}
}
}
impl_display_t!(ShowStatementFilter);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WithOption<T: AstInfo> {
pub key: Ident,
pub value: Option<WithOptionValue<T>>,
}
impl<T: AstInfo> AstDisplay for WithOption<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_node(&self.key);
if let Some(opt) = &self.value {
f.write_str(" = ");
f.write_node(opt);
}
}
}
impl_display_t!(WithOption);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WithOptionValue<T: AstInfo> {
Value(Value),
ObjectName(UnresolvedObjectName),
DataType(T::DataType),
}
impl<T: AstInfo> AstDisplay for WithOptionValue<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
WithOptionValue::Value(value) => f.write_node(value),
WithOptionValue::ObjectName(name) => f.write_node(name),
WithOptionValue::DataType(typ) => f.write_node(typ),
}
}
}
impl_display_t!(WithOptionValue);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TransactionMode {
AccessMode(TransactionAccessMode),
IsolationLevel(TransactionIsolationLevel),
}
impl AstDisplay for TransactionMode {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
use TransactionMode::*;
match self {
AccessMode(access_mode) => f.write_node(access_mode),
IsolationLevel(iso_level) => {
f.write_str("ISOLATION LEVEL ");
f.write_node(iso_level);
}
}
}
}
impl_display!(TransactionMode);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TransactionAccessMode {
ReadOnly,
ReadWrite,
}
impl AstDisplay for TransactionAccessMode {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
use TransactionAccessMode::*;
f.write_str(match self {
ReadOnly => "READ ONLY",
ReadWrite => "READ WRITE",
})
}
}
impl_display!(TransactionAccessMode);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TransactionIsolationLevel {
ReadUncommitted,
ReadCommitted,
RepeatableRead,
Serializable,
}
impl AstDisplay for TransactionIsolationLevel {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
use TransactionIsolationLevel::*;
f.write_str(match self {
ReadUncommitted => "READ UNCOMMITTED",
ReadCommitted => "READ COMMITTED",
RepeatableRead => "REPEATABLE READ",
Serializable => "SERIALIZABLE",
})
}
}
impl_display!(TransactionIsolationLevel);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SetVariableValue {
Ident(Ident),
Literal(Value),
}
impl AstDisplay for SetVariableValue {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
use SetVariableValue::*;
match self {
Ident(ident) => f.write_node(ident),
Literal(literal) => f.write_node(literal),
}
}
}
impl_display!(SetVariableValue);
/// SQL assignment `foo = expr` as used in SQLUpdate
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Assignment<T: AstInfo> {
pub id: Ident,
pub value: Expr<T>,
}
impl<T: AstInfo> AstDisplay for Assignment<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_node(&self.id);
f.write_str(" = ");
f.write_node(&self.value);
}
}
impl_display_t!(Assignment);
/// Specifies what [Statement::Explain] is actually explaining
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExplainStage {
/// The sql::HirRelationExpr after parsing
RawPlan,
/// Query Graph
QueryGraph,
/// Optimized Query Graph
OptimizedQueryGraph,
/// The mz_expr::MirRelationExpr after decorrelation
DecorrelatedPlan,
/// The mz_expr::MirRelationExpr after optimization
OptimizedPlan,
/// The render::plan::Plan
PhysicalPlan,
/// The dependent and selected timestamps
Timestamp,
}
impl AstDisplay for ExplainStage {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
ExplainStage::RawPlan => f.write_str("RAW PLAN"),
ExplainStage::OptimizedQueryGraph => f.write_str("OPTIMIZED QUERY GRAPH"),
ExplainStage::QueryGraph => f.write_str("QUERY GRAPH"),
ExplainStage::DecorrelatedPlan => f.write_str("DECORRELATED PLAN"),
ExplainStage::OptimizedPlan => f.write_str("OPTIMIZED PLAN"),
ExplainStage::PhysicalPlan => f.write_str("PHYSICAL PLAN"),
ExplainStage::Timestamp => f.write_str("TIMESTAMP"),
}
}
}
impl_display!(ExplainStage);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Explainee<T: AstInfo> {
View(T::ObjectName),
Query(Query<T>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExplainOptions {
pub typed: bool,
pub timing: bool,
}
impl<T: AstInfo> AstDisplay for Explainee<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
Self::View(name) => {
f.write_str("VIEW ");
f.write_node(name);
}
Self::Query(query) => f.write_node(query),
}
}
}
impl_display_t!(Explainee);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IfExistsBehavior {
Error,
Skip,
Replace,
}
/// `DECLARE ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DeclareStatement<T: AstInfo> {
pub name: Ident,
pub stmt: Box<Statement<T>>,
}
impl<T: AstInfo> AstDisplay for DeclareStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DECLARE ");
f.write_node(&self.name);
f.write_str(" CURSOR FOR ");
f.write_node(&self.stmt);
}
}
impl_display_t!(DeclareStatement);
/// `CLOSE ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CloseStatement {
pub name: Ident,
}
impl AstDisplay for CloseStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("CLOSE ");
f.write_node(&self.name);
}
}
impl_display!(CloseStatement);
/// `FETCH ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FetchStatement<T: AstInfo> {
pub name: Ident,
pub count: Option<FetchDirection>,
pub options: Vec<WithOption<T>>,
}
impl<T: AstInfo> AstDisplay for FetchStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("FETCH ");
if let Some(ref count) = self.count {
f.write_str(format!("{} ", count));
}
f.write_node(&self.name);
if !self.options.is_empty() {
f.write_str(" WITH (");
f.write_node(&display::comma_separated(&self.options));
f.write_str(")");
}
}
}
impl_display_t!(FetchStatement);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FetchDirection {
ForwardAll,
ForwardCount(u64),
}
impl AstDisplay for FetchDirection {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
match self {
FetchDirection::ForwardAll => f.write_str("ALL"),
FetchDirection::ForwardCount(count) => f.write_str(format!("{}", count)),
}
}
}
impl_display!(FetchDirection);
/// `PREPARE ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PrepareStatement<T: AstInfo> {
pub name: Ident,
pub stmt: Box<Statement<T>>,
}
impl<T: AstInfo> AstDisplay for PrepareStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("PREPARE ");
f.write_node(&self.name);
f.write_str(" AS ");
f.write_node(&self.stmt);
}
}
impl_display_t!(PrepareStatement);
/// `EXECUTE ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExecuteStatement<T: AstInfo> {
pub name: Ident,
pub params: Vec<Expr<T>>,
}
impl<T: AstInfo> AstDisplay for ExecuteStatement<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("EXECUTE ");
f.write_node(&self.name);
if !self.params.is_empty() {
f.write_str(" (");
f.write_node(&display::comma_separated(&self.params));
f.write_str(")");
}
}
}
impl_display_t!(ExecuteStatement);
/// `DEALLOCATE ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DeallocateStatement {
pub name: Option<Ident>,
}
impl AstDisplay for DeallocateStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("DEALLOCATE ");
match &self.name {
Some(name) => f.write_node(name),
None => f.write_str("ALL"),
};
}
}
impl_display!(DeallocateStatement);
/// `RAISE ...`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RaiseStatement {
pub severity: NoticeSeverity,
}
impl AstDisplay for RaiseStatement {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("RAISE ");
f.write_node(&self.severity);
}
}
impl_display!(RaiseStatement);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum NoticeSeverity {
Debug,
Info,
Log,
Notice,
Warning,
}
impl AstDisplay for NoticeSeverity {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str(match self {
NoticeSeverity::Debug => "DEBUG",
NoticeSeverity::Info => "INFO",
NoticeSeverity::Log => "LOG",
NoticeSeverity::Notice => "NOTICE",
NoticeSeverity::Warning => "WARNING",
})
}
}
impl_display!(NoticeSeverity);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AsOf<T: AstInfo> {
At(Expr<T>),
AtLeast(Expr<T>),
}
impl<T: AstInfo> AstDisplay for AsOf<T> {
fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
f.write_str("AS OF ");
match self {
AsOf::At(expr) => f.write_node(expr),
AsOf::AtLeast(expr) => {
f.write_str("AT LEAST ");
f.write_node(expr);
}
}
}
}
impl_display_t!(AsOf);
| 30.439373 | 99 | 0.600276 |
919c7cc67026939eefc1ab1ffb55420bc7ac9e9f | 41,764 | // Generated from definition io.k8s.api.policy.v1beta1.PodDisruptionBudget
/// PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PodDisruptionBudget {
pub metadata: crate::apimachinery::pkg::apis::meta::v1::ObjectMeta,
/// Specification of the desired behavior of the PodDisruptionBudget.
pub spec: Option<crate::api::policy::v1beta1::PodDisruptionBudgetSpec>,
/// Most recently observed status of the PodDisruptionBudget.
pub status: Option<crate::api::policy::v1beta1::PodDisruptionBudgetStatus>,
}
// Begin policy/v1beta1/PodDisruptionBudget
// Generated from operation createPolicyV1beta1NamespacedPodDisruptionBudget
impl PodDisruptionBudget {
/// create a PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::CreateResponse`]`<Self>>` constructor, or [`crate::CreateResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn create_namespaced_pod_disruption_budget(
namespace: &str,
body: &crate::api::policy::v1beta1::PodDisruptionBudget,
optional: crate::CreateOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::CreateResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets?",
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::post(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation deletePolicyV1beta1CollectionNamespacedPodDisruptionBudget
impl PodDisruptionBudget {
/// delete collection of PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::DeleteResponse`]`<`[`crate::List`]`<Self>>>` constructor, or [`crate::DeleteResponse`]`<`[`crate::List`]`<Self>>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `delete_optional`
///
/// Delete options. Use `Default::default()` to not pass any.
///
/// * `list_optional`
///
/// List options. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn delete_collection_namespaced_pod_disruption_budget(
namespace: &str,
delete_optional: crate::DeleteOptional<'_>,
list_optional: crate::ListOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::DeleteResponse<crate::List<Self>>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets?",
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
list_optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::delete(__url);
let __body = crate::serde_json::to_vec(&delete_optional).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation deletePolicyV1beta1NamespacedPodDisruptionBudget
impl PodDisruptionBudget {
/// delete a PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::DeleteResponse`]`<Self>>` constructor, or [`crate::DeleteResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the PodDisruptionBudget
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn delete_namespaced_pod_disruption_budget(
name: &str,
namespace: &str,
optional: crate::DeleteOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::DeleteResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets/{name}",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let __request = crate::http::Request::delete(__url);
let __body = crate::serde_json::to_vec(&optional).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation listPolicyV1beta1NamespacedPodDisruptionBudget
impl PodDisruptionBudget {
/// list or watch objects of kind PodDisruptionBudget
///
/// This operation only supports listing all items of this type.
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::ListResponse`]`<Self>>` constructor, or [`crate::ListResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn list_namespaced_pod_disruption_budget(
namespace: &str,
optional: crate::ListOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::ListResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets?",
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation listPolicyV1beta1PodDisruptionBudgetForAllNamespaces
impl PodDisruptionBudget {
/// list or watch objects of kind PodDisruptionBudget
///
/// This operation only supports listing all items of this type.
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::ListResponse`]`<Self>>` constructor, or [`crate::ListResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn list_pod_disruption_budget_for_all_namespaces(
optional: crate::ListOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::ListResponse<Self>>), crate::RequestError> {
let __url = "/apis/policy/v1beta1/poddisruptionbudgets?".to_owned();
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation patchPolicyV1beta1NamespacedPodDisruptionBudget
impl PodDisruptionBudget {
/// partially update the specified PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::PatchResponse`]`<Self>>` constructor, or [`crate::PatchResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the PodDisruptionBudget
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn patch_namespaced_pod_disruption_budget(
name: &str,
namespace: &str,
body: &crate::apimachinery::pkg::apis::meta::v1::Patch,
optional: crate::PatchOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::PatchResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets/{name}?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::patch(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static(match body {
crate::apimachinery::pkg::apis::meta::v1::Patch::Json(_) => "application/json-patch+json",
crate::apimachinery::pkg::apis::meta::v1::Patch::Merge(_) => "application/merge-patch+json",
crate::apimachinery::pkg::apis::meta::v1::Patch::StrategicMerge(_) => "application/strategic-merge-patch+json",
}));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation patchPolicyV1beta1NamespacedPodDisruptionBudgetStatus
impl PodDisruptionBudget {
/// partially update status of the specified PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::PatchResponse`]`<Self>>` constructor, or [`crate::PatchResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the PodDisruptionBudget
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn patch_namespaced_pod_disruption_budget_status(
name: &str,
namespace: &str,
body: &crate::apimachinery::pkg::apis::meta::v1::Patch,
optional: crate::PatchOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::PatchResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets/{name}/status?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::patch(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static(match body {
crate::apimachinery::pkg::apis::meta::v1::Patch::Json(_) => "application/json-patch+json",
crate::apimachinery::pkg::apis::meta::v1::Patch::Merge(_) => "application/merge-patch+json",
crate::apimachinery::pkg::apis::meta::v1::Patch::StrategicMerge(_) => "application/strategic-merge-patch+json",
}));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation readPolicyV1beta1NamespacedPodDisruptionBudget
impl PodDisruptionBudget {
/// read the specified PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`ReadNamespacedPodDisruptionBudgetResponse`]`>` constructor, or [`ReadNamespacedPodDisruptionBudgetResponse`] directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the PodDisruptionBudget
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn read_namespaced_pod_disruption_budget(
name: &str,
namespace: &str,
optional: ReadNamespacedPodDisruptionBudgetOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<ReadNamespacedPodDisruptionBudgetResponse>), crate::RequestError> {
let ReadNamespacedPodDisruptionBudgetOptional {
exact,
export,
pretty,
} = optional;
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets/{name}?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
if let Some(exact) = exact {
__query_pairs.append_pair("exact", &exact.to_string());
}
if let Some(export) = export {
__query_pairs.append_pair("export", &export.to_string());
}
if let Some(pretty) = pretty {
__query_pairs.append_pair("pretty", pretty);
}
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
/// Optional parameters of [`PodDisruptionBudget::read_namespaced_pod_disruption_budget`]
#[cfg(feature = "api")]
#[derive(Clone, Copy, Debug, Default)]
pub struct ReadNamespacedPodDisruptionBudgetOptional<'a> {
/// Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18.
pub exact: Option<bool>,
/// Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18.
pub export: Option<bool>,
/// If 'true', then the output is pretty printed.
pub pretty: Option<&'a str>,
}
/// Use `<ReadNamespacedPodDisruptionBudgetResponse as Response>::try_from_parts` to parse the HTTP response body of [`PodDisruptionBudget::read_namespaced_pod_disruption_budget`]
#[cfg(feature = "api")]
#[derive(Debug)]
pub enum ReadNamespacedPodDisruptionBudgetResponse {
Ok(crate::api::policy::v1beta1::PodDisruptionBudget),
Other(Result<Option<crate::serde_json::Value>, crate::serde_json::Error>),
}
#[cfg(feature = "api")]
impl crate::Response for ReadNamespacedPodDisruptionBudgetResponse {
fn try_from_parts(status_code: crate::http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> {
match status_code {
crate::http::StatusCode::OK => {
let result = match crate::serde_json::from_slice(buf) {
Ok(value) => value,
Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => return Err(crate::ResponseError::Json(err)),
};
Ok((ReadNamespacedPodDisruptionBudgetResponse::Ok(result), buf.len()))
},
_ => {
let (result, read) =
if buf.is_empty() {
(Ok(None), 0)
}
else {
match crate::serde_json::from_slice(buf) {
Ok(value) => (Ok(Some(value)), buf.len()),
Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => (Err(err), 0),
}
};
Ok((ReadNamespacedPodDisruptionBudgetResponse::Other(result), read))
},
}
}
}
// Generated from operation readPolicyV1beta1NamespacedPodDisruptionBudgetStatus
impl PodDisruptionBudget {
/// read status of the specified PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`ReadNamespacedPodDisruptionBudgetStatusResponse`]`>` constructor, or [`ReadNamespacedPodDisruptionBudgetStatusResponse`] directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the PodDisruptionBudget
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn read_namespaced_pod_disruption_budget_status(
name: &str,
namespace: &str,
optional: ReadNamespacedPodDisruptionBudgetStatusOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<ReadNamespacedPodDisruptionBudgetStatusResponse>), crate::RequestError> {
let ReadNamespacedPodDisruptionBudgetStatusOptional {
pretty,
} = optional;
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets/{name}/status?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
if let Some(pretty) = pretty {
__query_pairs.append_pair("pretty", pretty);
}
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
/// Optional parameters of [`PodDisruptionBudget::read_namespaced_pod_disruption_budget_status`]
#[cfg(feature = "api")]
#[derive(Clone, Copy, Debug, Default)]
pub struct ReadNamespacedPodDisruptionBudgetStatusOptional<'a> {
/// If 'true', then the output is pretty printed.
pub pretty: Option<&'a str>,
}
/// Use `<ReadNamespacedPodDisruptionBudgetStatusResponse as Response>::try_from_parts` to parse the HTTP response body of [`PodDisruptionBudget::read_namespaced_pod_disruption_budget_status`]
#[cfg(feature = "api")]
#[derive(Debug)]
pub enum ReadNamespacedPodDisruptionBudgetStatusResponse {
Ok(crate::api::policy::v1beta1::PodDisruptionBudget),
Other(Result<Option<crate::serde_json::Value>, crate::serde_json::Error>),
}
#[cfg(feature = "api")]
impl crate::Response for ReadNamespacedPodDisruptionBudgetStatusResponse {
fn try_from_parts(status_code: crate::http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> {
match status_code {
crate::http::StatusCode::OK => {
let result = match crate::serde_json::from_slice(buf) {
Ok(value) => value,
Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => return Err(crate::ResponseError::Json(err)),
};
Ok((ReadNamespacedPodDisruptionBudgetStatusResponse::Ok(result), buf.len()))
},
_ => {
let (result, read) =
if buf.is_empty() {
(Ok(None), 0)
}
else {
match crate::serde_json::from_slice(buf) {
Ok(value) => (Ok(Some(value)), buf.len()),
Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => (Err(err), 0),
}
};
Ok((ReadNamespacedPodDisruptionBudgetStatusResponse::Other(result), read))
},
}
}
}
// Generated from operation replacePolicyV1beta1NamespacedPodDisruptionBudget
impl PodDisruptionBudget {
/// replace the specified PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::ReplaceResponse`]`<Self>>` constructor, or [`crate::ReplaceResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the PodDisruptionBudget
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn replace_namespaced_pod_disruption_budget(
name: &str,
namespace: &str,
body: &crate::api::policy::v1beta1::PodDisruptionBudget,
optional: crate::ReplaceOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets/{name}?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::put(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation replacePolicyV1beta1NamespacedPodDisruptionBudgetStatus
impl PodDisruptionBudget {
/// replace status of the specified PodDisruptionBudget
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::ReplaceResponse`]`<Self>>` constructor, or [`crate::ReplaceResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the PodDisruptionBudget
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn replace_namespaced_pod_disruption_budget_status(
name: &str,
namespace: &str,
body: &crate::api::policy::v1beta1::PodDisruptionBudget,
optional: crate::ReplaceOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets/{name}/status?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::put(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation watchPolicyV1beta1NamespacedPodDisruptionBudget
impl PodDisruptionBudget {
/// list or watch objects of kind PodDisruptionBudget
///
/// This operation only supports watching one item, or a list of items, of this type for changes.
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::WatchResponse`]`<Self>>` constructor, or [`crate::WatchResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn watch_namespaced_pod_disruption_budget(
namespace: &str,
optional: crate::WatchOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::WatchResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/policy/v1beta1/namespaces/{namespace}/poddisruptionbudgets?",
namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation watchPolicyV1beta1PodDisruptionBudgetForAllNamespaces
impl PodDisruptionBudget {
/// list or watch objects of kind PodDisruptionBudget
///
/// This operation only supports watching one item, or a list of items, of this type for changes.
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::WatchResponse`]`<Self>>` constructor, or [`crate::WatchResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn watch_pod_disruption_budget_for_all_namespaces(
optional: crate::WatchOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::WatchResponse<Self>>), crate::RequestError> {
let __url = "/apis/policy/v1beta1/poddisruptionbudgets?".to_owned();
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// End policy/v1beta1/PodDisruptionBudget
impl crate::Resource for PodDisruptionBudget {
const API_VERSION: &'static str = "policy/v1beta1";
const GROUP: &'static str = "policy";
const KIND: &'static str = "PodDisruptionBudget";
const VERSION: &'static str = "v1beta1";
const URL_PATH_SEGMENT: &'static str = "poddisruptionbudgets";
type Scope = crate::NamespaceResourceScope;
}
impl crate::ListableResource for PodDisruptionBudget {
const LIST_KIND: &'static str = "PodDisruptionBudgetList";
}
impl crate::Metadata for PodDisruptionBudget {
type Ty = crate::apimachinery::pkg::apis::meta::v1::ObjectMeta;
fn metadata(&self) -> &<Self as crate::Metadata>::Ty {
&self.metadata
}
fn metadata_mut(&mut self) -> &mut<Self as crate::Metadata>::Ty {
&mut self.metadata
}
}
impl<'de> crate::serde::Deserialize<'de> for PodDisruptionBudget {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_api_version,
Key_kind,
Key_metadata,
Key_spec,
Key_status,
Other,
}
impl<'de> crate::serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: crate::serde::de::Error {
Ok(match v {
"apiVersion" => Field::Key_api_version,
"kind" => Field::Key_kind,
"metadata" => Field::Key_metadata,
"spec" => Field::Key_spec,
"status" => Field::Key_status,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = PodDisruptionBudget;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(<Self::Value as crate::Resource>::KIND)
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: crate::serde::de::MapAccess<'de> {
let mut value_metadata: Option<crate::apimachinery::pkg::apis::meta::v1::ObjectMeta> = None;
let mut value_spec: Option<crate::api::policy::v1beta1::PodDisruptionBudgetSpec> = None;
let mut value_status: Option<crate::api::policy::v1beta1::PodDisruptionBudgetStatus> = None;
while let Some(key) = crate::serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_api_version => {
let value_api_version: String = crate::serde::de::MapAccess::next_value(&mut map)?;
if value_api_version != <Self::Value as crate::Resource>::API_VERSION {
return Err(crate::serde::de::Error::invalid_value(crate::serde::de::Unexpected::Str(&value_api_version), &<Self::Value as crate::Resource>::API_VERSION));
}
},
Field::Key_kind => {
let value_kind: String = crate::serde::de::MapAccess::next_value(&mut map)?;
if value_kind != <Self::Value as crate::Resource>::KIND {
return Err(crate::serde::de::Error::invalid_value(crate::serde::de::Unexpected::Str(&value_kind), &<Self::Value as crate::Resource>::KIND));
}
},
Field::Key_metadata => value_metadata = Some(crate::serde::de::MapAccess::next_value(&mut map)?),
Field::Key_spec => value_spec = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_status => value_status = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: crate::serde::de::IgnoredAny = crate::serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(PodDisruptionBudget {
metadata: value_metadata.ok_or_else(|| crate::serde::de::Error::missing_field("metadata"))?,
spec: value_spec,
status: value_status,
})
}
}
deserializer.deserialize_struct(
<Self as crate::Resource>::KIND,
&[
"apiVersion",
"kind",
"metadata",
"spec",
"status",
],
Visitor,
)
}
}
impl crate::serde::Serialize for PodDisruptionBudget {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: crate::serde::Serializer {
let mut state = serializer.serialize_struct(
<Self as crate::Resource>::KIND,
3 +
self.spec.as_ref().map_or(0, |_| 1) +
self.status.as_ref().map_or(0, |_| 1),
)?;
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "apiVersion", <Self as crate::Resource>::API_VERSION)?;
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "kind", <Self as crate::Resource>::KIND)?;
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "metadata", &self.metadata)?;
if let Some(value) = &self.spec {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "spec", value)?;
}
if let Some(value) = &self.status {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "status", value)?;
}
crate::serde::ser::SerializeStruct::end(state)
}
}
#[cfg(feature = "schemars")]
impl crate::schemars::JsonSchema for PodDisruptionBudget {
fn schema_name() -> String {
"io.k8s.api.policy.v1beta1.PodDisruptionBudget".to_owned()
}
fn json_schema(__gen: &mut crate::schemars::gen::SchemaGenerator) -> crate::schemars::schema::Schema {
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Object))),
object: Some(Box::new(crate::schemars::schema::ObjectValidation {
properties: std::array::IntoIter::new([
(
"apiVersion".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
..Default::default()
}),
),
(
"kind".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
..Default::default()
}),
),
(
"metadata".to_owned(),
__gen.subschema_for::<crate::apimachinery::pkg::apis::meta::v1::ObjectMeta>(),
),
(
"spec".to_owned(),
{
let mut schema_obj = __gen.subschema_for::<crate::api::policy::v1beta1::PodDisruptionBudgetSpec>().into_object();
schema_obj.metadata = Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Specification of the desired behavior of the PodDisruptionBudget.".to_owned()),
..Default::default()
}));
crate::schemars::schema::Schema::Object(schema_obj)
},
),
(
"status".to_owned(),
{
let mut schema_obj = __gen.subschema_for::<crate::api::policy::v1beta1::PodDisruptionBudgetStatus>().into_object();
schema_obj.metadata = Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Most recently observed status of the PodDisruptionBudget.".to_owned()),
..Default::default()
}));
crate::schemars::schema::Schema::Object(schema_obj)
},
),
]).collect(),
required: std::array::IntoIter::new([
"metadata",
]).map(std::borrow::ToOwned::to_owned).collect(),
..Default::default()
})),
..Default::default()
})
}
}
| 46.559643 | 338 | 0.605234 |
793c322270e9bde4fd7814c186e3142421eee1aa | 1,615 | // Copyright 2021 Matthew Callens
//
// 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 anchor_lang::prelude::*;
use crate::error::CustomErrorCode;
use crate::event::ClosedUser;
use crate::{seeds, State, TagHash, User};
#[derive(Accounts)]
#[instruction(tag: TagHash)]
pub struct Deregister<'info> {
#[account(mut)]
pub owner: Signer<'info>,
#[account(
mut,
seeds = [
seeds::STATE
],
bump = state.bump[0],
)]
pub state: Box<Account<'info, State>>,
#[account(
mut,
seeds = [
seeds::USER,
tag.value.as_ref()
],
bump = user.bump[0],
has_one = owner @ CustomErrorCode::OwnerConstraintMismatch,
close = owner,
)]
pub user: Box<Account<'info, User>>,
}
pub fn handler(ctx: Context<Deregister>, _tag: TagHash) -> ProgramResult {
let state = &mut ctx.accounts.state;
state.registered = state.registered.checked_sub(1).unwrap();
emit!(ClosedUser {
pubkey: ctx.accounts.user.key(),
gms: ctx.accounts.user.total,
});
Ok(())
}
| 26.916667 | 75 | 0.635294 |
9bd08d5c4f0f023058e23b2c8bb8606f0de61f51 | 3,718 | extern crate legion;
extern crate legion_transform;
use legion::prelude::*;
use legion_transform::prelude::*;
fn main() {
// Create a normal Legion World
let mut world = Universe::new().create_world();
let mut resources = Resources::default();
// Create a system bundle (vec of systems) for LegionTransform
let mut transform_system_bundle = transform_system_bundle::build(&mut world, &mut resources);
// A user-defined space transform is split into 4 different components: [`Translation`,
// `Rotation`, `Scale`, `NonUniformScale`]. Any combination of these components can be added to
// an entity to transform it's space (exception: `Scale` and `NonUniformScale` are mutually
// exclusive).
// Note that all entities need an explicitly added `LocalToWorld` component to be considered for
// processing during transform system passes.
// Add an entity with just a Translation
// See: https://www.nalgebra.org/rustdoc/nalgebra/geometry/struct.Translation.html
// API on Translation, as a LegionTransform `Translation` is just a nalgebra `Translation3`.
world.insert(
(),
vec![(LocalToWorld::identity(), Translation::new(1.0, 2.0, 3.0))],
);
// Add an entity with just a Rotation.
// See: https://www.nalgebra.org/rustdoc/nalgebra/geometry/type.UnitQuaternion.html for the full
// API on Rotation, as a LegionTransform `Rotation` is just a nalgebra `UnityQuaternion`.
world.insert(
(),
vec![(
LocalToWorld::identity(),
Rotation::from_euler_angles(3.14, 0.0, 0.0),
)],
);
// Add an entity with just a uniform Scale (the default and strongly-preferred scale component).
// This is simply a `f32` wrapper.
world.insert((), vec![(LocalToWorld::identity(), Scale(2.0))]);
// Add an entity with just a NonUniformScale (This should be avoided unless you **really** need
// non-uniform scaling as it breaks things like physics colliders.
// See: https://docs.rs/nalgebra/0.10.1/nalgebra/struct.Vector3.html for the full API on
// NonUniformScale, as a LegionTransform `NonUniformScale` is simply a nalgebra `Vector3`,
// although note that it is wrapped in a tuple-struct.
world.insert(
(),
vec![(
LocalToWorld::identity(),
NonUniformScale::new(1.0, 2.0, 1.0),
)],
);
// Add an entity with a combination of Translation and Rotation
world.insert(
(),
vec![(
LocalToWorld::identity(),
Translation::new(1.0, 2.0, 3.0),
Rotation::from_euler_angles(3.14, 0.0, 0.0),
)],
);
// Add an entity with a combination of Translation and Rotation and uniform Scale.
world.insert(
(),
vec![(
LocalToWorld::identity(),
Translation::new(1.0, 2.0, 3.0),
Rotation::from_euler_angles(3.14, 0.0, 0.0),
Scale(2.0),
)],
);
// Run the system bundle (this API will likely change).
for system in transform_system_bundle.iter_mut() {
system.run(&mut world, &mut resources);
system
.command_buffer_mut(world.id())
.unwrap()
.write(&mut world);
}
// At this point all `LocalToWorld` components have correct values in them. Running the system
// again will result in a short-circuit as only changed components are considered for update.
let query = <Read<LocalToWorld>>::query();
for (entity, local_to_world) in query.iter_entities(&mut world) {
println!(
"Entity {} and a LocalToWorld matrix: {}",
entity, *local_to_world
);
}
}
| 37.555556 | 100 | 0.631791 |
56fc3d11731fceea7d9c48b08064922d38ff5aaa | 8,246 | // Copyright 2017 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
use std::mem;
use super::Json;
use super::path_expr::{PathExpression, PathLeg};
use super::super::Result;
/// `ModifyType` is for modify a JSON.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ModifyType {
/// `Insert` is for inserting a new element into a JSON.
Insert,
/// `Replace` is for replacing a old element from a JSON.
Replace,
/// `Set` = `Insert` | `Replace`
Set,
}
impl Json {
// Modifies a Json object by insert, replace or set.
// All path expressions cannot contain * or ** wildcard.
// If any error occurs, the input won't be changed.
pub fn modify(
&mut self,
path_expr_list: &[PathExpression],
mut values: Vec<Json>,
mt: ModifyType,
) -> Result<()> {
if path_expr_list.len() != values.len() {
return Err(box_err!("Incorrect parameter count"));
}
for expr in path_expr_list {
if expr.contains_any_asterisk() {
return Err(box_err!("Invalid path expression"));
}
}
for (expr, value) in path_expr_list.iter().zip(values.drain(..)) {
self.set_json(&expr.legs, value, mt);
}
Ok(())
}
// `set_json` is used in Json::modify().
fn set_json(&mut self, path_legs: &[PathLeg], value: Json, mt: ModifyType) {
if path_legs.is_empty() {
match mt {
ModifyType::Replace | ModifyType::Set => {
*self = value;
}
_ => {}
}
return;
}
let (current_leg, sub_path_legs) = (&path_legs[0], &path_legs[1..]);
if let PathLeg::Index(i) = *current_leg {
let base_data = mem::replace(self, Json::None);
let index = i as usize;
// If `base_data` is not an array, we should autowrap it to be an array.
// Then if the length of result array equals to 1, it's unwraped.
let (mut array, wrapped) = match base_data {
Json::Array(array) => (array, false),
_ => (vec![base_data], true),
};
if array.len() > index {
array[index].set_json(sub_path_legs, value, mt);
} else if sub_path_legs.is_empty() && mt != ModifyType::Replace {
// e.g. json_insert('[1, 2, 3]', '$[3]', "x") => '[1, 2, 3, "x"]'
array.push(value);
}
if (array.len() == 1) && wrapped {
*self = array.pop().unwrap();
} else {
*self = Json::Array(array);
}
return;
}
if let PathLeg::Key(ref key) = *current_leg {
if let Json::Object(ref mut map) = *self {
if map.contains_key(key) {
// e.g. json_replace('{"a": 1}', '$.a', 2) => '{"a": 2}'
let v = map.get_mut(key).unwrap();
v.set_json(sub_path_legs, value, mt);
} else if sub_path_legs.is_empty() && mt != ModifyType::Replace {
// e.g. json_insert('{"a": 1}', '$.b', 2) => '{"a": 1, "b": 2}'
map.insert(key.clone(), value);
}
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use super::super::path_expr::parse_json_path_expr;
#[test]
fn test_json_modify() {
let mut test_cases = vec![
(r#"null"#, "$", r#"{}"#, ModifyType::Set, r#"{}"#, true),
(r#"{}"#, "$.a", r#"3"#, ModifyType::Set, r#"{"a": 3}"#, true),
(
r#"{"a": 3}"#,
"$.a",
r#"[]"#,
ModifyType::Replace,
r#"{"a": []}"#,
true,
),
(
r#"{"a": []}"#,
"$.a[0]",
r#"3"#,
ModifyType::Set,
r#"{"a": [3]}"#,
true,
),
(
r#"{"a": [3]}"#,
"$.a[1]",
r#"4"#,
ModifyType::Insert,
r#"{"a": [3, 4]}"#,
true,
),
(
r#"{"a": [3]}"#,
"$[0]",
r#"4"#,
ModifyType::Set,
r#"4"#,
true,
),
(
r#"{"a": [3]}"#,
"$[1]",
r#"4"#,
ModifyType::Set,
r#"[{"a": [3]}, 4]"#,
true,
),
// Nothing changed because the path is empty and we want to insert.
(r#"{}"#, "$", r#"1"#, ModifyType::Insert, r#"{}"#, true),
// Nothing changed because the path without last leg doesn't exist.
(
r#"{"a": [3, 4]}"#,
"$.b[1]",
r#"3"#,
ModifyType::Set,
r#"{"a": [3, 4]}"#,
true,
),
// Nothing changed because the path without last leg doesn't exist.
(
r#"{"a": [3, 4]}"#,
"$.a[2].b",
r#"3"#,
ModifyType::Set,
r#"{"a": [3, 4]}"#,
true,
),
// Nothing changed because we want to insert but the full path exists.
(
r#"{"a": [3, 4]}"#,
"$.a[0]",
r#"30"#,
ModifyType::Insert,
r#"{"a": [3, 4]}"#,
true,
),
// Nothing changed because we want to replace but the full path doesn't exist.
(
r#"{"a": [3, 4]}"#,
"$.a[2]",
r#"30"#,
ModifyType::Replace,
r#"{"a": [3, 4]}"#,
true,
),
// Bad path expression.
(r#"null"#, "$.*", r#"{}"#, ModifyType::Set, r#"null"#, false),
(
r#"null"#,
"$[*]",
r#"{}"#,
ModifyType::Set,
r#"null"#,
false,
),
(
r#"null"#,
"$**.a",
r#"{}"#,
ModifyType::Set,
r#"null"#,
false,
),
(
r#"null"#,
"$**[3]",
r#"{}"#,
ModifyType::Set,
r#"null"#,
false,
),
];
for (i, (json, path, value, mt, expected, success)) in test_cases.drain(..).enumerate() {
let j: Result<Json> = json.parse();
assert!(j.is_ok(), "#{} expect json parse ok but got {:?}", i, j);
let p = parse_json_path_expr(path);
assert!(p.is_ok(), "#{} expect path parse ok but got {:?}", i, p);
let v = value.parse();
assert!(v.is_ok(), "#{} expect value parse ok but got {:?}", i, v);
let e: Result<Json> = expected.parse();
assert!(
e.is_ok(),
"#{} expect expected value parse ok but got {:?}",
i,
e
);
let (mut j, p, v, e) = (j.unwrap(), p.unwrap(), v.unwrap(), e.unwrap());
let r = j.modify(vec![p].as_slice(), vec![v], mt);
if success {
assert!(r.is_ok(), "#{} expect modify ok but got {:?}", i, r);
} else {
assert!(r.is_err(), "#{} expect modify error but got {:?}", i, r);
}
assert_eq!(e, j, "#{} expect modified json {:?} == {:?}", i, j, e);
}
}
}
| 33.384615 | 97 | 0.401407 |
e62e2cebca164be8824a41a3894fb1a0587a89f5 | 2,107 |
pub struct IconClosedCaptionOff {
props: crate::Props,
}
impl yew::Component for IconClosedCaptionOff {
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" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><g enable-background="new"><g><path d="M19,6H5v12h14V6z M11,11H9.5v-0.5h-2v3h2V13H11v1c0,0.55-0.45,1-1,1H7 c-0.55,0-1-0.45-1-1v-4c0-0.55,0.45-1,1-1h3c0.55,0,1,0.45,1,1V11z M18,11h-1.5v-0.5h-2v3h2V13H18v1c0,0.55-0.45,1-1,1h-3 c-0.55,0-1-0.45-1-1v-4c0-0.55,0.45-1,1-1h3c0.55,0,1,0.45,1,1V11z" enable-background="new" opacity=".3"/><path d="M5,20h14c1.1,0,2-0.9,2-2V6c0-1.1-0.9-2-2-2H5C3.89,4,3,4.9,3,6v12C3,19.1,3.89,20,5,20z M5,6h14v12H5V6z"/><path d="M10,9H7c-0.55,0-1,0.45-1,1v4c0,0.55,0.45,1,1,1h3c0.55,0,1-0.45,1-1v-1H9.5v0.5h-2v-3h2V11H11v-1C11,9.45,10.55,9,10,9z"/><path d="M17,9h-3c-0.55,0-1,0.45-1,1v4c0,0.55,0.45,1,1,1h3c0.55,0,1-0.45,1-1v-1h-1.5v0.5h-2v-3h2V11H18v-1 C18,9.45,17.55,9,17,9z"/></g></g></g></svg>
</svg>
}
}
}
| 45.804348 | 900 | 0.602278 |
50364d0b35602f6f63e77f78a7a02d965acf0d88 | 1,137 | mod backend;
mod frontend;
use backend::execute_program;
use frontend::instruction;
use std::{collections::HashMap, env, fs, path::Path};
use crate::backend::ExecutionContext;
use nom::{
error::{convert_error, VerboseError},
Err,
};
fn main() {
// Read contents of the file
let file_name = env::args().nth(1).expect("Introduceti numele fisierului!");
let path = Path::new(&file_name);
let mut i = fs::read_to_string(path).expect("Fisier invalid!");
i.insert(0, '\n');
let i: &str = &i;
// Parse the contents of the file
let result = instruction::program::<VerboseError<&str>>(i);
let (_, program) = result.unwrap_or_else(|e| {
if let Err::Error(e) | Err::Failure(e) = e {
let error_message = convert_error(i, e);
panic!("{}", error_message);
};
panic!("Programul nu este valid!");
});
dbg!(&program);
// Execute the program
let mut execution_context = ExecutionContext {
integers: HashMap::new(),
};
println!("Se executa...");
execute_program(&program, &mut execution_context);
println!("Gata!");
}
| 27.071429 | 80 | 0.613017 |
3971b4eb3fdea759de0c8aefdfd4a538db5709f9 | 1,347 | use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::{ready, TryFuture};
use pin_project::pin_project;
use super::{Filter, FilterBase, Func, Internal};
#[derive(Clone, Copy, Debug)]
pub struct Map<T, F> {
pub(super) filter: T,
pub(super) callback: F,
}
impl<T, F> FilterBase for Map<T, F>
where
T: Filter,
F: Func<T::Extract> + Clone + Send,
{
type Extract = (F::Output,);
type Error = T::Error;
type Future = MapFuture<T, F>;
#[inline]
fn filter(&self, _: Internal) -> Self::Future {
MapFuture {
extract: self.filter.filter(Internal),
callback: self.callback.clone(),
}
}
}
#[allow(missing_debug_implementations)]
#[pin_project]
pub struct MapFuture<T: Filter, F> {
#[pin]
extract: T::Future,
callback: F,
}
impl<T, F> Future for MapFuture<T, F>
where
T: Filter,
F: Func<T::Extract>,
{
type Output = Result<(F::Output,), T::Error>;
#[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let pin = self.project();
match ready!(pin.extract.try_poll(cx)) {
Ok(ex) => {
let ex = (pin.callback.call(ex),);
Poll::Ready(Ok(ex))
}
Err(err) => Poll::Ready(Err(err)),
}
}
}
| 22.45 | 79 | 0.55902 |
9ca036720cf5f9c9bcbbaa05a0df074f6224497f | 6,115 | mod edit_chat_invite_link;
pub use edit_chat_invite_link::EditChatInviteLinkBuilder;
mod unban_chat_sender_chat;
pub use unban_chat_sender_chat::UnbanChatSenderChatBuilder;
mod revoke_chat_invite_link;
pub use revoke_chat_invite_link::RevokeChatInviteLinkBuilder;
mod edit_message_reply_markup;
pub use edit_message_reply_markup::EditMessageReplyMarkupBuilder;
mod delete_chat_sticker_set;
pub use delete_chat_sticker_set::DeleteChatStickerSetBuilder;
mod send_message;
pub use send_message::SendMessageBuilder;
mod send_sticker;
pub use send_sticker::SendStickerBuilder;
mod delete_sticker_from_set;
pub use delete_sticker_from_set::DeleteStickerFromSetBuilder;
mod send_video_note;
pub use send_video_note::SendVideoNoteBuilder;
mod unpin_all_chat_messages;
pub use unpin_all_chat_messages::UnpinAllChatMessagesBuilder;
mod answer_callback_query;
pub use answer_callback_query::AnswerCallbackQueryBuilder;
mod send_contact;
pub use send_contact::SendContactBuilder;
mod send_chat_action;
pub use send_chat_action::SendChatActionBuilder;
mod delete_chat_photo;
pub use delete_chat_photo::DeleteChatPhotoBuilder;
mod send_poll;
pub use send_poll::SendPollBuilder;
mod get_user_profile_photos;
pub use get_user_profile_photos::GetUserProfilePhotosBuilder;
mod get_sticker_set;
pub use get_sticker_set::GetStickerSetBuilder;
mod answer_inline_query;
pub use answer_inline_query::AnswerInlineQueryBuilder;
mod get_my_commands;
pub use get_my_commands::GetMyCommandsBuilder;
mod edit_message_text;
pub use edit_message_text::EditMessageTextBuilder;
mod close;
pub use close::CloseBuilder;
mod delete_message;
pub use delete_message::DeleteMessageBuilder;
mod answer_pre_checkout_query;
pub use answer_pre_checkout_query::AnswerPreCheckoutQueryBuilder;
mod send_game;
pub use send_game::SendGameBuilder;
mod stop_message_live_location;
pub use stop_message_live_location::StopMessageLiveLocationBuilder;
mod get_updates;
pub use get_updates::GetUpdatesBuilder;
mod leave_chat;
pub use leave_chat::LeaveChatBuilder;
mod promote_chat_member;
pub use promote_chat_member::PromoteChatMemberBuilder;
mod log_out;
pub use log_out::LogOutBuilder;
mod stop_poll;
pub use stop_poll::StopPollBuilder;
mod edit_message_caption;
pub use edit_message_caption::EditMessageCaptionBuilder;
mod create_new_sticker_set;
pub use create_new_sticker_set::CreateNewStickerSetBuilder;
mod restrict_chat_member;
pub use restrict_chat_member::RestrictChatMemberBuilder;
mod set_chat_title;
pub use set_chat_title::SetChatTitleBuilder;
mod unban_chat_member;
pub use unban_chat_member::UnbanChatMemberBuilder;
mod decline_chat_join_request;
pub use decline_chat_join_request::DeclineChatJoinRequestBuilder;
mod set_chat_description;
pub use set_chat_description::SetChatDescriptionBuilder;
mod send_audio;
pub use send_audio::SendAudioBuilder;
mod delete_webhook;
pub use delete_webhook::DeleteWebhookBuilder;
mod get_webhook_info;
pub use get_webhook_info::GetWebhookInfoBuilder;
mod forward_message;
pub use forward_message::ForwardMessageBuilder;
mod send_location;
pub use send_location::SendLocationBuilder;
mod copy_message;
pub use copy_message::CopyMessageBuilder;
mod pin_chat_message;
pub use pin_chat_message::PinChatMessageBuilder;
mod set_my_commands;
pub use set_my_commands::SetMyCommandsBuilder;
mod ban_chat_sender_chat;
pub use ban_chat_sender_chat::BanChatSenderChatBuilder;
mod get_me;
pub use get_me::GetMeBuilder;
mod edit_message_media;
pub use edit_message_media::EditMessageMediaBuilder;
mod get_chat_member;
pub use get_chat_member::GetChatMemberBuilder;
mod add_sticker_to_set;
pub use add_sticker_to_set::AddStickerToSetBuilder;
mod set_webhook;
pub use set_webhook::SetWebhookBuilder;
mod set_sticker_position_in_set;
pub use set_sticker_position_in_set::SetStickerPositionInSetBuilder;
mod set_sticker_set_thumb;
pub use set_sticker_set_thumb::SetStickerSetThumbBuilder;
mod send_invoice;
pub use send_invoice::SendInvoiceBuilder;
mod answer_shipping_query;
pub use answer_shipping_query::AnswerShippingQueryBuilder;
mod send_voice;
pub use send_voice::SendVoiceBuilder;
mod send_document;
pub use send_document::SendDocumentBuilder;
mod get_chat_member_count;
pub use get_chat_member_count::GetChatMemberCountBuilder;
mod get_chat_administrators;
pub use get_chat_administrators::GetChatAdministratorsBuilder;
mod ban_chat_member;
pub use ban_chat_member::BanChatMemberBuilder;
mod set_chat_photo;
pub use set_chat_photo::SetChatPhotoBuilder;
mod send_photo;
pub use send_photo::SendPhotoBuilder;
mod get_chat;
pub use get_chat::GetChatBuilder;
mod send_venue;
pub use send_venue::SendVenueBuilder;
mod get_game_high_scores;
pub use get_game_high_scores::GetGameHighScoresBuilder;
mod unpin_chat_message;
pub use unpin_chat_message::UnpinChatMessageBuilder;
mod send_media_group;
pub use send_media_group::SendMediaGroupBuilder;
mod set_chat_sticker_set;
pub use set_chat_sticker_set::SetChatStickerSetBuilder;
mod export_chat_invite_link;
pub use export_chat_invite_link::ExportChatInviteLinkBuilder;
mod set_chat_permissions;
pub use set_chat_permissions::SetChatPermissionsBuilder;
mod edit_message_live_location;
pub use edit_message_live_location::EditMessageLiveLocationBuilder;
mod send_video;
pub use send_video::SendVideoBuilder;
mod upload_sticker_file;
pub use upload_sticker_file::UploadStickerFileBuilder;
mod set_passport_data_errors;
pub use set_passport_data_errors::SetPassportDataErrorsBuilder;
mod send_dice;
pub use send_dice::SendDiceBuilder;
mod set_chat_administrator_custom_title;
pub use set_chat_administrator_custom_title::SetChatAdministratorCustomTitleBuilder;
mod create_chat_invite_link;
pub use create_chat_invite_link::CreateChatInviteLinkBuilder;
mod approve_chat_join_request;
pub use approve_chat_join_request::ApproveChatJoinRequestBuilder;
mod get_file;
pub use get_file::GetFileBuilder;
mod send_animation;
pub use send_animation::SendAnimationBuilder;
mod delete_my_commands;
pub use delete_my_commands::DeleteMyCommandsBuilder;
mod set_game_score;
pub use set_game_score::SetGameScoreBuilder;
| 24.857724 | 84 | 0.866067 |
1dd196d35eb1f2b33be298bdf80de6c83d6ab32e | 5,477 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::chained_bft::{common::Round, consensus_types::vote_data::VoteData};
use crypto::{
hash::{CryptoHash, ACCUMULATOR_PLACEHOLDER_HASH, GENESIS_BLOCK_ID},
HashValue,
};
use failure::{Result, ResultExt};
use network::proto::QuorumCert as ProtoQuorumCert;
use proto_conv::{FromProto, IntoProto};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
fmt::{Display, Formatter},
};
use types::{
crypto_proxies::{LedgerInfoWithSignatures, ValidatorSigner, ValidatorVerifier},
ledger_info::LedgerInfo,
};
#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq)]
pub struct QuorumCert {
/// The vote information certified by the quorum.
vote_data: VoteData,
/// The signed LedgerInfo of a committed block that carries the data about the certified block.
signed_ledger_info: LedgerInfoWithSignatures,
}
impl Display for QuorumCert {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(
f,
"QuorumCert: [{}, {}]",
self.vote_data, self.signed_ledger_info
)
}
}
impl QuorumCert {
pub fn new(vote_data: VoteData, signed_ledger_info: LedgerInfoWithSignatures) -> Self {
QuorumCert {
vote_data,
signed_ledger_info,
}
}
/// All the vote data getters are just proxies for retrieving the values from the VoteData
pub fn certified_block_id(&self) -> HashValue {
self.vote_data.block_id()
}
pub fn certified_state_id(&self) -> HashValue {
self.vote_data.executed_state_id()
}
pub fn certified_block_round(&self) -> Round {
self.vote_data.block_round()
}
pub fn parent_block_id(&self) -> HashValue {
self.vote_data.parent_block_id()
}
pub fn parent_block_round(&self) -> Round {
self.vote_data.parent_block_round()
}
pub fn grandparent_block_id(&self) -> HashValue {
self.vote_data.grandparent_block_id()
}
pub fn grandparent_block_round(&self) -> Round {
self.vote_data.grandparent_block_round()
}
pub fn ledger_info(&self) -> &LedgerInfoWithSignatures {
&self.signed_ledger_info
}
pub fn committed_block_id(&self) -> Option<HashValue> {
let id = self.ledger_info().ledger_info().consensus_block_id();
if id.is_zero() {
None
} else {
Some(id)
}
}
/// QuorumCert for the genesis block:
/// - the ID of the block is predetermined by the `GENESIS_BLOCK_ID` constant.
/// - the accumulator root hash of the LedgerInfo is set to `ACCUMULATOR_PLACEHOLDER_HASH`
/// constant.
/// - the map of signatures is empty because genesis block is implicitly agreed.
pub fn certificate_for_genesis() -> QuorumCert {
let genesis_digest = VoteData::vote_digest(
*GENESIS_BLOCK_ID,
*ACCUMULATOR_PLACEHOLDER_HASH,
0,
*GENESIS_BLOCK_ID,
0,
*GENESIS_BLOCK_ID,
0,
);
let signer = ValidatorSigner::genesis();
let li = LedgerInfo::new(
0,
*ACCUMULATOR_PLACEHOLDER_HASH,
genesis_digest,
*GENESIS_BLOCK_ID,
0,
0,
None,
);
let signature = signer
.sign_message(li.hash())
.expect("Fail to sign genesis ledger info");
let mut signatures = HashMap::new();
signatures.insert(signer.author(), signature);
QuorumCert::new(
VoteData::new(
*GENESIS_BLOCK_ID,
*ACCUMULATOR_PLACEHOLDER_HASH,
0,
*GENESIS_BLOCK_ID,
0,
*GENESIS_BLOCK_ID,
0,
),
LedgerInfoWithSignatures::new(li, signatures),
)
}
pub fn verify(&self, validator: &ValidatorVerifier) -> failure::Result<()> {
let vote_hash = self.vote_data.hash();
ensure!(
self.ledger_info().ledger_info().consensus_data_hash() == vote_hash,
"Quorum Cert's hash mismatch LedgerInfo"
);
// Genesis is implicitly agreed upon, it doesn't have real signatures.
if self.vote_data.block_round() == 0
&& self.vote_data.block_id() == *GENESIS_BLOCK_ID
&& self.vote_data.executed_state_id() == *ACCUMULATOR_PLACEHOLDER_HASH
{
return Ok(());
}
self.ledger_info()
.verify(validator)
.with_context(|e| format!("Fail to verify QuorumCert: {:?}", e))?;
Ok(())
}
}
impl IntoProto for QuorumCert {
type ProtoType = ProtoQuorumCert;
fn into_proto(self) -> Self::ProtoType {
let mut proto = Self::ProtoType::new();
proto.set_vote_data(self.vote_data.into_proto());
proto.set_signed_ledger_info(self.signed_ledger_info.into_proto());
proto
}
}
impl FromProto for QuorumCert {
type ProtoType = ProtoQuorumCert;
fn from_proto(mut object: Self::ProtoType) -> Result<Self> {
let vote_data = VoteData::from_proto(object.take_vote_data())?;
let signed_ledger_info =
LedgerInfoWithSignatures::from_proto(object.take_signed_ledger_info())?;
Ok(QuorumCert {
vote_data,
signed_ledger_info,
})
}
}
| 30.943503 | 99 | 0.608727 |
ab80025ce60daac94642f09788c1554f8a56129d | 581 | // move_semantics3.rs
// Make me compile without adding new lines-- just changing existing lines!
// (no lines with multiple semicolons necessary!)
// Execute `rustlings hint move_semantics3` for hints :)
fn main() {
let mut vec0 = Vec::new();
let mut vec1 = fill_vec(&mut vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec:&mut Vec<i32>) -> &mut Vec<i32> {
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
| 22.346154 | 75 | 0.604131 |
d5ec1f2abbe096774d28d307703c4c8dcbe0e390 | 5,258 | use maze_lib::grid::Grid;
use maze_lib::{mazegen, pathfinding};
use rand::SeedableRng;
use rand_xorshift::XorShiftRng;
use std::io::Write;
use wasm_bindgen::prelude::*;
pub struct MazeApp {
grid: Grid,
}
static mut MAZE_APP: Option<MazeApp> = None;
#[wasm_bindgen]
pub fn app_init() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
unsafe {
MAZE_APP = Some(MazeApp {
grid: Grid::new(12, 12),
})
};
}
const DIAG_PATH: u8 = 0x07;
#[wasm_bindgen]
pub struct PfDataWasm {
path: Box<[usize]>,
diag: FinalizedDiagMapWasm,
pub nodes_generated: usize,
pub nodes_expanded: usize,
}
#[wasm_bindgen]
impl PfDataWasm {
pub fn path(&self) -> Box<[usize]> {
self.path.clone()
}
pub fn diag(&self) -> FinalizedDiagMapWasm {
self.diag.clone()
}
}
#[wasm_bindgen]
#[derive(Clone)]
pub struct FinalizedDiagMapWasm {
inner: Box<[u8]>,
generated_history: Box<[usize]>,
expanded_history: Box<[usize]>,
num_generated_history: Box<[u8]>,
}
#[wasm_bindgen]
impl FinalizedDiagMapWasm {
pub fn inner(&self) -> Box<[u8]> {
self.inner.clone()
}
pub fn generated_history(&self) -> Box<[usize]> {
self.generated_history.clone()
}
pub fn expanded_history(&self) -> Box<[usize]> {
self.expanded_history.clone()
}
pub fn num_generated_history(&self) -> Box<[u8]> {
self.num_generated_history.clone()
}
}
#[wasm_bindgen]
pub fn pathfind(start: usize, goal: usize, pathfind_algo: &str) -> PfDataWasm {
let app = unsafe { MAZE_APP.as_ref().unwrap() };
let pf_data = match pathfind_algo {
"UniformCostSearch" => pathfinding::algos::a_star(&app.grid, pathfinding::heuristics::null_h, start, goal, false),
"AStar" => pathfinding::algos::a_star(&app.grid, pathfinding::heuristics::manhattan_h, start, goal, false),
"GreedyBestFirst" => {
pathfinding::algos::a_star(&app.grid, pathfinding::heuristics::manhattan_h, start, goal, true)
}
"DepthFirstSearch" => pathfinding::algos::dfs(&app.grid, start, goal),
_ => panic!("Got a bad pathfinding algo from JS"),
}
.unwrap();
let mut pf_data_wasm: PfDataWasm = unsafe { std::mem::transmute(pf_data) };
for i in pf_data_wasm.path.iter() {
let i = *i as usize;
pf_data_wasm.diag.inner[i] = DIAG_PATH;
}
pf_data_wasm
}
#[wasm_bindgen]
pub fn djikstra(start: usize) -> Box<[u32]> {
let app = unsafe { MAZE_APP.as_ref().unwrap() };
let best_paths = pathfinding::algos::djikstra(&app.grid, start);
let longest_path = *best_paths.iter().max().unwrap();
let mut rgb_data = vec![0u32; best_paths.len()].into_boxed_slice();
for (rgb, path_len) in rgb_data.iter_mut().zip(best_paths.iter()) {
let intensity = (longest_path - *path_len) as f64 / longest_path as f64;
let dark = (255.0 * intensity).round() as u32;
let bright = 128 + (127.0 * intensity) as u32;
*rgb = dark << 16 | bright << 8 | dark;
}
rgb_data
}
#[wasm_bindgen]
pub fn change_grid(width: usize, height: usize) -> String {
let app = unsafe { MAZE_APP.as_mut().unwrap() };
let mut result = Vec::new();
app.grid = Grid::new(width, height);
writeln!(
result,
"<svg viewBox=\"-3 -3 {} {}\" xmlns=\"http://www.w3.org/2000/svg\">",
(app.grid.width * 3) + 6,
(app.grid.height * 3) + 6,
)
.unwrap();
writeln!(result, "<g id=\"g_skele\">").unwrap();
app.grid.write_skeleton_as_svg(&mut result).unwrap();
writeln!(result, "</g>").unwrap();
writeln!(result, "</svg>").unwrap();
unsafe { String::from_utf8_unchecked(result) }
}
#[wasm_bindgen]
pub struct MazeCarveResults {
maze_svg: String,
pub num_deadends: usize,
}
#[wasm_bindgen]
impl MazeCarveResults {
pub fn maze_svg(&self) -> String {
self.maze_svg.clone()
}
}
#[wasm_bindgen]
pub fn carve_maze(mazegen_algo: &str, seed_string: String) -> MazeCarveResults {
let app = unsafe { MAZE_APP.as_mut().unwrap() };
let algo = match mazegen_algo {
"BinaryTree" => mazegen::Algo::BinaryTree,
"Sidewinder" => mazegen::Algo::Sidewinder,
"AldousBroder" => mazegen::Algo::AldousBroder,
"Wilson" => mazegen::Algo::Wilson,
"HuntAndKill" => mazegen::Algo::HuntAndKill,
"RecursiveBacktracker" => mazegen::Algo::RecursiveBacktracker,
"Kruskal" => mazegen::Algo::Kruskal,
"RecursiveDivision" => mazegen::Algo::RecursiveDivision,
"Eller" => mazegen::Algo::Eller,
"PrimSimplified" => mazegen::Algo::PrimSimplified,
"PrimTrue" => mazegen::Algo::PrimTrue,
"Empty" => mazegen::Algo::Empty,
_ => panic!("Got a bad mazegen algo from JS"),
};
let mut result = Vec::new();
app.grid.reset();
let mut rng = if seed_string.is_empty() {
XorShiftRng::from_entropy()
} else {
let seed_u64 = fxhash::hash64(&seed_string);
XorShiftRng::seed_from_u64(seed_u64)
};
mazegen::carve_maze(&mut app.grid, &mut rng, algo);
writeln!(result, "<g id=\"g_maze\">").unwrap();
app.grid.write_maze_as_svg(&mut result).unwrap();
writeln!(result, "</g>").unwrap();
MazeCarveResults {
maze_svg: unsafe { String::from_utf8_unchecked(result) },
num_deadends: app.grid.dead_ends().count(),
}
}
| 29.706215 | 120 | 0.639977 |
eb885bfee137fa4b60431a0f509294a19ade6c82 | 534 | use sudograph::graphql_database;
graphql_database!("canisters/graphql/src/schema.graphql");
#[update]
async fn graphql_mutation_custom(mutation_string: String, variables_json_string: String) -> String {
let ec2_principal = ic_cdk::export::Principal::from_text("y6lgw-chi3g-2ok7i-75s5h-k34kj-ybcke-oq4nb-u4i7z-vclk4-hcpxa-hqe").expect("should be able to decode");
if ic_cdk::caller() != ec2_principal {
panic!("Not authorized");
}
return graphql_mutation(mutation_string, variables_json_string).await;
} | 38.142857 | 163 | 0.747191 |
f810b565a57678d24ae6d8124aa41d0880fc85cf | 2,518 | #[doc = "Reader of register DTLOCK"]
pub type R = crate::R<u32, super::DTLOCK>;
#[doc = "Writer for register DTLOCK"]
pub type W = crate::W<u32, super::DTLOCK>;
#[doc = "Register DTLOCK `reset()`'s with value 0"]
impl crate::ResetValue for super::DTLOCK {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "DTI Lock Key\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u16)]
pub enum LOCKKEY_A {
#[doc = "0: `0`"]
UNLOCKED = 0,
#[doc = "1: `1`"]
LOCKED = 1,
}
impl From<LOCKKEY_A> for u16 {
#[inline(always)]
fn from(variant: LOCKKEY_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `LOCKKEY`"]
pub type LOCKKEY_R = crate::R<u16, LOCKKEY_A>;
impl LOCKKEY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u16, LOCKKEY_A> {
use crate::Variant::*;
match self.bits {
0 => Val(LOCKKEY_A::UNLOCKED),
1 => Val(LOCKKEY_A::LOCKED),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `UNLOCKED`"]
#[inline(always)]
pub fn is_unlocked(&self) -> bool {
*self == LOCKKEY_A::UNLOCKED
}
#[doc = "Checks if the value of the field is `LOCKED`"]
#[inline(always)]
pub fn is_locked(&self) -> bool {
*self == LOCKKEY_A::LOCKED
}
}
#[doc = "Write proxy for field `LOCKKEY`"]
pub struct LOCKKEY_W<'a> {
w: &'a mut W,
}
impl<'a> LOCKKEY_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LOCKKEY_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "`0`"]
#[inline(always)]
pub fn unlocked(self) -> &'a mut W {
self.variant(LOCKKEY_A::UNLOCKED)
}
#[doc = "`1`"]
#[inline(always)]
pub fn locked(self) -> &'a mut W {
self.variant(LOCKKEY_A::LOCKED)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - DTI Lock Key"]
#[inline(always)]
pub fn lockkey(&self) -> LOCKKEY_R {
LOCKKEY_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - DTI Lock Key"]
#[inline(always)]
pub fn lockkey(&mut self) -> LOCKKEY_W {
LOCKKEY_W { w: self }
}
}
| 27.075269 | 74 | 0.552423 |
3a2209c15a92f4f0d42dc7390793c30c2bd5ffa1 | 6,165 | // Copyright (c) 2020 Huawei Technologies Co.,Ltd. All rights reserved.
//
// StratoVirt is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan
// PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
// http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
#![allow(missing_docs)]
//! Manages address resources that used by Vm's memory and emulated devices.
//!
//! # Examples
//!
//! ```rust
//! use std::sync::{Arc, Mutex};
//! extern crate address_space;
//! use address_space::{AddressSpace, Region, GuestAddress, HostMemMapping, RegionOps, FileBackend};
//!
//! struct DummyDevice;
//! impl DummyDevice {
//! fn read(&mut self, data: &mut [u8], base: GuestAddress, offset: u64) -> bool {
//! // read operation omitted
//! true
//! }
//! fn write(&mut self, data: &[u8], base: GuestAddress, offset: u64) -> bool {
//! // write operation omitted
//! true
//! }
//! }
//!
//! fn main() {
//! // 1. create address_space
//! let space = AddressSpace::new(Region::init_container_region(u64::max_value())).unwrap();
//!
//! // 2. create an Ram-type Region, and set it's priority
//! let mem_mapping = Arc::new(HostMemMapping::new(
//! GuestAddress(0),
//! None,
//! 0x1000,
//! None,
//! false,
//! false,
//! false,
//! ).unwrap());
//! let ram_region = Region::init_ram_region(mem_mapping.clone());
//! ram_region.set_priority(10);
//!
//! // 3. create a IO-type Region
//! let dev = Arc::new(Mutex::new(DummyDevice));
//! let dev_clone = dev.clone();
//! let read_ops = move |data: &mut [u8], addr: GuestAddress, offset: u64| -> bool {
//! let mut dev_locked = dev_clone.lock().unwrap();
//! dev_locked.read(data, addr, offset)
//! };
//! let dev_clone = dev.clone();
//! let write_ops = move |data: &[u8], addr: GuestAddress, offset: u64| -> bool {
//! let mut dev_locked = dev_clone.lock().unwrap();
//! dev_locked.write(data, addr, offset)
//! };
//! let dev_ops = RegionOps {
//! read: Arc::new(read_ops),
//! write: Arc::new(write_ops),
//! };
//!
//! let io_region = Region::init_io_region(0x1000, dev_ops);
//!
//! // 4. add sub_region to address_space's root region
//! space.root().add_subregion(ram_region, mem_mapping.start_address().raw_value());
//! space.root().add_subregion(io_region, 0x2000);
//!
//! // 5. access address_space
//! space.write_object(&0x11u64, GuestAddress(0));
//! }
//! ```
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
#[macro_use]
extern crate migration_derive;
mod address;
mod address_space;
mod host_mmap;
mod listener;
mod region;
mod state;
pub use crate::address_space::AddressSpace;
pub use address::{AddressRange, GuestAddress};
pub use host_mmap::{create_host_mmaps, FileBackend, HostMemMapping};
#[cfg(target_arch = "x86_64")]
pub use listener::KvmIoListener;
pub use listener::KvmMemoryListener;
pub use listener::{Listener, ListenerReqType};
pub use region::{FlatRange, Region, RegionIoEventFd, RegionType};
pub mod errors {
error_chain! {
foreign_links {
Io(std::io::Error);
}
errors {
ListenerRequest(req_type: crate::listener::ListenerReqType) {
display("Failed to call listener, request type is {:#?}", req_type)
}
UpdateTopology(base: u64, size: u64, reg_ty: crate::RegionType) {
display("Failed to update topology, base 0x{:X}, size 0x{:X}, region type is {:#?}", base, size, reg_ty)
}
IoEventFd {
display("Failed to clone EventFd")
}
AddrAlignUp(addr: u64, align: u64) {
display("Failed to align-up address, overflows: addr 0x{:X}, align 0x{:X}", addr, align)
}
RegionNotFound(addr: u64) {
display("Failed to find matched region, addr 0x{:X}", addr)
}
Overflow(addr: u64) {
display("Address overflows, addr is 0x{:X}", addr)
}
Mmap {
display("Failed to mmap")
}
IoAccess(base: u64, offset: u64, count: u64) {
display("Failed to access IO-type region, region base 0x{:X}, offset 0x{:X}, size 0x{:X}", base, offset, count)
}
RegionType(t: crate::RegionType) {
display("Wrong region type, {:#?}", t)
}
NoAvailKvmSlot(cnt: usize) {
display("No available kvm_mem_slot, total count is {}", cnt)
}
NoMatchedKvmSlot(addr: u64, sz: u64) {
display("Failed to find matched kvm_mem_slot, addr 0x{:X}, size 0x{:X}", addr, sz)
}
KvmSlotOverlap(add: (u64, u64), exist: (u64, u64)) {
display("Added KVM mem range (0x{:X}, 0x{:X}) overlaps with exist one (0x{:X}, 0x{:X})", add.0, add.1, exist.0, exist.1)
}
}
}
}
/// Provide Some operations of `Region`, mainly used by Vm's devices.
#[derive(Clone)]
pub struct RegionOps {
/// Read data from Region to argument `data`,
/// return `true` if read successfully, or return `false`.
///
/// # Arguments
///
/// * `data` - A u8-type array.
/// * `base` - Base address.
/// * `offset` - Offset from base address.
pub read: std::sync::Arc<dyn Fn(&mut [u8], GuestAddress, u64) -> bool + Send + Sync>,
/// Write `data` to memory,
/// return `true` if write successfully, or return `false`.
///
/// # Arguments
///
/// * `data` - A u8-type array.
/// * `base` - Base address.
/// * `offset` - Offset from base address.
pub write: std::sync::Arc<dyn Fn(&[u8], GuestAddress, u64) -> bool + Send + Sync>,
}
| 36.052632 | 136 | 0.580049 |
7a2eaac1fd214889f08dfa1e7282dd9285b87318 | 531 | // compile-pass
#![allow(dead_code)]
#![feature(never_type)]
#![feature(exhaustive_patterns)]
// Regression test for inhabitedness check. The old
// cache used to cause us to incorrectly decide
// that `test_b` was invalid.
struct Foo {
field1: !,
field2: Option<&'static Bar>,
}
struct Bar {
field1: &'static Foo
}
fn test_a() {
let x: Option<Foo> = None;
match x { None => () }
}
fn test_b() {
let x: Option<Bar> = None;
match x {
Some(_) => (),
None => ()
}
}
fn main() { }
| 16.090909 | 51 | 0.578154 |
3a458f2fae7767068ed59c2798077afcfe19d30a | 2,154 | use yew::prelude::*;
use yew::{Component, ComponentLink, Html, Properties};
use yewtil::NeqAssign;
pub struct StringInput {
link: ComponentLink<Self>,
pub(crate) props: Props,
}
#[derive(Properties, Clone, PartialEq)]
pub struct Props {
pub onchange: Callback<String>,
pub value: String,
#[prop_or("".to_string())]
pub placeholder: String,
#[prop_or("".to_string())]
pub class: String,
#[prop_or(None)]
pub onfocus: Option<Callback<()>>,
#[prop_or(None)]
pub onblur: Option<Callback<()>>,
}
pub enum Msg {
Value(String),
Ignored,
Focus,
UnFocus,
}
impl Component for StringInput {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self { link, props }
}
fn update(&mut self, msg: Self::Message) -> bool {
match msg {
Msg::Value(s) => {
self.props.onchange.emit(s);
true
}
Msg::Focus => {
if let Some(onfocus) = &self.props.onfocus {
onfocus.emit(());
}
true
}
Msg::UnFocus => {
if let Some(onblur) = &self.props.onblur {
onblur.emit(());
}
true
}
_ => false,
}
}
fn change(&mut self, props: Self::Properties) -> bool {
self.props.neq_assign(props)
}
fn view(&self) -> Html {
html! {
<input
onchange=self.link.callback(move |cd| {
if let ChangeData::Value(s) = cd {
Msg::Value(s)
} else {
Msg::Ignored
}
})
placeholder=self.props.placeholder.clone()
onblur=self.link.callback(move |_fe| Msg::UnFocus)
onfocus=self.link.callback(move |_fe| Msg::Focus)
value=self.props.value.clone()
class=format!("form-control {}", self.props.class)/>
}
}
}
| 25.046512 | 75 | 0.482823 |
79ea182fc8965e09419dd846001ee43f1f83e11d | 5,149 | #![allow(dead_code, unused_macros)]
use mun_compiler::{Config, DisplayColor, Driver, FileId, PathOrInline, RelativePathBuf};
use mun_runtime::{IntoFunctionDefinition, Runtime, RuntimeBuilder};
use std::io::Cursor;
use std::{cell::RefCell, path::PathBuf, rc::Rc, thread::sleep, time::Duration};
/// Implements a compiler and runtime in one that can invoke functions. Use of the TestDriver
/// enables quick testing of Mun constructs in the runtime with hot-reloading support.
pub(crate) struct TestDriver {
_temp_dir: tempfile::TempDir,
out_path: PathBuf,
file_id: FileId,
driver: Driver,
runtime: RuntimeOrBuilder,
}
enum RuntimeOrBuilder {
Runtime(Rc<RefCell<Runtime>>),
Builder(RuntimeBuilder),
Pending,
}
impl RuntimeOrBuilder {
pub fn spawn(&mut self) -> Result<(), anyhow::Error> {
let previous = std::mem::replace(self, RuntimeOrBuilder::Pending);
let runtime = match previous {
RuntimeOrBuilder::Runtime(runtime) => runtime,
RuntimeOrBuilder::Builder(builder) => builder.spawn()?,
_ => unreachable!(),
};
*self = RuntimeOrBuilder::Runtime(runtime);
Ok(())
}
}
impl TestDriver {
/// Construct a new TestDriver from a single Mun source
pub fn new(text: &str) -> Self {
let temp_dir = tempfile::TempDir::new().unwrap();
let config = Config {
out_dir: Some(temp_dir.path().to_path_buf()),
display_color: DisplayColor::Disable,
..Config::default()
};
let input = PathOrInline::Inline {
rel_path: RelativePathBuf::from("main.mun"),
contents: text.to_owned(),
};
let (mut driver, file_id) = Driver::with_file(config, input).unwrap();
let mut compiler_errors: Vec<u8> = Vec::new();
if driver
.emit_diagnostics(&mut Cursor::new(&mut compiler_errors))
.unwrap()
{
panic!(
"compiler errors:\n{}",
String::from_utf8(compiler_errors)
.expect("compiler errors are not UTF-8 formatted")
)
}
let out_path = driver.assembly_output_path(file_id);
driver.write_assembly(file_id, true).unwrap();
let builder = RuntimeBuilder::new(&out_path);
TestDriver {
_temp_dir: temp_dir,
driver,
out_path,
file_id,
runtime: RuntimeOrBuilder::Builder(builder),
}
}
/// Spawns a `Runtime` from the `RuntimeBuilder`, if it hadn't already been spawned.
pub fn spawn(&mut self) -> Result<(), anyhow::Error> {
self.runtime.spawn().map(|_| ())
}
/// Updates the text of the Mun source and ensures that the generated assembly has been reloaded.
pub fn update(&mut self, text: &str) {
self.runtime_mut(); // Ensures that the runtime is spawned prior to the update
self.driver.set_file_text(self.file_id, text);
let mut compiler_errors: Vec<u8> = Vec::new();
if self
.driver
.emit_diagnostics(&mut Cursor::new(&mut compiler_errors))
.unwrap()
{
panic!(
"compiler errors:\n{}",
String::from_utf8(compiler_errors)
.expect("compiler errors are not UTF-8 formatted")
)
}
let out_path = self.driver.assembly_output_path(self.file_id);
self.driver.write_assembly(self.file_id, true).unwrap();
assert_eq!(
&out_path, &self.out_path,
"recompiling did not result in the same assembly"
);
let start_time = std::time::Instant::now();
while !self.runtime_mut().borrow_mut().update() {
let now = std::time::Instant::now();
if now - start_time > std::time::Duration::from_secs(10) {
panic!("runtime did not update after recompilation within 10secs");
} else {
sleep(Duration::from_millis(1));
}
}
}
/// Adds a custom user function to the dispatch table.
pub fn insert_fn<S: AsRef<str>, F: IntoFunctionDefinition>(mut self, name: S, func: F) -> Self {
self.runtime = match self.runtime {
RuntimeOrBuilder::Builder(builder) => {
RuntimeOrBuilder::Builder(builder.insert_fn(name, func))
}
_ => unreachable!(),
};
self
}
/// Returns the `Runtime` used by this instance
pub fn runtime_mut(&mut self) -> &mut Rc<RefCell<Runtime>> {
self.runtime.spawn().unwrap();
match &mut self.runtime {
RuntimeOrBuilder::Runtime(r) => r,
_ => unreachable!(),
}
}
}
macro_rules! assert_invoke_eq {
($ExpectedType:ty, $ExpectedResult:expr, $Driver:expr, $($Arg:tt)+) => {
let result: $ExpectedType = mun_runtime::invoke_fn!($Driver.runtime_mut(), $($Arg)*).unwrap();
assert_eq!(result, $ExpectedResult, "{} == {:?}", stringify!(mun_runtime::invoke_fn!($Driver.runtime_mut(), $($Arg)*).unwrap()), $ExpectedResult);
}
}
| 37.043165 | 154 | 0.587687 |
3a23ad436ec121faacf8db7f2458fd4c3bbbe713 | 3,698 | use rmpv::{Utf8String, Value};
use rmpv::decode::read_value;
use std::fmt;
use unterflow_protocol::{RequestResponseMessage, SingleRequestMessage, TransportMessage};
use unterflow_protocol::io::{Data, HasData};
struct MessagePack<'a>(&'a Data);
impl<'a> fmt::Debug for MessagePack<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut reader = self.0.as_slice();
if let Ok(value) = read_value(&mut reader) {
// assume all message pack data has to be a map
// to distinguish non message pack data which still
// can be parsed somehow
if value.is_map() {
write!(f, "{}", value)?;
if let Some(values) = value.as_map() {
let payload_key = Value::String(Utf8String::from("payload"));
let payload = values.iter().find(|&&(ref key, _)| key == &payload_key);
if let Some(&(_, Value::Binary(ref bytes))) = payload {
if let Ok(value) = read_value(&mut bytes.as_slice()) {
write!(f, ", payload (decoded): {}", value)?;
}
}
}
return Ok(());
}
}
// default debug output
write!(f, "Data({:?})", self.0)
}
}
pub struct Message(pub TransportMessage);
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let message = &self.0;
match *message {
TransportMessage::RequestResponse(ref r) => {
writeln!(f, "{:?}", r.frame_header)?;
writeln!(f, "{:?}", r.transport_header)?;
writeln!(f, "{:?}", r.request_header)?;
writeln!(f, "{:?}", r.message_header)?;
match r.message {
RequestResponseMessage::ControlMessageRequest(ref r) => {
writeln!(f, "{:?}", r)?;
writeln!(f, "{:?}", MessagePack(r.data()))
}
RequestResponseMessage::ControlMessageResponse(ref r) => {
writeln!(f, "{:?}", r)?;
writeln!(f, "{:?}", MessagePack(r.data()))
}
RequestResponseMessage::ExecuteCommandRequest(ref r) => {
writeln!(f, "{:?}", r)?;
writeln!(f, "{:?}", MessagePack(r.data()))
}
RequestResponseMessage::ExecuteCommandResponse(ref r) => {
writeln!(f, "{:?}", r)?;
writeln!(f, "{:?}", MessagePack(r.data()))
}
}
}
TransportMessage::SingleRequest(ref r) => {
writeln!(f, "{:?}", r.frame_header)?;
writeln!(f, "{:?}", r.transport_header)?;
writeln!(f, "{:?}", r.message_header)?;
match r.message {
SingleRequestMessage::SubscribedEvent(ref r) => {
writeln!(f, "{:?}", r)?;
writeln!(f, "{:?}", MessagePack(r.data()))
}
SingleRequestMessage::AppendRequest(ref r) => {
writeln!(f, "{:?}", r)?;
writeln!(f, "{:?}", MessagePack(r.data()))
}
}
}
TransportMessage::ControlRequest(ref r) => {
writeln!(f, "{:?}", r.frame_header)?;
writeln!(f, "{:?}", r.transport_header)?;
writeln!(f, "{:?}", r.message)
}
}
}
}
| 40.195652 | 91 | 0.437534 |
2f5ae6a44c123d7eb1147ee787a22e3695922e87 | 1,967 | // Copyright © 2018-2022 The Twang Contributors.
//
// Licensed under any of:
// - Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
// - Boost Software License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt)
// - MIT License (https://mit-license.org/)
// At your choosing (See accompanying files LICENSE_APACHE_2_0.txt,
// LICENSE_MIT.txt and LICENSE_BOOST_1_0.txt).
use core::ops::Rem;
/// Floating point methods currently only available on std, that may be
/// implemented with the libm crate as dependency of core in the future.
pub(crate) trait Libm: Rem<Output = Self> + Sized {
fn cos(self) -> Self;
fn abs(self) -> Self;
fn copysign(self, other: Self) -> Self;
fn signum(self) -> Self;
fn exp(self) -> Self;
}
impl Libm for f32 {
#[inline(always)]
fn cos(self) -> Self {
libm::cosf(self)
}
#[inline(always)]
fn abs(self) -> Self {
libm::fabsf(self)
}
#[inline(always)]
fn copysign(self, other: Self) -> Self {
libm::copysignf(self, other)
}
#[inline(always)]
fn signum(self) -> Self {
if self.is_nan() {
Self::NAN
} else {
1.0_f32.copysign(self)
}
}
#[inline(always)]
fn exp(self) -> Self {
libm::expf(self)
}
}
#[cfg(test)]
mod tests {
// Tests stolen from https://doc.rust-lang.org/src/std/f32.rs.html
#[test]
fn math_signum() {
let f = 3.5_f32;
assert_eq!(f.copysign(0.42), 3.5_f32);
assert_eq!(f.copysign(-0.42), -3.5_f32);
assert_eq!((-f).copysign(0.42), 3.5_f32);
assert_eq!((-f).copysign(-0.42), -3.5_f32);
assert!(f32::NAN.copysign(1.0).is_nan());
}
#[test]
fn math_exp() {
let one = 1.0f32;
// e^1
let e = one.exp();
// ln(e) - 1 == 0
let abs_difference = (e.ln() - 1.0).abs();
assert!(abs_difference <= f32::EPSILON);
}
}
| 24.283951 | 80 | 0.565328 |
67c120e9313996e0df0494ec5b0b7b29672f962f | 7,970 | #![crate_name = "uu_wc"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Boden Garman <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uucore;
use getopts::{Matches, Options};
use std::fs::File;
use std::io::{stdin, BufRead, BufReader, Read};
use std::path::Path;
use std::result::Result as StdResult;
use std::str::from_utf8;
struct Settings {
show_bytes: bool,
show_chars: bool,
show_lines: bool,
show_words: bool,
show_max_line_length: bool,
}
impl Settings {
fn new(matches: &Matches) -> Settings {
let settings = Settings {
show_bytes: matches.opt_present("bytes"),
show_chars: matches.opt_present("chars"),
show_lines: matches.opt_present("lines"),
show_words: matches.opt_present("words"),
show_max_line_length: matches.opt_present("L"),
};
if settings.show_bytes || settings.show_chars || settings.show_lines || settings.show_words
|| settings.show_max_line_length
{
return settings;
}
Settings {
show_bytes: true,
show_chars: false,
show_lines: true,
show_words: true,
show_max_line_length: false,
}
}
}
struct Result {
title: String,
bytes: usize,
chars: usize,
lines: usize,
words: usize,
max_line_length: usize,
}
static NAME: &str = "wc";
static VERSION: &str = env!("CARGO_PKG_VERSION");
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("c", "bytes", "print the byte counts");
opts.optflag("m", "chars", "print the character counts");
opts.optflag("l", "lines", "print the newline counts");
opts.optflag(
"L",
"max-line-length",
"print the length of the longest line",
);
opts.optflag("w", "words", "print the word counts");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let mut matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "Invalid options\n{}", f),
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {0} [OPTION]... [FILE]...", NAME);
println!("");
println!(
"{}",
opts.usage("Print newline, word and byte counts for each FILE")
);
println!("With no FILE, or when FILE is -, read standard input.");
return 0;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.free.is_empty() {
matches.free.push("-".to_owned());
}
let settings = Settings::new(&matches);
match wc(matches.free, &settings) {
Ok(()) => ( /* pass */ ),
Err(e) => return e,
}
0
}
const CR: u8 = '\r' as u8;
const LF: u8 = '\n' as u8;
const SPACE: u8 = ' ' as u8;
const TAB: u8 = '\t' as u8;
const SYN: u8 = 0x16 as u8;
const FF: u8 = 0x0C as u8;
#[inline(always)]
fn is_word_seperator(byte: u8) -> bool {
byte == SPACE || byte == TAB || byte == CR || byte == SYN || byte == FF
}
fn wc(files: Vec<String>, settings: &Settings) -> StdResult<(), i32> {
let mut total_line_count: usize = 0;
let mut total_word_count: usize = 0;
let mut total_char_count: usize = 0;
let mut total_byte_count: usize = 0;
let mut total_longest_line_length: usize = 0;
let mut results = vec![];
let mut max_width: usize = 0;
for path in &files {
let mut reader = open(&path[..])?;
let mut line_count: usize = 0;
let mut word_count: usize = 0;
let mut byte_count: usize = 0;
let mut char_count: usize = 0;
let mut longest_line_length: usize = 0;
let mut raw_line = Vec::new();
// reading from a TTY seems to raise a condition on, rather than return Some(0) like a file.
// hence the option wrapped in a result here
while match reader.read_until(LF, &mut raw_line) {
Ok(n) if n > 0 => true,
Err(ref e) if !raw_line.is_empty() => {
show_warning!("Error while reading {}: {}", path, e);
!raw_line.is_empty()
}
_ => false,
} {
// GNU 'wc' only counts lines that end in LF as lines
if *raw_line.last().unwrap() == LF {
line_count += 1;
}
byte_count += raw_line.len();
// try and convert the bytes to UTF-8 first
let current_char_count;
match from_utf8(&raw_line[..]) {
Ok(line) => {
word_count += line.split_whitespace().count();
current_char_count = line.chars().count();
}
Err(..) => {
word_count += raw_line.split(|&x| is_word_seperator(x)).count();
current_char_count = raw_line.iter().filter(|c| c.is_ascii()).count()
}
}
char_count += current_char_count;
if current_char_count > longest_line_length {
// we subtract one here because `line.len()` includes the LF
// matches GNU 'wc' behaviour
longest_line_length = current_char_count - 1;
}
raw_line.truncate(0);
}
results.push(Result {
title: path.clone(),
bytes: byte_count,
chars: char_count,
lines: line_count,
words: word_count,
max_line_length: longest_line_length,
});
total_line_count += line_count;
total_word_count += word_count;
total_char_count += char_count;
total_byte_count += byte_count;
if longest_line_length > total_longest_line_length {
total_longest_line_length = longest_line_length;
}
// used for formatting
max_width = total_byte_count.to_string().len() + 1;
}
for result in &results {
print_stats(settings, &result, max_width);
}
if files.len() > 1 {
let result = Result {
title: "total".to_owned(),
bytes: total_byte_count,
chars: total_char_count,
lines: total_line_count,
words: total_word_count,
max_line_length: total_longest_line_length,
};
print_stats(settings, &result, max_width);
}
Ok(())
}
fn print_stats(settings: &Settings, result: &Result, max_width: usize) {
if settings.show_lines {
print!("{:1$}", result.lines, max_width);
}
if settings.show_words {
print!("{:1$}", result.words, max_width);
}
if settings.show_bytes {
print!("{:1$}", result.bytes, max_width);
}
if settings.show_chars {
print!("{:1$}", result.chars, max_width);
}
if settings.show_max_line_length {
print!("{:1$}", result.max_line_length, max_width);
}
if result.title != "-" {
println!(" {}", result.title);
} else {
println!("");
}
}
fn open(path: &str) -> StdResult<BufReader<Box<dyn Read + 'static>>, i32> {
if "-" == path {
let reader = Box::new(stdin()) as Box<dyn Read>;
return Ok(BufReader::new(reader));
}
let fpath = Path::new(path);
if fpath.is_dir() {
show_info!("{}: is a directory", path);
}
match File::open(&fpath) {
Ok(fd) => {
let reader = Box::new(fd) as Box<dyn Read>;
Ok(BufReader::new(reader))
}
Err(e) => {
show_error!("wc: {}: {}", path, e);
Err(1)
}
}
}
| 28.262411 | 100 | 0.548306 |
e57688355134a0ea02d9ebd665ba136d34e958b7 | 135 | use add_one;
use rand;
fn main() {
let num = 10;
println!("Hello, world! {} plus one is {}!", num, add_one::add_one(num));
}
| 15 | 77 | 0.57037 |
f703ff99660c6ae4691119ad4d830d8b530f0300 | 44,774 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// ignore-lexer-test FIXME #15679
//! An owned, growable string that enforces that its contents are valid UTF-8.
#![stable]
use core::prelude::*;
use core::borrow::{Cow, IntoCow};
use core::default::Default;
use core::fmt;
use core::hash;
use core::mem;
use core::ptr;
use core::ops;
use core::raw::Slice as RawSlice;
use unicode::str as unicode_str;
use unicode::str::Utf16Item;
use slice::CloneSliceExt;
use str::{mod, CharRange, FromStr, Utf8Error};
use vec::{DerefVec, Vec, as_vec};
/// A growable string stored as a UTF-8 encoded buffer.
#[deriving(Clone, PartialOrd, Eq, Ord)]
#[stable]
pub struct String {
vec: Vec<u8>,
}
/// A possible error value from the `String::from_utf8` function.
#[stable]
pub struct FromUtf8Error {
bytes: Vec<u8>,
error: Utf8Error,
}
/// A possible error value from the `String::from_utf16` function.
#[stable]
#[allow(missing_copy_implementations)]
pub struct FromUtf16Error(());
impl String {
/// Creates a new string buffer initialized with the empty string.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// ```
#[inline]
#[stable]
pub fn new() -> String {
String {
vec: Vec::new(),
}
}
/// Creates a new string buffer with the given capacity.
/// The string will be able to hold exactly `capacity` bytes without
/// reallocating. If `capacity` is 0, the string will not allocate.
///
/// # Examples
///
/// ```
/// let mut s = String::with_capacity(10);
/// ```
#[inline]
#[stable]
pub fn with_capacity(capacity: uint) -> String {
String {
vec: Vec::with_capacity(capacity),
}
}
/// Creates a new string buffer from the given string.
///
/// # Examples
///
/// ```
/// let s = String::from_str("hello");
/// assert_eq!(s.as_slice(), "hello");
/// ```
#[inline]
#[experimental = "needs investigation to see if to_string() can match perf"]
pub fn from_str(string: &str) -> String {
String { vec: string.as_bytes().to_vec() }
}
/// Returns the vector as a string buffer, if possible, taking care not to
/// copy it.
///
/// # Failure
///
/// If the given vector is not valid UTF-8, then the original vector and the
/// corresponding error is returned.
///
/// # Examples
///
/// ```rust
/// # #![allow(deprecated)]
/// use std::str::Utf8Error;
///
/// let hello_vec = vec![104, 101, 108, 108, 111];
/// let s = String::from_utf8(hello_vec).unwrap();
/// assert_eq!(s, "hello");
///
/// let invalid_vec = vec![240, 144, 128];
/// let s = String::from_utf8(invalid_vec).err().unwrap();
/// assert_eq!(s.utf8_error(), Utf8Error::TooShort);
/// assert_eq!(s.into_bytes(), vec![240, 144, 128]);
/// ```
#[inline]
#[stable]
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
match str::from_utf8(vec.as_slice()) {
Ok(..) => Ok(String { vec: vec }),
Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
}
}
/// Converts a vector of bytes to a new UTF-8 string.
/// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
///
/// # Examples
///
/// ```rust
/// let input = b"Hello \xF0\x90\x80World";
/// let output = String::from_utf8_lossy(input);
/// assert_eq!(output.as_slice(), "Hello \u{FFFD}World");
/// ```
#[stable]
pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> {
match str::from_utf8(v) {
Ok(s) => return Cow::Borrowed(s),
Err(..) => {}
}
static TAG_CONT_U8: u8 = 128u8;
static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
let mut i = 0;
let total = v.len();
fn unsafe_get(xs: &[u8], i: uint) -> u8 {
unsafe { *xs.get_unchecked(i) }
}
fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
if i >= total {
0
} else {
unsafe_get(xs, i)
}
}
let mut res = String::with_capacity(total);
if i > 0 {
unsafe {
res.as_mut_vec().push_all(v[..i])
};
}
// subseqidx is the index of the first byte of the subsequence we're looking at.
// It's used to copy a bunch of contiguous good codepoints at once instead of copying
// them one by one.
let mut subseqidx = 0;
while i < total {
let i_ = i;
let byte = unsafe_get(v, i);
i += 1;
macro_rules! error(() => ({
unsafe {
if subseqidx != i_ {
res.as_mut_vec().push_all(v[subseqidx..i_]);
}
subseqidx = i;
res.as_mut_vec().push_all(REPLACEMENT);
}
}));
if byte < 128u8 {
// subseqidx handles this
} else {
let w = unicode_str::utf8_char_width(byte);
match w {
2 => {
if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
3 => {
match (byte, safe_get(v, i, total)) {
(0xE0 , 0xA0 ... 0xBF) => (),
(0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
(0xED , 0x80 ... 0x9F) => (),
(0xEE ... 0xEF, 0x80 ... 0xBF) => (),
_ => {
error!();
continue;
}
}
i += 1;
if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
4 => {
match (byte, safe_get(v, i, total)) {
(0xF0 , 0x90 ... 0xBF) => (),
(0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
(0xF4 , 0x80 ... 0x8F) => (),
_ => {
error!();
continue;
}
}
i += 1;
if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
_ => {
error!();
continue;
}
}
}
}
if subseqidx < total {
unsafe {
res.as_mut_vec().push_all(v[subseqidx..total])
};
}
Cow::Owned(res)
}
/// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
/// if `v` contains any invalid data.
///
/// # Examples
///
/// ```rust
/// // 𝄞music
/// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0x0069, 0x0063];
/// assert_eq!(String::from_utf16(v).unwrap(),
/// "𝄞music".to_string());
///
/// // 𝄞mu<invalid>ic
/// v[4] = 0xD800;
/// assert!(String::from_utf16(v).is_err());
/// ```
#[stable]
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
let mut s = String::with_capacity(v.len());
for c in unicode_str::utf16_items(v) {
match c {
Utf16Item::ScalarValue(c) => s.push(c),
Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
}
}
Ok(s)
}
/// Decode a UTF-16 encoded vector `v` into a string, replacing
/// invalid data with the replacement character (U+FFFD).
///
/// # Examples
///
/// ```rust
/// // 𝄞mus<invalid>ic<invalid>
/// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0xDD1E, 0x0069, 0x0063,
/// 0xD834];
///
/// assert_eq!(String::from_utf16_lossy(v),
/// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
/// ```
#[stable]
pub fn from_utf16_lossy(v: &[u16]) -> String {
unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
}
/// Convert a vector of `char`s to a `String`.
///
/// # Examples
///
/// ```rust
/// # #![allow(deprecated)]
/// let chars = &['h', 'e', 'l', 'l', 'o'];
/// let s = String::from_chars(chars);
/// assert_eq!(s.as_slice(), "hello");
/// ```
#[inline]
#[deprecated = "use .collect() instead"]
pub fn from_chars(chs: &[char]) -> String {
chs.iter().map(|c| *c).collect()
}
/// Creates a new `String` from a length, capacity, and pointer.
///
/// This is unsafe because:
/// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
/// * We assume that the `Vec` contains valid UTF-8.
#[inline]
#[stable]
pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
String {
vec: Vec::from_raw_parts(buf, length, capacity),
}
}
/// Creates a `String` from a null-terminated `*const u8` buffer.
///
/// This function is unsafe because we dereference memory until we find the
/// NUL character, which is not guaranteed to be present. Additionally, the
/// slice is not checked to see whether it contains valid UTF-8
#[unstable = "just renamed from `mod raw`"]
pub unsafe fn from_raw_buf(buf: *const u8) -> String {
String::from_str(str::from_c_str(buf as *const i8))
}
/// Creates a `String` from a `*const u8` buffer of the given length.
///
/// This function is unsafe because it blindly assumes the validity of the
/// pointer `buf` for `len` bytes of memory. This function will copy the
/// memory from `buf` into a new allocation (owned by the returned
/// `String`).
///
/// This function is also unsafe because it does not validate that the
/// buffer is valid UTF-8 encoded data.
#[unstable = "just renamed from `mod raw`"]
pub unsafe fn from_raw_buf_len(buf: *const u8, len: uint) -> String {
String::from_utf8_unchecked(Vec::from_raw_buf(buf, len))
}
/// Converts a vector of bytes to a new `String` without checking if
/// it contains valid UTF-8. This is unsafe because it assumes that
/// the UTF-8-ness of the vector has already been validated.
#[inline]
#[stable]
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
String { vec: bytes }
}
/// Return the underlying byte buffer, encoded as UTF-8.
///
/// # Examples
///
/// ```
/// let s = String::from_str("hello");
/// let bytes = s.into_bytes();
/// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
/// ```
#[inline]
#[stable]
pub fn into_bytes(self) -> Vec<u8> {
self.vec
}
/// Creates a string buffer by repeating a character `length` times.
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// let s = String::from_char(5, 'a');
/// assert_eq!(s.as_slice(), "aaaaa");
/// ```
#[inline]
#[deprecated = "use repeat(ch).take(length).collect() instead"]
pub fn from_char(length: uint, ch: char) -> String {
if length == 0 {
return String::new()
}
let mut buf = String::new();
buf.push(ch);
let size = buf.len() * (length - 1);
buf.reserve_exact(size);
for _ in range(1, length) {
buf.push(ch)
}
buf
}
/// Pushes the given string onto this string buffer.
///
/// # Examples
///
/// ```
/// let mut s = String::from_str("foo");
/// s.push_str("bar");
/// assert_eq!(s.as_slice(), "foobar");
/// ```
#[inline]
#[stable]
pub fn push_str(&mut self, string: &str) {
self.vec.push_all(string.as_bytes())
}
/// Pushes `ch` onto the given string `count` times.
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// let mut s = String::from_str("foo");
/// s.grow(5, 'Z');
/// assert_eq!(s.as_slice(), "fooZZZZZ");
/// ```
#[inline]
#[deprecated = "deprecated in favor of .extend(repeat(ch).take(count))"]
pub fn grow(&mut self, count: uint, ch: char) {
for _ in range(0, count) {
self.push(ch)
}
}
/// Returns the number of bytes that this string buffer can hold without
/// reallocating.
///
/// # Examples
///
/// ```
/// let s = String::with_capacity(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable]
pub fn capacity(&self) -> uint {
self.vec.capacity()
}
/// Deprecated: Renamed to `reserve`.
#[deprecated = "Renamed to `reserve`"]
pub fn reserve_additional(&mut self, extra: uint) {
self.vec.reserve(extra)
}
/// Reserves capacity for at least `additional` more bytes to be inserted
/// in the given `String`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// # Panics
///
/// Panics if the new capacity overflows `uint`.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// s.reserve(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable]
pub fn reserve(&mut self, additional: uint) {
self.vec.reserve(additional)
}
/// Reserves the minimum capacity for exactly `additional` more bytes to be
/// inserted in the given `String`. Does nothing if the capacity is already
/// sufficient.
///
/// Note that the allocator may give the collection more space than it
/// requests. Therefore capacity can not be relied upon to be precisely
/// minimal. Prefer `reserve` if future insertions are expected.
///
/// # Panics
///
/// Panics if the new capacity overflows `uint`.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// s.reserve(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable]
pub fn reserve_exact(&mut self, additional: uint) {
self.vec.reserve_exact(additional)
}
/// Shrinks the capacity of this string buffer to match its length.
///
/// # Examples
///
/// ```
/// let mut s = String::from_str("foo");
/// s.reserve(100);
/// assert!(s.capacity() >= 100);
/// s.shrink_to_fit();
/// assert_eq!(s.capacity(), 3);
/// ```
#[inline]
#[stable]
pub fn shrink_to_fit(&mut self) {
self.vec.shrink_to_fit()
}
/// Adds the given character to the end of the string.
///
/// # Examples
///
/// ```
/// let mut s = String::from_str("abc");
/// s.push('1');
/// s.push('2');
/// s.push('3');
/// assert_eq!(s.as_slice(), "abc123");
/// ```
#[inline]
#[stable]
pub fn push(&mut self, ch: char) {
if (ch as u32) < 0x80 {
self.vec.push(ch as u8);
return;
}
let cur_len = self.len();
// This may use up to 4 bytes.
self.vec.reserve(4);
unsafe {
// Attempt to not use an intermediate buffer by just pushing bytes
// directly onto this string.
let slice = RawSlice {
data: self.vec.as_ptr().offset(cur_len as int),
len: 4,
};
let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
self.vec.set_len(cur_len + used);
}
}
/// Works with the underlying buffer as a byte slice.
///
/// # Examples
///
/// ```
/// let s = String::from_str("hello");
/// let b: &[_] = &[104, 101, 108, 108, 111];
/// assert_eq!(s.as_bytes(), b);
/// ```
#[inline]
#[stable]
pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
self.vec.as_slice()
}
/// Shortens a string to the specified length.
///
/// # Panics
///
/// Panics if `new_len` > current length,
/// or if `new_len` is not a character boundary.
///
/// # Examples
///
/// ```
/// let mut s = String::from_str("hello");
/// s.truncate(2);
/// assert_eq!(s.as_slice(), "he");
/// ```
#[inline]
#[stable]
pub fn truncate(&mut self, new_len: uint) {
assert!(self.is_char_boundary(new_len));
self.vec.truncate(new_len)
}
/// Removes the last character from the string buffer and returns it.
/// Returns `None` if this string buffer is empty.
///
/// # Examples
///
/// ```
/// let mut s = String::from_str("foo");
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('f'));
/// assert_eq!(s.pop(), None);
/// ```
#[inline]
#[stable]
pub fn pop(&mut self) -> Option<char> {
let len = self.len();
if len == 0 {
return None
}
let CharRange {ch, next} = self.char_range_at_reverse(len);
unsafe {
self.vec.set_len(next);
}
Some(ch)
}
/// Removes the character from the string buffer at byte position `idx` and
/// returns it.
///
/// # Warning
///
/// This is an O(n) operation as it requires copying every element in the
/// buffer.
///
/// # Panics
///
/// If `idx` does not lie on a character boundary, or if it is out of
/// bounds, then this function will panic.
///
/// # Examples
///
/// ```
/// let mut s = String::from_str("foo");
/// assert_eq!(s.remove(0), 'f');
/// assert_eq!(s.remove(1), 'o');
/// assert_eq!(s.remove(0), 'o');
/// ```
#[stable]
pub fn remove(&mut self, idx: uint) -> char {
let len = self.len();
assert!(idx <= len);
let CharRange { ch, next } = self.char_range_at(idx);
unsafe {
ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
self.vec.as_ptr().offset(next as int),
len - next);
self.vec.set_len(len - (next - idx));
}
ch
}
/// Insert a character into the string buffer at byte position `idx`.
///
/// # Warning
///
/// This is an O(n) operation as it requires copying every element in the
/// buffer.
///
/// # Panics
///
/// If `idx` does not lie on a character boundary or is out of bounds, then
/// this function will panic.
#[stable]
pub fn insert(&mut self, idx: uint, ch: char) {
let len = self.len();
assert!(idx <= len);
assert!(self.is_char_boundary(idx));
self.vec.reserve(4);
let mut bits = [0, ..4];
let amt = ch.encode_utf8(&mut bits).unwrap();
unsafe {
ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int),
self.vec.as_ptr().offset(idx as int),
len - idx);
ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
bits.as_ptr(),
amt);
self.vec.set_len(len + amt);
}
}
/// Views the string buffer as a mutable sequence of bytes.
///
/// This is unsafe because it does not check
/// to ensure that the resulting string will be valid UTF-8.
///
/// # Examples
///
/// ```
/// let mut s = String::from_str("hello");
/// unsafe {
/// let vec = s.as_mut_vec();
/// assert!(vec == &mut vec![104, 101, 108, 108, 111]);
/// vec.reverse();
/// }
/// assert_eq!(s.as_slice(), "olleh");
/// ```
#[stable]
pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
&mut self.vec
}
/// Return the number of bytes in this string.
///
/// # Examples
///
/// ```
/// let a = "foo".to_string();
/// assert_eq!(a.len(), 3);
/// ```
#[inline]
#[stable]
pub fn len(&self) -> uint { self.vec.len() }
/// Returns true if the string contains no bytes
///
/// # Examples
///
/// ```
/// let mut v = String::new();
/// assert!(v.is_empty());
/// v.push('a');
/// assert!(!v.is_empty());
/// ```
#[stable]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Truncates the string, returning it to 0 length.
///
/// # Examples
///
/// ```
/// let mut s = "foo".to_string();
/// s.clear();
/// assert!(s.is_empty());
/// ```
#[inline]
#[stable]
pub fn clear(&mut self) {
self.vec.clear()
}
}
impl FromUtf8Error {
/// Consume this error, returning the bytes that were attempted to make a
/// `String` with.
#[stable]
pub fn into_bytes(self) -> Vec<u8> { self.bytes }
/// Access the underlying UTF8-error that was the cause of this error.
#[stable]
pub fn utf8_error(&self) -> Utf8Error { self.error }
}
impl fmt::Show for FromUtf8Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.error.fmt(f)
}
}
impl fmt::Show for FromUtf16Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"invalid utf-16: lone surrogate found".fmt(f)
}
}
#[experimental = "waiting on FromIterator stabilization"]
impl FromIterator<char> for String {
fn from_iter<I:Iterator<char>>(iterator: I) -> String {
let mut buf = String::new();
buf.extend(iterator);
buf
}
}
#[experimental = "waiting on FromIterator stabilization"]
impl<'a> FromIterator<&'a str> for String {
fn from_iter<I:Iterator<&'a str>>(iterator: I) -> String {
let mut buf = String::new();
buf.extend(iterator);
buf
}
}
#[experimental = "waiting on Extend stabilization"]
impl Extend<char> for String {
fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
for ch in iterator {
self.push(ch)
}
}
}
#[experimental = "waiting on Extend stabilization"]
impl<'a> Extend<&'a str> for String {
fn extend<I: Iterator<&'a str>>(&mut self, mut iterator: I) {
// A guess that at least one byte per iterator element will be needed.
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
for s in iterator {
self.push_str(s)
}
}
}
#[stable]
impl PartialEq for String {
#[inline]
fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
}
macro_rules! impl_eq {
($lhs:ty, $rhs: ty) => {
#[stable]
impl<'a> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable]
impl<'a> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
}
}
}
impl_eq! { String, &'a str }
impl_eq! { CowString<'a>, String }
#[stable]
impl<'a, 'b> PartialEq<&'b str> for CowString<'a> {
#[inline]
fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable]
impl<'a, 'b> PartialEq<CowString<'a>> for &'b str {
#[inline]
fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[experimental = "waiting on Str stabilization"]
#[allow(deprecated)]
impl Str for String {
#[inline]
#[stable]
fn as_slice<'a>(&'a self) -> &'a str {
unsafe { mem::transmute(self.vec.as_slice()) }
}
}
#[stable]
impl Default for String {
#[stable]
fn default() -> String {
String::new()
}
}
#[experimental = "waiting on Show stabilization"]
impl fmt::Show for String {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
#[experimental = "waiting on Hash stabilization"]
impl<H: hash::Writer> hash::Hash<H> for String {
#[inline]
fn hash(&self, hasher: &mut H) {
(**self).hash(hasher)
}
}
#[allow(deprecated)]
#[deprecated = "Use overloaded `core::cmp::PartialEq`"]
impl<'a, S: Str> Equiv<S> for String {
#[inline]
fn equiv(&self, other: &S) -> bool {
self.as_slice() == other.as_slice()
}
}
#[experimental = "waiting on Add stabilization"]
impl<'a> Add<&'a str, String> for String {
fn add(mut self, other: &str) -> String {
self.push_str(other);
self
}
}
impl ops::Slice<uint, str> for String {
#[inline]
fn as_slice_<'a>(&'a self) -> &'a str {
unsafe { mem::transmute(self.vec.as_slice()) }
}
#[inline]
fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
self[][*from..]
}
#[inline]
fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
self[][..*to]
}
#[inline]
fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
self[][*from..*to]
}
}
#[experimental = "waiting on Deref stabilization"]
impl ops::Deref<str> for String {
fn deref<'a>(&'a self) -> &'a str {
unsafe { mem::transmute(self.vec[]) }
}
}
/// Wrapper type providing a `&String` reference via `Deref`.
#[experimental]
pub struct DerefString<'a> {
x: DerefVec<'a, u8>
}
impl<'a> Deref<String> for DerefString<'a> {
fn deref<'b>(&'b self) -> &'b String {
unsafe { mem::transmute(&*self.x) }
}
}
/// Convert a string slice to a wrapper type providing a `&String` reference.
///
/// # Examples
///
/// ```
/// use std::string::as_string;
///
/// fn string_consumer(s: String) {
/// assert_eq!(s, "foo".to_string());
/// }
///
/// let string = as_string("foo").clone();
/// string_consumer(string);
/// ```
#[experimental]
pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
DerefString { x: as_vec(x.as_bytes()) }
}
impl FromStr for String {
#[inline]
fn from_str(s: &str) -> Option<String> {
Some(String::from_str(s))
}
}
/// Trait for converting a type to a string, consuming it in the process.
#[deprecated = "trait will be removed"]
pub trait IntoString {
/// Consume and convert to a string.
fn into_string(self) -> String;
}
/// A generic trait for converting a value to a string
pub trait ToString {
/// Converts the value of `self` to an owned string
fn to_string(&self) -> String;
}
impl<T: fmt::Show> ToString for T {
fn to_string(&self) -> String {
let mut buf = Vec::<u8>::new();
let _ = fmt::write(&mut buf, format_args!("{}", *self));
String::from_utf8(buf).unwrap()
}
}
impl IntoCow<'static, String, str> for String {
fn into_cow(self) -> CowString<'static> {
Cow::Owned(self)
}
}
impl<'a> IntoCow<'a, String, str> for &'a str {
fn into_cow(self) -> CowString<'a> {
Cow::Borrowed(self)
}
}
/// Unsafe operations
#[deprecated]
pub mod raw {
use super::String;
use vec::Vec;
/// Creates a new `String` from a length, capacity, and pointer.
///
/// This is unsafe because:
/// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
/// * We assume that the `Vec` contains valid UTF-8.
#[inline]
#[deprecated = "renamed to String::from_raw_parts"]
pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
String::from_raw_parts(buf, length, capacity)
}
/// Creates a `String` from a `*const u8` buffer of the given length.
///
/// This function is unsafe because of two reasons:
///
/// * A raw pointer is dereferenced and transmuted to `&[u8]`;
/// * The slice is not checked to see whether it contains valid UTF-8.
#[deprecated = "renamed to String::from_raw_buf_len"]
pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
String::from_raw_buf_len(buf, len)
}
/// Creates a `String` from a null-terminated `*const u8` buffer.
///
/// This function is unsafe because we dereference memory until we find the NUL character,
/// which is not guaranteed to be present. Additionally, the slice is not checked to see
/// whether it contains valid UTF-8
#[deprecated = "renamed to String::from_raw_buf"]
pub unsafe fn from_buf(buf: *const u8) -> String {
String::from_raw_buf(buf)
}
/// Converts a vector of bytes to a new `String` without checking if
/// it contains valid UTF-8. This is unsafe because it assumes that
/// the UTF-8-ness of the vector has already been validated.
#[inline]
#[deprecated = "renamed to String::from_utf8_unchecked"]
pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
String::from_utf8_unchecked(bytes)
}
}
/// A clone-on-write string
#[stable]
pub type CowString<'a> = Cow<'a, String, str>;
#[allow(deprecated)]
impl<'a> Str for CowString<'a> {
#[inline]
fn as_slice<'b>(&'b self) -> &'b str {
(**self).as_slice()
}
}
#[cfg(test)]
mod tests {
use prelude::*;
use test::Bencher;
use str::Utf8Error;
use str;
use super::as_string;
#[test]
fn test_as_string() {
let x = "foo";
assert_eq!(x, as_string(x).as_slice());
}
#[test]
fn test_from_str() {
let owned: Option<::std::string::String> = from_str("string");
assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
}
#[test]
fn test_from_utf8() {
let xs = b"hello".to_vec();
assert_eq!(String::from_utf8(xs).unwrap(),
String::from_str("hello"));
let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
assert_eq!(String::from_utf8(xs).unwrap(),
String::from_str("ศไทย中华Việt Nam"));
let xs = b"hello\xFF".to_vec();
let err = String::from_utf8(xs).err().unwrap();
assert_eq!(err.utf8_error(), Utf8Error::TooShort);
assert_eq!(err.into_bytes(), b"hello\xff".to_vec());
}
#[test]
fn test_from_utf8_lossy() {
let xs = b"hello";
let ys: str::CowString = "hello".into_cow();
assert_eq!(String::from_utf8_lossy(xs), ys);
let xs = "ศไทย中华Việt Nam".as_bytes();
let ys: str::CowString = "ศไทย中华Việt Nam".into_cow();
assert_eq!(String::from_utf8_lossy(xs), ys);
let xs = b"Hello\xC2 There\xFF Goodbye";
assert_eq!(String::from_utf8_lossy(xs),
String::from_str("Hello\u{FFFD} There\u{FFFD} Goodbye").into_cow());
let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
assert_eq!(String::from_utf8_lossy(xs),
String::from_str("Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye").into_cow());
let xs = b"\xF5foo\xF5\x80bar";
assert_eq!(String::from_utf8_lossy(xs),
String::from_str("\u{FFFD}foo\u{FFFD}\u{FFFD}bar").into_cow());
let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
assert_eq!(String::from_utf8_lossy(xs),
String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}baz").into_cow());
let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
assert_eq!(String::from_utf8_lossy(xs),
String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}\u{FFFD}baz").into_cow());
let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\
foo\u{10000}bar").into_cow());
// surrogates
let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}foo\
\u{FFFD}\u{FFFD}\u{FFFD}bar").into_cow());
}
#[test]
fn test_from_utf16() {
let pairs =
[(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
0xd800_u16, 0xdf30_u16, 0x000a_u16]),
(String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
0x000a_u16]),
(String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
(String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
0x000a_u16 ]),
// Issue #12318, even-numbered non-BMP planes
(String::from_str("\u{20000}"),
vec![0xD840, 0xDC00])];
for p in pairs.iter() {
let (s, u) = (*p).clone();
let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>();
let u_as_string = String::from_utf16(u.as_slice()).unwrap();
assert!(::unicode::str::is_utf16(u.as_slice()));
assert_eq!(s_as_utf16, u);
assert_eq!(u_as_string, s);
assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u);
}
}
#[test]
fn test_utf16_invalid() {
// completely positive cases tested above.
// lead + eof
assert!(String::from_utf16(&[0xD800]).is_err());
// lead + lead
assert!(String::from_utf16(&[0xD800, 0xD800]).is_err());
// isolated trail
assert!(String::from_utf16(&[0x0061, 0xDC00]).is_err());
// general
assert!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]).is_err());
}
#[test]
fn test_from_utf16_lossy() {
// completely positive cases tested above.
// lead + eof
assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\u{FFFD}"));
// lead + lead
assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]),
String::from_str("\u{FFFD}\u{FFFD}"));
// isolated trail
assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\u{FFFD}"));
// general
assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]),
String::from_str("\u{FFFD}𐒋\u{FFFD}"));
}
#[test]
fn test_from_buf_len() {
unsafe {
let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
}
}
#[test]
fn test_from_buf() {
unsafe {
let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
let b = a.as_ptr();
let c = super::raw::from_buf(b);
assert_eq!(c, String::from_str("AAAAAAA"));
}
}
#[test]
fn test_push_bytes() {
let mut s = String::from_str("ABC");
unsafe {
let mv = s.as_mut_vec();
mv.push_all(&[b'D']);
}
assert_eq!(s, "ABCD");
}
#[test]
fn test_push_str() {
let mut s = String::new();
s.push_str("");
assert_eq!(s.slice_from(0), "");
s.push_str("abc");
assert_eq!(s.slice_from(0), "abc");
s.push_str("ประเทศไทย中华Việt Nam");
assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam");
}
#[test]
fn test_push() {
let mut data = String::from_str("ประเทศไทย中");
data.push('华');
data.push('b'); // 1 byte
data.push('¢'); // 2 byte
data.push('€'); // 3 byte
data.push('𤭢'); // 4 byte
assert_eq!(data, "ประเทศไทย中华b¢€𤭢");
}
#[test]
fn test_pop() {
let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
assert_eq!(data.pop().unwrap(), '华');
assert_eq!(data, "ประเทศไทย中");
}
#[test]
fn test_str_truncate() {
let mut s = String::from_str("12345");
s.truncate(5);
assert_eq!(s, "12345");
s.truncate(3);
assert_eq!(s, "123");
s.truncate(0);
assert_eq!(s, "");
let mut s = String::from_str("12345");
let p = s.as_ptr();
s.truncate(3);
s.push_str("6");
let p_ = s.as_ptr();
assert_eq!(p_, p);
}
#[test]
#[should_fail]
fn test_str_truncate_invalid_len() {
let mut s = String::from_str("12345");
s.truncate(6);
}
#[test]
#[should_fail]
fn test_str_truncate_split_codepoint() {
let mut s = String::from_str("\u{FC}"); // ü
s.truncate(1);
}
#[test]
fn test_str_clear() {
let mut s = String::from_str("12345");
s.clear();
assert_eq!(s.len(), 0);
assert_eq!(s, "");
}
#[test]
fn test_str_add() {
let a = String::from_str("12345");
let b = a + "2";
let b = b + "2";
assert_eq!(b.len(), 7);
assert_eq!(b, "1234522");
}
#[test]
fn remove() {
let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
assert_eq!(s.remove(0), 'ศ');
assert_eq!(s.len(), 33);
assert_eq!(s, "ไทย中华Việt Nam; foobar");
assert_eq!(s.remove(17), 'ệ');
assert_eq!(s, "ไทย中华Vit Nam; foobar");
}
#[test] #[should_fail]
fn remove_bad() {
"ศ".to_string().remove(1);
}
#[test]
fn insert() {
let mut s = "foobar".to_string();
s.insert(0, 'ệ');
assert_eq!(s, "ệfoobar");
s.insert(6, 'ย');
assert_eq!(s, "ệfooยbar");
}
#[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
#[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }
#[test]
fn test_slicing() {
let s = "foobar".to_string();
assert_eq!("foobar", s[]);
assert_eq!("foo", s[..3]);
assert_eq!("bar", s[3..]);
assert_eq!("oob", s[1..4]);
}
#[test]
fn test_simple_types() {
assert_eq!(1i.to_string(), "1");
assert_eq!((-1i).to_string(), "-1");
assert_eq!(200u.to_string(), "200");
assert_eq!(2u8.to_string(), "2");
assert_eq!(true.to_string(), "true");
assert_eq!(false.to_string(), "false");
assert_eq!(().to_string(), "()");
assert_eq!(("hi".to_string()).to_string(), "hi");
}
#[test]
fn test_vectors() {
let x: Vec<int> = vec![];
assert_eq!(x.to_string(), "[]");
assert_eq!((vec![1i]).to_string(), "[1]");
assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]");
assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() ==
"[[], [1], [1, 1]]");
}
#[test]
fn test_from_iterator() {
let s = "ศไทย中华Việt Nam".to_string();
let t = "ศไทย中华";
let u = "Việt Nam";
let a: String = s.chars().collect();
assert_eq!(s, a);
let mut b = t.to_string();
b.extend(u.chars());
assert_eq!(s, b);
let c: String = vec![t, u].into_iter().collect();
assert_eq!(s, c);
let mut d = t.to_string();
d.extend(vec![u].into_iter());
assert_eq!(s, d);
}
#[bench]
fn bench_with_capacity(b: &mut Bencher) {
b.iter(|| {
String::with_capacity(100)
});
}
#[bench]
fn bench_push_str(b: &mut Bencher) {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
b.iter(|| {
let mut r = String::new();
r.push_str(s);
});
}
const REPETITIONS: u64 = 10_000;
#[bench]
fn bench_push_str_one_byte(b: &mut Bencher) {
b.bytes = REPETITIONS;
b.iter(|| {
let mut r = String::new();
for _ in range(0, REPETITIONS) {
r.push_str("a")
}
});
}
#[bench]
fn bench_push_char_one_byte(b: &mut Bencher) {
b.bytes = REPETITIONS;
b.iter(|| {
let mut r = String::new();
for _ in range(0, REPETITIONS) {
r.push('a')
}
});
}
#[bench]
fn bench_push_char_two_bytes(b: &mut Bencher) {
b.bytes = REPETITIONS * 2;
b.iter(|| {
let mut r = String::new();
for _ in range(0, REPETITIONS) {
r.push('â')
}
});
}
#[bench]
fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ";
assert_eq!(100, s.len());
b.iter(|| {
let _ = String::from_utf8_lossy(s);
});
}
#[bench]
fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
assert_eq!(100, s.len());
b.iter(|| {
let _ = String::from_utf8_lossy(s);
});
}
#[bench]
fn from_utf8_lossy_invalid(b: &mut Bencher) {
let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
b.iter(|| {
let _ = String::from_utf8_lossy(s);
});
}
#[bench]
fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
let s = Vec::from_elem(100, 0xF5u8);
b.iter(|| {
let _ = String::from_utf8_lossy(s.as_slice());
});
}
}
| 29.475971 | 99 | 0.51617 |
913d848ae39bc04905e33b67809c918d916f4057 | 94,146 | #![allow(deprecated)]
use std::{fs::read_to_string, path::PathBuf};
use swc_common::chain;
use swc_ecma_parser::{EsConfig, Syntax, TsConfig};
use swc_ecma_transforms_base::resolver::resolver;
use swc_ecma_transforms_compat::{
es2015::{arrow, block_scoping, classes, function_name, template_literal},
es2016::exponentation,
es2017::async_to_generator,
es2020::{class_properties, typescript_class_properties},
es3::reserved_words,
};
use swc_ecma_transforms_testing::{compare_stdout, test, test_exec, Tester};
use swc_ecma_visit::Fold;
fn ts() -> Syntax {
Syntax::Typescript(TsConfig {
..Default::default()
})
}
fn syntax() -> Syntax {
Syntax::Es(EsConfig {
class_private_props: true,
class_props: true,
..Default::default()
})
}
fn tr(t: &Tester) -> impl Fold {
chain!(
resolver(),
function_name(),
class_properties(),
classes(Some(t.comments.clone())),
block_scoping(),
reserved_words(false),
)
}
test!(
syntax(),
|t| tr(t),
public_static_infer_name,
r#"
var Foo = class {
static num = 0;
}
"#,
r#"
var Foo = function() {
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
};
_defineProperty(Foo, 'num', 0);
return Foo;
}();
"#
);
test_exec!(
syntax(),
|t| tr(t),
public_call_exec,
r#"
class Foo {
foo = function() {
return this;
}
test(other) {
return [this.foo(), other.foo()];
}
}
const f = new Foo;
const o = new Foo;
const test = f.test(o);
expect(test[0]).toBe(f);
expect(test[1]).toBe(o);
"#
);
test!(
syntax(),
|t| tr(t),
public_instance_computed,
r#"
function test(x) {
class F {
[x] = 1;
constructor() {}
}
x = 'deadbeef';
expect(new F().foo).toBe(1);
x = 'wrong';
expect(new F().foo).toBe(1);
}
test('foo');
"#,
r#"
function test(x) {
var _x = x;
var F = function F() {
'use strict';
_classCallCheck(this, F);
_defineProperty(this, _x, 1);
};
x = 'deadbeef';
expect(new F().foo).toBe(1);
x = 'wrong';
expect(new F().foo).toBe(1);
}
test('foo');
"#
);
test!(
syntax(),
|t| tr(t),
public_super_statement,
r#"
class Foo extends Bar {
bar = "foo";
constructor() {
super();
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function (Bar) {
'use strict';
_inherits(Foo, Bar);
function Foo() {
_classCallCheck(this, Foo);
var _this;
_this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).call(this));
_defineProperty(_assertThisInitialized(_this), "bar", "foo");
return _this;
}
return Foo;
}(Bar);
"#
);
test!(
syntax(),
|t| tr(t),
private_foobar,
r#"
class Child extends Parent {
constructor() {
super();
}
#scopedFunctionWithThis = () => {
this.name = {};
}
}
"#,
r#"
var Child =
/*#__PURE__*/
function (Parent) {
'use strict';
_inherits(Child, Parent);
function Child() {
_classCallCheck(this, Child);
var _this;
_this = _possibleConstructorReturn(this, _getPrototypeOf(Child).call(this));
_scopedFunctionWithThis.set(_assertThisInitialized(_this), {
writable: true,
value: () => {
_this.name = {};
}
});
return _this;
}
return Child;
}(Parent);
var _scopedFunctionWithThis = new WeakMap();
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_call_exec,
r#"
class Foo {
#foo = function() {
return this;
}
test(other) {
return [this.#foo(), other.#foo()];
}
}
const f = new Foo;
const o = new Foo;
const test = f.test(o);
expect(test[0]).toBe(f);
expect(test[1]).toBe(o);
"#
);
test!(
syntax(),
|t| tr(t),
public_derived_multiple_supers,
r#"
class Foo extends Bar {
bar = "foo";
constructor() {
if (condition) {
super();
} else {
super();
}
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function (Bar) {
'use strict';
_inherits(Foo, Bar);
function Foo() {
_classCallCheck(this, Foo);
var _this;
if (condition) {
_this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).call(this));
_defineProperty(_assertThisInitialized(_this), "bar", "foo");
} else {
_this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).call(this));
_defineProperty(_assertThisInitialized(_this), "bar", "foo");
}
return _possibleConstructorReturn(_this);
}
return Foo;
}(Bar);
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_static_call_exec,
r#"
class Foo {
static #foo = function(x) {
return x;
}
test(x) {
return Foo.#foo(x);
}
}
const f = new Foo;
const test = f.test();
expect(f.test("bar")).toBe("bar");
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_instance_undefined_exec,
r#"
class Foo {
#bar;
test() {
return this.#bar;
}
}
expect(new Foo().test()).toBe(undefined);
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_instance_exec,
r#"
class Foo {
#bar = "foo";
test() {
return this.#bar;
}
update() {
this.#bar++;
}
set(val) {
this.#bar = val;
}
static test(foo) {
return foo.#bar;
}
static update(foo) {
foo.#bar **= 2;
}
}
const f = new Foo();
expect(f.test()).toBe("foo");
expect(Foo.test(f)).toBe("foo");
expect("bar" in f).toBe(false);
f.set(1);
expect(f.test()).toBe(1);
f.update();
expect(Foo.test(f)).toBe(2);
Foo.update(f);
expect(f.test()).toBe(4);
"#
);
test!(
syntax(),
|t| tr(t),
public_regression_t6719,
r#"
function withContext(ComposedComponent) {
return class WithContext extends Component {
static propTypes = {
context: PropTypes.shape(
{
addCss: PropTypes.func,
setTitle: PropTypes.func,
setMeta: PropTypes.func,
}
),
};
};
}
"#,
r#"
function withContext(ComposedComponent) {
return (function() {
var WithContext = function(Component) {
'use strict';
_inherits(WithContext, Component);
function WithContext() {
_classCallCheck(this, WithContext);
return _possibleConstructorReturn(this, _getPrototypeOf(WithContext).apply(this, arguments));
}
return WithContext;
}(Component);
_defineProperty(WithContext, 'propTypes', {
context: PropTypes.shape({
addCss: PropTypes.func,
setTitle: PropTypes.func,
setMeta: PropTypes.func
})
});
return WithContext;
})();
}
"#
);
test!(
syntax(),
|t| tr(t),
public_super_with_collision,
r#"
class A {
force = force;
foo = super.method();
constructor(force) {}
}
"#,
r#"
var A = function A(force1) {
'use strict';
_classCallCheck(this, A);
_defineProperty(this, "force", force);
_defineProperty(this, "foo", _get(_getPrototypeOf(A.prototype), "method", this).call(this));
};
"#
);
test!(
syntax(),
|t| tr(t),
public_call,
r#"
class Foo {
foo = function() {
return this;
}
test(other) {
this.foo();
other.obj.foo();
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
_defineProperty(this, "foo", function () {
return this;
});
}
_createClass(Foo, [{
key: "test",
value: function test(other) {
this.foo();
other.obj.foo();
}
}]);
return Foo;
}();
"#
);
test_exec!(
syntax(),
|t| tr(t),
public_instance_computed_exec,
r#"
function test(x) {
class F {
[x] = 1;
constructor() {}
}
x = 'deadbeef';
expect(new F().foo).toBe(1);
x = 'wrong';
expect(new F().foo).toBe(1);
}
test('foo');
"#
);
test!(
syntax(),
|t| tr(t),
private_declaration_order,
r#"
class C {
y = this.#x;
#x;
}
expect(() => {
new C();
}).toThrow();
"#,
r#"
var C = function C() {
'use strict';
_classCallCheck(this, C);
_defineProperty(this, "y", _classPrivateFieldGet(this, _x));
_x.set(this, {
writable: true,
value: void 0
});
};
var _x = new WeakMap();
expect(() => {
new C();
}).toThrow();
"#
);
test!(
syntax(),
|t| tr(t),
nested_class_super_call_in_key,
r#"
class Hello {
constructor() {
return {
toString() {
return 'hello';
},
};
}
}
class Outer extends Hello {
constructor() {
class Inner {
[super()] = "hello";
}
return new Inner();
}
}
expect(new Outer().hello).toBe('hello');
"#,
r#"
var Hello = function Hello() {
'use strict';
_classCallCheck(this, Hello);
return {
toString() {
return 'hello';
}
};
};
var Outer = function (Hello) {
'use strict';
_inherits(Outer, Hello);
function Outer() {
_classCallCheck(this, Outer);
var _this;
var _ref = _this = _possibleConstructorReturn(this, _getPrototypeOf(Outer).call(this));
var Inner = function Inner() {
_classCallCheck(this, Inner);
_defineProperty(this, _ref, "hello");
};
return _possibleConstructorReturn(_this, new Inner());
}
return Outer;
}(Hello);
expect(new Outer().hello).toBe('hello');
"#
);
test!(
syntax(),
|t| tr(t),
public_instance_undefined,
r#"
class Foo {
bar;
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_defineProperty(this, "bar", void 0);
};
"#
);
test!(
syntax(),
|t| tr(t),
private_derived_multiple_supers,
r#"
class Foo extends Bar {
#bar = "foo";
constructor() {
if (condition) {
super();
} else {
super();
}
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function (Bar) {
'use strict';
_inherits(Foo, Bar);
function Foo() {
_classCallCheck(this, Foo);
var _this;
if (condition) {
_this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).call(this));
_bar.set(_assertThisInitialized(_this), {
writable: true,
value: "foo"
});
} else {
_this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).call(this));
_bar.set(_assertThisInitialized(_this), {
writable: true,
value: "foo"
});
}
return _possibleConstructorReturn(_this);
}
return Foo;
}(Bar);
var _bar = new WeakMap();
"#
);
test_exec!(
syntax(),
|t| tr(t),
public_native_classes_exec,
r#"
class Foo {
static foo = "foo";
bar = "bar";
static test() {
return Foo.foo;
}
test() {
return this.bar;
}
}
const f = new Foo();
expect("foo" in Foo).toBe(true)
expect("bar" in f).toBe(true)
expect(Foo.test()).toBe("foo")
expect(f.test()).toBe("bar")
"#
);
test!(
syntax(),
|t| tr(t),
public_regression_t2983,
r#"
call(class {
static test = true
});
export default class {
static test = true
}
"#,
r#"
call(function() {
var _class = function _class() {
'use strict';
_classCallCheck(this, _class);
};
_defineProperty(_class, 'test', true);
return _class;
}());
var _class = function _class() {
'use strict';
_classCallCheck(this, _class);
};
_defineProperty(_class, 'test', true);
export { _class as default }
"#
);
test!(
syntax(),
|t| tr(t),
public_static,
r#"
class Foo {
static bar = "foo";
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
};
_defineProperty(Foo, "bar", "foo");
"#
);
test!(
syntax(),
|t| tr(t),
private_instance_undefined,
r#"
class Foo {
#bar;
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_bar.set(this, {
writable: true,
value: void 0
});
};
var _bar = new WeakMap();
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_declaration_order_exec,
r#"
class C {
y = this.#x;
#x;
}
expect(() => {
new C();
}).toThrow();
"#
);
test!(
syntax(),
|t| tr(t),
public_update,
r#"
class Foo {
foo = 0;
test(other) {
this.foo++;
++this.foo;
other.obj.foo++;
++other.obj.foo;
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
_defineProperty(this, "foo", 0);
}
_createClass(Foo, [{
key: "test",
value: function test(other) {
this.foo++;
++this.foo;
other.obj.foo++;
++other.obj.foo;
}
}]);
return Foo;
}();
"#
);
test!(
syntax(),
|t| tr(t),
public_super_call,
r#"
class A {
foo() {
return "bar";
}
}
class B extends A {
foo = super.foo();
}
"#,
r#"
var A =
/*#__PURE__*/
function () {
'use strict';
function A() {
_classCallCheck(this, A);
}
_createClass(A, [{
key: "foo",
value: function foo() {
return "bar";
}
}]);
return A;
}();
var B =
/*#__PURE__*/
function (A) {
'use strict';
_inherits(B, A);
function B() {
_classCallCheck(this, B);
var _this;
_this = _possibleConstructorReturn(this, _getPrototypeOf(B).apply(this, arguments));
_defineProperty(_assertThisInitialized(_this), "foo", _get(_getPrototypeOf(B.prototype), "foo", _assertThisInitialized(_this)).call(_this));
return _this;
}
return B;
}(A);
"#
);
test!(
syntax(),
|t| tr(t),
private_constructor_collision,
r#"
var foo = "bar";
class Foo {
#bar = foo;
constructor() {
var foo = "foo";
}
}
"#,
r#"
var foo = "bar";
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_bar.set(this, {
writable: true,
value: foo
});
var foo1 = "foo";
};
var _bar = new WeakMap();
"#
);
test!(
syntax(),
|t| tr(t),
public_constructor_collision,
r#"
var foo = "bar";
class Foo {
bar = foo;
static bar = baz;
constructor() {
var foo = "foo";
var baz = "baz";
}
}
"#,
r#"
var foo = "bar";
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_defineProperty(this, "bar", foo);
var foo1 = "foo";
var baz = "baz";
};
_defineProperty(Foo, "bar", baz);
"#
);
test!(
syntax(),
|t| tr(t),
public_computed,
r#"
const foo = "foo";
const bar = () => {};
const four = 4;
class MyClass {
static [one()] = "test";
static [2 * 4 + 7] = "247";
static [2 * four + 7] = "247";
static [2 * four + seven] = "247";
[null] = "null";
[undefined] = "undefined";
[void 0] = "void 0";
get ["whatever"]() {}
set ["whatever"](value) {}
get [computed()]() {}
set [computed()](value) {}
["test" + one]() {}
static [10]() {}
[/regex/] = "regex";
[foo] = "foo";
[bar] = "bar";
[baz] = "baz";
[`template`] = "template";
[`template${expression}`] = "template-with-expression";
}
"#,
r#"
var foo = 'foo';
var bar = ()=>{
};
var four = 4;
var _ref = one(),
_ref1 = 2 * 4 + 7,
_ref2 = 2 * four + 7,
_ref3 = 2 * four + seven,
_ref4 = null,
_undefined = undefined,
_ref5 = void 0,
tmp = 'whatever',
tmp1 = 'whatever',
tmp2 = computed(),
tmp3 = computed(),
tmp4 = 'test' + one,
tmp5 = 10,
_ref6 = /regex/,
_foo = foo,
_bar = bar,
_baz = baz,
_ref7 = `template`, _ref8 = `template${expression}`;
var MyClass = function() {
'use strict';
function MyClass() {
_classCallCheck(this, MyClass);
_defineProperty(this, _ref4, 'null');
_defineProperty(this, _undefined, 'undefined');
_defineProperty(this, _ref5, 'void 0');
_defineProperty(this, _ref6, 'regex');
_defineProperty(this, _foo, 'foo');
_defineProperty(this, _bar, 'bar');
_defineProperty(this, _baz, 'baz');
_defineProperty(this, _ref7, 'template');
_defineProperty(this, _ref8, 'template-with-expression');
}
_createClass(MyClass, [{
key: tmp, get: function () {
}
}, {
key: tmp1, set: function (value) {
}
}, {
key: tmp2, get: function () {
}
}, {
key: tmp3, set: function (value) {
}
}, {
key: tmp4, value: function () {
}
}], [{
key: tmp5, value: function () {
}
}]);
return MyClass;
}();
_defineProperty(MyClass, _ref, 'test');
_defineProperty(MyClass, _ref1, '247');
_defineProperty(MyClass, _ref2, '247');
_defineProperty(MyClass, _ref3, '247');
"#
);
test!(
syntax(),
|t| tr(t),
public_assignment,
r#"
class Foo {
foo = 0;
test(other) {
this.foo++;
this.foo += 1;
this.foo = 2;
other.obj.foo++;
other.obj.foo += 1;
other.obj.foo = 2;
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
_defineProperty(this, "foo", 0);
}
_createClass(Foo, [{
key: "test",
value: function test(other) {
this.foo++;
this.foo += 1;
this.foo = 2;
other.obj.foo++;
other.obj.foo += 1;
other.obj.foo = 2;
}
}]);
return Foo;
}();
"#
);
test_exec!(
syntax(),
|t| tr(t),
public_static_exec,
r#"
class Foo {
static num = 0;
static str = "foo";
}
expect(Foo.num).toBe(0);
expect(Foo.num = 1).toBe(1);
expect(Foo.str).toBe("foo");
expect(Foo.str = "bar").toBe("bar");
"#
);
test_exec!(
syntax(),
|t| tr(t),
regression_7371_exec_1,
r#"
class C {
}
class A extends C {
field = 1;
constructor() {
super();
class B extends C {
constructor() {
super();
expect(this.field).toBeUndefined();
}
}
expect(this.field).toBe(1)
new B();
}
}
new A();
"#
);
test_exec!(
syntax(),
|t| tr(t),
regression_7371_exec_2,
r#"
class Obj {
constructor() {
return {};
}
}
// ensure superClass is still transformed
class SuperClass extends Obj {
field = 1;
constructor() {
class B extends (super(), Obj) {
constructor() {
super();
expect(this.field).toBeUndefined()
}
}
expect(this.field).toBe(1)
new B();
}
}
new SuperClass();
// ensure ComputedKey Method is still transformed
class ComputedMethod extends Obj {
field = 1;
constructor() {
class B extends Obj {
constructor() {
super();
expect(this.field).toBeUndefined()
}
[super()]() { }
}
expect(this.field).toBe(1)
new B();
}
}
new ComputedMethod();
// ensure ComputedKey Field is still transformed
class ComputedField extends Obj {
field = 1;
constructor() {
class B extends Obj {
constructor() {
super();
expect(this.field).toBeUndefined()
}
[super()] = 1;
}
expect(this.field).toBe(1)
new B();
}
}
new ComputedField();
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_static_inherited_exec,
r#"
class Base {
static #foo = 1;
static getThis() {
return this.#foo;
}
static updateThis(val) {
return (this.#foo = val);
}
static getClass() {
return Base.#foo;
}
static updateClass(val) {
return (Base.#foo = val);
}
}
class Sub1 extends Base {
static #foo = 2;
static update(val) {
return (this.#foo = val);
}
}
class Sub2 extends Base {}
expect(Base.getThis()).toBe(1);
expect(Base.getClass()).toBe(1);
expect(() => Sub1.getThis()).toThrow();
expect(Sub1.getClass()).toBe(1);
expect(() => Sub2.getThis()).toThrow();
expect(Sub2.getClass()).toBe(1);
expect(Sub1.update(3)).toBe(3);
expect(Base.getThis()).toBe(1);
expect(Base.getClass()).toBe(1);
expect(() => Sub1.getThis()).toThrow();
expect(Sub1.getClass()).toBe(1);
expect(() => Sub2.getThis()).toThrow();
expect(Sub2.getClass()).toBe(1);
expect(Base.updateThis(4)).toBe(4);
expect(Base.getThis()).toBe(4);
expect(Base.getClass()).toBe(4);
expect(() => Sub1.getThis()).toThrow();
expect(Sub1.getClass()).toBe(4);
expect(() => Sub2.getThis()).toThrow();
expect(Sub2.getClass()).toBe(4);
expect(Base.updateClass(5)).toBe(5);
expect(Base.getThis()).toBe(5);
expect(Base.getClass()).toBe(5);
expect(() => Sub1.getThis()).toThrow();
expect(Sub1.getClass()).toBe(5);
expect(() => Sub2.getThis()).toThrow();
expect(Sub2.getClass()).toBe(5);
expect(() => Sub2.updateThis(6)).toThrow();
expect(Sub2.updateClass(7)).toBe(7);
expect(Base.getThis()).toBe(7);
expect(Base.getClass()).toBe(7);
expect(() => Sub1.getThis()).toThrow();
expect(Sub1.getClass()).toBe(7);
expect(() => Sub2.getThis()).toThrow();
expect(Sub2.getClass()).toBe(7);
"#
);
test_exec!(
syntax(),
|t| tr(t),
nested_class_super_property_in_key_exec,
r#"
class Hello {
toString() {
return 'hello';
}
}
class Outer extends Hello {
constructor() {
super();
class Inner {
[super.toString()] = 'hello';
}
return new Inner();
}
}
expect(new Outer().hello).toBe('hello');
"#
);
test!(
syntax(),
|t| tr(t),
private_super_statement,
r#"
class Foo extends Bar {
#bar = "foo";
constructor() {
super();
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function (Bar) {
'use strict';
_inherits(Foo, Bar);
function Foo() {
_classCallCheck(this, Foo);
var _this;
_this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).call(this));
_bar.set(_assertThisInitialized(_this), {
writable: true,
value: "foo"
});
return _this;
}
return Foo;
}(Bar);
var _bar = new WeakMap();
"#
);
test!(
syntax(),
|t| tr(t),
private_private_in_derived,
r#"
class Outer {
#outer;
constructor() {
class Test extends this.#outer {
}
}
}
"#,
r#"
var Outer = function Outer() {
'use strict';
_classCallCheck(this, Outer);
var _this = this;
_outer.set(this, {
writable: true,
value: void 0
});
var Test = function (_super) {
_inherits(Test, _super);
function Test() {
_classCallCheck(this, Test);
return _possibleConstructorReturn(this, _getPrototypeOf(Test).apply(this, arguments));
}
return Test;
}(_classPrivateFieldGet(_this, _outer));
};
var _outer = new WeakMap();
"#
);
test!(
syntax(),
|t| tr(t),
private_update,
r#"
class Foo {
#foo = 0;
test(other) {
this.#foo++;
++this.#foo;
other.obj.#foo++;
++other.obj.#foo;
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
_foo.set(this, {
writable: true,
value: 0
});
}
_createClass(Foo, [{
key: "test",
value: function test(other) {
var old, _obj, old1, _obj1;
_classPrivateFieldSet(this, _foo, (old = +_classPrivateFieldGet(this, _foo)) + 1), old;
_classPrivateFieldSet(this, _foo, +_classPrivateFieldGet(this, _foo) + 1);
_classPrivateFieldSet(_obj = other.obj, _foo, (old1 = +_classPrivateFieldGet(_obj, _foo)) + 1), old1;
_classPrivateFieldSet(_obj1 = other.obj, _foo, +_classPrivateFieldGet(_obj1, _foo) + 1);
}
}]);
return Foo;
}();
var _foo = new WeakMap();
"#
);
test!(
syntax(),
|t| tr(t),
public_super_expression,
r#"
class Foo extends Bar {
bar = "foo";
constructor() {
foo(super());
}
}
"#,
r#"
var Foo = function (Bar) {
'use strict';
_inherits(Foo, Bar);
function Foo() {
_classCallCheck(this, Foo);
var _this;
var _temp;
foo((_temp = _this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).call(this)), _defineProperty(_assertThisInitialized(_this), "bar", "foo"), _temp));
return _possibleConstructorReturn(_this);
}
return Foo;
}(Bar);
"#
);
test_exec!(
syntax(),
|t| tr(t),
public_computed_initialization_order_exec,
r#"
const actualOrder = [];
const track = i => {
actualOrder.push(i);
return i;
};
class MyClass {
static [track(1)] = track(10);
[track(2)] = track(13);
get [track(3)]() {
return "foo";
}
set [track(4)](value) {
this.bar = value;
}
[track(5)] = track(14);
static [track(6)] = track(11);
static [track(7)] = track(12);
[track(8)]() {}
[track(9)] = track(15);
}
const inst = new MyClass();
const expectedOrder = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
expect(actualOrder).toEqual(expectedOrder);
expect(MyClass[1]).toBe(10);
expect(inst[2]).toBe(13);
expect(inst[3]).toBe("foo");
inst[4] = "baz";
expect(inst.bar).toBe("baz");
expect(inst[5]).toBe(14);
expect(MyClass[6]).toBe(11);
expect(MyClass[7]).toBe(12);
expect(typeof inst[8]).toBe("function");
expect(inst[9]).toBe(15);
"#
);
test_exec!(
syntax(),
|t| tr(t),
nested_class_super_call_in_key_exec,
r#"
class Hello {
constructor() {
return {
toString() {
return 'hello';
},
};
}
}
class Outer extends Hello {
constructor() {
class Inner {
[super()] = "hello";
}
return new Inner();
}
}
expect(new Outer().hello).toBe('hello');
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_update_exec,
r#"
class Foo {
#foo = 0;
test(other) {
return [
this.#foo++,
this.#foo,
++this.#foo,
this.#foo,
other.obj.#foo++,
other.obj.#foo,
++other.obj.#foo,
other.obj.#foo,
];
}
}
const f = new Foo;
const results = f.test({ obj: f });
expect(results[0]).toBe(0);
expect(results[1]).toBe(1);
expect(results[2]).toBe(2);
expect(results[3]).toBe(2);
expect(results[4]).toBe(2);
expect(results[5]).toBe(3);
expect(results[6]).toBe(4);
expect(results[7]).toBe(4);
"#
);
test!(
syntax(),
|t| tr(t),
public_extracted_this,
r#"
var foo = "bar";
class Foo {
bar = this;
baz = foo;
constructor(foo) {
}
}
"#,
r#"
var foo = "bar";
var Foo = function Foo(foo1) {
'use strict';
_classCallCheck(this, Foo);
_defineProperty(this, "bar", this);
_defineProperty(this, "baz", foo);
};
"#
);
test!(
syntax(),
|t| tr(t),
private_derived,
r#"
class Foo {
#prop = "foo";
}
class Bar extends Foo {
#prop = "bar";
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_prop.set(this, {
writable: true,
value: "foo"
});
};
var _prop = new WeakMap();
var Bar =
/*#__PURE__*/
function (Foo) {
'use strict';
_inherits(Bar, Foo);
function Bar() {
_classCallCheck(this, Bar);
var _this;
_this = _possibleConstructorReturn(this, _getPrototypeOf(Bar).apply(this, arguments));
_prop1.set(_assertThisInitialized(_this), {
writable: true,
value: "bar"
});
return _this;
}
return Bar;
}(Foo);
var _prop1 = new WeakMap();
"#
);
test!(
syntax(),
|t| tr(t),
private_super_call,
r#"
class A {
foo() {
return "bar";
}
}
class B extends A {
#foo = super.foo();
}
"#,
r#"
var A = function () {
'use strict';
function A() {
_classCallCheck(this, A);
}
_createClass(A, [{
key: "foo",
value: function foo() {
return "bar";
}
}]);
return A;
}();
var B =
/*#__PURE__*/
function (A) {
'use strict';
_inherits(B, A);
function B() {
_classCallCheck(this, B);
var _this;
_this = _possibleConstructorReturn(this, _getPrototypeOf(B).apply(this, arguments));
_foo.set(_assertThisInitialized(_this), {
writable: true,
value: _get(_getPrototypeOf(B.prototype), "foo", _assertThisInitialized(_this)).call(_this)
});
return _this;
}
return B;
}(A);
var _foo = new WeakMap();
"#
);
test!(
syntax(),
|t| tr(t),
private_reference_in_other_property,
r#"
class Foo {
one = this.#private;
#two = this.#private;
#private = 0;
three = this.#private;
#four = this.#private;
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_defineProperty(this, "one", _classPrivateFieldGet(this, _private));
_two.set(this, {
writable: true,
value: _classPrivateFieldGet(this, _private)
});
_private.set(this, {
writable: true,
value: 0
});
_defineProperty(this, "three", _classPrivateFieldGet(this, _private));
_four.set(this, {
writable: true,
value: _classPrivateFieldGet(this, _private)
});
};
var _two = new WeakMap();
var _private = new WeakMap();
var _four = new WeakMap();
"#
);
test!(
syntax(),
|t| tr(t),
nested_class_super_property_in_key,
r#"
class Hello {
toString() {
return 'hello';
}
}
class Outer extends Hello {
constructor() {
super();
class Inner {
[super.toString()] = 'hello';
}
return new Inner();
}
}
expect(new Outer().hello).toBe('hello');
"#,
r#"
var Hello = function () {
'use strict';
function Hello() {
_classCallCheck(this, Hello);
}
_createClass(Hello, [{
key: "toString",
value: function toString() {
return 'hello';
}
}]);
return Hello;
}();
var Outer = function (Hello) {
'use strict';
_inherits(Outer, Hello);
function Outer() {
_classCallCheck(this, Outer);
var _this = _possibleConstructorReturn(this, _getPrototypeOf(Outer).call(this));
var _ref = _get(_getPrototypeOf(Outer.prototype), 'toString', _assertThisInitialized(_this)).call(_this);
var Inner = function Inner() {
_classCallCheck(this, Inner);
_defineProperty(this, _ref, 'hello');
};
return _possibleConstructorReturn(_this, new Inner());
}
return Outer;
}(Hello);
expect(new Outer().hello).toBe('hello');
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_reevaluated_exec,
r#"
function classFactory() {
return class Foo {
#foo = "foo";
static #bar = "bar";
instance() {
return this.#foo;
}
static() {
return Foo.#bar;
}
static instance(inst) {
return inst.#foo;
}
static static() {
return Foo.#bar;
}
};
}
const Foo1 = classFactory();
const Foo2 = classFactory();
const f1 = new Foo1();
const f2 = new Foo2();
expect(f1.instance()).toBe("foo");
expect(f1.static()).toBe("bar");
expect(f2.instance()).toBe("foo");
expect(f2.static()).toBe("bar");
expect(Foo1.instance(f1)).toBe("foo");
expect(Foo1.static()).toBe("bar");
expect(Foo2.instance(f2)).toBe("foo");
expect(Foo2.static()).toBe("bar");
expect(() => {
f1.instance.call(f2), undefined;
}).toThrow();
expect(() => {
f2.instance.call(f1), undefined;
}).toThrow();
expect(() => {
Foo1.instance(f2), undefined;
}).toThrow();
expect(() => {
Foo2.instance(f1), undefined;
}).toThrow();
"#
);
test!(
syntax(),
|t| tr(t),
public_numeric,
r#"
class Foo {
0 = "foo";
1 = "bar";
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_defineProperty(this, 0, "foo");
_defineProperty(this, 1, "bar");
};
"#
);
test!(
syntax(),
|t| tr(t),
private_assignment,
r#"
class Foo {
#foo = 0;
test(other) {
this.#foo += 1;
this.#foo = 2;
other.obj.#foo += 1;
other.obj.#foo = 2;
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
_foo.set(this, {
writable: true,
value: 0
});
}
_createClass(Foo, [{
key: "test",
value: function test(other) {
var _obj;
_classPrivateFieldSet(this, _foo, _classPrivateFieldGet(this, _foo) + 1);
_classPrivateFieldSet(this, _foo, 2);
_classPrivateFieldSet(_obj = other.obj, _foo, _classPrivateFieldGet(_obj, _foo) + 1);
_classPrivateFieldSet(other.obj, _foo, 2);
}
}]);
return Foo;
}();
var _foo = new WeakMap();
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_constructor_collision_exec,
r#"
var foo = "bar";
class Foo {
#bar = foo;
constructor() {
var foo = "foo";
}
test() {
return this.#bar;
}
}
const f = new Foo;
expect(f.test()).toBe(foo);
expect("bar" in f).toBe(false);
"#
);
test!(
syntax(),
|t| tr(t),
public_static_export,
r#"
export class MyClass {
static property = value;
}
export default class MyClass2 {
static property = value;
}
"#,
r#"
export var MyClass = function MyClass() {
'use strict';
_classCallCheck(this, MyClass);
};
_defineProperty(MyClass, "property", value);
var MyClass2 = function MyClass2() {
'use strict';
_classCallCheck(this, MyClass2);
};
_defineProperty(MyClass2, "property", value);
export { MyClass2 as default };
"#
);
test!(
syntax(),
|t| tr(t),
private_multiple,
r#"
class Foo {
#x = 0;
#y = this.#x;
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_x.set(this, {
writable: true,
value: 0
});
_y.set(this, {
writable: true,
value: _classPrivateFieldGet(this, _x)
});
};
var _x = new WeakMap();
var _y = new WeakMap();
"#
);
test!(
syntax(),
|t| tr(t),
public_derived,
r#"
class Foo extends Bar {
bar = "foo";
}
"#,
r#"
var Foo =
/*#__PURE__*/
function (Bar) {
'use strict';
_inherits(Foo, Bar);
function Foo() {
_classCallCheck(this, Foo);
var _this;
_this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).apply(this, arguments))
_defineProperty(_assertThisInitialized(_this), "bar", "foo");
return _this;
}
return Foo;
}(Bar);
"#
);
test_exec!(
syntax(),
|t| tr(t),
public_static_undefined_exec,
r#"
class Foo {
static num;
}
expect("num" in Foo).toBe(true);
expect(Foo.num).toBeUndefined();
"#
);
test!(
syntax(),
|t| tr(t),
public_instance,
r#"
class Foo {
bar = "foo";
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
_defineProperty(this, "bar", "foo");
};
"#
);
test_exec!(
syntax(),
|t| tr(t),
static_property_tdz_edgest_case_exec,
r#"
expect(() => {
class A {
static [{ x: A || 0 }.x];
}
}).toThrow();
"#
);
test!(
syntax(),
|t| tr(t),
public_non_block_arrow_func,
r#"
export default param =>
class App {
static props = {
prop1: 'prop1',
prop2: 'prop2'
}
getParam() {
return param;
}
}
"#,
r#"
export default ((param)=>{
var App = function() {
'use strict';
function App() {
_classCallCheck(this, App);
}
_createClass(App, [{
key: 'getParam',
value: function getParam() {
return param;
}
}]);
return App;
}();
_defineProperty(App, 'props', {
prop1: 'prop1', prop2: 'prop2'
});
return App;
});
"#
);
test!(
syntax(),
|t| tr(t),
public_static_undefined,
r#"
class Foo {
static bar;
}
"#,
r#"
var Foo = function Foo() {
'use strict';
_classCallCheck(this, Foo);
};
_defineProperty(Foo, "bar", void 0);
"#
);
test_exec!(
syntax(),
|t| tr(t),
public_static_infer_name_exec,
r#"
var Foo = class {
static num = 0;
}
expect(Foo.num).toBe(0);
expect(Foo.num = 1).toBe(1);
expect(Foo.name).toBe("Foo");
"#
);
test_exec!(
syntax(),
|t| tr(t),
static_property_tdz_general_exec,
r#"
expect(() => {
class C {
static [C + 3] = 3;
}
}).toThrow();
"#
);
test!(
syntax(),
|t| tr(t),
private_call,
r#"
class Foo {
#foo = function() {
return this;
}
test(other) {
this.#foo();
other.obj.#foo();
}
}
"#,
r#"
var Foo = function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
var _this = this;
_foo.set(this, {
writable: true,
value: function () {
return _this;
}
});
}
_createClass(Foo, [{
key: "test",
value: function test(other) {
var _obj;
_classPrivateFieldGet(this, _foo).call(this);
_classPrivateFieldGet(_obj = other.obj, _foo).call(_obj);
}
}]);
return Foo;
}();
var _foo = new WeakMap();
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_derived_exec,
r#"
class Foo {
#prop = "foo";
foo() {
return this.#prop;
}
}
class Bar extends Foo {
#prop = "bar";
bar() {
return this.#prop;
}
}
const f = new Foo;
expect(f.foo()).toBe("foo");
const b = new Bar;
expect(b.foo()).toBe("foo");
expect(b.bar()).toBe("bar");
"#
);
test!(
syntax(),
|t| tr(t),
private_extracted_this,
r#"
var foo = "bar";
class Foo {
#bar = this;
#baz = foo;
constructor(foo) {
}
}
"#,
r#"
var foo = "bar";
var Foo = function Foo(foo1) {
'use strict';
_classCallCheck(this, Foo);
_bar.set(this, {
writable: true,
value: this
});
_baz.set(this, {
writable: true,
value: foo
});
};
var _bar = new WeakMap();
var _baz = new WeakMap();
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_canonical_exec,
r#"
class Point {
#x;
#y;
constructor(x = 0, y = 0) {
this.#x = +x;
this.#y = +y;
}
get x() { return this.#x }
set x(value) { this.#x = +value }
get y() { return this.#y }
set y(value) { this.#y = +value }
equals(p) { return this.#x === p.#x && this.#y === p.#y }
toString() { return `Point<${ this.#x },${ this.#y }>` }
}
const p1 = new Point(1, 2);
const p2 = new Point(2, 3);
const p3 = new Point(1, 2);
expect(p1.x).toBe(1);
expect(p1.y).toBe(2);
expect(p2.x).toBe(2);
expect(p2.y).toBe(3);
expect(p3.x).toBe(1);
expect(p3.y).toBe(2);
expect(p1.equals(p1)).toBe(true)
expect(p1.equals(p2)).toBe(false)
expect(p1.equals(p3)).toBe(true)
expect(p2.equals(p1)).toBe(false)
expect(p2.equals(p2)).toBe(true)
expect(p2.equals(p3)).toBe(false)
expect(p3.equals(p1)).toBe(true)
expect(p3.equals(p2)).toBe(false)
expect(p3.equals(p3)).toBe(true)
expect(p1.toString()).toBe("Point<1,2>")
expect(p2.toString()).toBe("Point<2,3>")
expect(p3.toString()).toBe("Point<1,2>")
p1.x += 1;
p1.y = 3;
p2.x -= 1;
p2.y = 3;
p3.x = 0;
p3.y = 0;
expect(p1.x).toBe(2);
expect(p1.y).toBe(3);
expect(p2.x).toBe(1);
expect(p2.y).toBe(3);
expect(p3.x).toBe(0);
expect(p3.y).toBe(0);
expect(p1.equals(p1)).toBe(true)
expect(p1.equals(p2)).toBe(false)
expect(p1.equals(p3)).toBe(false)
expect(p2.equals(p1)).toBe(false)
expect(p2.equals(p2)).toBe(true)
expect(p2.equals(p3)).toBe(false)
expect(p3.equals(p1)).toBe(false)
expect(p3.equals(p2)).toBe(false)
expect(p3.equals(p3)).toBe(true)
expect(p1.toString()).toBe("Point<2,3>")
expect(p2.toString()).toBe("Point<1,3>")
expect(p3.toString()).toBe("Point<0,0>")
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_static_undefined_exec,
r#"
class Foo {
static #bar;
static test() {
return Foo.#bar;
}
test() {
return Foo.#bar;
}
}
expect("bar" in Foo).toBe(false);
expect(Foo.test()).toBe(undefined);
expect(Foo.test()).toBe(undefined);
"#
);
test_exec!(
syntax(),
|t| tr(t),
public_update_exec,
r#"
class Foo {
foo = 0;
test(other) {
return [
this.foo++,
this.foo,
++this.foo,
this.foo,
other.obj.foo++,
other.obj.foo,
++other.obj.foo,
other.obj.foo,
];
}
}
const f = new Foo;
const results = f.test({ obj: f });
expect(results[0]).toBe(0);
expect(results[1]).toBe(1);
expect(results[2]).toBe(2);
expect(results[3]).toBe(2);
expect(results[4]).toBe(2);
expect(results[5]).toBe(3);
expect(results[6]).toBe(4);
expect(results[7]).toBe(4);
"#
);
test!(
syntax(),
|t| tr(t),
private_static_call,
r#"
class Foo {
static #foo = function(x) {
return x;
}
test(x) {
return Foo.#foo(x);
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
}
_createClass(Foo, [{
key: "test",
value: function test(x) {
return _classStaticPrivateFieldSpecGet(Foo, Foo, _foo).call(Foo, x);
}
}]);
return Foo;
}();
var _foo = {
writable: true,
value: function (x) {
return x;
}
};
"#
);
test!(
syntax(),
|t| tr(t),
private_super_expression,
r#"
class Foo extends Bar {
#bar = "foo";
constructor() {
foo(super());
}
}
"#,
r#"
var Foo =
/*#__PURE__*/
function (Bar) {
'use strict';
_inherits(Foo, Bar);
function Foo() {
_classCallCheck(this, Foo);
var _this;
var _temp;
foo((_temp = _this = _possibleConstructorReturn(this, _getPrototypeOf(Foo).call(this)),
_bar.set(_assertThisInitialized(_this), {
writable: true,
value: "foo"
}), _temp));
return _possibleConstructorReturn(_this);
}
return Foo;
}(Bar);
var _bar = new WeakMap();
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_native_classes_exec,
r#"
class Foo {
static #foo = "foo";
#bar = "bar";
static test() {
return Foo.#foo;
}
test() {
return this.#bar;
}
}
const f = new Foo();
expect("foo" in Foo).toBe(false)
expect("bar" in f).toBe(false)
expect(Foo.test()).toBe("foo")
expect(f.test()).toBe("bar")
"#
);
test_exec!(
syntax(),
|t| tr(t),
private_multiple_exec,
r#"
class Foo {
#x = 0;
#y = this.#x + 1;
test() {
return this.#y;
}
}
const f = new Foo();
expect(f.test()).toBe(1);
"#
);
test!(
syntax(),
|t| tr(t),
custom_instance_update,
"
class Foo {
#x = 0;
test() {
this.#x++;
++this.#x;
}
}
",
"
var Foo = function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
_x.set(this, {
writable: true,
value: 0
});
}
_createClass(Foo, [{
key: 'test',
value: function test() {
var old;
_classPrivateFieldSet(this, _x, (old = +_classPrivateFieldGet(this, _x)) + 1), old;
_classPrivateFieldSet(this, _x, +_classPrivateFieldGet(this, _x) + 1);
}
}]);
return Foo;
}();
var _x = new WeakMap();
"
);
test!(
syntax(),
|t| tr(t),
custom_static_update,
"
class Foo {
static #x = 0;
test() {
Foo.#x++;
++Foo.#x;
}
}
",
"
var Foo = function () {
'use strict';
function Foo() {
_classCallCheck(this, Foo);
}
_createClass(Foo, [{
key: 'test',
value: function test() {
var old;
_classStaticPrivateFieldSpecSet(Foo, Foo, _x, (old = +_classStaticPrivateFieldSpecGet(Foo, \
Foo, _x)) + 1), old;
_classStaticPrivateFieldSpecSet(Foo, Foo, _x, +_classStaticPrivateFieldSpecGet(Foo, Foo, _x) \
+ 1);
}
}]);
return Foo;
}();
var _x = {
writable: true,
value: 0
};"
);
test!(
syntax(),
|_| chain!(resolver(), class_properties()),
issue_308,
"function bar(props) {}
class Foo {
constructor() {
super();
bar();
}
onBar = () => {
bar();
};
}",
"function bar(props) {
}
class Foo{
constructor(){
super();
_defineProperty(this, 'onBar', ()=>{
bar();
});
bar();
}
}
"
);
test!(
syntax(),
|t| chain!(
resolver(),
class_properties(),
classes(Some(t.comments.clone()))
),
issue_342,
"class Foo {
constructor(bar) {
this._bar = bar;
}
qux = {
frob: (bar) => {},
};
}",
"
let Foo = function Foo(bar) {
'use strict';
_classCallCheck(this, Foo);
_defineProperty(this, 'qux', {
frob: (bar)=>{
}
});
this._bar = bar;
};"
);
test!(
syntax(),
|_| chain!(resolver(), class_properties(), block_scoping()),
issue_443,
"
const MODE = 1;
class foo {
static MODE = MODE;
constructor() {
this.mode = MODE;
}
}
",
"var MODE = 1;
class foo{
constructor(){
this.mode = MODE;
}
}
_defineProperty(foo, 'MODE', MODE);"
);
// public_regression_t7364
test!(
syntax(),
|_| chain!(class_properties(), async_to_generator()),
public_regression_t7364,
r#"
class MyClass {
myAsyncMethod = async () => {
console.log(this);
}
}
(class MyClass2 {
myAsyncMethod = async () => {
console.log(this);
}
})
export default class MyClass3 {
myAsyncMethod = async () => {
console.log(this);
}
}
"#,
r#"
class MyClass {
constructor(){
_defineProperty(this, "myAsyncMethod", _asyncToGenerator((function*() {
console.log(this);
}).bind(this)).bind(this));
}
}
(class MyClass2 {
constructor(){
_defineProperty(this, "myAsyncMethod", _asyncToGenerator((function*() {
console.log(this);
}).bind(this)).bind(this));
}
})
class MyClass3 {
constructor(){
_defineProperty(this, "myAsyncMethod", _asyncToGenerator((function*() {
console.log(this);
}).bind(this)).bind(this));
}
}
export { MyClass3 as default };
"#
);
// private_regression_t6719
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_regression_t6719,
r#"
function withContext(ComposedComponent) {
return class WithContext extends Component {
static #propTypes = {
context: PropTypes.shape(
{
addCss: PropTypes.func,
setTitle: PropTypes.func,
setMeta: PropTypes.func,
}
),
};
};
}
"#,
r#"
function withContext(ComposedComponent) {
return (function() {
class WithContext extends Component{
}
var _propTypes = {
writable: true,
value: {
context: PropTypes.shape({
addCss: PropTypes.func,
setTitle: PropTypes.func,
setMeta: PropTypes.func
})
}
};
return WithContext;
})();
}
"#
);
// public_foobar
//test!(syntax(),|_| tr("{
// "plugins": [ "proposal-class-properties"],
// "presets": ["env"]
//}
//"), public_foobar, r#"
//class Child extends Parent {
// constructor() {
// super();
// }
//
// scopedFunctionWithThis = () => {
// this.name = {};
// }
//}
//
//"#, r#"
//var Child =
// /*#__PURE__*/
//function (_Parent) {
// "use strict";
//
// _inherits(Child, _Parent);
//
// function Child() {
// var _this;
//
// _classCallCheck(this, Child);
// _this = _possibleConstructorReturn(this,
// _getPrototypeOf(Child).call(this));
// _defineProperty(_assertThisInitialized(_this), "scopedFunctionWithThis",
// function () { _this.name = {};
// });
// return _this;
// }
//
// return Child;
//}(Parent);
//
//"#);
// private_reevaluated
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_reevaluated,
r#"
function classFactory() {
return class Foo {
#foo = "foo";
static #bar = "bar";
instance() {
return this.#foo;
}
static() {
return Foo.#bar;
}
static instance(inst) {
return inst.#foo;
}
static static() {
return Foo.#bar;
}
};
}
"#,
r#"
function classFactory() {
return (function() {
class Foo{
instance() {
return _classPrivateFieldGet(this, _foo);
}
static() {
return _classStaticPrivateFieldSpecGet(Foo, Foo, _bar);
}
static instance(inst) {
return _classPrivateFieldGet(inst, _foo);
}
static static() {
return _classStaticPrivateFieldSpecGet(Foo, Foo, _bar);
}
constructor(){
_foo.set(this, {
writable: true,
value: 'foo'
});
}
}
var _foo = new WeakMap();
var _bar = {
writable: true,
value: 'bar'
};
return Foo;
})();
}
"#
);
// private_static
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_static,
r#"
class Foo {
static #bar = "foo";
static test() {
return Foo.#bar;
}
test() {
return Foo.#bar;
}
}
expect("bar" in Foo).toBe(false)
expect(Foo.test()).toBe("foo")
expect(Foo.test()).toBe("foo")
"#,
r#"
class Foo {
static test() {
return _classStaticPrivateFieldSpecGet(Foo, Foo, _bar);
}
test() {
return _classStaticPrivateFieldSpecGet(Foo, Foo, _bar);
}
}
var _bar = {
writable: true,
value: "foo"
};
expect("bar" in Foo).toBe(false);
expect(Foo.test()).toBe("foo");
expect(Foo.test()).toBe("foo");
"#
);
// private_destructuring_object_pattern_1
test!(
syntax(),
|t| chain!(
class_properties(),
classes(Some(t.comments.clone())),
block_scoping()
),
private_destructuring_object_pattern_1,
r#"
class Foo {
#client
constructor(props) {
this.#client = 'foo';
({ x: this.x = this.#client, y: this.#client, z: this.z = this.#client } = props)
}
}
"#,
r#"
var Foo = function Foo(props) {
"use strict";
_classCallCheck(this, Foo);
_client.set(this, {
writable: true,
value: void 0
});
_classPrivateFieldSet(this, _client, 'foo');
({
x: this.x = _classPrivateFieldGet(this, _client),
y: _classPrivateFieldDestructureSet(this, _client).value,
z: this.z = _classPrivateFieldGet(this, _client)
} = props);
};
var _client = new WeakMap();
"#
);
// private_static_inherited
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_static_inherited,
r#"
class Base {
static #foo = 1;
static getThis() {
return this.#foo;
}
static updateThis(val) {
return (this.#foo = val);
}
static getClass() {
return Base.#foo;
}
static updateClass(val) {
return (Base.#foo = val);
}
}
class Sub1 extends Base {
static #foo = 2;
static update(val) {
return (this.#foo = val);
}
}
class Sub2 extends Base {}
"#,
r#"
class Base {
static getThis() {
return _classStaticPrivateFieldSpecGet(this, Base, _foo);
}
static updateThis(val) {
return _classStaticPrivateFieldSpecSet(this, Base, _foo, val);
}
static getClass() {
return _classStaticPrivateFieldSpecGet(Base, Base, _foo);
}
static updateClass(val) {
return _classStaticPrivateFieldSpecSet(Base, Base, _foo, val);
}
}
var _foo = {
writable: true,
value: 1
};
class Sub1 extends Base {
static update(val) {
return _classStaticPrivateFieldSpecSet(this, Sub1, _foo1, val);
}
}
var _foo1 = {
writable: true,
value: 2
};
class Sub2 extends Base {}
"#
);
// private_destructuring_object_pattern_1_exec
test_exec!(
syntax(),
|_| class_properties(),
private_destructuring_object_pattern_1_exec,
r#"
class Foo {
#client
constructor(props) {
this.#client = 'foo';
;({ x: this.x = this.#client, y: this.#client, z: this.z = this.#client } = props)
}
getClient() {
return this.#client;
}
}
const foo = new Foo({ y: 'bar' });
expect(foo.getClient()).toBe('bar');
expect(foo.x).toBe('foo');
expect(foo.z).toBe('bar');
"#
);
// private_static_undefined
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_static_undefined,
r#"
class Foo {
static #bar;
static test() {
return Foo.#bar;
}
test() {
return Foo.#bar;
}
}
"#,
r#"
class Foo {
static test() {
return _classStaticPrivateFieldSpecGet(Foo, Foo, _bar);
}
test() {
return _classStaticPrivateFieldSpecGet(Foo, Foo, _bar);
}
}
var _bar = {
writable: true,
value: void 0
};
"#
);
// private_destructuring_array_pattern
test!(
syntax(),
|t| chain!(
class_properties(),
classes(Some(t.comments.clone())),
block_scoping()
),
private_destructuring_array_pattern,
r#"
class Foo {
#client
constructor(props) {
([this.#client] = props);
}
}
"#,
r#"
var Foo = function Foo(props) {
"use strict";
_classCallCheck(this, Foo);
_client.set(this, {
writable: true,
value: void 0
});
[_classPrivateFieldDestructureSet(this, _client).value] = props;
};
var _client = new WeakMap();
"#
);
// private_regression_t2983
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_regression_t2983,
r#"
call(class {
static #test = true
});
export default class {
static #test = true
}
"#,
r#"
call(function() {
class _class{
}
var _test = {
writable: true,
value: true
};
return _class;
}());
class _class{
}
var _test = {
writable: true,
value: true
};
export { _class as default }
"#
);
// private_regression_t7364
test!(
syntax(),
|_| chain!(class_properties(), async_to_generator(), block_scoping()),
private_regression_t7364,
r#"
class MyClass {
#myAsyncMethod = async () => {
console.log(this);
}
}
(class MyClass2 {
#myAsyncMethod = async () => {
console.log(this);
}
})
export default class MyClass3 {
#myAsyncMethod = async () => {
console.log(this);
}
}
"#,
r#"
class MyClass {
constructor(){
_myAsyncMethod.set(this, {
writable: true,
value: _asyncToGenerator((function*() {
console.log(this);
}).bind(this)).bind(this)
});
}
}
var _myAsyncMethod = new WeakMap();
(function() {
class MyClass2 {
constructor(){
_myAsyncMethod.set(this, {
writable: true,
value: _asyncToGenerator((function*() {
console.log(this);
}).bind(this)).bind(this)
});
}
}
var _myAsyncMethod = new WeakMap();
return MyClass2;
})();
class MyClass3 {
constructor(){
_myAsyncMethod1.set(this, {
writable: true,
value: _asyncToGenerator((function*() {
console.log(this);
}).bind(this)).bind(this)
});
}
}
var _myAsyncMethod1 = new WeakMap();
export { MyClass3 as default };
"#
);
// private_destructuring_array_pattern_1
test!(
syntax(),
|t| chain!(
class_properties(),
classes(Some(t.comments.clone())),
block_scoping()
),
private_destructuring_array_pattern_1,
r#"
class Foo {
#client
constructor(props) {
this.#client = 1;
([this.x = this.#client, this.#client, this.y = this.#client] = props);
}
}
"#,
r#"
var Foo = function Foo(props) {
"use strict";
_classCallCheck(this, Foo);
_client.set(this, {
writable: true,
value: void 0
});
_classPrivateFieldSet(this, _client, 1);
[this.x = _classPrivateFieldGet(this, _client), _classPrivateFieldDestructureSet(this, _client).value, this.y = _classPrivateFieldGet(this, _client)] = props;
};
var _client = new WeakMap();
"#
);
// regression_8882_exec
test_exec!(
syntax(),
|_| class_properties(),
regression_8882_exec,
r#"
const classes = [];
for (let i = 0; i <= 10; ++i) {
classes.push(
class A {
[i] = `computed field ${i}`;
static foo = `static field ${i}`;
#bar = `private field ${i}`;
getBar() {
return this.#bar;
}
}
);
}
for(let i=0; i<= 10; ++i) {
const clazz = classes[i];
expect(clazz.foo).toBe('static field ' + i);
const instance = new clazz();
expect(Object.getOwnPropertyNames(instance)).toEqual([String(i)])
expect(instance[i]).toBe('computed field ' + i);
expect(instance.getBar()).toBe('private field ' + i);
}
"#
);
//// regression_6154
//test!(syntax(),|_| tr("{
// "presets": ["env"],
// "plugins": class_properties()
//}
//"), regression_6154, r#"
//class Test {
// constructor() {
// class Other extends Test {
// a = () => super.test;
// static a = () => super.test;
// }
// }
//}
//
//"#, r#"
//function _typeof(obj) { if (typeof Symbol === "function" && typeof
// Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return
// typeof obj; }; } else { _typeof = function _typeof(obj) { return obj &&
// typeof Symbol === "function" && obj.constructor === Symbol && obj !==
// Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
//
//function _possibleConstructorReturn(self, call) { if (call && (_typeof(call)
// === "object" || typeof call === "function")) { return call; } return
// _assertThisInitialized(self); }
//
//function _assertThisInitialized(self) { if (self === void 0) { throw new
// ReferenceError("this hasn't been initialised - super() hasn't been called");
// } return self; }
//
//function _inherits(subClass, superClass) { if (typeof superClass !==
// "function" && superClass !== null) { throw new TypeError("Super expression
// must either be null or a function"); } subClass.prototype =
// Object.create(superClass && superClass.prototype, { constructor: { value:
// subClass, writable: true, configurable: true } }); if (superClass)
// _setPrototypeOf(subClass, superClass); }
//
//function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ||
// function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return
// _setPrototypeOf(o, p); }
//
//function _get(target, property, receiver) { if (typeof Reflect !==
// "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function
// _get(target, property, receiver) { var base = _superPropBase(target,
// property); if (!base) return; var desc =
// Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return
// desc.get.call(receiver); } return desc.value; }; } return _get(target,
// property, receiver || target); }
//
//function _superPropBase(object, property) { while
// (!Object.prototype.hasOwnProperty.call(object, property)) { object =
// _getPrototypeOf(object); if (object === null) break; } return object; }
//
//function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ?
// Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ ||
// Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
//
//function _defineProperty(obj, key, value) { if (key in obj) {
// Object.defineProperty(obj, key, { value: value, enumerable: true,
// configurable: true, writable: true }); } else { obj[key] = value; } return
// obj; }
//
//function _classCallCheck(instance, Constructor) { if (!(instance instanceof
// Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//
//var Test = function Test() {
// "use strict";
//
// _classCallCheck(this, Test);
//
// var Other =
// /*#__PURE__*/
// function (_Test) {
// _inherits(Other, _Test);
//
// function Other() {
// var _getPrototypeOf2;
//
// var _this;
//
// _classCallCheck(this, Other);
//
// for (var _len = arguments.length, args = new Array(_len), _key = 0; _key
// < _len; _key++) { args[_key] = arguments[_key];
// }
//
// _this = _possibleConstructorReturn(this, (_getPrototypeOf2 =
// _getPrototypeOf(Other)).call.apply(_getPrototypeOf2, [this].concat(args)));
//
// _defineProperty(_assertThisInitialized(_this), "a", function () {
// return _get(_getPrototypeOf(Other.prototype), "test",
// _assertThisInitialized(_this)); });
//
// return _this;
// }
//
// return Other;
// }(Test);
//
// _defineProperty(Other, "a", function () {
// return _get(_getPrototypeOf(Other), "test", Other);
// });
//};
//
//"#);
// private_static_export
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_static_export,
r#"
export class MyClass {
static #property = value;
}
export default class MyClass2 {
static #property = value;
}
"#,
r#"
export class MyClass {}
var _property = {
writable: true,
value: value
};
class MyClass2{
}
var _property1 = {
writable: true,
value: value
};
export { MyClass2 as default }
"#
);
// static_property_tdz_edgest_case
test!(
syntax(),
|t| chain!(class_properties(), classes(Some(t.comments.clone()))),
static_property_tdz_edgest_case,
r#"
class A {
static [{ x: A || 0 }.x];
}
"#,
r#"
var _x = {
x: (_classNameTDZError("A"), A) || 0
}.x;
let A = function A() {
"use strict";
_classCallCheck(this, A);
};
_defineProperty(A, _x, void 0);
"#
);
// regression_6153
test!(
syntax(),
|_| chain!(class_properties(), arrow()),
regression_6153,
r#"
() => {
class Foo {
fn = () => console.log(this);
static fn = () => console.log(this);
}
};
() => class Bar {
fn = () => console.log(this);
static fn = () => console.log(this);
};
() => {
class Baz {
fn = () => console.log(this);
force = force
static fn = () => console.log(this);
constructor(force) {}
}
};
var qux = function() {
class Qux {
fn = () => console.log(this);
static fn = () => console.log(this);
}
}.bind(this)
"#,
r#"
(function () {
class Foo {
constructor() {
var _this = this;
_defineProperty(this, 'fn', function() {
return console.log(_this);
});
}
}
_defineProperty(Foo, "fn", function () {
return console.log(Foo);
});
});
(function () {
class Bar {
constructor() {
var _this = this;
_defineProperty(this, 'fn', function() {
return console.log(_this);
});
}
}
_defineProperty(Bar, "fn", function () {
return console.log(Bar);
});
return Bar;
});
(function () {
class Baz {
constructor(force){
var _this = this;
_defineProperty(this, 'fn', function() {
return console.log(_this);
});
_defineProperty(this, "force", force);
}
}
_defineProperty(Baz, "fn", function () {
return console.log(Baz);
});
});
var qux = (function () {
class Qux {
constructor() {
var _this = this;
_defineProperty(this, 'fn', function() {
return console.log(_this);
});
}
}
_defineProperty(Qux, "fn", function () {
return console.log(Qux);
});
}).bind(this);
"#
);
// regression_7371
test!(
syntax(),
|_| chain!(class_properties(), arrow()),
regression_7371,
r#"
"use strict";
class C {
}
class A extends C {
field = 1;
constructor() {
super();
class B extends C {
constructor() {
super();
expect(this.field).toBeUndefined();
}
}
expect(this.field).toBe(1)
new B();
}
}
new A();
class Obj {
constructor() {
return {};
}
}
// ensure superClass is still transformed
class SuperClass extends Obj {
field = 1;
constructor() {
class B extends (super(), Obj) {
constructor() {
super();
expect(this.field).toBeUndefined()
}
}
expect(this.field).toBe(1)
new B();
}
}
new SuperClass();
// ensure ComputedKey Method is still transformed
class ComputedMethod extends Obj {
field = 1;
constructor() {
class B extends Obj {
constructor() {
super();
expect(this.field).toBeUndefined()
}
[super()]() { }
}
expect(this.field).toBe(1)
new B();
}
}
new ComputedMethod();
// ensure ComputedKey Field is still transformed
class ComputedField extends Obj {
field = 1;
constructor() {
class B extends Obj {
constructor() {
super();
expect(this.field).toBeUndefined()
}
[super()] = 1;
}
expect(this.field).toBe(1)
new B();
}
}
new ComputedField();
"#,
r#"
"use strict";
class C {}
class A extends C {
constructor() {
super();
_defineProperty(this, "field", 1);
class B extends C {
constructor() {
super();
expect(this.field).toBeUndefined();
}
}
expect(this.field).toBe(1);
new B();
}
}
new A();
class Obj {
constructor() {
return {};
}
} // ensure superClass is still transformed
class SuperClass extends Obj {
constructor() {
var _temp;
class B extends (_temp = super(), _defineProperty(this, 'field', 1), _temp, Obj) {
constructor() {
super();
expect(this.field).toBeUndefined();
}
}
expect(this.field).toBe(1);
new B();
}
}
new SuperClass(); // ensure ComputedKey Method is still transformed
class ComputedMethod extends Obj {
constructor() {
var _temp;
var tmp = (_temp = super(), _defineProperty(this, "field", 1), _temp);
class B extends Obj {
[tmp]() {}
constructor() {
super();
expect(this.field).toBeUndefined();
}
}
expect(this.field).toBe(1);
new B();
}
}
new ComputedMethod(); // ensure ComputedKey Field is still transformed
class ComputedField extends Obj {
constructor() {
var _temp;
var _ref = (_temp = super(), _defineProperty(this, "field", 1), _temp);
class B extends Obj {
constructor() {
super();
_defineProperty(this, _ref, 1);
expect(this.field).toBeUndefined();
}
}
expect(this.field).toBe(1);
new B();
}
}
new ComputedField();
"#
);
// private_canonical
test!(
syntax(),
|t| chain!(
class_properties(),
classes(Some(t.comments.clone())),
block_scoping()
),
private_canonical,
r#"
class Point {
#x;
#y;
constructor(x = 0, y = 0) {
this.#x = +x;
this.#y = +y;
}
get x() { return this.#x }
set x(value) { this.#x = +value }
get y() { return this.#y }
set y(value) { this.#y = +value }
equals(p) { return this.#x === p.#x && this.#y === p.#y }
toString() { return `Point<${ this.#x },${ this.#y }>` }
}
"#,
r#"
var Point =
/*#__PURE__*/
function () {
"use strict";
function Point(x = 0, y = 0) {
_classCallCheck(this, Point);
_x.set(this, {
writable: true,
value: void 0
});
_y.set(this, {
writable: true,
value: void 0
});
_classPrivateFieldSet(this, _x, +x);
_classPrivateFieldSet(this, _y, +y);
}
_createClass(Point, [{
key: "x",
get: function () {
return _classPrivateFieldGet(this, _x);
},
set: function (value) {
_classPrivateFieldSet(this, _x, +value);
}
}, {
key: "y",
get: function () {
return _classPrivateFieldGet(this, _y);
},
set: function (value) {
_classPrivateFieldSet(this, _y, +value);
}
}, {
key: "equals",
value: function equals(p) {
return _classPrivateFieldGet(this, _x) === _classPrivateFieldGet(p, _x) && _classPrivateFieldGet(this, _y) === _classPrivateFieldGet(p, _y);
}
}, {
key: "toString",
value: function toString() {
return `Point<${_classPrivateFieldGet(this, _x)},${_classPrivateFieldGet(this, _y)}>`;
}
}]);
return Point;
}();
var _x = new WeakMap();
var _y = new WeakMap();
"#
);
// regression_8882
test!(
syntax(),
|_| class_properties(),
regression_8882,
r#"
const classes = [];
for(let i = 0; i <= 10; ++i){
classes.push(function() {
class A{
getBar() {
return _classPrivateFieldGet(this, _bar);
}
constructor(){
_defineProperty(this, i, `computed field ${i}`);
_bar.set(this, {
writable: true,
value: `private field ${i}`
});
}
}
_defineProperty(A, 'foo', `static field ${i}`);
var _bar = new WeakMap();
return A;
}());
}
"#,
r#"
const classes = [];
for(let i = 0; i <= 10; ++i){
classes.push(function() {
class A{
getBar() {
return _classPrivateFieldGet(this, _bar);
}
constructor(){
_defineProperty(this, i, `computed field ${i}`);
_bar.set(this, {
writable: true,
value: `private field ${i}`
});
}
}
_defineProperty(A, 'foo', `static field ${i}`);
var _bar = new WeakMap();
return A;
}());
}
"#
);
// private_destructuring_array_pattern_3
test!(
syntax(),
|t| chain!(
class_properties(),
classes(Some(t.comments.clone())),
block_scoping()
),
private_destructuring_array_pattern_3,
r#"
class Foo {
#client
constructor(props) {
([this.#client = 5] = props);
}
}
"#,
r#"
var Foo = function Foo(props) {
"use strict";
_classCallCheck(this, Foo);
_client.set(this, {
writable: true,
value: void 0
});
[_classPrivateFieldDestructureSet(this, _client).value = 5] = props;
};
var _client = new WeakMap();
"#
);
// public_static_super_exec
test_exec!(
syntax(),
|_| class_properties(),
public_static_super_exec,
r#"
class A {
static prop = 1;
}
class B extends A {
static prop = 2;
static propA = super.prop;
static getPropA = () => super.prop;
}
const { prop, propA, getPropA } = B;
expect(prop).toBe(2);
expect(propA).toBe(1);
expect(getPropA()).toBe(1);
"#
);
// private_destructuring_array_pattern_2
test!(
syntax(),
|t| chain!(
class_properties(),
classes(Some(t.comments.clone())),
block_scoping()
),
private_destructuring_array_pattern_2,
r#"
class Foo {
#client
constructor(props) {
([x, ...this.#client] = props);
}
}
"#,
r#"
var Foo = function Foo(props) {
"use strict";
_classCallCheck(this, Foo);
_client.set(this, {
writable: true,
value: void 0
});
[x, ..._classPrivateFieldDestructureSet(this, _client).value] = props;
};
var _client = new WeakMap();
"#
);
// private_non_block_arrow_func
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_non_block_arrow_func,
r#"
export default param =>
class App {
static #props = {
prop1: 'prop1',
prop2: 'prop2'
}
getParam() {
return param;
}
}
"#,
r#"
export default ((param)=>{
class App{
getParam() {
return param;
}
}
var _props = {
writable: true,
value: {
prop1: 'prop1',
prop2: 'prop2'
}
};
return App;
});
"#
);
// regression_8110
test!(
syntax(),
|_| class_properties(),
regression_8110,
r#"
const field = Symbol('field');
class A {
[field] = 10;
}
"#,
r#"
const field = Symbol('field');
var _field = field;
class A{
constructor(){
_defineProperty(this, _field, 10);
}
}
"#
);
// public_computed_without_block_exec
test_exec!(
syntax(),
|_| class_properties(),
public_computed_without_block_exec,
r#"
const createClass = (k) => class { [k()] = 2 };
const clazz = createClass(() => 'foo');
const instance = new clazz();
expect(instance.foo).toBe(2);
"#
);
// private_instance
test!(
syntax(),
|t| chain!(
class_properties(),
exponentation(),
classes(Some(t.comments.clone())),
block_scoping(),
),
private_instance,
r#"
class Foo {
#bar = "foo";
}
"#,
r#"
var Foo = function Foo() {
"use strict";
_classCallCheck(this, Foo);
_bar.set(this, {
writable: true,
value: "foo"
});
};
var _bar = new WeakMap();
"#
);
// static_property_tdz_general
test!(
syntax(),
|t| chain!(class_properties(), classes(Some(t.comments.clone()))),
static_property_tdz_general,
r#"
class C {
static [C + 3] = 3;
}
"#,
r#"
var _ref = (_classNameTDZError('C'), C) + 3;
let C = function C() {
"use strict";
_classCallCheck(this, C);
};
_defineProperty(C, _ref, 3);
"#
);
// public_native_classes
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
public_native_classes,
r#"
class Foo {
static foo = "foo";
bar = "bar";
}
"#,
r#"
class Foo {
constructor() {
_defineProperty(this, "bar", "bar");
}
}
_defineProperty(Foo, "foo", "foo");
"#
);
// public_arrow_static_this_without_transform
test!(
// Emitting class properties is not supported yet.
ignore,
syntax(),
|_| arrow(),
public_arrow_static_this_without_transform,
r#"
class Foo {
static fn = () => console.log(this);
}
"#,
r#"
var _this = this;
class Foo {
static fn = function () {
return console.log(_this);
};
}
"#
);
// private_static_infer_name
test!(
// Seems useless, while being hard to implement.
ignore,
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_static_infer_name,
r#"
var Foo = class {
static #num = 0;
}
"#,
r#"
var _class, _temp, _num;
var Foo = (_temp = _class = class Foo {}, _num = {
writable: true,
value: 0
}, _temp);
"#
);
// regression_7951
test!(
syntax(),
|_| chain!(resolver(), class_properties()),
regression_7951,
r#"
export class Foo extends Bar {
static foo = {};
test = args;
}
"#,
r#"
export class Foo extends Bar {
constructor(...args1) {
super(...args1);
_defineProperty(this, "test", args);
}
}
_defineProperty(Foo, "foo", {});
"#
);
// private_native_classes
test!(
syntax(),
|_| chain!(class_properties(), block_scoping()),
private_native_classes,
r#"
class Foo {
static #foo = "foo";
#bar = "bar";
static test() {
return Foo.#foo;
}
test() {
return this.#bar;
}
}
"#,
r#"
class Foo {
static test() {
return _classStaticPrivateFieldSpecGet(Foo, Foo, _foo);
}
test() {
return _classPrivateFieldGet(this, _bar);
}
constructor() {
_bar.set(this, {
writable: true,
value: "bar"
});
}
}
var _foo = {
writable: true,
value: "foo"
};
var _bar = new WeakMap();
"#
);
// public_computed_without_block
test!(
syntax(),
|t| chain!(
class_properties(),
classes(Some(t.comments.clone())),
block_scoping()
),
public_computed_without_block,
r#"
const createClass = (k) => class { [k()] = 2 };
"#,
r#"
var createClass = (k)=>{
var _ref = k();
var _class = function _class() {
'use strict';
_classCallCheck(this, _class);
_defineProperty(this, _ref, 2);
};
return _class;
};
"#
);
// private_destructuring_array_pattern_2_exec
test_exec!(
syntax(),
|_| class_properties(),
private_destructuring_array_pattern_2_exec,
r#"
class Foo {
#client
constructor(props) {
let x;
;([x, ...this.#client] = props);
}
getClient() {
return this.#client;
}
}
const foo = new Foo(['foo', 'bar', 'baz', 'quu']);
expect(foo.getClient()).toEqual(['bar', 'baz', 'quu']);
"#
);
// public_static_super
test!(
syntax(),
|t| chain!(
class_properties(),
classes(Some(t.comments.clone())),
block_scoping()
),
public_static_super,
r#"
class A {
static prop = 1;
}
class B extends A {
static prop = 2;
static propA = super.prop;
static getPropA = () => super.prop;
}
"#,
r#"
var A = function A() {
"use strict";
_classCallCheck(this, A);
};
_defineProperty(A, "prop", 1);
var B =
/*#__PURE__*/
function (A) {
"use strict";
_inherits(B, A);
function B() {
_classCallCheck(this, B);
return _possibleConstructorReturn(this, _getPrototypeOf(B).apply(this, arguments));
}
return B;
}(A);
_defineProperty(B, "prop", 2);
_defineProperty(B, "propA", _get(_getPrototypeOf(B), "prop", B));
_defineProperty(B, "getPropA", () => _get(_getPrototypeOf(B), "prop", B));
"#
);
// private_destructuring_array_pattern_exec
test_exec!(
syntax(),
|_| class_properties(),
private_destructuring_array_pattern_exec,
r#"
class Foo {
#client
constructor(props) {
;([this.#client] = props);
}
getClient() {
return this.#client;
}
}
const foo = new Foo(['bar']);
expect(foo.getClient()).toBe('bar');
"#
);
// private_destructuring_array_pattern_1_exec
test_exec!(
syntax(),
|_| class_properties(),
private_destructuring_array_pattern_1_exec,
r#"
class Foo {
#client
constructor(props) {
this.#client = 1;
;([this.x = this.#client, this.#client, this.y = this.#client] = props);
}
getClient() {
return this.#client;
}
}
const foo = new Foo([undefined, 'bar']);
expect(foo.getClient()).toBe('bar');
expect(foo.x).toBe(1);
expect(foo.y).toBe('bar');
"#
);
test!(
syntax(),
|_| typescript_class_properties(),
issue_1122_1,
"
const identifier = 'bar';
class Foo {
[identifier] = 5;
}
",
"
const identifier = \"bar\";
class Foo {
constructor(){
this[identifier] = 5;
}
}
"
);
test!(
syntax(),
|_| typescript_class_properties(),
issue_1122_2,
"
const identifier = 'bar';
class Foo {
identifier = 5;
}
",
"
const identifier = \"bar\";
class Foo {
constructor(){
this.identifier = 5;
}
}
"
);
test!(
syntax(),
|_| typescript_class_properties(),
issue_1122_3,
"
const identifier = 'bar';
class Foo {
['identifier'] = 5;
}
",
"
const identifier = \"bar\";
class Foo {
constructor(){
this[\"identifier\"] = 5;
}
}
"
);
test!(
syntax(),
|_| typescript_class_properties(),
issue_1122_4,
"
const identifier = 'bar';
class Foo {
static [identifier] = 5;
}
",
"
const identifier = \"bar\";
class Foo {
}
Foo[identifier] = 5;
"
);
test!(
syntax(),
|_| typescript_class_properties(),
issue_1122_5,
"
const identifier = 'bar';
class Foo {
static identifier = 5;
}
",
"
const identifier = \"bar\";
class Foo {
}
Foo.identifier = 5;
"
);
test!(
ts(),
|_| chain!(resolver(), class_properties()),
issue_890_1,
"const DURATION = 1000
export class HygieneTest {
private readonly duration: number = DURATION
constructor(duration?: number) {
this.duration = duration ?? DURATION
}
getDuration() {
return this.duration
}
}",
"const DURATION = 1000;
export class HygieneTest {
getDuration() {
return this.duration;
}
constructor(duration: number){
_defineProperty(this, 'duration', DURATION);
this.duration = duration ?? DURATION;
}
}",
ok_if_code_eq
);
test!(
syntax(),
|_| class_properties(),
issue_1306_1,
r#"
class Animal {
#name;
constructor(name) {
this.#name = name
}
noise() {
return this.#name
}
}
"#,
"
class Animal {
noise() {
return _classPrivateFieldGet(this, _name);
}
constructor(name){
_name.set(this, {
writable: true,
value: void 0
});
_classPrivateFieldSet(this, _name, name);
}
}
var _name = new WeakMap();
"
);
test!(
syntax(),
|_| class_properties(),
issue_1306_2,
r#"
class Animal {
#name;
constructor(name) {
this.#name = name
}
noise() {
return this.#name.toUpperCase()
}
}
"#,
"
class Animal {
noise() {
return _classPrivateFieldGet(this, _name).toUpperCase();
}
constructor(name){
_name.set(this, {
writable: true,
value: void 0
});
_classPrivateFieldSet(this, _name, name);
}
}
var _name = new WeakMap();
"
);
test!(
syntax(),
|_| class_properties(),
issue_1333_1,
"
class Foo {
get connected() {
return this.#ws2 && this.#ws.readyState === _ws1.default.OPEN;
}
}
",
"
class Foo {
get connected() {
return _classPrivateFieldGet(this, _ws2) && _classPrivateFieldGet(this, _ws).readyState \
=== _ws1.default.OPEN;
}
}
"
);
test!(
syntax(),
|_| class_properties(),
issue_1333_2,
"
class Test {
#ws;
_packet(raw) {
/** @type {DiscordPacket} */
let pak;
try {
pak = this.#serialization.decode(raw);
this.manager.emit(ClientEvent.RAW_PACKET, pak, this);
} catch (e) {
this.manager.client.emit(ClientEvent.SHARD_ERROR, e, this);
return;
}
switch (pak.t) {
case 'READY':
this.emit(ShardEvent.READY);
this.session.id = pak.d.session_id;
this.expectedGuilds = new Set(pak.d.guilds.map((g) => g.id));
this.status = Status.WAITING_FOR_GUILDS;
this.heartbeat.acked = true;
this.heartbeat.new('ready');
break;
case 'RESUMED':
/**
* Emitted when a shards connection has been resumed.
* @event Shard#resumed
*/
this.emit(ShardEvent.RESUMED);
this.status = Status.READY;
this.heartbeat.acked = true;
this.heartbeat.new('resumed');
break;
}
if (pak.s !== null) {
if (this.#seq !== -1 && pak.s > this.#seq + 1) {
this._debug(`Non-consecutive sequence [${this.#seq} => ${pak.s}]`);
}
this.#seq = pak.s;
}
switch (pak.op) {
case GatewayOp.HELLO:
this.heartbeat.delay = pak.d.heartbeat_interval;
this.session.hello();
break;
case GatewayOp.RECONNECT:
this._debug('Gateway asked us to reconnect.');
this.destroy({ code: 4000 });
break;
case GatewayOp.INVALID_SESSION:
this._debug(`Invalid Session: Resumable => ${pak.d}`);
if (pak.d) {
this.session.resume();
break;
}
this.#seq = -1;
this.session.reset();
this.status = Status.RECONNECTING;
this.emit(ShardEvent.INVALID_SESSION);
break;
case GatewayOp.HEARTBEAT:
this.heartbeat.new('requested');
break;
case GatewayOp.HEARTBEAT_ACK:
this.heartbeat.ack();
break;
default:
if (
this.status === Status.WAITING_FOR_GUILDS &&
pak.t === 'GUILD_CREATE'
) {
this.expectedGuilds.delete(pak.d.id);
this._checkReady();
}
}
}
}
",
"
class Test {
_packet(raw) {
let pak;
try {
pak = _classPrivateFieldGet(this, _serialization).decode(raw);
this.manager.emit(ClientEvent.RAW_PACKET, pak, this);
} catch (e) {
this.manager.client.emit(ClientEvent.SHARD_ERROR, e, this);
return;
}
switch(pak.t){
case 'READY':
this.emit(ShardEvent.READY);
this.session.id = pak.d.session_id;
this.expectedGuilds = new Set(pak.d.guilds.map((g)=>g.id
));
this.status = Status.WAITING_FOR_GUILDS;
this.heartbeat.acked = true;
this.heartbeat.new('ready');
break;
case 'RESUMED':
this.emit(ShardEvent.RESUMED);
this.status = Status.READY;
this.heartbeat.acked = true;
this.heartbeat.new('resumed');
break;
}
if (pak.s !== null) {
if (_classPrivateFieldGet(this, _seq) !== -1 && pak.s > _classPrivateFieldGet(this, \
_seq) + 1) {
this._debug(`Non-consecutive sequence [${_classPrivateFieldGet(this, _seq)} => \
${pak.s}]`);
}
_classPrivateFieldSet(this, _seq, pak.s);
}
switch(pak.op){
case GatewayOp.HELLO:
this.heartbeat.delay = pak.d.heartbeat_interval;
this.session.hello();
break;
case GatewayOp.RECONNECT:
this._debug('Gateway asked us to reconnect.');
this.destroy({
code: 4000
});
break;
case GatewayOp.INVALID_SESSION:
this._debug(`Invalid Session: Resumable => ${pak.d}`);
if (pak.d) {
this.session.resume();
break;
}
_classPrivateFieldSet(this, _seq, -1);
this.session.reset();
this.status = Status.RECONNECTING;
this.emit(ShardEvent.INVALID_SESSION);
break;
case GatewayOp.HEARTBEAT:
this.heartbeat.new('requested');
break;
case GatewayOp.HEARTBEAT_ACK:
this.heartbeat.ack();
break;
default:
if (this.status === Status.WAITING_FOR_GUILDS && pak.t === 'GUILD_CREATE') {
this.expectedGuilds.delete(pak.d.id);
this._checkReady();
}
}
}
constructor(){
_ws.set(this, {
writable: true,
value: void 0
});
}
}
var _ws = new WeakMap();
"
);
test!(
syntax(),
|_| class_properties(),
issue_1333_3,
"
class Test {
#ws;
_packet(raw) {
/** @type {DiscordPacket} */
let pak;
try {
pak = this.#serialization.decode(raw);
this.manager.emit(ClientEvent.RAW_PACKET, pak, this);
} catch (e) {
this.manager.client.emit(ClientEvent.SHARD_ERROR, e, this);
return;
}
switch (pak.t) {
case 'READY':
case 'RESUMED':
}
}
}
",
"
class Test {
_packet(raw) {
let pak;
try {
pak = _classPrivateFieldGet(this, _serialization).decode(raw);
this.manager.emit(ClientEvent.RAW_PACKET, pak, this);
} catch (e) {
this.manager.client.emit(ClientEvent.SHARD_ERROR, e, this);
return;
}
switch(pak.t){
case 'READY':
case 'RESUMED':
}
}
constructor(){
_ws.set(this, {
writable: true,
value: void 0
});
}
}
var _ws = new WeakMap();
"
);
test!(
syntax(),
|_| class_properties(),
issue_1333_4,
"
class Test {
#ws;
_packet(raw) {
/** @type {DiscordPacket} */
let pak;
try {
pak = this.#serialization.decode(raw);
} catch (e) {
return;
}
}
}
",
"
class Test {
_packet(raw) {
let pak;
try {
pak = _classPrivateFieldGet(this, _serialization).decode(raw);
} catch (e) {
return;
}
}
constructor(){
_ws.set(this, {
writable: true,
value: void 0
});
}
}
var _ws = new WeakMap();
"
);
test!(
syntax(),
|_| class_properties(),
issue_1333_5,
"
class Test {
_packet(raw) {
pak = this.#serialization.decode(raw);
}
}
",
"
class Test {
_packet(raw) {
pak = _classPrivateFieldGet(this, _serialization).decode(raw);
}
}
"
);
test!(
syntax(),
|_| class_properties(),
issue_1333_6,
"
class Test {
_packet(raw) {
this.#serialization.decode(raw);
}
}
",
"
class Test {
_packet(raw) {
_classPrivateFieldGet(this, _serialization).decode(raw);
}
}
"
);
test!(
syntax(),
|_| { class_properties() },
issue_1660_1,
"
console.log(class { run() { } });
",
"
console.log(class _class {
run() {
}
});
"
);
test!(
syntax(),
|_| chain!(class_properties(), async_to_generator()),
issue_1694_1,
"
class MyClass {
#get() {
return 1
}
constructor() {
this.#get(foo);
}
}
",
"
var _get = new WeakSet();
class MyClass {
constructor(){
_get.add(this);
_classPrivateMethodGet(this, _get, get).call(this, foo);
}
}
function get() {
return 1;
}
"
);
test!(
syntax(),
|_| chain!(class_properties(), async_to_generator()),
issue_1694_2,
"
class MyClass {
static #get() {
return 1
}
constructor() {
MyClass.#get(foo);
}
}
",
"
var _get = new WeakSet();
class MyClass {
constructor(){
_get.add(this);
_classStaticPrivateMethodGet(MyClass, MyClass, get).call(MyClass, foo);
}
}
function get() {
return 1;
}
"
);
test!(
syntax(),
|_| chain!(class_properties(), async_to_generator()),
issue_1702_1,
"
class Foo {
#y;
static #z = 3;
constructor() {
this.x = 1;
this.#y = 2;
this.#sssss();
}
#sssss() {
console.log(this.x, this.#y, Foo.#z);
}
}
const instance = new Foo();
",
"
var _sssss = new WeakSet();
class Foo {
constructor(){
_y.set(this, {
writable: true,
value: void 0
});
_sssss.add(this);
this.x = 1;
_classPrivateFieldSet(this, _y, 2);
_classPrivateMethodGet(this, _sssss, sssss).call(this);
}
}
var _y = new WeakMap();
var _z = {
writable: true,
value: 3
};
function sssss() {
console.log(this.x, _classPrivateFieldGet(this, _y), _classStaticPrivateFieldSpecGet(Foo, \
Foo, _z));
}
const instance = new Foo();
"
);
test!(
syntax(),
|_| class_properties(),
issue_1711_1,
"
class Foo {
#value() {
return 1;
}
// #value = 1;
get(target) {
return target.#value;
}
}
",
"
var _value = new WeakSet();
class Foo {
get(target) {
return _classPrivateMethodGet(target, _value, value);
}
constructor(){
_value.add(this);
}
}
function value() {
return 1;
}
"
);
test_exec!(
syntax(),
|_| class_properties(),
issue_1742_1,
"
class Foo {
#tag() {
return this;
}
#tag2 = this.#tag;
constructor() {
const receiver = this.#tag`tagged template`;
expect(receiver).toBe(this);
const receiver2 = this.#tag2`tagged template`;
expect(receiver2).toBe(this);
}
}
new Foo();
"
);
test_exec!(
syntax(),
|_| chain!(class_properties(), template_literal()),
issue_1742_2,
"
class Foo {
#tag() {
return this;
}
#tag2 = this.#tag;
constructor() {
const receiver = this.#tag`tagged template`;
expect(receiver).toBe(this);
const receiver2 = this.#tag2`tagged template`;
expect(receiver2).toBe(this);
}
}
new Foo();
"
);
test!(
syntax(),
|_| class_properties(),
issue_1742_3,
"
class Foo {
#tag() {
return this;
}
#tag2 = this.#tag;
constructor() {
const receiver = this.#tag`tagged template`;
expect(receiver).toBe(this);
const receiver2 = this.#tag2`tagged template`;
expect(receiver2).toBe(this);
}
}
new Foo();
",
"
var _tag = new WeakSet();
class Foo {
constructor(){
_tag.add(this);
_tag2.set(this, {
writable: true,
value: _classPrivateMethodGet(this, _tag, tag)
});
const receiver = _classPrivateMethodGet(this, _tag, tag).bind(this)`tagged template`;
expect(receiver).toBe(this);
const receiver2 = _classPrivateFieldGet(this, _tag2).bind(this)`tagged template`;
expect(receiver2).toBe(this);
}
}
var _tag2 = new WeakMap();
function tag() {
return this;
}
new Foo();
"
);
test!(
syntax(),
|_| class_properties(),
issue_1869_1,
"
class TestClass {
static Something = 'hello';
static SomeProperties = {
firstProp: TestClass.Something,
};
}
function someClassDecorator(c) {
return c;
}
",
"
class TestClass {
}
_defineProperty(TestClass, 'Something', 'hello');
_defineProperty(TestClass, 'SomeProperties', {
firstProp: TestClass.Something
});
function someClassDecorator(c) {
return c;
}
"
);
test!(
syntax(),
|_| class_properties(),
issue_1869_2,
"
var _class;
let TestClass = _class = someClassDecorator((_class = class TestClass {
static Something = 'hello';
static SomeProperties = {
firstProp: TestClass.Something
};
}) || _class) || _class;
function someClassDecorator(c) {
return c;
}
",
"
var _class;
let TestClass = _class = someClassDecorator((_class = function() {
class TestClass {
}
_defineProperty(TestClass, 'Something', 'hello');
_defineProperty(TestClass, 'SomeProperties', {
firstProp: TestClass.Something
});
return TestClass;
}()) || _class) || _class;
function someClassDecorator(c) {
return c;
}
"
);
test!(
syntax(),
|_| class_properties(),
issue_2021_1,
"
class Item extends Component {
constructor(props) {
super(props);
}
input = this.props.item;
}
",
"
class Item extends Component {
constructor(props){
super(props);
_defineProperty(this, 'input', this.props.item);
}
}
"
);
#[testing::fixture("tests/fixture/classes/**/exec.js")]
fn exec(input: PathBuf) {
let src = read_to_string(&input).unwrap();
compare_stdout(Default::default(), |_| class_properties(), &src);
}
| 16.878093 | 162 | 0.547256 |
acc57d1e30bc3c0debfd4dd48a594f603de6ef79 | 25,196 | #![deny(rust_2018_idioms)]
#![doc(
html_logo_url = "https://storage.googleapis.com/fdo-gitlab-uploads/project/avatar/3213/zbus-logomark.png"
)]
//! This crate provides the main API you will use to interact with D-Bus from Rust. It takes care of
//! the establishment of a connection, the creation, sending and receiving of different kind of
//! D-Bus messages (method calls, signals etc) for you.
//!
//! zbus crate is currently Linux-specific[^otheros].
//!
//! ### Getting Started
//!
//! The best way to get started with zbus is the [book], where we start with basic D-Bus concepts
//! and explain with code samples, how zbus makes D-Bus easy.
//!
//! ### Example code
//!
//! #### Client
//!
//! This code display a notification on your Freedesktop.org-compatible OS:
//!
//! ```rust,no_run
//! use std::{collections::HashMap, error::Error};
//!
//! use zbus::{Connection, dbus_proxy};
//! use zvariant::Value;
//!
//! #[dbus_proxy(
//! interface = "org.freedesktop.Notifications",
//! default_service = "org.freedesktop.Notifications",
//! default_path = "/org/freedesktop/Notifications"
//! )]
//! trait Notifications {
//! fn notify(
//! &self,
//! app_name: &str,
//! replaces_id: u32,
//! app_icon: &str,
//! summary: &str,
//! body: &str,
//! actions: &[&str],
//! hints: &HashMap<&str, &Value<'_>>,
//! expire_timeout: i32,
//! ) -> zbus::Result<u32>;
//! }
//!
//! // Although we use `async-std` here, you can use any async runtime of choice.
//! #[async_std::main]
//! async fn main() -> Result<(), Box<dyn Error>> {
//! let connection = Connection::session().await?;
//!
//! // `dbus_proxy` macro creates `NotificationProxy` based on `Notifications` trait.
//! let proxy = NotificationsProxy::new(&connection).await?;
//! let reply = proxy.notify(
//! "my-app",
//! 0,
//! "dialog-information",
//! "A summary",
//! "Some body",
//! &[],
//! &HashMap::new(),
//! 5000,
//! ).await?;
//! dbg!(reply);
//!
//! Ok(())
//! }
//! ```
//!
//! #### Server
//!
//! A simple service that politely greets whoever calls its `SayHello` method:
//!
//! ```rust,no_run
//! use std::{
//! error::Error,
//! thread::sleep,
//! time::Duration,
//! };
//! use zbus::{ObjectServer, ConnectionBuilder, dbus_interface, fdo};
//!
//! struct Greeter {
//! count: u64
//! }
//!
//! #[dbus_interface(name = "org.zbus.MyGreeter1")]
//! impl Greeter {
//! // Can be `async` as well.
//! fn say_hello(&mut self, name: &str) -> String {
//! self.count += 1;
//! format!("Hello {}! I have been called: {}", name, self.count)
//! }
//! }
//!
//! // Although we use `async-std` here, you can use any async runtime of choice.
//! #[async_std::main]
//! async fn main() -> Result<(), Box<dyn Error>> {
//! let greeter = Greeter { count: 0 };
//! let _ = ConnectionBuilder::session()?
//! .name("org.zbus.MyGreeter")?
//! .serve_at("/org/zbus/MyGreeter", greeter)?
//! .build()
//! .await?;
//!
//! // Do other things or go to sleep.
//! sleep(Duration::from_secs(60));
//!
//! Ok(())
//! }
//! ```
//!
//! You can use the following command to test it:
//!
//! ```bash
//! $ busctl --user call \
//! org.zbus.MyGreeter \
//! /org/zbus/MyGreeter \
//! org.zbus.MyGreeter1 \
//! SayHello s "Maria"
//! Hello Maria!
//! $
//! ```
//!
//! ### Blocking API
//!
//! While zbus is primarily asynchronous (since 2.0), [blocking wrappers][bw] are provided for
//! convenience.
//!
//! ### Compatibility with async runtimes
//!
//! zbus is runtime-agnostic and should work out of the box with different Rust async runtimes.
//! However, in order to achieve that, zbus spawns a thread per connection to handle various
//! internal tasks. If that is something you would like to avoid, you need to:
//! * Use [`ConnectionBuilder`] and disable the `internal_executor` flag.
//! * Ensure the [internal executor keeps ticking continuously][iektc].
//!
//! [book]: https://dbus.pages.freedesktop.org/zbus/
//! [bw]: https://docs.rs/zbus/2.0.0-beta.7/zbus/blocking/index.html
//! [iektc]: `Connection::executor`
//!
//! [^otheros]: Support for other OS exist, but it is not supported to the same extent. D-Bus
//! clients in javascript (running from any browser) do exist though. And zbus may also be
//! working from the browser sometime in the future too, thanks to Rust 🦀 and WebAssembly 🕸.
//!
#[cfg(doctest)]
mod doctests {
// Book markdown checks
doc_comment::doctest!("../../book/src/client.md");
doc_comment::doctest!("../../book/src/concepts.md");
doc_comment::doctest!("../../book/src/connection.md");
doc_comment::doctest!("../../book/src/contributors.md");
doc_comment::doctest!("../../book/src/introduction.md");
doc_comment::doctest!("../../book/src/server.md");
doc_comment::doctest!("../../book/src/blocking.md");
}
mod error;
pub use error::*;
mod address;
pub use address::*;
mod guid;
pub use guid::*;
mod message;
pub use message::*;
mod message_header;
pub use message_header::*;
mod message_field;
pub use message_field::*;
mod message_fields;
pub use message_fields::*;
mod handshake;
pub(crate) use handshake::*;
mod connection;
pub use connection::*;
mod connection_builder;
pub use connection_builder::*;
mod message_stream;
pub use message_stream::*;
mod object_server;
pub use object_server::*;
mod proxy;
pub use proxy::*;
mod proxy_builder;
pub use proxy_builder::*;
mod signal_context;
pub use signal_context::*;
mod interface;
pub use interface::*;
mod utils;
pub use utils::*;
#[macro_use]
pub mod fdo;
mod raw;
pub use raw::Socket;
pub mod blocking;
pub mod xml;
pub use zbus_macros::{dbus_interface, dbus_proxy, DBusError};
// Required for the macros to function within this crate.
extern crate self as zbus;
// Macro support module, not part of the public API.
#[doc(hidden)]
pub mod export {
pub use async_trait;
pub use futures_core;
pub use futures_util;
pub use serde;
pub use static_assertions;
}
pub use zbus_names as names;
pub use zvariant;
use zvariant::OwnedFd;
#[cfg(test)]
mod tests {
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
fs::File,
os::unix::io::{AsRawFd, FromRawFd},
sync::{mpsc::channel, Arc, Condvar, Mutex},
};
use async_io::block_on;
use enumflags2::BitFlags;
use ntest::timeout;
use test_env_log::test;
use zbus_names::UniqueName;
use zvariant::{Fd, OwnedObjectPath, OwnedValue, Type};
use crate::{
blocking::{self, MessageStream},
fdo::{RequestNameFlags, RequestNameReply},
Connection, InterfaceDeref, Message, MessageFlags, Result, SignalContext,
};
#[test]
fn msg() {
let mut m = Message::method(
None::<()>,
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus.Peer"),
"GetMachineId",
&(),
)
.unwrap();
m.modify_primary_header(|primary| {
primary.set_flags(BitFlags::from(MessageFlags::NoAutoStart));
primary.serial_num_or_init(|| 11);
Ok(())
})
.unwrap();
let primary = m.primary_header();
assert!(*primary.serial_num().unwrap() == 11);
assert!(primary.flags() == MessageFlags::NoAutoStart);
}
#[test]
#[timeout(15000)]
fn basic_connection() {
let connection = blocking::Connection::session()
.map_err(|e| {
println!("error: {}", e);
e
})
.unwrap();
// Hello method is already called during connection creation so subsequent calls are expected to fail but only
// with a D-Bus error.
match connection.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"Hello",
&(),
) {
Err(crate::Error::MethodError(_, _, _)) => (),
Err(e) => panic!("{}", e),
_ => panic!(),
};
}
#[test]
#[timeout(15000)]
fn basic_connection_async() {
async_io::block_on(test_basic_connection()).unwrap();
}
async fn test_basic_connection() -> Result<()> {
let connection = Connection::session().await?;
match connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"Hello",
&(),
)
.await
{
Err(crate::Error::MethodError(_, _, _)) => (),
Err(e) => panic!("{}", e),
_ => panic!(),
};
Ok(())
}
#[test]
#[timeout(15000)]
fn fdpass_systemd() {
let connection = blocking::Connection::system().unwrap();
let reply = connection
.call_method(
Some("org.freedesktop.systemd1"),
"/org/freedesktop/systemd1",
Some("org.freedesktop.systemd1.Manager"),
"DumpByFileDescriptor",
&(),
)
.unwrap();
assert!(reply
.body_signature()
.map(|s| s == <Fd>::signature())
.unwrap());
let fd: Fd = reply.body().unwrap();
let _fds = reply.disown_fds();
assert!(fd.as_raw_fd() >= 0);
let f = unsafe { File::from_raw_fd(fd.as_raw_fd()) };
f.metadata().unwrap();
}
#[test]
#[timeout(15000)]
fn freedesktop_api() {
let connection = blocking::Connection::session()
.map_err(|e| {
println!("error: {}", e);
e
})
.unwrap();
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"RequestName",
&(
"org.freedesktop.zbus.sync",
BitFlags::from(RequestNameFlags::ReplaceExisting),
),
)
.unwrap();
assert!(reply.body_signature().map(|s| s == "u").unwrap());
let reply: RequestNameReply = reply.body().unwrap();
assert_eq!(reply, RequestNameReply::PrimaryOwner);
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"GetId",
&(),
)
.unwrap();
assert!(reply
.body_signature()
.map(|s| s == <&str>::signature())
.unwrap());
let id: &str = reply.body().unwrap();
println!("Unique ID of the bus: {}", id);
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"NameHasOwner",
&"org.freedesktop.zbus.sync",
)
.unwrap();
assert!(reply
.body_signature()
.map(|s| s == bool::signature())
.unwrap());
assert!(reply.body::<bool>().unwrap());
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"GetNameOwner",
&"org.freedesktop.zbus.sync",
)
.unwrap();
assert!(reply
.body_signature()
.map(|s| s == <&str>::signature())
.unwrap());
assert_eq!(
reply.body::<UniqueName<'_>>().unwrap(),
*connection.unique_name().unwrap(),
);
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"GetConnectionCredentials",
&"org.freedesktop.DBus",
)
.unwrap();
assert!(reply.body_signature().map(|s| s == "a{sv}").unwrap());
let hashmap: HashMap<&str, OwnedValue> = reply.body().unwrap();
let pid: u32 = (&hashmap["ProcessID"]).try_into().unwrap();
println!("DBus bus PID: {}", pid);
let uid: u32 = (&hashmap["UnixUserID"]).try_into().unwrap();
println!("DBus bus UID: {}", uid);
}
#[test]
#[timeout(15000)]
fn freedesktop_api_async() {
async_io::block_on(test_freedesktop_api()).unwrap();
}
async fn test_freedesktop_api() -> Result<()> {
let connection = Connection::session().await?;
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"RequestName",
&(
"org.freedesktop.zbus.async",
BitFlags::from(RequestNameFlags::ReplaceExisting),
),
)
.await
.unwrap();
assert!(reply.body_signature().map(|s| s == "u").unwrap());
let reply: RequestNameReply = reply.body().unwrap();
assert_eq!(reply, RequestNameReply::PrimaryOwner);
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"GetId",
&(),
)
.await
.unwrap();
assert!(reply
.body_signature()
.map(|s| s == <&str>::signature())
.unwrap());
let id: &str = reply.body().unwrap();
println!("Unique ID of the bus: {}", id);
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"NameHasOwner",
&"org.freedesktop.zbus.async",
)
.await
.unwrap();
assert!(reply
.body_signature()
.map(|s| s == bool::signature())
.unwrap());
assert!(reply.body::<bool>().unwrap());
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"GetNameOwner",
&"org.freedesktop.zbus.async",
)
.await
.unwrap();
assert!(reply
.body_signature()
.map(|s| s == <&str>::signature())
.unwrap());
assert_eq!(
reply.body::<UniqueName<'_>>().unwrap(),
*connection.unique_name().unwrap(),
);
let reply = connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus"),
"GetConnectionCredentials",
&"org.freedesktop.DBus",
)
.await
.unwrap();
assert!(reply.body_signature().map(|s| s == "a{sv}").unwrap());
let hashmap: HashMap<&str, OwnedValue> = reply.body().unwrap();
let pid: u32 = (&hashmap["ProcessID"]).try_into().unwrap();
println!("DBus bus PID: {}", pid);
let uid: u32 = (&hashmap["UnixUserID"]).try_into().unwrap();
println!("DBus bus UID: {}", uid);
Ok(())
}
#[test]
#[timeout(15000)]
fn issue_68() {
// Tests the fix for https://gitlab.freedesktop.org/dbus/zbus/-/issues/68
//
// While this is not an exact reproduction of the issue 68, the underlying problem it
// produces is exactly the same: `Connection::call_method` dropping all incoming messages
// while waiting for the reply to the method call.
let conn = blocking::Connection::session().unwrap();
let stream = MessageStream::from(&conn);
// Send a message as client before service starts to process messages
let client_conn = blocking::Connection::session().unwrap();
let destination = conn.unique_name().map(UniqueName::<'_>::from);
let msg = Message::method(
None::<()>,
destination,
"/org/freedesktop/Issue68",
Some("org.freedesktop.Issue68"),
"Ping",
&(),
)
.unwrap();
let serial = client_conn.send_message(msg).unwrap();
crate::blocking::fdo::DBusProxy::new(&conn)
.unwrap()
.get_id()
.unwrap();
for m in stream {
let msg = m.unwrap();
if *msg.primary_header().serial_num().unwrap() == serial {
break;
}
}
}
#[test]
#[timeout(15000)]
fn issue104() {
// Tests the fix for https://gitlab.freedesktop.org/dbus/zbus/-/issues/104
//
// The issue is caused by `dbus_proxy` macro adding `()` around the return value of methods
// with multiple out arguments, ending up with double parenthesis around the signature of
// the return type and zbus only removing the outer `()` only and then it not matching the
// signature we receive on the reply message.
use zvariant::{ObjectPath, Value};
struct Secret;
#[super::dbus_interface(name = "org.freedesktop.Secret.Service")]
impl Secret {
fn open_session(
&self,
_algorithm: &str,
input: Value<'_>,
) -> zbus::fdo::Result<(OwnedValue, OwnedObjectPath)> {
Ok((
OwnedValue::from(input),
ObjectPath::try_from("/org/freedesktop/secrets/Blah")
.unwrap()
.into(),
))
}
}
let secret = Secret;
let conn = blocking::ConnectionBuilder::session()
.unwrap()
.serve_at("/org/freedesktop/secrets", secret)
.unwrap()
.build()
.unwrap();
let service_name = conn.unique_name().unwrap().clone();
let child = std::thread::spawn(move || {
let conn = blocking::Connection::session().unwrap();
#[super::dbus_proxy(interface = "org.freedesktop.Secret.Service", gen_async = false)]
trait Secret {
fn open_session(
&self,
algorithm: &str,
input: &zvariant::Value<'_>,
) -> zbus::Result<(OwnedValue, OwnedObjectPath)>;
}
let proxy = SecretProxy::builder(&conn)
.destination(UniqueName::from(service_name))
.unwrap()
.path("/org/freedesktop/secrets")
.unwrap()
.build()
.unwrap();
proxy.open_session("plain", &Value::from("")).unwrap();
2u32
});
let val = child.join().expect("failed to join");
assert_eq!(val, 2);
}
// This one we just want to see if it builds, no need to run it. For details see:
//
// https://gitlab.freedesktop.org/dbus/zbus/-/issues/121
#[test]
#[ignore]
fn issue_121() {
use crate::dbus_proxy;
#[dbus_proxy(interface = "org.freedesktop.IBus")]
trait IBus {
/// CurrentInputContext property
#[dbus_proxy(property)]
fn current_input_context(&self) -> zbus::Result<OwnedObjectPath>;
/// Engines property
#[dbus_proxy(property)]
fn engines(&self) -> zbus::Result<Vec<zvariant::OwnedValue>>;
}
}
#[test]
#[timeout(15000)]
fn issue_122() {
let conn = blocking::Connection::session().unwrap();
let stream = MessageStream::from(&conn);
#[allow(clippy::mutex_atomic)]
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pair2 = Arc::clone(&pair);
let child = std::thread::spawn(move || {
{
let (lock, cvar) = &*pair2;
let mut started = lock.lock().unwrap();
*started = true;
cvar.notify_one();
}
for m in stream {
let msg = m.unwrap();
let hdr = msg.header().unwrap();
if hdr.member().unwrap().map(|m| m.as_str()) == Some("ZBusIssue122") {
break;
}
}
});
// Wait for the receiving thread to start up.
let (lock, cvar) = &*pair;
let mut started = lock.lock().unwrap();
while !*started {
started = cvar.wait(started).unwrap();
}
// Still give it some milliseconds to ensure it's already blocking on receive_message call
// when we send a message.
std::thread::sleep(std::time::Duration::from_millis(100));
let destination = conn.unique_name().map(UniqueName::<'_>::from);
let msg = Message::method(
None::<()>,
destination,
"/does/not/matter",
None::<()>,
"ZBusIssue122",
&(),
)
.unwrap();
conn.send_message(msg).unwrap();
child.join().unwrap();
}
#[test]
#[ignore]
fn issue_81() {
use zbus::dbus_proxy;
use zvariant::derive::{OwnedValue, Type};
#[derive(
Debug, PartialEq, Clone, Type, OwnedValue, serde::Serialize, serde::Deserialize,
)]
pub struct DbusPath {
id: String,
path: OwnedObjectPath,
}
#[dbus_proxy]
trait Session {
#[dbus_proxy(property)]
fn sessions_tuple(&self) -> zbus::Result<(String, String)>;
#[dbus_proxy(property)]
fn sessions_struct(&self) -> zbus::Result<DbusPath>;
}
}
#[test]
#[timeout(15000)]
fn issue173() {
// Tests the fix for https://gitlab.freedesktop.org/dbus/zbus/-/issues/173
//
// The issue is caused by proxy not keeping track of its destination's owner changes
// (service restart) and failing to receive signals as a result.
let (tx, rx) = channel();
let child = std::thread::spawn(move || {
let conn = blocking::Connection::session().unwrap();
#[super::dbus_proxy(
interface = "org.freedesktop.zbus.ComeAndGo",
default_service = "org.freedesktop.zbus.ComeAndGo",
default_path = "/org/freedesktop/zbus/ComeAndGo"
)]
trait ComeAndGo {
#[dbus_proxy(signal)]
fn the_signal(&self) -> zbus::Result<()>;
}
let proxy = ComeAndGoProxyBlocking::new(&conn).unwrap();
let tx_clone = tx.clone();
let (signal_tx, signal_rx) = channel();
proxy
.connect_the_signal(move || {
tx_clone.send(()).unwrap();
signal_tx.send(()).unwrap();
})
.unwrap();
tx.send(()).unwrap();
// We receive two signals, each time from different unique names. W/o the fix for
// issue#173, the second iteration hangs.
for _ in 0..2 {
signal_rx.recv().unwrap();
}
});
struct ComeAndGo;
#[super::dbus_interface(name = "org.freedesktop.zbus.ComeAndGo")]
impl ComeAndGo {
#[dbus_interface(signal)]
async fn the_signal(signal_ctxt: &SignalContext<'_>) -> zbus::Result<()>;
}
rx.recv().unwrap();
for _ in 0..2 {
let conn = blocking::ConnectionBuilder::session()
.unwrap()
.serve_at("/org/freedesktop/zbus/ComeAndGo", ComeAndGo)
.unwrap()
.name("org.freedesktop.zbus.ComeAndGo")
.unwrap()
.build()
.unwrap();
conn.object_server_mut()
.with(
"/org/freedesktop/zbus/ComeAndGo",
|_: InterfaceDeref<'_, ComeAndGo>, ctxt| block_on(ComeAndGo::the_signal(&ctxt)),
)
.unwrap();
rx.recv().unwrap();
// Now we release the name ownership to use a different connection (i-e new unique name).
conn.release_name("org.freedesktop.zbus.ComeAndGo").unwrap();
}
child.join().unwrap();
}
}
| 30.17485 | 118 | 0.519646 |
ef94d4ebe69717fa0b5fb0b515131ceb4333338c | 11,326 | use std::env;
use std::fs;
use std::path::PathBuf;
fn link(name: &str, bundled: bool) {
use std::env::var;
let target = var("TARGET").unwrap();
let target: Vec<_> = target.split('-').collect();
if target.get(2) == Some(&"windows") {
println!("cargo:rustc-link-lib=dylib={}", name);
if bundled && target.get(3) == Some(&"gnu") {
let dir = var("CARGO_MANIFEST_DIR").unwrap();
println!("cargo:rustc-link-search=native={}/{}", dir, target[0]);
}
}
}
fn fail_on_empty_directory(name: &str) {
if fs::read_dir(name).unwrap().count() == 0 {
println!(
"The `{}` directory is empty, did you forget to pull the submodules?",
name
);
println!("Try `git submodule update --init --recursive`");
panic!();
}
}
fn rocksdb_include_dir() -> String {
match env::var("ROCKSDB_INCLUDE_DIR") {
Ok(val) => val,
Err(_) => "rocksdb/include".to_string(),
}
}
fn bindgen_rocksdb() {
let bindings = bindgen::Builder::default()
.header(rocksdb_include_dir() + "/rocksdb/c.h")
.derive_debug(false)
.blacklist_type("max_align_t") // https://github.com/rust-lang-nursery/rust-bindgen/issues/550
.ctypes_prefix("libc")
.size_t_is_usize(true)
.generate()
.expect("unable to generate rocksdb bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("unable to write rocksdb bindings");
}
fn build_rocksdb() {
let target = env::var("TARGET").unwrap();
let mut config = cc::Build::new();
config.include("rocksdb/include/");
config.include("rocksdb/");
config.include("rocksdb/third-party/gtest-1.8.1/fused-src/");
if cfg!(feature = "snappy") {
config.define("SNAPPY", Some("1"));
config.include("snappy/");
}
if cfg!(feature = "lz4") {
config.define("LZ4", Some("1"));
config.include("lz4/lib/");
}
if cfg!(feature = "zstd") {
config.define("ZSTD", Some("1"));
config.include("zstd/lib/");
config.include("zstd/lib/dictBuilder/");
}
if cfg!(feature = "zlib") {
config.define("ZLIB", Some("1"));
config.include("zlib/");
}
if cfg!(feature = "bzip2") {
config.define("BZIP2", Some("1"));
config.include("bzip2/");
}
config.include(".");
config.define("NDEBUG", Some("1"));
let mut lib_sources = include_str!("rocksdb_lib_sources.txt")
.trim()
.split('\n')
.map(str::trim)
.collect::<Vec<&'static str>>();
// We have a pregenerated a version of build_version.cc in the local directory
lib_sources = lib_sources
.iter()
.cloned()
.filter(|file| *file != "util/build_version.cc")
.collect::<Vec<&'static str>>();
if target.contains("x86_64") {
// This is needed to enable hardware CRC32C. Technically, SSE 4.2 is
// only available since Intel Nehalem (about 2010) and AMD Bulldozer
// (about 2011).
config.define("HAVE_SSE42", Some("1"));
config.flag_if_supported("-msse2");
config.flag_if_supported("-msse4.1");
config.flag_if_supported("-msse4.2");
if !target.contains("android") {
config.define("HAVE_PCLMUL", Some("1"));
config.flag_if_supported("-mpclmul");
}
}
if target.contains("darwin") {
config.define("OS_MACOSX", Some("1"));
config.define("ROCKSDB_PLATFORM_POSIX", Some("1"));
config.define("ROCKSDB_LIB_IO_POSIX", Some("1"));
} else if target.contains("android") {
config.define("OS_ANDROID", Some("1"));
config.define("ROCKSDB_PLATFORM_POSIX", Some("1"));
config.define("ROCKSDB_LIB_IO_POSIX", Some("1"));
} else if target.contains("linux") {
config.define("OS_LINUX", Some("1"));
config.define("ROCKSDB_PLATFORM_POSIX", Some("1"));
config.define("ROCKSDB_LIB_IO_POSIX", Some("1"));
} else if target.contains("freebsd") {
config.define("OS_FREEBSD", Some("1"));
config.define("ROCKSDB_PLATFORM_POSIX", Some("1"));
config.define("ROCKSDB_LIB_IO_POSIX", Some("1"));
} else if target.contains("windows") {
link("rpcrt4", false);
link("shlwapi", false);
config.define("OS_WIN", Some("1"));
config.define("ROCKSDB_WINDOWS_UTF8_FILENAMES", Some("1"));
if &target == "x86_64-pc-windows-gnu" {
// Tell MinGW to create localtime_r wrapper of localtime_s function.
config.define("_POSIX_C_SOURCE", None);
// Tell MinGW to use at least Windows Vista headers instead of the ones of Windows XP.
// (This is minimum supported version of rocksdb)
config.define("_WIN32_WINNT", Some("0x0600"));
}
// Remove POSIX-specific sources
lib_sources = lib_sources
.iter()
.cloned()
.filter(|file| match *file {
"port/port_posix.cc" | "env/env_posix.cc" | "env/fs_posix.cc"
| "env/io_posix.cc" => false,
_ => true,
})
.collect::<Vec<&'static str>>();
// Add Windows-specific sources
lib_sources.push("port/win/port_win.cc");
lib_sources.push("port/win/env_win.cc");
lib_sources.push("port/win/env_default.cc");
lib_sources.push("port/win/win_logger.cc");
lib_sources.push("port/win/io_win.cc");
lib_sources.push("port/win/win_thread.cc");
}
if target.contains("msvc") {
config.flag("-EHsc");
} else {
config.flag(&cxx_standard());
// this was breaking the build on travis due to
// > 4mb of warnings emitted.
config.flag("-Wno-unused-parameter");
}
for file in lib_sources {
let file = "rocksdb/".to_string() + file;
config.file(&file);
}
config.file("build_version.cc");
config.cpp(true);
config.compile("librocksdb.a");
}
fn build_snappy() {
let target = env::var("TARGET").unwrap();
let endianness = env::var("CARGO_CFG_TARGET_ENDIAN").unwrap();
let mut config = cc::Build::new();
config.include("snappy/");
config.include(".");
config.define("NDEBUG", Some("1"));
config.extra_warnings(false);
if target.contains("msvc") {
config.flag("-EHsc");
} else {
// Snappy requires C++11.
// See: https://github.com/google/snappy/blob/master/CMakeLists.txt#L32-L38
config.flag("-std=c++11");
}
if endianness == "big" {
config.define("SNAPPY_IS_BIG_ENDIAN", Some("1"));
}
config.file("snappy/snappy.cc");
config.file("snappy/snappy-sinksource.cc");
config.file("snappy/snappy-c.cc");
config.cpp(true);
config.compile("libsnappy.a");
}
fn build_lz4() {
let mut compiler = cc::Build::new();
compiler
.file("lz4/lib/lz4.c")
.file("lz4/lib/lz4frame.c")
.file("lz4/lib/lz4hc.c")
.file("lz4/lib/xxhash.c");
compiler.opt_level(3);
let target = env::var("TARGET").unwrap();
if &target == "i686-pc-windows-gnu" {
compiler.flag("-fno-tree-vectorize");
}
compiler.compile("liblz4.a");
}
fn build_zstd() {
let mut compiler = cc::Build::new();
compiler.include("zstd/lib/");
compiler.include("zstd/lib/common");
compiler.include("zstd/lib/legacy");
let globs = &[
"zstd/lib/common/*.c",
"zstd/lib/compress/*.c",
"zstd/lib/decompress/*.c",
"zstd/lib/dictBuilder/*.c",
"zstd/lib/legacy/*.c",
];
for pattern in globs {
for path in glob::glob(pattern).unwrap() {
let path = path.unwrap();
compiler.file(path);
}
}
compiler.opt_level(3);
compiler.extra_warnings(false);
compiler.define("ZSTD_LIB_DEPRECATED", Some("0"));
compiler.compile("libzstd.a");
}
fn build_zlib() {
let mut compiler = cc::Build::new();
let globs = &["zlib/*.c"];
for pattern in globs {
for path in glob::glob(pattern).unwrap() {
let path = path.unwrap();
compiler.file(path);
}
}
compiler.flag_if_supported("-Wno-implicit-function-declaration");
compiler.opt_level(3);
compiler.extra_warnings(false);
compiler.compile("libz.a");
}
fn build_bzip2() {
let mut compiler = cc::Build::new();
compiler
.file("bzip2/blocksort.c")
.file("bzip2/bzlib.c")
.file("bzip2/compress.c")
.file("bzip2/crctable.c")
.file("bzip2/decompress.c")
.file("bzip2/huffman.c")
.file("bzip2/randtable.c");
compiler
.define("_FILE_OFFSET_BITS", Some("64"))
.define("BZ_NO_STDIO", None);
compiler.extra_warnings(false);
compiler.opt_level(3);
compiler.extra_warnings(false);
compiler.compile("libbz2.a");
}
fn try_to_find_and_link_lib(lib_name: &str) -> bool {
if let Ok(lib_dir) = env::var(&format!("{}_LIB_DIR", lib_name)) {
println!("cargo:rustc-link-search=native={}", lib_dir);
let mode = match env::var_os(&format!("{}_STATIC", lib_name)) {
Some(_) => "static",
None => "dylib",
};
println!("cargo:rustc-link-lib={}={}", mode, lib_name.to_lowercase());
return true;
}
false
}
fn cxx_standard() -> String {
env::var("ROCKSDB_CXX_STD").map_or("-std=c++11".to_owned(), |cxx_std| {
if !cxx_std.starts_with("-std=") {
format!("-std={}", cxx_std)
} else {
cxx_std
}
})
}
fn main() {
bindgen_rocksdb();
if !try_to_find_and_link_lib("ROCKSDB") {
println!("cargo:rerun-if-changed=rocksdb/");
fail_on_empty_directory("rocksdb");
build_rocksdb();
} else {
let target = env::var("TARGET").unwrap();
// according to https://github.com/alexcrichton/cc-rs/blob/master/src/lib.rs#L2189
if target.contains("apple") || target.contains("freebsd") || target.contains("openbsd") {
println!("cargo:rustc-link-lib=dylib=c++");
} else if target.contains("linux") {
println!("cargo:rustc-link-lib=dylib=stdc++");
}
}
if cfg!(feature = "snappy") && !try_to_find_and_link_lib("SNAPPY") {
println!("cargo:rerun-if-changed=snappy/");
fail_on_empty_directory("snappy");
build_snappy();
}
if cfg!(feature = "lz4") && !try_to_find_and_link_lib("LZ4") {
println!("cargo:rerun-if-changed=lz4/");
fail_on_empty_directory("lz4");
build_lz4();
}
if cfg!(feature = "zstd") && !try_to_find_and_link_lib("ZSTD") {
println!("cargo:rerun-if-changed=zstd/");
fail_on_empty_directory("zstd");
build_zstd();
}
if cfg!(feature = "zlib") && !try_to_find_and_link_lib("Z") {
println!("cargo:rerun-if-changed=zlib/");
fail_on_empty_directory("zlib");
build_zlib();
}
if cfg!(feature = "bzip2") && !try_to_find_and_link_lib("BZ2") {
println!("cargo:rerun-if-changed=bzip2/");
fail_on_empty_directory("bzip2");
build_bzip2();
}
}
| 30.693767 | 102 | 0.574784 |
e5f7d2fdb9ecd767314bae9e785b7901cc6c1a38 | 31,015 | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use tidb_query_codegen::rpn_fn;
use super::super::expr::EvalContext;
use crate::codec::data_type::*;
use crate::codec::mysql::time::extension::DateTimeExtension;
use crate::codec::mysql::time::weekmode::WeekMode;
use crate::codec::mysql::time::WeekdayExtension;
use crate::codec::mysql::Time;
use crate::codec::Error;
use crate::expr::SqlMode;
use crate::Result;
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn date_format(
ctx: &mut EvalContext,
t: &Option<DateTime>,
layout: &Option<Bytes>,
) -> Result<Option<Bytes>> {
use std::str::from_utf8;
if t.is_none() || layout.is_none() {
return Ok(None);
}
let (t, layout) = (t.as_ref().unwrap(), layout.as_ref().unwrap());
if t.invalid_zero() {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(&format!("{}", t)))
.map(|_| Ok(None))?;
}
let t = t.date_format(from_utf8(layout.as_slice()).map_err(Error::Encoding)?);
if let Err(err) = t {
return ctx.handle_invalid_time_error(err).map(|_| Ok(None))?;
}
Ok(Some(t.unwrap().into_bytes()))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn week_with_mode(
ctx: &mut EvalContext,
t: &Option<DateTime>,
m: &Option<Int>,
) -> Result<Option<Int>> {
if t.is_none() || m.is_none() {
return Ok(None);
}
let (t, m) = (t.as_ref().unwrap(), m.as_ref().unwrap());
if t.invalid_zero() {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(&format!("{}", t)))
.map(|_| Ok(None))?;
}
let week = t.week(WeekMode::from_bits_truncate(*m as u32));
Ok(Some(i64::from(week)))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn week_day(ctx: &mut EvalContext, t: &Option<DateTime>) -> Result<Option<Int>> {
if t.is_none() {
return Ok(None);
}
let t = t.as_ref().unwrap();
if t.invalid_zero() {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(&format!("{}", t)))
.map(|_| Ok(None))?;
}
let day = t.weekday().num_days_from_monday();
Ok(Some(i64::from(day)))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn day_of_week(ctx: &mut EvalContext, t: &Option<DateTime>) -> Result<Option<Int>> {
if t.is_none() {
return Ok(None);
}
let t = t.as_ref().unwrap();
if t.invalid_zero() {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(t))
.map(|_| Ok(None))?;
}
let day = t.weekday().number_from_sunday();
Ok(Some(Int::from(day)))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn day_of_year(ctx: &mut EvalContext, t: &Option<DateTime>) -> Result<Option<Int>> {
if t.is_none() {
return Ok(None);
}
let t = t.as_ref().unwrap();
if t.invalid_zero() {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(t))
.map(|_| Ok(None))?;
}
let day = t.days();
Ok(Some(Int::from(day)))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn week_of_year(ctx: &mut EvalContext, t: &Option<DateTime>) -> Result<Option<Int>> {
if t.is_none() {
return Ok(None);
}
let t = t.as_ref().unwrap();
if t.invalid_zero() {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(t))
.map(|_| Ok(None))?;
}
let week = t.week(WeekMode::from_bits_truncate(3));
Ok(Some(Int::from(week)))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn to_days(ctx: &mut EvalContext, t: &Option<DateTime>) -> Result<Option<Int>> {
let t = match t {
Some(v) => v,
_ => return Ok(None),
};
if t.invalid_zero() {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(t))
.map(|_| Ok(None))?;
}
Ok(Some(Int::from(t.day_number())))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn from_days(ctx: &mut EvalContext, arg: &Option<Int>) -> Result<Option<Time>> {
arg.map_or(Ok(None), |daynr: Int| {
let time = Time::from_days(ctx, daynr as u32)?;
Ok(Some(time))
})
}
#[rpn_fn]
#[inline]
pub fn month(t: &Option<DateTime>) -> Result<Option<Int>> {
t.map_or(Ok(None), |time| Ok(Some(Int::from(time.month()))))
}
#[rpn_fn]
#[inline]
pub fn hour(t: &Option<Duration>) -> Result<Option<Int>> {
Ok(t.as_ref().map(|t| i64::from(t.hours())))
}
#[rpn_fn]
#[inline]
pub fn minute(t: &Option<Duration>) -> Result<Option<Int>> {
Ok(t.as_ref().map(|t| i64::from(t.minutes())))
}
#[rpn_fn]
#[inline]
pub fn second(t: &Option<Duration>) -> Result<Option<Int>> {
Ok(t.as_ref().map(|t| i64::from(t.secs())))
}
#[rpn_fn]
#[inline]
pub fn micro_second(t: &Option<Duration>) -> Result<Option<Int>> {
Ok(t.as_ref().map(|t| i64::from(t.subsec_micros())))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn year(ctx: &mut EvalContext, t: &Option<DateTime>) -> Result<Option<Int>> {
let t = match t {
Some(v) => v,
_ => return Ok(None),
};
if t.is_zero() {
if ctx.cfg.sql_mode.contains(SqlMode::NO_ZERO_DATE) {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(&format!("{}", t)))
.map(|_| Ok(None))?;
}
return Ok(Some(0));
}
Ok(Some(Int::from(t.year())))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn day_of_month(ctx: &mut EvalContext, t: &Option<DateTime>) -> Result<Option<Int>> {
let t = match t {
Some(v) => v,
_ => return Ok(None),
};
if t.is_zero() {
if ctx.cfg.sql_mode.contains(SqlMode::NO_ZERO_DATE) {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(&format!("{}", t)))
.map(|_| Ok(None))?;
}
return Ok(Some(0));
}
Ok(Some(Int::from(t.day())))
}
#[rpn_fn(capture = [ctx])]
#[inline]
pub fn day_name(ctx: &mut EvalContext, t: &Option<DateTime>) -> Result<Option<Bytes>> {
match t {
Some(t) => {
if t.invalid_zero() {
return ctx
.handle_invalid_time_error(Error::incorrect_datetime_value(t))
.map(|_| Ok(None))?;
}
Ok(Some(t.weekday().name().to_string().into_bytes()))
}
None => Ok(None),
}
}
#[rpn_fn]
#[inline]
pub fn period_add(p: &Option<Int>, n: &Option<Int>) -> Result<Option<Int>> {
Ok(match (p, n) {
(Some(p), Some(n)) => {
if *p == 0 {
Some(0)
} else {
let (month, _) =
(i64::from(DateTime::period_to_month(*p as u64) as i32)).overflowing_add(*n);
Some(DateTime::month_to_period(u64::from(month as u32)) as i64)
}
}
_ => None,
})
}
#[rpn_fn]
#[inline]
pub fn period_diff(p1: &Option<Int>, p2: &Option<Int>) -> Result<Option<Int>> {
match (p1, p2) {
(Some(p1), Some(p2)) => Ok(Some(
DateTime::period_to_month(*p1 as u64) as i64
- DateTime::period_to_month(*p2 as u64) as i64,
)),
_ => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
use tipb::ScalarFuncSig;
use crate::codec::error::ERR_TRUNCATE_WRONG_VALUE;
use crate::codec::mysql::Time;
use crate::rpn_expr::types::test_util::RpnFnScalarEvaluator;
use tidb_query_datatype::FieldTypeTp;
#[test]
fn test_date_format() {
use std::sync::Arc;
use crate::expr::{EvalConfig, EvalContext, Flag, SqlMode};
let cases = vec![
(
"2010-01-07 23:12:34.12345",
"%b %M %m %c %D %d %e %j %k %h %i %p %r %T %s %f %U %u
%V %v %a %W %w %X %x %Y %y %%",
"Jan January 01 1 7th 07 7 007 23 11 12 PM 11:12:34 PM 23:12:34 34 123450 01 01
01 01 Thu Thursday 4 2010 2010 2010 10 %",
),
(
"2012-12-21 23:12:34.123456",
"%b %M %m %c %D %d %e %j %k %h %i %p %r %T %s %f %U
%u %V %v %a %W %w %X %x %Y %y %%",
"Dec December 12 12 21st 21 21 356 23 11 12 PM 11:12:34 PM 23:12:34 34 123456 51
51 51 51 Fri Friday 5 2012 2012 2012 12 %",
),
(
"0000-01-01 00:00:00.123456",
// Functions week() and yearweek() don't support multi mode,
// so the result of "%U %u %V %Y" is different from MySQL.
"%b %M %m %c %D %d %e %j %k %h %i %p %r %T %s %f %v
%x %Y %y %%",
"Jan January 01 1 1st 01 1 001 0 12 00 AM 12:00:00 AM 00:00:00 00 123456 52
4294967295 0000 00 %",
),
(
"2016-09-3 00:59:59.123456",
"abc%b %M %m %c %D %d %e %j %k %h %i %p %r %T %s %f %U
%u %V %v %a %W %w %X %x %Y %y!123 %%xyz %z",
"abcSep September 09 9 3rd 03 3 247 0 12 59 AM 12:59:59 AM 00:59:59 59 123456 35
35 35 35 Sat Saturday 6 2016 2016 2016 16!123 %xyz z",
),
(
"2012-10-01 00:00:00",
"%b %M %m %c %D %d %e %j %k %H %i %p %r %T %s %f %v
%x %Y %y %%",
"Oct October 10 10 1st 01 1 275 0 00 00 AM 12:00:00 AM 00:00:00 00 000000 40
2012 2012 12 %",
),
];
for (date, format, expect) in cases {
let date =
Some(DateTime::parse_datetime(&mut EvalContext::default(), date, 6, true).unwrap());
let format = Some(format.as_bytes().to_vec());
let expect = Some(expect.as_bytes().to_vec());
let output = RpnFnScalarEvaluator::new()
.push_param(date.clone())
.push_param(format.clone())
.evaluate(ScalarFuncSig::DateFormatSig)
.unwrap();
assert_eq!(output, expect, "{:?} {:?}", date, format);
}
// // TODO: pass this test after refactoring the issue #3953 is fixed.
// {
// let format: Option<Bytes> = Some("abc%b %M %m %c %D %d %e %j".as_bytes().to_vec());
// let time: Option<DateTime> = Some( DateTime::parse_utc_datetime("0000-00-00 00:00:00", 6).unwrap());
//
// let mut cfg = EvalConfig::new();
// cfg.set_flag(Flag::IN_UPDATE_OR_DELETE_STMT)
// .set_sql_mode(SqlMode::NO_ZERO_DATE | SqlMode::STRICT_ALL_TABLES);
// let ctx = EvalContext::new(Arc::new(cfg));
//
// let output = RpnFnScalarEvaluator::new()
// .context(ctx)
// .push_param(time.clone())
// .push_param(format)
// .evaluate::<Bytes>(ScalarFuncSig::DateFormatSig);
// assert!(output.is_err());
// }
{
let mut cfg = EvalConfig::new();
cfg.set_flag(Flag::IN_UPDATE_OR_DELETE_STMT)
.set_sql_mode(SqlMode::NO_ZERO_DATE | SqlMode::STRICT_ALL_TABLES);
let ctx = EvalContext::new(Arc::new(cfg));
let output = RpnFnScalarEvaluator::new()
.context(ctx)
.push_param(None::<DateTime>)
.push_param(None::<Bytes>)
.evaluate::<Bytes>(ScalarFuncSig::DateFormatSig)
.unwrap();
assert_eq!(output, None);
}
// test date format when format is None
let cases: Vec<(Option<&str>, Option<&str>)> = vec![
(Some("2010-01-07 23:12:34.12345"), None),
(None, None),
// TODO: pass this test after refactoring the issue #3953 is fixed.
// (
// "0000-00-00 00:00:00",
// Some(
// "%b %M %m %c %D %d %e %j %k %H %i %p %r %T %s %f %v
// %x %Y %y %%",
// ),
// ),
];
for (date, format) in cases {
let date = date.map(|d| {
DateTime::parse_datetime(&mut EvalContext::default(), d, 6, true).unwrap()
});
let format = format.map(|s| s.as_bytes().to_vec());
let output = RpnFnScalarEvaluator::new()
.push_param(date.clone())
.push_param(format.clone())
.evaluate::<Bytes>(ScalarFuncSig::DateFormatSig)
.unwrap();
assert_eq!(output, None, "{:?} {:?}", date, format);
}
}
#[test]
fn test_week_with_mode() {
let cases = vec![
("2008-02-20 00:00:00", Some(1), Some(8i64)),
("2008-12-31 00:00:00", Some(1), Some(53i64)),
("2000-01-01", Some(0), Some(0i64)),
("2008-02-20", Some(0), Some(7i64)),
("2017-01-01", Some(0), Some(1i64)),
("2017-01-01", Some(1), Some(0i64)),
("2017-01-01", Some(2), Some(1i64)),
("2017-01-01", Some(3), Some(52i64)),
("2017-01-01", Some(4), Some(1i64)),
("2017-01-01", Some(5), Some(0i64)),
("2017-01-01", Some(6), Some(1i64)),
("2017-01-01", Some(7), Some(52i64)),
("2017-12-31", Some(0), Some(53i64)),
("2017-12-31", Some(1), Some(52i64)),
("2017-12-31", Some(2), Some(53i64)),
("2017-12-31", Some(3), Some(52i64)),
("2017-12-31", Some(4), Some(53i64)),
("2017-12-31", Some(5), Some(52i64)),
("2017-12-31", Some(6), Some(1i64)),
("2017-12-31", Some(7), Some(52i64)),
("2017-12-31", Some(14), Some(1i64)),
("2017-12-31", None::<Int>, None),
("0000-00-00", Some(0), None),
("2018-12-00", Some(0), None),
("2018-00-03", Some(0), None),
];
let mut ctx = EvalContext::default();
for (arg1, arg2, exp) in cases {
let datetime = Some(DateTime::parse_datetime(&mut ctx, arg1, 6, true).unwrap());
let output = RpnFnScalarEvaluator::new()
.push_param(datetime.clone())
.push_param(arg2)
.evaluate(ScalarFuncSig::WeekWithMode)
.unwrap();
assert_eq!(output, exp);
}
let output = RpnFnScalarEvaluator::new()
.push_param(None::<DateTime>)
.push_param(Some(0))
.evaluate::<Int>(ScalarFuncSig::WeekWithMode)
.unwrap();
assert_eq!(output, None);
}
#[test]
fn test_week_day() {
let cases = vec![
("2018-12-03", Some(0i64)),
("2018-12-04", Some(1i64)),
("2018-12-05", Some(2i64)),
("2018-12-06", Some(3i64)),
("2018-12-07", Some(4i64)),
("2018-12-08", Some(5i64)),
("2018-12-09", Some(6i64)),
("0000-00-00", None),
("2018-12-00", None),
("2018-00-03", None),
];
let mut ctx = EvalContext::default();
for (arg, exp) in cases {
let datetime = Some(DateTime::parse_datetime(&mut ctx, arg, 6, true).unwrap());
let output = RpnFnScalarEvaluator::new()
.push_param(datetime.clone())
.evaluate(ScalarFuncSig::WeekDay)
.unwrap();
assert_eq!(output, exp);
}
let output = RpnFnScalarEvaluator::new()
.push_param(None::<DateTime>)
.evaluate::<Int>(ScalarFuncSig::WeekDay)
.unwrap();
assert_eq!(output, None);
}
#[test]
fn test_week_of_year() {
let cases = vec![
("2018-01-01", Some(1i64)),
("2018-02-28", Some(9i64)),
("2018-06-01", Some(22i64)),
("2018-07-31", Some(31i64)),
("2018-11-01", Some(44i64)),
("2018-12-30", Some(52i64)),
("2018-12-31", Some(1i64)),
("2017-01-01", Some(52i64)),
("2017-12-31", Some(52i64)),
("0000-00-00", None),
("2018-12-00", None),
("2018-00-03", None),
];
let mut ctx = EvalContext::default();
for (arg, exp) in cases {
let datetime = Some(DateTime::parse_datetime(&mut ctx, arg, 6, true).unwrap());
let output = RpnFnScalarEvaluator::new()
.push_param(datetime.clone())
.evaluate(ScalarFuncSig::WeekOfYear)
.unwrap();
assert_eq!(output, exp);
}
let output = RpnFnScalarEvaluator::new()
.push_param(None::<DateTime>)
.evaluate::<Int>(ScalarFuncSig::WeekOfYear)
.unwrap();
assert_eq!(output, None);
}
#[test]
fn test_day_of_week() {
let cases = vec![
("2018-11-11 00:00:00.000000", Some(1)),
("2018-11-12 00:00:00.000000", Some(2)),
("2018-11-13 00:00:00.000000", Some(3)),
("2018-11-14 00:00:00.000000", Some(4)),
("2018-11-15 00:00:00.000000", Some(5)),
("2018-11-16 00:00:00.000000", Some(6)),
("2018-11-17 00:00:00.000000", Some(7)),
("2018-11-18 00:00:00.000000", Some(1)),
("0000-00-00 00:00:00.000000", None),
("2018-11-00 00:00:00.000000", None),
("2018-00-11 00:00:00.000000", None),
];
let mut ctx = EvalContext::default();
for (arg, exp) in cases {
let datetime = Some(DateTime::parse_datetime(&mut ctx, arg, 6, true).unwrap());
let output = RpnFnScalarEvaluator::new()
.push_param(datetime.clone())
.evaluate(ScalarFuncSig::DayOfWeek)
.unwrap();
assert_eq!(output, exp);
}
let output = RpnFnScalarEvaluator::new()
.push_param(None::<DateTime>)
.evaluate::<Int>(ScalarFuncSig::DayOfWeek)
.unwrap();
assert_eq!(output, None);
}
#[test]
fn test_day_of_year() {
let cases = vec![
("2018-11-11 00:00:00.000000", Some(315)),
("2018-11-12 00:00:00.000000", Some(316)),
("2018-11-30 00:00:00.000000", Some(334)),
("2018-12-31 00:00:00.000000", Some(365)),
("2016-12-31 00:00:00.000000", Some(366)),
("0000-00-00 00:00:00.000000", None),
("2018-11-00 00:00:00.000000", None),
("2018-00-11 00:00:00.000000", None),
];
let mut ctx = EvalContext::default();
for (arg, exp) in cases {
let datetime = Some(DateTime::parse_datetime(&mut ctx, arg, 6, true).unwrap());
let output = RpnFnScalarEvaluator::new()
.push_param(datetime.clone())
.evaluate(ScalarFuncSig::DayOfYear)
.unwrap();
assert_eq!(output, exp);
}
let output = RpnFnScalarEvaluator::new()
.push_param(None::<DateTime>)
.evaluate::<Int>(ScalarFuncSig::DayOfYear)
.unwrap();
assert_eq!(output, None);
}
#[test]
fn test_to_days() {
let cases = vec![
(Some("950501"), Some(728779)),
(Some("2007-10-07"), Some(733321)),
(Some("2008-10-07"), Some(733687)),
(Some("08-10-07"), Some(733687)),
(Some("0000-01-01"), Some(1)),
(Some("2007-10-07 00:00:59"), Some(733321)),
(Some("0000-00-00 00:00:00"), None),
(None, None),
];
let mut ctx = EvalContext::default();
for (arg, exp) in cases {
let time = match arg {
Some(arg) => Some(Time::parse_datetime(&mut ctx, arg, 6, true).unwrap()),
None => None,
};
let output = RpnFnScalarEvaluator::new()
.push_param(time.clone())
.evaluate(ScalarFuncSig::ToDays)
.unwrap();
assert_eq!(output, exp);
}
}
#[test]
fn test_from_days() {
let cases = vec![
(ScalarValue::Int(Some(-140)), Some("0000-00-00")), // mysql FROM_DAYS returns 0000-00-00 for any day <= 365.
(ScalarValue::Int(Some(140)), Some("0000-00-00")), // mysql FROM_DAYS returns 0000-00-00 for any day <= 365.
(ScalarValue::Int(Some(735_000)), Some("2012-05-12")), // Leap year.
(ScalarValue::Int(Some(735_030)), Some("2012-06-11")),
(ScalarValue::Int(Some(735_130)), Some("2012-09-19")),
(ScalarValue::Int(Some(734_909)), Some("2012-02-11")),
(ScalarValue::Int(Some(734_878)), Some("2012-01-11")),
(ScalarValue::Int(Some(734_927)), Some("2012-02-29")),
(ScalarValue::Int(Some(734_634)), Some("2011-05-12")), // Non Leap year.
(ScalarValue::Int(Some(734_664)), Some("2011-06-11")),
(ScalarValue::Int(Some(734_764)), Some("2011-09-19")),
(ScalarValue::Int(Some(734_544)), Some("2011-02-11")),
(ScalarValue::Int(Some(734_513)), Some("2011-01-11")),
(ScalarValue::Int(Some(3_652_424)), Some("9999-12-31")),
(ScalarValue::Int(Some(3_652_425)), Some("0000-00-00")), // mysql FROM_DAYS returns 0000-00-00 for any day >= 3652425
(ScalarValue::Int(None), None),
];
let mut ctx = EvalContext::default();
for (arg, exp) in cases {
let datetime: Option<Time> =
exp.map(|exp: &str| Time::parse_date(&mut ctx, exp).unwrap());
let output: Option<Time> = RpnFnScalarEvaluator::new()
.push_param(arg)
.evaluate(ScalarFuncSig::FromDays)
.unwrap();
assert_eq!(output, datetime);
}
}
#[test]
fn test_month() {
let cases = vec![
(Some("0000-00-00 00:00:00"), Some(0i64)),
(Some("2018-01-01 01:01:01"), Some(1i64)),
(Some("2018-02-01 01:01:01"), Some(2i64)),
(Some("2018-03-01 01:01:01"), Some(3i64)),
(Some("2018-04-01 01:01:01"), Some(4i64)),
(Some("2018-05-01 01:01:01"), Some(5i64)),
(Some("2018-06-01 01:01:01"), Some(6i64)),
(Some("2018-07-01 01:01:01"), Some(7i64)),
(Some("2018-08-01 01:01:01"), Some(8i64)),
(Some("2018-09-01 01:01:01"), Some(9i64)),
(Some("2018-10-01 01:01:01"), Some(10i64)),
(Some("2018-11-01 01:01:01"), Some(11i64)),
(Some("2018-12-01 01:01:01"), Some(12i64)),
(None, None),
];
let mut ctx = EvalContext::default();
for (time, expect) in cases {
let time = time.map(|t| DateTime::parse_datetime(&mut ctx, t, 6, true).unwrap());
let output = RpnFnScalarEvaluator::new()
.push_param(time)
.evaluate(ScalarFuncSig::Month)
.unwrap();
assert_eq!(output, expect);
}
}
#[test]
fn test_hour_min_sec_micro_sec() {
// test hour, minute, second, micro_second
let cases: Vec<(&str, i8, i64, i64, i64, i64)> = vec![
("0 00:00:00.0", 0, 0, 0, 0, 0),
("31 11:30:45", 0, 31 * 24 + 11, 30, 45, 0),
("11:30:45.123345", 3, 11, 30, 45, 123000),
("11:30:45.123345", 5, 11, 30, 45, 123350),
("11:30:45.123345", 6, 11, 30, 45, 123345),
("11:30:45.1233456", 6, 11, 30, 45, 123346),
("11:30:45.000010", 6, 11, 30, 45, 10),
("11:30:45.00010", 5, 11, 30, 45, 100),
("-11:30:45.9233456", 0, 11, 30, 46, 0),
("-11:30:45.9233456", 1, 11, 30, 45, 900000),
("272:59:59.94", 2, 272, 59, 59, 940000),
("272:59:59.99", 1, 273, 0, 0, 0),
("272:59:59.99", 0, 273, 0, 0, 0),
];
for (arg, fsp, h, m, s, ms) in cases {
let duration =
Some(Duration::parse(&mut EvalContext::default(), arg.as_bytes(), fsp).unwrap());
let test_case_func = |sig, res| {
let output = RpnFnScalarEvaluator::new()
.push_param(duration.clone())
.evaluate::<Int>(sig)
.unwrap();
assert_eq!(output, Some(res));
};
test_case_func(ScalarFuncSig::Hour, h);
test_case_func(ScalarFuncSig::Minute, m);
test_case_func(ScalarFuncSig::Second, s);
test_case_func(ScalarFuncSig::MicroSecond, ms);
}
// test NULL case
let test_null_case = |sig| {
let output = RpnFnScalarEvaluator::new()
.push_param(None::<Duration>)
.evaluate::<Int>(sig)
.unwrap();
assert_eq!(output, None);
};
test_null_case(ScalarFuncSig::Hour);
test_null_case(ScalarFuncSig::Minute);
test_null_case(ScalarFuncSig::Second);
test_null_case(ScalarFuncSig::MicroSecond);
}
#[test]
fn test_year() {
let cases = vec![
(Some("0000-00-00 00:00:00"), Some(0i64)),
(Some("1-01-01 01:01:01"), Some(1i64)),
(Some("2018-01-01 01:01:01"), Some(2018i64)),
(Some("2019-01-01 01:01:01"), Some(2019i64)),
(Some("2020-01-01 01:01:01"), Some(2020i64)),
(Some("2021-01-01 01:01:01"), Some(2021i64)),
(Some("2022-01-01 01:01:01"), Some(2022i64)),
(Some("2023-01-01 01:01:01"), Some(2023i64)),
(Some("2024-01-01 01:01:01"), Some(2024i64)),
(Some("2025-01-01 01:01:01"), Some(2025i64)),
(Some("2026-01-01 01:01:01"), Some(2026i64)),
(Some("2027-01-01 01:01:01"), Some(2027i64)),
(Some("2028-01-01 01:01:01"), Some(2028i64)),
(Some("2029-01-01 01:01:01"), Some(2029i64)),
(None, None),
];
let mut ctx = EvalContext::default();
for (time, expect) in cases {
let time = time.map(|t| DateTime::parse_datetime(&mut ctx, t, 6, true).unwrap());
let output = RpnFnScalarEvaluator::new()
.push_param(time)
.evaluate(ScalarFuncSig::Year)
.unwrap();
assert_eq!(output, expect);
}
}
#[test]
fn test_day_of_month() {
let cases = vec![
(Some("0000-00-00 00:00:00.000000"), Some(0)),
(Some("2018-02-01 00:00:00.000000"), Some(1)),
(Some("2018-02-15 00:00:00.000000"), Some(15)),
(Some("2018-02-28 00:00:00.000000"), Some(28)),
(Some("2016-02-29 00:00:00.000000"), Some(29)),
(None, None),
];
let mut ctx = EvalContext::default();
for (time, expect) in cases {
let time = time.map(|t| DateTime::parse_datetime(&mut ctx, t, 6, true).unwrap());
let output = RpnFnScalarEvaluator::new()
.push_param(time)
.evaluate(ScalarFuncSig::DayOfMonth)
.unwrap();
assert_eq!(output, expect);
}
}
#[test]
fn test_day_name() {
let cases = vec![
(None, None, None),
(Some("0000-00-00"), Some(ERR_TRUNCATE_WRONG_VALUE), None),
(Some("2019-11-17"), None, Some("Sunday")),
(Some("2019-11-18"), None, Some("Monday")),
(Some("2019-11-19"), None, Some("Tuesday")),
(Some("2019-11-20"), None, Some("Wednesday")),
(Some("2019-11-21"), None, Some("Thursday")),
(Some("2019-11-22"), None, Some("Friday")),
(Some("2019-11-23"), None, Some("Saturday")),
(Some("2019-11-24"), None, Some("Sunday")),
(Some("2019-11-00"), Some(ERR_TRUNCATE_WRONG_VALUE), None),
(Some("2019-00-00"), Some(ERR_TRUNCATE_WRONG_VALUE), None),
(Some("2019-00-01"), Some(ERR_TRUNCATE_WRONG_VALUE), None),
(Some("2019-11-24 00:00:00.000000"), None, Some("Sunday")),
];
for (arg, err_code, exp) in cases {
let mut ctx = EvalContext::default();
let arg = arg.map(|arg: &str| Time::parse_date(&mut ctx, arg).unwrap());
let (output, ctx) = RpnFnScalarEvaluator::new()
.push_param(arg)
.context(ctx)
.evaluate_raw(FieldTypeTp::String, ScalarFuncSig::DayName);
let output = output.unwrap();
assert_eq!(output.as_bytes(), &exp.map(|v| v.as_bytes().to_vec()));
if let Some(err_code) = err_code {
assert_eq!(ctx.warnings.warnings[0].get_code(), err_code);
}
}
}
#[test]
fn test_period_add() {
let cases = vec![
(2, 222, 201808),
(0, 222, 0),
(196802, 14, 196904),
(6901, 13, 207002),
(7001, 13, 197102),
(200212, 9223372036854775807, 200211),
(9223372036854775807, 0, 27201459511),
(9223372036854775807, 9223372036854775807, 27201459510),
(201611, 2, 201701),
(201611, 3, 201702),
(201611, -13, 201510),
(1611, 3, 201702),
(7011, 3, 197102),
(12323, 10, 12509),
(0, 3, 0),
];
for (arg1, arg2, exp) in cases {
let output = RpnFnScalarEvaluator::new()
.push_param(Some(arg1))
.push_param(Some(arg2))
.evaluate(ScalarFuncSig::PeriodAdd)
.unwrap();
assert_eq!(output, Some(exp));
}
}
#[test]
fn test_period_diff() {
let cases = vec![
(213002, 7010, 1912),
(213002, 215810, -344),
(2202, 9601, 313),
(202202, 9601, 313),
(200806, 6907, -733),
(201611, 201611, 0),
(200802, 200703, 11),
(0, 999999999, -120000086),
(9999999, 0, 1200086),
(411, 200413, -2),
(197000, 207700, -1284),
(201701, 201611, 2),
(201702, 201611, 3),
(201510, 201611, -13),
(201702, 1611, 3),
(197102, 7011, 3),
(12509, 12323, 10),
(12509, 12323, 10),
];
for (arg1, arg2, exp) in cases {
let output = RpnFnScalarEvaluator::new()
.push_param(Some(arg1))
.push_param(Some(arg2))
.evaluate(ScalarFuncSig::PeriodDiff)
.unwrap();
assert_eq!(output, Some(exp));
}
}
}
| 36.488235 | 130 | 0.49418 |
fbfcf392055e3775bffc59840aabe9a7b638f6c8 | 4,372 | //! Unit tests for the tokens module.
#![cfg(test)]
use super::*;
use frame_support::{assert_noop, assert_ok};
use mock::*;
#[test]
fn new_auction_should_work() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(AuctionModule::new_auction(10, Some(100)), 0);
});
}
#[test]
fn update_auction_should_work() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(AuctionModule::new_auction(10, Some(100)), 0);
assert_noop!(
AuctionModule::update_auction(
1,
AuctionInfo {
bid: Some((ALICE, 100)),
start: 10,
end: Some(100)
}
),
Error::<Runtime>::AuctionNotExist,
);
assert_ok!(AuctionModule::update_auction(
0,
AuctionInfo {
bid: Some((ALICE, 100)),
start: 10,
end: Some(100)
}
));
});
}
#[test]
fn auction_info_should_work() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(AuctionModule::new_auction(10, Some(100)), 0);
assert_eq!(
AuctionModule::auction_info(0),
Some(AuctionInfo {
bid: None,
start: 10,
end: Some(100)
})
);
});
}
#[test]
fn bid_should_work() {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(AuctionModule::new_auction(0, Some(5)), 0);
assert_eq!(
AuctionModule::auction_info(0),
Some(AuctionInfo {
bid: None,
start: 0,
end: Some(5)
})
);
assert_ok!(AuctionModule::bid(Origin::signed(ALICE), 0, 20));
let bid_event = TestEvent::auction(Event::Bid(0, ALICE, 20));
assert!(System::events().iter().any(|record| record.event == bid_event));
assert_eq!(
AuctionModule::auction_info(0),
Some(AuctionInfo {
bid: Some((ALICE, 20)),
start: 0,
end: Some(11)
})
);
});
}
#[test]
fn bid_should_fail() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(AuctionModule::new_auction(10, Some(100)), 0);
assert_ok!(AuctionModule::new_auction(0, Some(100)), 1);
assert_noop!(
AuctionModule::bid(Origin::signed(ALICE), 0, 20),
Error::<Runtime>::AuctionNotStarted
);
assert_noop!(
AuctionModule::bid(Origin::signed(BOB), 1, 20),
Error::<Runtime>::BidNotAccepted,
);
assert_noop!(
AuctionModule::bid(Origin::signed(ALICE), 1, 0),
Error::<Runtime>::InvalidBidPrice,
);
});
}
#[test]
fn remove_auction_should_work() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(AuctionModule::new_auction(10, Some(100)), 0);
assert_eq!(AuctionModule::auctions_index(), 1);
assert_eq!(AuctionModule::auctions(0).is_some(), true);
assert_eq!(AuctionModule::auction_end_time(100, 0), Some(()));
AuctionModule::remove_auction(0);
assert_eq!(AuctionModule::auctions(0), None);
assert_eq!(AuctionModule::auction_end_time(100, 0), None);
});
}
#[test]
fn cleanup_auction_should_work() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(AuctionModule::new_auction(10, Some(100)), 0);
assert_eq!(AuctionModule::auctions_index(), 1);
assert_ok!(AuctionModule::new_auction(10, Some(50)), 1);
assert_eq!(AuctionModule::auctions_index(), 2);
assert_eq!(AuctionModule::auctions(0).is_some(), true);
assert_eq!(AuctionModule::auctions(1).is_some(), true);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(0).count(), 0);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(50).count(), 1);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(100).count(), 1);
AuctionModule::on_finalize(50);
assert_eq!(AuctionModule::auctions(0).is_some(), true);
assert_eq!(AuctionModule::auctions(1).is_some(), false);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(0).count(), 0);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(50).count(), 0);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(100).count(), 1);
AuctionModule::on_finalize(100);
assert_eq!(AuctionModule::auctions(0).is_some(), false);
assert_eq!(AuctionModule::auctions(1).is_some(), false);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(0).count(), 0);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(50).count(), 0);
assert_eq!(<AuctionEndTime<Runtime>>::iter_prefix(100).count(), 0);
});
}
#[test]
fn cannot_add_new_auction_when_no_available_id() {
ExtBuilder::default().build().execute_with(|| {
<AuctionsIndex<Runtime>>::put(AuctionId::max_value());
assert_noop!(
AuctionModule::new_auction(0, None),
Error::<Runtime>::NoAvailableAuctionId
);
});
}
| 27.847134 | 75 | 0.675206 |
ebbb0fe1a375c7c6875d0808840f91a268a07063 | 5,541 | // Copyright 2019-2020 Parity Technologies (UK) Ltd.
//
// 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.
//! Traits and interfaces to operate with storage entities.
//!
//! Generally a type is said to be a storage entity if it implements the
//! `SpreadLayout` trait. This defines certain constants and routines in order
//! to tell a smart contract how to load and store instances of this type
//! from and to the contract's storage.
//!
//! The `PackedLayout` trait can then be implemented on top of the `SpreadLayout`
//! for types that further allow to be stored in the contract storage in a more
//! compressed format to a single storage cell.
mod impls;
mod keyptr;
mod optspec;
mod packed;
mod spread;
pub(crate) use self::optspec::{
clear_spread_root_opt,
pull_packed_root_opt,
pull_spread_root_opt,
push_packed_root_opt,
push_spread_root_opt,
};
pub use self::{
impls::{
forward_clear_packed,
forward_pull_packed,
forward_push_packed,
},
keyptr::KeyPtr,
packed::PackedLayout,
spread::SpreadLayout,
};
use ink_primitives::Key;
/// Pulls an instance of type `T` from the contract storage using spread layout.
///
/// The root key denotes the offset into the contract storage where the
/// instance of type `T` is being pulled from.
///
/// # Note
///
/// - The routine assumes that the instance has previously been stored to
/// the contract storage using spread layout.
/// - Users should prefer using this function directly instead of using the
/// trait methods on [`SpreadLayout`].
pub fn pull_spread_root<T>(root_key: &Key) -> T
where
T: SpreadLayout,
{
let mut ptr = KeyPtr::from(*root_key);
<T as SpreadLayout>::pull_spread(&mut ptr)
}
/// Clears the entity from the contract storage using spread layout.
///
/// The root key denotes the offset into the contract storage where the
/// instance of type `T` is being cleared from.
///
/// # Note
///
/// - The routine assumes that the instance has previously been stored to
/// the contract storage using spread layout.
/// - Users should prefer using this function directly instead of using the
/// trait methods on [`SpreadLayout`].
pub fn clear_spread_root<T>(entity: &T, root_key: &Key)
where
T: SpreadLayout,
{
let mut ptr = KeyPtr::from(*root_key);
<T as SpreadLayout>::clear_spread(entity, &mut ptr);
}
/// Pushes the entitiy to the contract storage using spread layout.
///
/// The root key denotes the offset into the contract storage where the
/// instance of type `T` is being pushed to.
///
/// # Note
///
/// - The routine will push the given entity to the contract storage using
/// spread layout.
/// - Users should prefer using this function directly instead of using the
/// trait methods on [`SpreadLayout`].
pub fn push_spread_root<T>(entity: &T, root_key: &Key)
where
T: SpreadLayout,
{
let mut ptr = KeyPtr::from(*root_key);
<T as SpreadLayout>::push_spread(entity, &mut ptr);
}
/// Pulls an instance of type `T` from the contract storage using packed layout.
///
/// The root key denotes the offset into the contract storage where the
/// instance of type `T` is being pulled from.
///
/// # Note
///
/// - The routine assumes that the instance has previously been stored to
/// the contract storage using packed layout.
/// - Users should prefer using this function directly instead of using the
/// trait methods on [`PackedLayout`].
pub fn pull_packed_root<T>(root_key: &Key) -> T
where
T: PackedLayout,
{
let mut entity = crate::env::get_contract_storage::<T>(*root_key)
.expect("storage entry was empty")
.expect("could not properly decode storage entry");
<T as PackedLayout>::pull_packed(&mut entity, root_key);
entity
}
/// Pushes the entitiy to the contract storage using packed layout.
///
/// The root key denotes the offset into the contract storage where the
/// instance of type `T` is being pushed to.
///
/// # Note
///
/// - The routine will push the given entity to the contract storage using
/// packed layout.
/// - Users should prefer using this function directly instead of using the
/// trait methods on [`PackedLayout`].
pub fn push_packed_root<T>(entity: &T, root_key: &Key)
where
T: PackedLayout,
{
<T as PackedLayout>::push_packed(entity, root_key);
crate::env::set_contract_storage(*root_key, entity);
}
/// Clears the entity from the contract storage using packed layout.
///
/// The root key denotes the offset into the contract storage where the
/// instance of type `T` is being cleared from.
///
/// # Note
///
/// - The routine assumes that the instance has previously been stored to
/// the contract storage using packed layout.
/// - Users should prefer using this function directly instead of using the
/// trait methods on [`PackedLayout`].
pub fn clear_packed_root<T>(entity: &T, root_key: &Key)
where
T: PackedLayout,
{
<T as PackedLayout>::clear_packed(entity, root_key);
crate::env::clear_contract_storage(*root_key);
}
| 33.179641 | 81 | 0.708717 |
012d7835102709746f745fddf090a19d6d1acee8 | 1,768 | use fltk::{app, frame::*, image::PngImage, window::*};
use std::error::Error;
use std::fs;
use std::thread::sleep;
use std::time::{Duration, Instant};
pub fn run_viewer(
width: i32,
height: i32,
image_file: &'static str,
) -> Result<(), Box<dyn Error + '_>> {
let app = app::App::default();
let mut window_instance = Window::default()
.with_size(width + 10, height + 25) //on Mac borders mess things up
.with_label("Viewer")
.center_screen();
let mut frame = Frame::default().size_of(&window_instance);
let image = PngImage::load("output.png")?;
frame.set_image(Some(image));
// To remove an image
// frame.set_image(None::<PngImage>);
window_instance.end();
window_instance.make_resizable(true);
window_instance.show();
let mut modified = fs::metadata("output.png")?.modified()?;
app::add_idle(move || {
let execution_time = Instant::now();
let metadata = match fs::metadata(image_file) {
Ok(it) => it,
Err(err) => panic!(err),
};
let new_modified = match metadata.modified() {
Ok(it) => it,
Err(err) => panic!(err),
};
if modified != new_modified {
modified = new_modified;
println!("{:?}", modified);
let new_image = match PngImage::load(image_file) {
Ok(it) => it,
Err(err) => panic!(err),
};
frame.set_image(Some(new_image));
window_instance.redraw();
}
let elapsed = execution_time.elapsed();
let millis = 1000.0 / 60.0 - (elapsed.as_millis() as f64);
sleep(Duration::from_millis(millis as u64));
});
app.run()?;
Ok(())
}
| 27.625 | 75 | 0.553167 |
d501e738d89a3998db66fcfc335294c57658007b | 2,615 | use crate::errors::*;
use crate::types::*;
use uuid::Uuid;
/// Options to be used when a message content is copied without a link to the original message
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MessageCopyOptions {
#[doc(hidden)]
#[serde(rename(serialize = "@extra", deserialize = "@extra"))]
extra: Option<String>,
#[serde(rename(serialize = "@client_id", deserialize = "@client_id"))]
client_id: Option<i32>,
/// True, if content of the message needs to be copied without a link to the original message. Always true if the message is forwarded to a secret chat
send_copy: bool,
/// True, if media caption of the message copy needs to be replaced. Ignored if send_copy is false
replace_caption: bool,
/// New message caption. Ignored if replace_caption is false
new_caption: FormattedText,
}
impl RObject for MessageCopyOptions {
#[doc(hidden)]
fn extra(&self) -> Option<&str> {
self.extra.as_deref()
}
#[doc(hidden)]
fn client_id(&self) -> Option<i32> {
self.client_id
}
}
impl MessageCopyOptions {
pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> {
Ok(serde_json::from_str(json.as_ref())?)
}
pub fn builder() -> RTDMessageCopyOptionsBuilder {
let mut inner = MessageCopyOptions::default();
inner.extra = Some(Uuid::new_v4().to_string());
RTDMessageCopyOptionsBuilder { inner }
}
pub fn send_copy(&self) -> bool {
self.send_copy
}
pub fn replace_caption(&self) -> bool {
self.replace_caption
}
pub fn new_caption(&self) -> &FormattedText {
&self.new_caption
}
}
#[doc(hidden)]
pub struct RTDMessageCopyOptionsBuilder {
inner: MessageCopyOptions,
}
impl RTDMessageCopyOptionsBuilder {
pub fn build(&self) -> MessageCopyOptions {
self.inner.clone()
}
pub fn send_copy(&mut self, send_copy: bool) -> &mut Self {
self.inner.send_copy = send_copy;
self
}
pub fn replace_caption(&mut self, replace_caption: bool) -> &mut Self {
self.inner.replace_caption = replace_caption;
self
}
pub fn new_caption<T: AsRef<FormattedText>>(&mut self, new_caption: T) -> &mut Self {
self.inner.new_caption = new_caption.as_ref().clone();
self
}
}
impl AsRef<MessageCopyOptions> for MessageCopyOptions {
fn as_ref(&self) -> &MessageCopyOptions {
self
}
}
impl AsRef<MessageCopyOptions> for RTDMessageCopyOptionsBuilder {
fn as_ref(&self) -> &MessageCopyOptions {
&self.inner
}
}
| 28.11828 | 155 | 0.651625 |
b9ccd3c3cd7ffaeeb202ab7e9ecb0cd66ba2a86a | 2,458 | pub struct Gpu {
vram: [u8, ..0x2000],
oam: [u8, ..0xA0],
lcdc: u8,
stat: u8,
scy: u8,
scx: u8,
ly: u8,
lyc: u8,
wy: u8,
wx: u8,
bgp: u8,
obp0: u8,
obp1: u8
}
impl Gpu {
pub fn new() -> Gpu {
Gpu {
vram: [0x00, ..0x2000],
oam: [0x00, ..0xA0],
lcdc: 0x91,
stat: 0x00,
scy: 0x00,
scx: 0x00,
ly: 0x00,
lyc: 0x00,
wy: 0x00,
wx: 0x00,
bgp: 0xFC,
obp0: 0xFF,
obp1: 0xFF
}
}
pub fn write_byte(&mut self, address: u16, value: u8) {
match address {
0x8000..0x9FFF => {
self.vram[address as uint - 0x8000] = value;
},
0xFE00..0xFE9F => {
self.oam[address as uint - 0xFE00] = value;
},
0xFF40 => {
self.lcdc = value;
},
0xFF41 => {
self.stat = value;
},
0xFF42 => {
self.scy = value;
},
0xFF43 => {
self.scx = value;
},
0xFF44 => {
self.ly = value;
},
0xFF45 => {
self.lyc = value;
},
0xFF46 => {
fail!("DMA transfer not implemented");
},
0xFF47 => {
self.bgp = value;
},
0xFF48 => {
self.obp0 = value;
},
0xFF49 => {
self.obp1 = value;
},
0xFF4A => {
self.wy = value;
},
0xFF4B => {
self.wx = value;
},
_ => unreachable!()
}
}
pub fn read_byte(&self, address: u16) -> u8 {
match address {
0x8000..0x9FFF => self.vram[address as uint - 0x8000],
0xFE00..0xFE9F => self.oam[address as uint - 0xFE00],
0xFF40 => self.lcdc,
0xFF41 => self.stat,
0xFF42 => self.scy,
0xFF43 => self.scx,
0xFF44 => self.ly,
0xFF45 => self.lyc,
0xFF47 => self.bgp,
0xFF48 => self.obp0,
0xFF49 => self.obp1,
0xFF4A => self.wy,
0xFF4B => self.wx,
_ => unreachable!()
}
}
}
| 23.864078 | 66 | 0.35476 |
fcf0c3d8507ceb4b95d0ba8d4f6a56e0c8c17894 | 6,608 | use std::collections::HashSet;
use std::fmt;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::{Distance, GPSBounds, Line, PolyLine, Polygon, Pt2D};
/// Maybe a misnomer, but like a PolyLine, but closed.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Ring {
// first equals last
pts: Vec<Pt2D>,
}
impl Ring {
pub fn new(pts: Vec<Pt2D>) -> Result<Ring> {
if pts.len() < 3 {
bail!("Can't make a ring with < 3 points");
}
if pts[0] != *pts.last().unwrap() {
bail!("Can't make a ring with mismatching first/last points");
}
if pts.windows(2).any(|pair| pair[0] == pair[1]) {
bail!("Ring has ~dupe adjacent pts");
}
let result = Ring { pts };
let mut seen_pts = HashSet::new();
for pt in result.pts.iter().skip(1) {
seen_pts.insert(pt.to_hashable());
}
if seen_pts.len() != result.pts.len() - 1 {
bail!("Ring has repeat non-adjacent points");
}
Ok(result)
}
pub fn must_new(pts: Vec<Pt2D>) -> Ring {
Ring::new(pts).unwrap()
}
/// Draws the ring with some thickness, with half of it straddling the interor of the ring, and
/// half on the outside.
pub fn to_outline(&self, thickness: Distance) -> Polygon {
// TODO Has a weird corner. Use the polygon offset thing instead?
PolyLine::unchecked_new(self.pts.clone()).make_polygons(thickness)
}
pub fn to_polygon(self) -> Polygon {
Polygon::with_holes(self, Vec::new())
}
pub fn points(&self) -> &Vec<Pt2D> {
&self.pts
}
pub fn into_points(self) -> Vec<Pt2D> {
self.pts
}
/// Be careful with the order of results. Hits on an earlier line segment of other show up
/// first, but if the ring hits a line segment at multiple points, who knows. Dedupes.
pub fn all_intersections(&self, other: &PolyLine) -> Vec<Pt2D> {
let mut hits = Vec::new();
let mut seen = HashSet::new();
for l1 in other.lines() {
for l2 in self
.pts
.windows(2)
.map(|pair| Line::must_new(pair[0], pair[1]))
{
if let Some(pt) = l1.intersection(&l2) {
if !seen.contains(&pt.to_hashable()) {
hits.push(pt);
seen.insert(pt.to_hashable());
}
}
}
}
hits
}
pub(crate) fn get_both_slices_btwn(
&self,
pt1: Pt2D,
pt2: Pt2D,
) -> Option<(PolyLine, PolyLine)> {
assert!(pt1 != pt2);
let pl = PolyLine::unchecked_new(self.pts.clone());
let mut dist1 = pl.dist_along_of_point(pt1)?.0;
let mut dist2 = pl.dist_along_of_point(pt2)?.0;
if dist1 > dist2 {
std::mem::swap(&mut dist1, &mut dist2);
}
if dist1 == dist2 {
return None;
}
let candidate1 = pl.maybe_exact_slice(dist1, dist2).ok()?;
let candidate2 = pl
.maybe_exact_slice(dist2, pl.length())
.ok()?
.must_extend(pl.maybe_exact_slice(Distance::ZERO, dist1).ok()?);
Some((candidate1, candidate2))
}
pub fn get_shorter_slice_btwn(&self, pt1: Pt2D, pt2: Pt2D) -> Option<PolyLine> {
let (candidate1, candidate2) = self.get_both_slices_btwn(pt1, pt2)?;
if candidate1.length() < candidate2.length() {
Some(candidate1)
} else {
Some(candidate2)
}
}
/// Extract all PolyLines and Rings. Doesn't handle crazy double loops and stuff.
pub fn split_points(pts: &Vec<Pt2D>) -> Result<(Vec<PolyLine>, Vec<Ring>)> {
let mut seen = HashSet::new();
let mut intersections = HashSet::new();
for pt in pts {
let pt = pt.to_hashable();
if seen.contains(&pt) {
intersections.insert(pt);
} else {
seen.insert(pt);
}
}
intersections.insert(pts[0].to_hashable());
intersections.insert(pts.last().unwrap().to_hashable());
let mut polylines = Vec::new();
let mut rings = Vec::new();
let mut current = Vec::new();
for pt in pts.iter().cloned() {
current.push(pt);
if intersections.contains(&pt.to_hashable()) && current.len() > 1 {
if current[0] == pt && current.len() >= 3 {
rings.push(Ring::new(current.drain(..).collect())?);
} else {
polylines.push(PolyLine::new(current.drain(..).collect())?);
}
current.push(pt);
}
}
Ok((polylines, rings))
}
pub fn contains_pt(&self, pt: Pt2D) -> bool {
PolyLine::unchecked_new(self.pts.clone())
.dist_along_of_point(pt)
.is_some()
}
/// Produces a GeoJSON polygon, optionally mapping the world-space points back to GPS.
pub fn to_geojson(&self, gps: Option<&GPSBounds>) -> geojson::Geometry {
let mut pts = Vec::new();
if let Some(ref gps) = gps {
for pt in gps.convert_back(&self.pts) {
pts.push(vec![pt.x(), pt.y()]);
}
} else {
for pt in &self.pts {
pts.push(vec![pt.x(), pt.y()]);
}
}
geojson::Geometry::new(geojson::Value::Polygon(vec![pts]))
}
/// Translates the ring by a fixed offset.
pub fn translate(mut self, dx: f64, dy: f64) -> Ring {
for pt in &mut self.pts {
*pt = pt.offset(dx, dy);
}
self
}
}
impl fmt::Display for Ring {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "Ring::new(vec![")?;
for pt in &self.pts {
writeln!(f, " Pt2D::new({}, {}),", pt.x(), pt.y())?;
}
write!(f, "])")
}
}
impl From<Ring> for geo::LineString<f64> {
fn from(ring: Ring) -> Self {
let coords = ring
.pts
.into_iter()
.map(geo::Coordinate::from)
.collect::<Vec<_>>();
Self(coords)
}
}
impl From<geo::LineString<f64>> for Ring {
fn from(line_string: geo::LineString<f64>) -> Self {
// Dedupe adjacent points. Only needed for results from concave hull.
let mut pts: Vec<Pt2D> = line_string.0.into_iter().map(Pt2D::from).collect();
pts.dedup();
Self::must_new(pts)
}
}
| 31.466667 | 99 | 0.5227 |
efe64f2469db222aedcad17e948af312030b4598 | 5,044 | use super::Decoder;
use crate::flowgger::config::Config;
use crate::flowgger::record::Record;
use crate::flowgger::utils;
use chrono::{Datelike, NaiveDateTime, Utc};
#[derive(Clone)]
pub struct RFC3164Decoder {}
impl RFC3164Decoder {
pub fn new(_config: &Config) -> RFC3164Decoder {
RFC3164Decoder {}
}
}
impl Decoder for RFC3164Decoder {
/// Implementation of the RF3164 decoder. Decode a string into a record object
///
/// # Arguments
/// * `line` - String to decode
///
/// # Returns
/// * Record object containing the log info extracted
///
fn decode(&self, line: &str) -> Result<Record, &'static str> {
// Get the optional pri part and remove it from the string
let (pri, _msg) = parse_strip_pri(line)?;
// The event may have several consecutive spaces as separator
let tokens_vec = _msg.split_whitespace().collect::<Vec<&str>>();
// If we have less than 4 tokens, the input can't be valid
if tokens_vec.len() > 3 {
// Date is made of the first 3 space separated tokens, rebuild it
let _date_str = tokens_vec[0..3].join(" ");
let _hostname = tokens_vec[3];
// All that remains is the message that may contain several spaces, so rebuild it
let _message = tokens_vec[4..].join(" ");
let ts = parse_ts(&_date_str)?;
let record = Record {
ts,
hostname: _hostname.to_owned(),
facility: pri.facility,
severity: pri.severity,
appname: None,
procid: None,
msgid: None,
msg: Some(_message.to_owned()),
full_msg: Some(line.to_owned()),
sd: None,
};
Ok(record)
} else {
Err("Malformed RFC3164 event: Invalid timestamp or hostname")
}
}
}
struct Pri {
facility: Option<u8>,
severity: Option<u8>,
}
fn parse_strip_pri(event: &str) -> Result<(Pri, &str), &'static str> {
if event.starts_with('<') {
let pri_end_index = event
.find('>')
.ok_or("Malformed RFC3164 event: Invalid priority")?;
let (pri, msg) = event.split_at(pri_end_index + 1);
let npri: u8 = pri
.trim_start_matches('<')
.trim_end_matches('>')
.parse()
.or(Err("Invalid priority"))?;
Ok((
Pri {
facility: Some(npri >> 3),
severity: Some(npri & 7),
},
msg,
))
} else {
Ok((
Pri {
facility: None,
severity: None,
},
event,
))
}
}
fn parse_ts(ts_str: &str) -> Result<f64, &'static str> {
// Append the year to parse a full ts
let current_year = Utc::now().year();
let ts = format!("{} {}", current_year, ts_str);
match NaiveDateTime::parse_from_str(&ts, "%Y %b %d %H:%M:%S") {
Ok(date) => Ok(utils::PreciseTimestamp::from_naive_datetime(date).as_f64()),
Err(_) => Err("Unable to parse the date"),
}
}
#[cfg(test)]
use crate::flowgger::utils::test_utils::rfc_test_utils::ts_from_partial_date_time;
#[test]
fn test_rfc3164_decode() {
let msg = r#"Aug 6 11:15:24 testhostname appname 69 42 [origin@123 software="te\st sc\"ript" swVersion="0.0.1"] test message"#;
let cfg = Config::from_string("[input]\n[input.ltsv_schema]\nformat = \"rfc3164\"\n").unwrap();
let expected_ts = ts_from_partial_date_time(8, 6, 11, 15, 24);
let decoder = RFC3164Decoder::new(&cfg);
let res = decoder.decode(msg).unwrap();
assert_eq!(res.facility, None);
assert_eq!(res.severity, None);
assert_eq!(res.ts, expected_ts);
assert_eq!(res.hostname, "testhostname");
assert_eq!(res.appname, None);
assert_eq!(res.procid, None);
assert_eq!(res.msgid, None);
assert_eq!(res.msg, Some(r#"appname 69 42 [origin@123 software="te\st sc\"ript" swVersion="0.0.1"] test message"#.to_string()));
assert_eq!(res.full_msg, Some(msg.to_string()));
}
#[test]
fn test_rfc3164_decode_with_pri() {
let msg = r#"<13>Aug 6 11:15:24 testhostname appname 69 42 [origin@123 software="te\st sc\"ript" swVersion="0.0.1"] test message"#;
let cfg = Config::from_string("[input]\n[input.ltsv_schema]\nformat = \"rfc3164\"\n").unwrap();
let expected_ts = ts_from_partial_date_time(8, 6, 11, 15, 24);
let decoder = RFC3164Decoder::new(&cfg);
let res = decoder.decode(msg).unwrap();
assert_eq!(res.facility, Some(1));
assert_eq!(res.severity, Some(5));
assert_eq!(res.ts, expected_ts);
assert_eq!(res.hostname, "testhostname");
assert_eq!(res.appname, None);
assert_eq!(res.procid, None);
assert_eq!(res.msgid, None);
assert_eq!(res.msg, Some(r#"appname 69 42 [origin@123 software="te\st sc\"ript" swVersion="0.0.1"] test message"#.to_string()));
assert_eq!(res.full_msg, Some(msg.to_string()));
}
| 34.547945 | 136 | 0.585646 |
3314ba5ec6f1c17df268c1d2577e47143a1d4817 | 6,320 | use geom::{CornerRadii, Distance, Polygon, Pt2D};
use crate::{
include_labeled_bytes, text, Button, Drawable, EdgeInsets, EventCtx, GeomBatch, GfxCtx,
Outcome, OutlineStyle, Prerender, ScreenDims, ScreenPt, ScreenRectangle, Style, Text, Widget,
WidgetImpl, WidgetOutput,
};
// TODO MAX_CHAR_WIDTH is a hardcoded nonsense value
const TEXT_WIDTH: f64 = 2.0 * text::MAX_CHAR_WIDTH;
// TODO Allow text entry
// TODO Allow click and hold
// TODO Grey out the buttons when we're maxed out
pub struct Spinner {
low: isize,
high: isize,
pub current: isize,
up: Button,
down: Button,
outline: OutlineStyle,
drawable: Drawable,
top_left: ScreenPt,
dims: ScreenDims,
}
impl Spinner {
pub fn widget(ctx: &EventCtx, (low, high): (isize, isize), current: isize) -> Widget {
Widget::new(Box::new(Self::new(ctx, (low, high), current)))
}
pub fn new(ctx: &EventCtx, (low, high): (isize, isize), mut current: isize) -> Self {
let button_builder = ctx
.style()
.btn_plain
.btn()
.padding(EdgeInsets {
top: 2.0,
bottom: 2.0,
left: 4.0,
right: 4.0,
})
.image_dims(17.0);
let up = button_builder
.clone()
.image_bytes(include_labeled_bytes!("../../icons/arrow_up.svg"))
.corner_rounding(CornerRadii {
top_left: 0.0,
top_right: 5.0,
bottom_right: 0.0,
bottom_left: 5.0,
})
.build(ctx, "increase value");
let down = button_builder
.image_bytes(include_labeled_bytes!("../../icons/arrow_down.svg"))
.corner_rounding(CornerRadii {
top_left: 5.0,
top_right: 0.0,
bottom_right: 5.0,
bottom_left: 0.0,
})
.build(ctx, "decrease value");
let outline = ctx.style().btn_outline.outline;
let dims = ScreenDims::new(
TEXT_WIDTH + up.get_dims().width,
up.get_dims().height + down.get_dims().height + 1.0,
);
if current < low {
warn!(
"Spinner's initial value is out of bounds! {}, bounds ({}, {})",
current, low, high
);
current = low;
} else if high < current {
warn!(
"Spinner's initial value is out of bounds! {}, bounds ({}, {})",
current, low, high
);
current = high;
}
let mut spinner = Spinner {
low,
high,
current,
up,
down,
drawable: Drawable::empty(ctx),
outline,
top_left: ScreenPt::new(0.0, 0.0),
dims,
};
spinner.drawable = spinner.drawable(ctx.prerender, ctx.style());
spinner
}
pub fn modify(&mut self, ctx: &EventCtx, delta: isize) {
self.current += delta;
self.current = self.current.min(self.high);
self.current = self.current.max(self.low);
self.drawable = self.drawable(ctx.prerender, ctx.style());
}
fn drawable(&self, prerender: &Prerender, style: &Style) -> Drawable {
let mut batch = GeomBatch::from(vec![(
style.field_bg,
Polygon::rounded_rectangle(self.dims.width, self.dims.height, 5.0),
)]);
batch.append(
Text::from(self.current.to_string())
.render_autocropped(prerender)
.centered_on(Pt2D::new(TEXT_WIDTH / 2.0, self.dims.height / 2.0)),
);
batch.push(
self.outline.1,
Polygon::rounded_rectangle(self.dims.width, self.dims.height, 5.0)
.to_outline(Distance::meters(self.outline.0))
.unwrap(),
);
prerender.upload(batch)
}
}
impl WidgetImpl for Spinner {
fn get_dims(&self) -> ScreenDims {
self.dims
}
fn set_pos(&mut self, top_left: ScreenPt) {
// TODO This works, but it'd be kind of cool if we could construct a tiny little Panel
// here and use that. Wait, why can't we? ...
self.top_left = top_left;
self.up
.set_pos(ScreenPt::new(top_left.x + TEXT_WIDTH, top_left.y));
self.down.set_pos(ScreenPt::new(
top_left.x + TEXT_WIDTH,
top_left.y + self.up.get_dims().height,
));
}
fn event(&mut self, ctx: &mut EventCtx, output: &mut WidgetOutput) {
self.up.event(ctx, output);
if let Outcome::Clicked(_) = output.outcome {
output.outcome = Outcome::Changed;
self.current = (self.current + 1).min(self.high);
self.drawable = self.drawable(&ctx.prerender, ctx.style());
ctx.no_op_event(true, |ctx| self.up.event(ctx, output));
return;
}
self.down.event(ctx, output);
if let Outcome::Clicked(_) = output.outcome {
output.outcome = Outcome::Changed;
self.current = (self.current - 1).max(self.low);
self.drawable = self.drawable(&ctx.prerender, ctx.style());
ctx.no_op_event(true, |ctx| self.down.event(ctx, output));
return;
}
if let Some(pt) = ctx.canvas.get_cursor_in_screen_space() {
if ScreenRectangle::top_left(self.top_left, self.dims).contains(pt) {
if let Some((_, dy)) = ctx.input.get_mouse_scroll() {
if dy > 0.0 && self.current != self.high {
self.current += 1;
output.outcome = Outcome::Changed;
self.drawable = self.drawable(&ctx.prerender, ctx.style());
}
if dy < 0.0 && self.current != self.low {
self.current -= 1;
output.outcome = Outcome::Changed;
self.drawable = self.drawable(&ctx.prerender, ctx.style());
}
}
}
}
}
fn draw(&self, g: &mut GfxCtx) {
g.redraw_at(self.top_left, &self.drawable);
self.up.draw(g);
self.down.draw(g);
}
}
| 33.089005 | 97 | 0.522152 |
502162685651a598dbdd626402b4102007d89904 | 7,013 | use spdx::ParseError;
macro_rules! test_validate {
(ok [$($text:expr => [$($expected:expr),+$(,)?]),+$(,)?]) => {
$(
let val_expr = spdx::Expression::parse($text).unwrap();
let mut reqs = val_expr.requirements().enumerate();
$(
let actual = reqs.next().unwrap();
let actual_str = format!("{}", actual.1.req);
let expected_str = $expected;
similar_asserts::assert_eq!(actual_str, expected_str, "failed @ index {}", actual.0);
)+
if let Some((_, additional)) = reqs.next() {
assert!(false, "found additional requirement {}", additional.req);
}
)+
};
}
macro_rules! err {
($text:expr => $reason:ident @ $range:expr) => {
let act_err = spdx::Expression::parse($text).unwrap_err();
let expected = ParseError {
original: $text,
span: $range,
reason: spdx::error::Reason::$reason,
};
similar_asserts::assert_eq!(act_err, expected);
};
($text:expr => $unexpected:expr; $range:expr) => {
let act_err = spdx::Expression::parse($text).unwrap_err();
let expected = ParseError {
original: $text,
span: $range,
reason: spdx::error::Reason::Unexpected($unexpected),
};
similar_asserts::assert_eq!(act_err, expected);
};
}
#[test]
fn fails_empty() {
err!("" => Empty @ 0..0);
err!(" " => Empty @ 0..1);
err!("\n\t\n" => Empty @ 0..3);
err!("()" => &["<license>", "("]; 1..2);
err!("( )" => &["<license>", "("]; 2..3);
err!("( )" => &["<license>", "("]; 4..5);
err!(" ( )" => &["<license>", "("]; 4..5);
err!("AND" => &["<license>", "("]; 0..3);
}
#[test]
fn fails_unbalanced_parens() {
err!("(Apache-2.0" => UnclosedParens @ 0..1);
err!("BSD-3-Clause-No-Nuclear-License)" => UnopenedParens @ 31..32);
err!("((BSD-3-Clause-No-Nuclear-License OR MIT)" => UnclosedParens @ 0..1);
err!("(BSD-3-Clause-No-Nuclear-License OR MIT) AND Glulxe)" => UnopenedParens @ 51..52);
err!("Glulxe OR MIT) AND BSD-3-Clause-No-Nuclear-License" => UnopenedParens @ 13..14);
err!("Glulxe OR ( MIT AND BSD-3-Clause-No-Nuclear-License" => UnclosedParens @ 10..11);
}
#[test]
fn fails_bad_exception() {
err!("Apache-2.0 WITH WITH LLVM-exception OR Apache-2.0" => &["<exception>"]; 16..20);
err!("Apache-2.0 WITH WITH LLVM-exception" => &["<exception>"]; 16..20);
err!("(Apache-2.0) WITH LLVM-exception" => &["AND", "OR"]; 13..17);
err!("Apache-2.0 (WITH LLVM-exception)" => &["AND", "OR", "WITH", ")", "+"]; 11..12);
err!("(Apache-2.0 WITH) LLVM-exception" => &["<exception>"]; 16..17);
err!("(Apache-2.0 WITH)+ LLVM-exception" => &["<exception>"]; 16..17);
err!("Apache-2.0 WITH MIT" => &["<exception>"]; 16..19);
err!("Apache-2.0 WITH WITH MIT" => &["<exception>"]; 16..20);
err!("Apache-2.0 AND WITH MIT" => &["<license>", "("]; 15..19);
err!("Apache-2.0 WITH AND MIT" => &["<exception>"]; 16..19);
err!("Apache-2.0 WITH" => &["<exception>"]; 15..15);
}
#[test]
fn fails_bad_plus() {
err!("LAL-1.2 +" => SeparatedPlus @ 7..8);
err!("+LAL-1.2" => &["<license>", "("]; 0..1);
err!("++LAL-1.2" => &["<license>", "("]; 0..1);
err!("LAL+-1.2" => UnknownTerm @ 0..3);
err!("LAL-+1.2" => UnknownTerm @ 0..4);
err!("LAL-1.+2" => UnknownTerm @ 0..6);
err!("LAL-1.2++" => &["AND", "OR", "WITH", ")"]; 8..9);
// + can only be applied to valid SDPX short identifiers, not license/doc refs
err!("LicenseRef-Nope+" => &["AND", "OR", "WITH", ")"]; 15..16);
err!("LAL-1.2 AND+" => &["<license>", "("]; 11..12);
err!("LAL-1.2 OR +" => SeparatedPlus @ 10..11);
err!("LAL-1.2 WITH+ LLVM-exception" => &["<exception>"]; 12..13);
err!("LAL-1.2 WITH LLVM-exception+" => &["AND", "OR", ")"]; 27..28);
}
#[test]
fn fails_bad_ops() {
err!("MIT-advertising AND" => &["<license>", "("]; 19..19);
err!("MIT-advertising OR MIT AND" => &["<license>", "("]; 26..26);
err!("MIT-advertising OR OR MIT" => &["<license>", "("]; 19..21);
err!("MIT-advertising OR AND MIT" => &["<license>", "("]; 19..22);
err!("MIT-advertising AND OR MIT" => &["<license>", "("]; 20..22);
err!("(MIT-advertising AND) MIT" => &["<license>", "("]; 20..21);
err!("MIT-advertising (AND MIT)" => &["AND", "OR", "WITH", ")", "+"]; 16..17);
err!("OR MIT-advertising" => &["<license>", "("]; 0..2);
err!("MIT-advertising WITH AND" => &["<exception>"]; 21..24);
}
#[test]
fn validates_single() {
test_validate!(ok [
"MIT" => ["MIT"],
"Apache-2.0" => ["Apache-2.0"],
]);
}
#[test]
fn validates_canonical() {
let canonical = "Apache-2.0 OR MIT";
let canonical_w_parens = "(Apache-2.0 OR MIT)";
test_validate!(ok [
canonical => ["Apache-2.0", "MIT"],
canonical_w_parens => ["Apache-2.0", "MIT"],
]);
}
#[test]
fn validates_single_with_exception() {
let with_exception = "Apache-2.0 WITH LLVM-exception";
test_validate!(ok [
with_exception => [with_exception],
]);
}
#[test]
fn validates_complex() {
let complex = "(Apache-2.0 WITH LLVM-exception OR Apache-2.0) AND MIT";
test_validate!(ok [
complex => [
"Apache-2.0 WITH LLVM-exception",
"Apache-2.0",
"MIT",
]
]);
}
#[test]
fn validates_parens_plus() {
let expression = "(MIT AND (BitTorrent-1.1+ OR BSD-3-Clause))";
test_validate!(ok [
expression => [
"MIT",
"BitTorrent-1.1+",
"BSD-3-Clause",
]
]);
}
#[test]
fn validates_leading_parens() {
let leading_parens = "((Apache-2.0 WITH LLVM-exception) OR Apache-2.0) AND OpenSSL OR MIT";
test_validate!(ok [
leading_parens => [
"Apache-2.0 WITH LLVM-exception",
"Apache-2.0",
"OpenSSL",
"MIT",
]
]);
}
#[test]
fn validates_trailing_parens() {
let trailing_parens = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 AND (OpenSSL OR MIT)";
test_validate!(ok [
trailing_parens => [
"Apache-2.0 WITH LLVM-exception",
"Apache-2.0",
"OpenSSL",
"MIT",
]
]);
}
#[test]
fn validates_middle_parens() {
let middle_parens = "Apache-2.0 WITH LLVM-exception OR (Apache-2.0 AND OpenSSL) OR MIT";
test_validate!(ok [
middle_parens => [
"Apache-2.0 WITH LLVM-exception",
"Apache-2.0",
"OpenSSL",
"MIT",
]
]);
}
#[test]
fn validates_excessive_parens() {
let excessive_parens =
"((((Apache-2.0 WITH LLVM-exception) OR (Apache-2.0)) AND (OpenSSL)) OR (MIT))";
test_validate!(ok [
excessive_parens=> [
"Apache-2.0 WITH LLVM-exception",
"Apache-2.0",
"OpenSSL",
"MIT",
]
]);
}
| 30.894273 | 101 | 0.51376 |
5dcd466032436a873948e61de77e139636b7084a | 71,875 | use crate::Element;
use crate::{UncertainFloat, Isotope, AtomicScatteringFactor, XrayScatteringFactor, NeutronScatteringFactor};
pub fn load() -> Element {
Element {
atomic_number: 62,
name: "Samarium",
symbol: "Sm",
mass: 150.36_f64,
common_ions: vec![3],
uncommon_ions: vec![2],
xray_scattering: Some(XrayScatteringFactor {
table: vec![
AtomicScatteringFactor { energy: 0.01_f64, f1: None, f2: Some(0.187_643_f64) },
AtomicScatteringFactor { energy: 0.010_161_7_f64, f1: None, f2: Some(0.195_336_f64) },
AtomicScatteringFactor { energy: 0.010_326_1_f64, f1: None, f2: Some(0.203_345_f64) },
AtomicScatteringFactor { energy: 0.010_493_1_f64, f1: None, f2: Some(0.211_681_f64) },
AtomicScatteringFactor { energy: 0.010_662_8_f64, f1: None, f2: Some(0.220_36_f64) },
AtomicScatteringFactor { energy: 0.010_835_3_f64, f1: None, f2: Some(0.229_394_f64) },
AtomicScatteringFactor { energy: 0.011_010_6_f64, f1: None, f2: Some(0.238_799_f64) },
AtomicScatteringFactor { energy: 0.011_188_6_f64, f1: None, f2: Some(0.248_589_f64) },
AtomicScatteringFactor { energy: 0.011_369_6_f64, f1: None, f2: Some(0.258_781_f64) },
AtomicScatteringFactor { energy: 0.011_553_5_f64, f1: None, f2: Some(0.269_391_f64) },
AtomicScatteringFactor { energy: 0.011_740_4_f64, f1: None, f2: Some(0.280_435_f64) },
AtomicScatteringFactor { energy: 0.011_930_3_f64, f1: None, f2: Some(0.291_933_f64) },
AtomicScatteringFactor { energy: 0.012_123_2_f64, f1: None, f2: Some(0.303_902_f64) },
AtomicScatteringFactor { energy: 0.012_319_3_f64, f1: None, f2: Some(0.315_122_f64) },
AtomicScatteringFactor { energy: 0.012_518_6_f64, f1: None, f2: Some(0.326_091_f64) },
AtomicScatteringFactor { energy: 0.012_721_f64, f1: None, f2: Some(0.337_442_f64) },
AtomicScatteringFactor { energy: 0.012_926_8_f64, f1: None, f2: Some(0.349_187_f64) },
AtomicScatteringFactor { energy: 0.013_135_9_f64, f1: None, f2: Some(0.361_342_f64) },
AtomicScatteringFactor { energy: 0.013_348_3_f64, f1: None, f2: Some(0.373_919_f64) },
AtomicScatteringFactor { energy: 0.013_564_2_f64, f1: None, f2: Some(0.386_934_f64) },
AtomicScatteringFactor { energy: 0.013_783_6_f64, f1: None, f2: Some(0.399_806_f64) },
AtomicScatteringFactor { energy: 0.014_006_6_f64, f1: None, f2: Some(0.411_591_f64) },
AtomicScatteringFactor { energy: 0.014_233_1_f64, f1: None, f2: Some(0.423_723_f64) },
AtomicScatteringFactor { energy: 0.014_463_3_f64, f1: None, f2: Some(0.436_213_f64) },
AtomicScatteringFactor { energy: 0.014_697_3_f64, f1: None, f2: Some(0.449_071_f64) },
AtomicScatteringFactor { energy: 0.014_935_f64, f1: None, f2: Some(0.462_308_f64) },
AtomicScatteringFactor { energy: 0.015_176_5_f64, f1: None, f2: Some(0.475_936_f64) },
AtomicScatteringFactor { energy: 0.015_422_f64, f1: None, f2: Some(0.488_902_f64) },
AtomicScatteringFactor { energy: 0.015_671_4_f64, f1: None, f2: Some(0.501_112_f64) },
AtomicScatteringFactor { energy: 0.015_924_9_f64, f1: None, f2: Some(0.513_626_f64) },
AtomicScatteringFactor { energy: 0.016_182_5_f64, f1: None, f2: Some(0.526_453_f64) },
AtomicScatteringFactor { energy: 0.016_444_2_f64, f1: None, f2: Some(0.539_6_f64) },
AtomicScatteringFactor { energy: 0.016_710_2_f64, f1: None, f2: Some(0.553_075_f64) },
AtomicScatteringFactor { energy: 0.016_980_5_f64, f1: None, f2: Some(0.566_841_f64) },
AtomicScatteringFactor { energy: 0.017_255_1_f64, f1: None, f2: Some(0.579_76_f64) },
AtomicScatteringFactor { energy: 0.017_534_2_f64, f1: None, f2: Some(0.592_972_f64) },
AtomicScatteringFactor { energy: 0.017_817_8_f64, f1: None, f2: Some(0.606_486_f64) },
AtomicScatteringFactor { energy: 0.018_106_f64, f1: None, f2: Some(0.620_308_f64) },
AtomicScatteringFactor { energy: 0.018_398_9_f64, f1: None, f2: Some(0.634_445_f64) },
AtomicScatteringFactor { energy: 0.018_696_4_f64, f1: None, f2: Some(0.653_063_f64) },
AtomicScatteringFactor { energy: 0.018_998_8_f64, f1: None, f2: Some(0.676_143_f64) },
AtomicScatteringFactor { energy: 0.019_306_1_f64, f1: None, f2: Some(0.700_039_f64) },
AtomicScatteringFactor { energy: 0.019_618_4_f64, f1: None, f2: Some(0.724_78_f64) },
AtomicScatteringFactor { energy: 0.019_935_7_f64, f1: None, f2: Some(0.784_056_f64) },
AtomicScatteringFactor { energy: 0.020_258_2_f64, f1: None, f2: Some(0.883_332_f64) },
AtomicScatteringFactor { energy: 0.020_585_8_f64, f1: None, f2: Some(1.090_93_f64) },
AtomicScatteringFactor { energy: 0.020_918_8_f64, f1: None, f2: Some(1.468_53_f64) },
AtomicScatteringFactor { energy: 0.021_257_1_f64, f1: None, f2: Some(1.670_1_f64) },
AtomicScatteringFactor { energy: 0.021_600_9_f64, f1: None, f2: Some(1.694_71_f64) },
AtomicScatteringFactor { energy: 0.021_950_3_f64, f1: None, f2: Some(1.719_67_f64) },
AtomicScatteringFactor { energy: 0.022_305_3_f64, f1: None, f2: Some(1.862_42_f64) },
AtomicScatteringFactor { energy: 0.022_666_1_f64, f1: None, f2: Some(2.367_32_f64) },
AtomicScatteringFactor { energy: 0.023_032_7_f64, f1: None, f2: Some(2.785_27_f64) },
AtomicScatteringFactor { energy: 0.023_405_3_f64, f1: None, f2: Some(2.932_8_f64) },
AtomicScatteringFactor { energy: 0.023_783_8_f64, f1: None, f2: Some(2.760_46_f64) },
AtomicScatteringFactor { energy: 0.024_168_5_f64, f1: None, f2: Some(3.252_8_f64) },
AtomicScatteringFactor { energy: 0.024_559_4_f64, f1: None, f2: Some(6.097_2_f64) },
AtomicScatteringFactor { energy: 0.024_956_6_f64, f1: None, f2: Some(6.859_31_f64) },
AtomicScatteringFactor { energy: 0.025_360_3_f64, f1: None, f2: Some(8.395_57_f64) },
AtomicScatteringFactor { energy: 0.025_770_5_f64, f1: None, f2: Some(9.529_2_f64) },
AtomicScatteringFactor { energy: 0.026_187_3_f64, f1: None, f2: Some(10.440_9_f64) },
AtomicScatteringFactor { energy: 0.026_610_9_f64, f1: None, f2: Some(11.080_2_f64) },
AtomicScatteringFactor { energy: 0.027_041_3_f64, f1: None, f2: Some(11.415_f64) },
AtomicScatteringFactor { energy: 0.027_478_6_f64, f1: None, f2: Some(11.626_1_f64) },
AtomicScatteringFactor { energy: 0.027_923_1_f64, f1: None, f2: Some(11.841_f64) },
AtomicScatteringFactor { energy: 0.028_374_7_f64, f1: None, f2: Some(12.06_f64) },
AtomicScatteringFactor { energy: 0.028_833_7_f64, f1: None, f2: Some(12.125_1_f64) },
AtomicScatteringFactor { energy: 0.029_3_f64, f1: Some(3.679_89_f64), f2: Some(12.173_2_f64) },
AtomicScatteringFactor { energy: 0.029_773_9_f64, f1: Some(4.484_81_f64), f2: Some(12.221_5_f64) },
AtomicScatteringFactor { energy: 0.030_255_5_f64, f1: Some(5.297_47_f64), f2: Some(11.846_2_f64) },
AtomicScatteringFactor { energy: 0.030_744_9_f64, f1: Some(5.788_23_f64), f2: Some(11.418_f64) },
AtomicScatteringFactor { energy: 0.031_242_1_f64, f1: Some(6.130_25_f64), f2: Some(11.139_2_f64) },
AtomicScatteringFactor { energy: 0.031_747_5_f64, f1: Some(6.452_26_f64), f2: Some(10.877_3_f64) },
AtomicScatteringFactor { energy: 0.032_260_9_f64, f1: Some(6.726_31_f64), f2: Some(10.623_6_f64) },
AtomicScatteringFactor { energy: 0.032_782_7_f64, f1: Some(6.974_08_f64), f2: Some(10.424_5_f64) },
AtomicScatteringFactor { energy: 0.033_313_f64, f1: Some(7.215_95_f64), f2: Some(10.229_2_f64) },
AtomicScatteringFactor { energy: 0.033_851_8_f64, f1: Some(7.450_01_f64), f2: Some(10.037_4_f64) },
AtomicScatteringFactor { energy: 0.034_399_3_f64, f1: Some(7.669_44_f64), f2: Some(9.815_08_f64) },
AtomicScatteringFactor { energy: 0.034_955_7_f64, f1: Some(7.833_14_f64), f2: Some(9.587_34_f64) },
AtomicScatteringFactor { energy: 0.035_521_1_f64, f1: Some(7.958_15_f64), f2: Some(9.394_47_f64) },
AtomicScatteringFactor { energy: 0.036_095_6_f64, f1: Some(8.065_17_f64), f2: Some(9.211_36_f64) },
AtomicScatteringFactor { energy: 0.036_679_4_f64, f1: Some(8.127_84_f64), f2: Some(9.057_1_f64) },
AtomicScatteringFactor { energy: 0.037_272_7_f64, f1: Some(8.213_01_f64), f2: Some(8.953_89_f64) },
AtomicScatteringFactor { energy: 0.037_875_5_f64, f1: Some(8.314_54_f64), f2: Some(8.851_88_f64) },
AtomicScatteringFactor { energy: 0.038_488_2_f64, f1: Some(8.425_55_f64), f2: Some(8.751_f64) },
AtomicScatteringFactor { energy: 0.039_110_7_f64, f1: Some(8.534_69_f64), f2: Some(8.622_61_f64) },
AtomicScatteringFactor { energy: 0.039_743_2_f64, f1: Some(8.621_01_f64), f2: Some(8.492_38_f64) },
AtomicScatteringFactor { energy: 0.040_386_1_f64, f1: Some(8.688_64_f64), f2: Some(8.364_12_f64) },
AtomicScatteringFactor { energy: 0.041_039_3_f64, f1: Some(8.738_53_f64), f2: Some(8.245_11_f64) },
AtomicScatteringFactor { energy: 0.041_703_1_f64, f1: Some(8.779_4_f64), f2: Some(8.132_13_f64) },
AtomicScatteringFactor { energy: 0.042_377_6_f64, f1: Some(8.803_9_f64), f2: Some(8.020_7_f64) },
AtomicScatteringFactor { energy: 0.043_063_f64, f1: Some(8.799_72_f64), f2: Some(7.910_79_f64) },
AtomicScatteringFactor { energy: 0.043_759_5_f64, f1: Some(8.753_45_f64), f2: Some(7.856_18_f64) },
AtomicScatteringFactor { energy: 0.044_467_3_f64, f1: Some(8.746_72_f64), f2: Some(7.839_91_f64) },
AtomicScatteringFactor { energy: 0.045_186_5_f64, f1: Some(8.750_21_f64), f2: Some(7.823_65_f64) },
AtomicScatteringFactor { energy: 0.045_917_4_f64, f1: Some(8.746_85_f64), f2: Some(7.824_14_f64) },
AtomicScatteringFactor { energy: 0.046_66_f64, f1: Some(8.766_34_f64), f2: Some(7.839_59_f64) },
AtomicScatteringFactor { energy: 0.047_414_7_f64, f1: Some(8.798_72_f64), f2: Some(7.855_06_f64) },
AtomicScatteringFactor { energy: 0.048_181_6_f64, f1: Some(8.837_98_f64), f2: Some(7.870_56_f64) },
AtomicScatteringFactor { energy: 0.048_960_9_f64, f1: Some(8.882_46_f64), f2: Some(7.886_1_f64) },
AtomicScatteringFactor { energy: 0.049_752_8_f64, f1: Some(8.931_04_f64), f2: Some(7.901_66_f64) },
AtomicScatteringFactor { energy: 0.050_557_6_f64, f1: Some(8.982_96_f64), f2: Some(7.917_26_f64) },
AtomicScatteringFactor { energy: 0.051_375_3_f64, f1: Some(9.037_69_f64), f2: Some(7.932_89_f64) },
AtomicScatteringFactor { energy: 0.052_206_2_f64, f1: Some(9.094_88_f64), f2: Some(7.948_54_f64) },
AtomicScatteringFactor { energy: 0.053_050_6_f64, f1: Some(9.154_29_f64), f2: Some(7.964_24_f64) },
AtomicScatteringFactor { energy: 0.053_908_7_f64, f1: Some(9.215_76_f64), f2: Some(7.979_95_f64) },
AtomicScatteringFactor { energy: 0.054_780_6_f64, f1: Some(9.279_26_f64), f2: Some(7.995_71_f64) },
AtomicScatteringFactor { energy: 0.055_666_7_f64, f1: Some(9.344_85_f64), f2: Some(8.011_49_f64) },
AtomicScatteringFactor { energy: 0.056_567_f64, f1: Some(9.412_71_f64), f2: Some(8.027_3_f64) },
AtomicScatteringFactor { energy: 0.057_482_f64, f1: Some(9.483_17_f64), f2: Some(8.043_14_f64) },
AtomicScatteringFactor { energy: 0.058_411_7_f64, f1: Some(9.556_82_f64), f2: Some(8.059_02_f64) },
AtomicScatteringFactor { energy: 0.059_356_4_f64, f1: Some(9.634_68_f64), f2: Some(8.074_93_f64) },
AtomicScatteringFactor { energy: 0.060_316_5_f64, f1: Some(9.718_69_f64), f2: Some(8.090_86_f64) },
AtomicScatteringFactor { energy: 0.061_292_1_f64, f1: Some(9.813_42_f64), f2: Some(8.106_83_f64) },
AtomicScatteringFactor { energy: 0.062_283_4_f64, f1: Some(9.935_83_f64), f2: Some(8.122_58_f64) },
AtomicScatteringFactor { energy: 0.063_290_8_f64, f1: Some(10.053_8_f64), f2: Some(8.064_86_f64) },
AtomicScatteringFactor { energy: 0.064_314_5_f64, f1: Some(10.142_f64), f2: Some(8.007_55_f64) },
AtomicScatteringFactor { energy: 0.065_354_7_f64, f1: Some(10.212_1_f64), f2: Some(7.950_66_f64) },
AtomicScatteringFactor { energy: 0.066_411_8_f64, f1: Some(10.271_2_f64), f2: Some(7.894_16_f64) },
AtomicScatteringFactor { energy: 0.067_485_9_f64, f1: Some(10.321_f64), f2: Some(7.838_06_f64) },
AtomicScatteringFactor { energy: 0.068_577_5_f64, f1: Some(10.362_6_f64), f2: Some(7.782_37_f64) },
AtomicScatteringFactor { energy: 0.069_686_7_f64, f1: Some(10.396_5_f64), f2: Some(7.727_07_f64) },
AtomicScatteringFactor { energy: 0.070_813_8_f64, f1: Some(10.423_1_f64), f2: Some(7.672_16_f64) },
AtomicScatteringFactor { energy: 0.071_959_1_f64, f1: Some(10.442_4_f64), f2: Some(7.617_65_f64) },
AtomicScatteringFactor { energy: 0.073_123_f64, f1: Some(10.454_5_f64), f2: Some(7.563_52_f64) },
AtomicScatteringFactor { energy: 0.074_305_7_f64, f1: Some(10.459_2_f64), f2: Some(7.509_77_f64) },
AtomicScatteringFactor { energy: 0.075_507_6_f64, f1: Some(10.456_f64), f2: Some(7.456_41_f64) },
AtomicScatteringFactor { energy: 0.076_728_9_f64, f1: Some(10.444_2_f64), f2: Some(7.403_43_f64) },
AtomicScatteringFactor { energy: 0.077_969_9_f64, f1: Some(10.420_6_f64), f2: Some(7.350_82_f64) },
AtomicScatteringFactor { energy: 0.079_231_f64, f1: Some(10.390_4_f64), f2: Some(7.311_25_f64) },
AtomicScatteringFactor { energy: 0.080_512_5_f64, f1: Some(10.358_3_f64), f2: Some(7.272_31_f64) },
AtomicScatteringFactor { energy: 0.081_814_7_f64, f1: Some(10.322_1_f64), f2: Some(7.233_57_f64) },
AtomicScatteringFactor { energy: 0.083_138_f64, f1: Some(10.280_3_f64), f2: Some(7.195_05_f64) },
AtomicScatteringFactor { energy: 0.084_482_7_f64, f1: Some(10.232_7_f64), f2: Some(7.156_72_f64) },
AtomicScatteringFactor { energy: 0.085_849_1_f64, f1: Some(10.180_3_f64), f2: Some(7.118_61_f64) },
AtomicScatteringFactor { energy: 0.087_237_7_f64, f1: Some(10.128_8_f64), f2: Some(7.080_69_f64) },
AtomicScatteringFactor { energy: 0.088_648_7_f64, f1: Some(10.065_8_f64), f2: Some(7.020_09_f64) },
AtomicScatteringFactor { energy: 0.090_082_5_f64, f1: Some(9.982_47_f64), f2: Some(6.959_14_f64) },
AtomicScatteringFactor { energy: 0.091_539_5_f64, f1: Some(9.883_42_f64), f2: Some(6.898_71_f64) },
AtomicScatteringFactor { energy: 0.093_020_1_f64, f1: Some(9.770_15_f64), f2: Some(6.838_8_f64) },
AtomicScatteringFactor { energy: 0.094_524_6_f64, f1: Some(9.643_95_f64), f2: Some(6.779_42_f64) },
AtomicScatteringFactor { energy: 0.096_053_5_f64, f1: Some(9.508_54_f64), f2: Some(6.720_55_f64) },
AtomicScatteringFactor { energy: 0.097_607_1_f64, f1: Some(9.381_36_f64), f2: Some(6.652_19_f64) },
AtomicScatteringFactor { energy: 0.099_185_8_f64, f1: Some(9.214_f64), f2: Some(6.526_57_f64) },
AtomicScatteringFactor { energy: 0.100_79_f64, f1: Some(8.999_1_f64), f2: Some(6.403_32_f64) },
AtomicScatteringFactor { energy: 0.102_42_f64, f1: Some(8.746_16_f64), f2: Some(6.282_4_f64) },
AtomicScatteringFactor { energy: 0.104_077_f64, f1: Some(8.466_19_f64), f2: Some(6.163_76_f64) },
AtomicScatteringFactor { energy: 0.105_76_f64, f1: Some(8.189_23_f64), f2: Some(6.047_36_f64) },
AtomicScatteringFactor { energy: 0.107_471_f64, f1: Some(7.983_15_f64), f2: Some(5.767_49_f64) },
AtomicScatteringFactor { energy: 0.109_209_f64, f1: Some(7.477_69_f64), f2: Some(5.312_42_f64) },
AtomicScatteringFactor { energy: 0.110_975_f64, f1: Some(6.742_54_f64), f2: Some(4.893_26_f64) },
AtomicScatteringFactor { energy: 0.112_77_f64, f1: Some(5.782_24_f64), f2: Some(4.564_8_f64) },
AtomicScatteringFactor { energy: 0.114_594_f64, f1: Some(4.689_96_f64), f2: Some(4.311_73_f64) },
AtomicScatteringFactor { energy: 0.116_448_f64, f1: Some(3.399_11_f64), f2: Some(4.083_31_f64) },
AtomicScatteringFactor { energy: 0.118_331_f64, f1: Some(1.843_23_f64), f2: Some(3.881_38_f64) },
AtomicScatteringFactor { energy: 0.120_245_f64, f1: Some(-0.126_763_f64), f2: Some(3.689_42_f64) },
AtomicScatteringFactor { energy: 0.122_19_f64, f1: Some(-2.697_54_f64), f2: Some(3.617_52_f64) },
AtomicScatteringFactor { energy: 0.124_166_f64, f1: Some(-6.661_1_f64), f2: Some(3.606_49_f64) },
AtomicScatteringFactor { energy: 0.126_175_f64, f1: Some(-11.918_1_f64), f2: Some(5.741_29_f64) },
AtomicScatteringFactor { energy: 0.128_215_f64, f1: Some(-17.728_8_f64), f2: Some(10.051_f64) },
AtomicScatteringFactor { energy: 0.130_289_f64, f1: Some(-24.093_3_f64), f2: Some(17.713_9_f64) },
AtomicScatteringFactor { energy: 0.132_397_f64, f1: Some(-29.482_6_f64), f2: Some(40.643_7_f64) },
AtomicScatteringFactor { energy: 0.134_538_f64, f1: Some(-14.493_2_f64), f2: Some(61.657_3_f64) },
AtomicScatteringFactor { energy: 0.136_714_f64, f1: Some(11.359_6_f64), f2: Some(48.303_3_f64) },
AtomicScatteringFactor { energy: 0.138_925_f64, f1: Some(13.424_9_f64), f2: Some(38.567_3_f64) },
AtomicScatteringFactor { energy: 0.141_172_f64, f1: Some(13.139_9_f64), f2: Some(39.277_4_f64) },
AtomicScatteringFactor { energy: 0.143_456_f64, f1: Some(18.522_f64), f2: Some(38.931_4_f64) },
AtomicScatteringFactor { energy: 0.145_776_f64, f1: Some(20.903_1_f64), f2: Some(34.805_6_f64) },
AtomicScatteringFactor { energy: 0.148_134_f64, f1: Some(21.981_3_f64), f2: Some(32.847_4_f64) },
AtomicScatteringFactor { energy: 0.150_53_f64, f1: Some(23.175_6_f64), f2: Some(31.134_4_f64) },
AtomicScatteringFactor { energy: 0.152_964_f64, f1: Some(24.221_3_f64), f2: Some(29.510_8_f64) },
AtomicScatteringFactor { energy: 0.155_439_f64, f1: Some(25.085_7_f64), f2: Some(27.971_8_f64) },
AtomicScatteringFactor { energy: 0.157_953_f64, f1: Some(25.776_7_f64), f2: Some(26.513_1_f64) },
AtomicScatteringFactor { energy: 0.160_507_f64, f1: Some(26.305_5_f64), f2: Some(25.130_5_f64) },
AtomicScatteringFactor { energy: 0.163_103_f64, f1: Some(26.670_7_f64), f2: Some(23.819_9_f64) },
AtomicScatteringFactor { energy: 0.165_742_f64, f1: Some(26.750_6_f64), f2: Some(22.675_9_f64) },
AtomicScatteringFactor { energy: 0.168_422_f64, f1: Some(26.892_4_f64), f2: Some(21.789_2_f64) },
AtomicScatteringFactor { energy: 0.171_146_f64, f1: Some(27.075_8_f64), f2: Some(20.937_3_f64) },
AtomicScatteringFactor { energy: 0.173_915_f64, f1: Some(27.227_2_f64), f2: Some(20.118_6_f64) },
AtomicScatteringFactor { energy: 0.176_727_f64, f1: Some(27.337_8_f64), f2: Some(19.332_f64) },
AtomicScatteringFactor { energy: 0.179_586_f64, f1: Some(27.398_6_f64), f2: Some(18.576_1_f64) },
AtomicScatteringFactor { energy: 0.182_491_f64, f1: Some(27.376_7_f64), f2: Some(17.849_8_f64) },
AtomicScatteringFactor { energy: 0.185_442_f64, f1: Some(27.286_f64), f2: Some(17.256_f64) },
AtomicScatteringFactor { energy: 0.188_442_f64, f1: Some(27.247_5_f64), f2: Some(16.748_f64) },
AtomicScatteringFactor { energy: 0.191_489_f64, f1: Some(27.223_7_f64), f2: Some(16.255_f64) },
AtomicScatteringFactor { energy: 0.194_587_f64, f1: Some(27.194_f64), f2: Some(15.776_5_f64) },
AtomicScatteringFactor { energy: 0.197_734_f64, f1: Some(27.149_1_f64), f2: Some(15.312_f64) },
AtomicScatteringFactor { energy: 0.200_932_f64, f1: Some(27.080_9_f64), f2: Some(14.861_3_f64) },
AtomicScatteringFactor { energy: 0.204_182_f64, f1: Some(26.975_8_f64), f2: Some(14.423_8_f64) },
AtomicScatteringFactor { energy: 0.207_485_f64, f1: Some(26.770_4_f64), f2: Some(14.058_1_f64) },
AtomicScatteringFactor { energy: 0.210_84_f64, f1: Some(26.623_4_f64), f2: Some(13.799_1_f64) },
AtomicScatteringFactor { energy: 0.214_251_f64, f1: Some(26.521_8_f64), f2: Some(13.545_f64) },
AtomicScatteringFactor { energy: 0.217_716_f64, f1: Some(26.423_3_f64), f2: Some(13.295_5_f64) },
AtomicScatteringFactor { energy: 0.221_237_f64, f1: Some(26.317_1_f64), f2: Some(13.050_6_f64) },
AtomicScatteringFactor { energy: 0.224_816_f64, f1: Some(26.187_3_f64), f2: Some(12.810_2_f64) },
AtomicScatteringFactor { energy: 0.228_452_f64, f1: Some(25.958_1_f64), f2: Some(12.636_3_f64) },
AtomicScatteringFactor { energy: 0.232_147_f64, f1: Some(25.806_f64), f2: Some(12.577_3_f64) },
AtomicScatteringFactor { energy: 0.235_902_f64, f1: Some(25.721_8_f64), f2: Some(12.518_6_f64) },
AtomicScatteringFactor { energy: 0.239_717_f64, f1: Some(25.660_7_f64), f2: Some(12.460_2_f64) },
AtomicScatteringFactor { energy: 0.243_595_f64, f1: Some(25.615_9_f64), f2: Some(12.402_f64) },
AtomicScatteringFactor { energy: 0.247_535_f64, f1: Some(25.582_2_f64), f2: Some(12.344_1_f64) },
AtomicScatteringFactor { energy: 0.251_538_f64, f1: Some(25.555_8_f64), f2: Some(12.286_5_f64) },
AtomicScatteringFactor { energy: 0.255_607_f64, f1: Some(25.532_9_f64), f2: Some(12.229_2_f64) },
AtomicScatteringFactor { energy: 0.259_741_f64, f1: Some(25.508_5_f64), f2: Some(12.172_1_f64) },
AtomicScatteringFactor { energy: 0.263_942_f64, f1: Some(25.466_8_f64), f2: Some(12.122_8_f64) },
AtomicScatteringFactor { energy: 0.268_211_f64, f1: Some(25.441_7_f64), f2: Some(12.110_3_f64) },
AtomicScatteringFactor { energy: 0.272_549_f64, f1: Some(25.432_3_f64), f2: Some(12.097_7_f64) },
AtomicScatteringFactor { energy: 0.276_957_f64, f1: Some(25.431_8_f64), f2: Some(12.085_2_f64) },
AtomicScatteringFactor { energy: 0.281_437_f64, f1: Some(25.435_6_f64), f2: Some(12.072_6_f64) },
AtomicScatteringFactor { energy: 0.285_989_f64, f1: Some(25.440_6_f64), f2: Some(12.060_1_f64) },
AtomicScatteringFactor { energy: 0.290_615_f64, f1: Some(25.443_4_f64), f2: Some(12.047_6_f64) },
AtomicScatteringFactor { energy: 0.295_315_f64, f1: Some(25.437_7_f64), f2: Some(12.035_1_f64) },
AtomicScatteringFactor { energy: 0.300_092_f64, f1: Some(25.402_2_f64), f2: Some(12.022_6_f64) },
AtomicScatteringFactor { energy: 0.304_945_f64, f1: Some(25.356_5_f64), f2: Some(12.090_3_f64) },
AtomicScatteringFactor { energy: 0.309_878_f64, f1: Some(25.353_f64), f2: Some(12.184_5_f64) },
AtomicScatteringFactor { energy: 0.314_89_f64, f1: Some(25.385_7_f64), f2: Some(12.279_4_f64) },
AtomicScatteringFactor { energy: 0.319_983_f64, f1: Some(25.437_9_f64), f2: Some(12.375_f64) },
AtomicScatteringFactor { energy: 0.325_158_f64, f1: Some(25.507_4_f64), f2: Some(12.471_4_f64) },
AtomicScatteringFactor { energy: 0.330_418_f64, f1: Some(25.593_6_f64), f2: Some(12.568_6_f64) },
AtomicScatteringFactor { energy: 0.335_762_f64, f1: Some(25.697_4_f64), f2: Some(12.666_5_f64) },
AtomicScatteringFactor { energy: 0.341_192_f64, f1: Some(25.825_9_f64), f2: Some(12.765_1_f64) },
AtomicScatteringFactor { energy: 0.346_711_f64, f1: Some(25.974_4_f64), f2: Some(12.835_3_f64) },
AtomicScatteringFactor { energy: 0.352_319_f64, f1: Some(26.116_9_f64), f2: Some(12.893_8_f64) },
AtomicScatteringFactor { energy: 0.358_017_f64, f1: Some(26.262_5_f64), f2: Some(12.959_2_f64) },
AtomicScatteringFactor { energy: 0.363_808_f64, f1: Some(26.420_5_f64), f2: Some(13.025_f64) },
AtomicScatteringFactor { energy: 0.369_692_f64, f1: Some(26.602_1_f64), f2: Some(13.091_1_f64) },
AtomicScatteringFactor { energy: 0.375_672_f64, f1: Some(26.805_3_f64), f2: Some(13.131_7_f64) },
AtomicScatteringFactor { energy: 0.381_748_f64, f1: Some(27.002_8_f64), f2: Some(13.152_4_f64) },
AtomicScatteringFactor { energy: 0.387_922_f64, f1: Some(27.204_5_f64), f2: Some(13.173_1_f64) },
AtomicScatteringFactor { energy: 0.394_197_f64, f1: Some(27.460_2_f64), f2: Some(13.193_8_f64) },
AtomicScatteringFactor { energy: 0.400_573_f64, f1: Some(27.701_7_f64), f2: Some(13.109_5_f64) },
AtomicScatteringFactor { energy: 0.407_052_f64, f1: Some(27.895_4_f64), f2: Some(13.020_6_f64) },
AtomicScatteringFactor { energy: 0.413_635_f64, f1: Some(28.066_5_f64), f2: Some(12.932_2_f64) },
AtomicScatteringFactor { energy: 0.420_326_f64, f1: Some(28.222_7_f64), f2: Some(12.844_4_f64) },
AtomicScatteringFactor { energy: 0.427_124_f64, f1: Some(28.367_f64), f2: Some(12.757_3_f64) },
AtomicScatteringFactor { energy: 0.434_032_f64, f1: Some(28.501_3_f64), f2: Some(12.670_7_f64) },
AtomicScatteringFactor { energy: 0.441_052_f64, f1: Some(28.626_6_f64), f2: Some(12.584_7_f64) },
AtomicScatteringFactor { energy: 0.448_186_f64, f1: Some(28.741_4_f64), f2: Some(12.499_3_f64) },
AtomicScatteringFactor { energy: 0.455_435_f64, f1: Some(28.845_1_f64), f2: Some(12.420_4_f64) },
AtomicScatteringFactor { energy: 0.462_802_f64, f1: Some(28.949_f64), f2: Some(12.350_1_f64) },
AtomicScatteringFactor { energy: 0.470_287_f64, f1: Some(29.052_f64), f2: Some(12.280_1_f64) },
AtomicScatteringFactor { energy: 0.477_894_f64, f1: Some(29.152_6_f64), f2: Some(12.210_6_f64) },
AtomicScatteringFactor { energy: 0.485_623_f64, f1: Some(29.250_5_f64), f2: Some(12.141_5_f64) },
AtomicScatteringFactor { energy: 0.493_478_f64, f1: Some(29.345_7_f64), f2: Some(12.072_8_f64) },
AtomicScatteringFactor { energy: 0.501_459_f64, f1: Some(29.438_4_f64), f2: Some(12.004_5_f64) },
AtomicScatteringFactor { energy: 0.509_57_f64, f1: Some(29.528_8_f64), f2: Some(11.936_5_f64) },
AtomicScatteringFactor { energy: 0.517_812_f64, f1: Some(29.617_2_f64), f2: Some(11.869_f64) },
AtomicScatteringFactor { energy: 0.526_187_f64, f1: Some(29.704_8_f64), f2: Some(11.801_8_f64) },
AtomicScatteringFactor { energy: 0.534_698_f64, f1: Some(29.794_5_f64), f2: Some(11.735_f64) },
AtomicScatteringFactor { energy: 0.543_346_f64, f1: Some(29.885_8_f64), f2: Some(11.657_3_f64) },
AtomicScatteringFactor { energy: 0.552_134_f64, f1: Some(29.970_5_f64), f2: Some(11.573_5_f64) },
AtomicScatteringFactor { energy: 0.561_065_f64, f1: Some(30.047_1_f64), f2: Some(11.482_5_f64) },
AtomicScatteringFactor { energy: 0.570_139_f64, f1: Some(30.112_4_f64), f2: Some(11.388_6_f64) },
AtomicScatteringFactor { energy: 0.579_361_f64, f1: Some(30.168_1_f64), f2: Some(11.296_9_f64) },
AtomicScatteringFactor { energy: 0.588_732_f64, f1: Some(30.216_9_f64), f2: Some(11.206_3_f64) },
AtomicScatteringFactor { energy: 0.598_254_f64, f1: Some(30.259_8_f64), f2: Some(11.116_9_f64) },
AtomicScatteringFactor { energy: 0.607_93_f64, f1: Some(30.297_f64), f2: Some(11.028_2_f64) },
AtomicScatteringFactor { energy: 0.617_763_f64, f1: Some(30.329_4_f64), f2: Some(10.940_2_f64) },
AtomicScatteringFactor { energy: 0.627_755_f64, f1: Some(30.359_7_f64), f2: Some(10.852_3_f64) },
AtomicScatteringFactor { energy: 0.637_908_f64, f1: Some(30.386_3_f64), f2: Some(10.757_6_f64) },
AtomicScatteringFactor { energy: 0.648_226_f64, f1: Some(30.404_4_f64), f2: Some(10.652_9_f64) },
AtomicScatteringFactor { energy: 0.658_711_f64, f1: Some(30.403_5_f64), f2: Some(10.542_2_f64) },
AtomicScatteringFactor { energy: 0.669_365_f64, f1: Some(30.382_7_f64), f2: Some(10.432_7_f64) },
AtomicScatteringFactor { energy: 0.680_191_f64, f1: Some(30.344_f64), f2: Some(10.34_f64) },
AtomicScatteringFactor { energy: 0.691_193_f64, f1: Some(30.304_4_f64), f2: Some(10.260_1_f64) },
AtomicScatteringFactor { energy: 0.702_372_f64, f1: Some(30.274_1_f64), f2: Some(10.182_7_f64) },
AtomicScatteringFactor { energy: 0.713_733_f64, f1: Some(30.241_4_f64), f2: Some(10.089_1_f64) },
AtomicScatteringFactor { energy: 0.725_277_f64, f1: Some(30.188_4_f64), f2: Some(9.984_84_f64) },
AtomicScatteringFactor { energy: 0.737_008_f64, f1: Some(30.117_7_f64), f2: Some(9.881_52_f64) },
AtomicScatteringFactor { energy: 0.748_928_f64, f1: Some(30.031_6_f64), f2: Some(9.779_31_f64) },
AtomicScatteringFactor { energy: 0.761_042_f64, f1: Some(29.931_f64), f2: Some(9.678_02_f64) },
AtomicScatteringFactor { energy: 0.773_351_f64, f1: Some(29.816_6_f64), f2: Some(9.575_98_f64) },
AtomicScatteringFactor { energy: 0.785_859_f64, f1: Some(29.685_4_f64), f2: Some(9.468_62_f64) },
AtomicScatteringFactor { energy: 0.798_57_f64, f1: Some(29.529_f64), f2: Some(9.357_22_f64) },
AtomicScatteringFactor { energy: 0.811_486_f64, f1: Some(29.347_6_f64), f2: Some(9.247_38_f64) },
AtomicScatteringFactor { energy: 0.824_611_f64, f1: Some(29.140_6_f64), f2: Some(9.138_67_f64) },
AtomicScatteringFactor { energy: 0.837_949_f64, f1: Some(28.906_4_f64), f2: Some(9.031_11_f64) },
AtomicScatteringFactor { energy: 0.851_502_f64, f1: Some(28.641_7_f64), f2: Some(8.922_77_f64) },
AtomicScatteringFactor { energy: 0.865_274_f64, f1: Some(28.341_9_f64), f2: Some(8.813_22_f64) },
AtomicScatteringFactor { energy: 0.879_269_f64, f1: Some(27.999_4_f64), f2: Some(8.702_79_f64) },
AtomicScatteringFactor { energy: 0.893_491_f64, f1: Some(27.609_2_f64), f2: Some(8.593_72_f64) },
AtomicScatteringFactor { energy: 0.907_943_f64, f1: Some(27.164_2_f64), f2: Some(8.486_04_f64) },
AtomicScatteringFactor { energy: 0.922_628_f64, f1: Some(26.656_4_f64), f2: Some(8.379_75_f64) },
AtomicScatteringFactor { energy: 0.937_551_f64, f1: Some(26.069_6_f64), f2: Some(8.269_18_f64) },
AtomicScatteringFactor { energy: 0.952_715_f64, f1: Some(25.384_3_f64), f2: Some(8.158_48_f64) },
AtomicScatteringFactor { energy: 0.968_124_f64, f1: Some(24.573_5_f64), f2: Some(8.047_87_f64) },
AtomicScatteringFactor { energy: 0.983_783_f64, f1: Some(23.600_9_f64), f2: Some(7.939_03_f64) },
AtomicScatteringFactor { energy: 0.999_695_f64, f1: Some(22.408_9_f64), f2: Some(7.831_12_f64) },
AtomicScatteringFactor { energy: 1.015_86_f64, f1: Some(20.900_3_f64), f2: Some(7.724_09_f64) },
AtomicScatteringFactor { energy: 1.032_29_f64, f1: Some(18.889_5_f64), f2: Some(7.613_93_f64) },
AtomicScatteringFactor { energy: 1.048_99_f64, f1: Some(15.965_f64), f2: Some(7.504_11_f64) },
AtomicScatteringFactor { energy: 1.065_96_f64, f1: Some(10.826_5_f64), f2: Some(7.394_6_f64) },
AtomicScatteringFactor { energy: 1.083_2_f64, f1: Some(-23.692_6_f64), f2: Some(7.286_68_f64) },
AtomicScatteringFactor { energy: 1.083_3_f64, f1: Some(-29.095_3_f64), f2: Some(7.286_06_f64) },
AtomicScatteringFactor { energy: 1.083_5_f64, f1: Some(-29.092_8_f64), f2: Some(31.644_5_f64) },
AtomicScatteringFactor { energy: 1.100_72_f64, f1: Some(10.960_4_f64), f2: Some(31.627_6_f64) },
AtomicScatteringFactor { energy: 1.118_52_f64, f1: Some(16.582_7_f64), f2: Some(31.610_4_f64) },
AtomicScatteringFactor { energy: 1.136_61_f64, f1: Some(19.963_8_f64), f2: Some(31.593_f64) },
AtomicScatteringFactor { energy: 1.155_f64, f1: Some(22.438_6_f64), f2: Some(31.575_7_f64) },
AtomicScatteringFactor { energy: 1.173_68_f64, f1: Some(24.422_5_f64), f2: Some(31.558_5_f64) },
AtomicScatteringFactor { energy: 1.192_66_f64, f1: Some(26.099_7_f64), f2: Some(31.541_f64) },
AtomicScatteringFactor { energy: 1.211_95_f64, f1: Some(27.568_3_f64), f2: Some(31.523_6_f64) },
AtomicScatteringFactor { energy: 1.231_55_f64, f1: Some(28.887_f64), f2: Some(31.506_3_f64) },
AtomicScatteringFactor { energy: 1.251_47_f64, f1: Some(30.094_1_f64), f2: Some(31.489_6_f64) },
AtomicScatteringFactor { energy: 1.271_72_f64, f1: Some(31.216_1_f64), f2: Some(31.473_2_f64) },
AtomicScatteringFactor { energy: 1.292_29_f64, f1: Some(32.272_5_f64), f2: Some(31.457_3_f64) },
AtomicScatteringFactor { energy: 1.313_19_f64, f1: Some(33.278_1_f64), f2: Some(31.441_6_f64) },
AtomicScatteringFactor { energy: 1.334_43_f64, f1: Some(34.244_5_f64), f2: Some(31.425_9_f64) },
AtomicScatteringFactor { energy: 1.356_01_f64, f1: Some(35.181_5_f64), f2: Some(31.41_f64) },
AtomicScatteringFactor { energy: 1.377_94_f64, f1: Some(36.098_1_f64), f2: Some(31.394_1_f64) },
AtomicScatteringFactor { energy: 1.400_23_f64, f1: Some(37.004_f64), f2: Some(31.378_3_f64) },
AtomicScatteringFactor { energy: 1.422_88_f64, f1: Some(37.911_1_f64), f2: Some(31.362_4_f64) },
AtomicScatteringFactor { energy: 1.445_89_f64, f1: Some(38.843_f64), f2: Some(31.346_9_f64) },
AtomicScatteringFactor { energy: 1.469_28_f64, f1: Some(39.846_f64), f2: Some(31.268_2_f64) },
AtomicScatteringFactor { energy: 1.493_04_f64, f1: Some(40.928_7_f64), f2: Some(31.093_5_f64) },
AtomicScatteringFactor { energy: 1.517_19_f64, f1: Some(41.622_9_f64), f2: Some(30.520_6_f64) },
AtomicScatteringFactor { energy: 1.541_73_f64, f1: Some(41.790_5_f64), f2: Some(30.389_f64) },
AtomicScatteringFactor { energy: 1.566_67_f64, f1: Some(43.012_5_f64), f2: Some(31.161_1_f64) },
AtomicScatteringFactor { energy: 1.592_01_f64, f1: Some(44.518_1_f64), f2: Some(30.688_3_f64) },
AtomicScatteringFactor { energy: 1.617_76_f64, f1: Some(45.495_8_f64), f2: Some(30.036_8_f64) },
AtomicScatteringFactor { energy: 1.643_92_f64, f1: Some(46.265_2_f64), f2: Some(29.399_1_f64) },
AtomicScatteringFactor { energy: 1.670_51_f64, f1: Some(46.754_3_f64), f2: Some(28.775_1_f64) },
AtomicScatteringFactor { energy: 1.697_53_f64, f1: Some(46.973_2_f64), f2: Some(28.452_8_f64) },
AtomicScatteringFactor { energy: 1.724_99_f64, f1: Some(47.810_2_f64), f2: Some(28.669_4_f64) },
AtomicScatteringFactor { energy: 1.752_89_f64, f1: Some(48.852_5_f64), f2: Some(28.218_8_f64) },
AtomicScatteringFactor { energy: 1.781_24_f64, f1: Some(49.612_9_f64), f2: Some(27.630_5_f64) },
AtomicScatteringFactor { energy: 1.810_05_f64, f1: Some(50.256_1_f64), f2: Some(27.051_6_f64) },
AtomicScatteringFactor { energy: 1.839_32_f64, f1: Some(50.826_8_f64), f2: Some(26.484_6_f64) },
AtomicScatteringFactor { energy: 1.869_07_f64, f1: Some(51.344_5_f64), f2: Some(25.929_3_f64) },
AtomicScatteringFactor { energy: 1.899_3_f64, f1: Some(51.819_1_f64), f2: Some(25.385_6_f64) },
AtomicScatteringFactor { energy: 1.930_02_f64, f1: Some(52.257_7_f64), f2: Some(24.853_6_f64) },
AtomicScatteringFactor { energy: 1.961_24_f64, f1: Some(52.665_1_f64), f2: Some(24.332_7_f64) },
AtomicScatteringFactor { energy: 1.992_96_f64, f1: Some(53.041_f64), f2: Some(23.822_6_f64) },
AtomicScatteringFactor { energy: 2.025_2_f64, f1: Some(53.409_f64), f2: Some(23.335_6_f64) },
AtomicScatteringFactor { energy: 2.057_95_f64, f1: Some(53.756_9_f64), f2: Some(22.833_4_f64) },
AtomicScatteringFactor { energy: 2.091_24_f64, f1: Some(54.074_1_f64), f2: Some(22.339_8_f64) },
AtomicScatteringFactor { energy: 2.125_06_f64, f1: Some(54.369_5_f64), f2: Some(21.854_9_f64) },
AtomicScatteringFactor { energy: 2.159_43_f64, f1: Some(54.644_4_f64), f2: Some(21.378_f64) },
AtomicScatteringFactor { energy: 2.194_36_f64, f1: Some(54.900_9_f64), f2: Some(20.910_2_f64) },
AtomicScatteringFactor { energy: 2.229_85_f64, f1: Some(55.139_7_f64), f2: Some(20.450_1_f64) },
AtomicScatteringFactor { energy: 2.265_92_f64, f1: Some(55.361_9_f64), f2: Some(19.999_f64) },
AtomicScatteringFactor { energy: 2.302_57_f64, f1: Some(55.569_2_f64), f2: Some(19.556_5_f64) },
AtomicScatteringFactor { energy: 2.339_81_f64, f1: Some(55.762_4_f64), f2: Some(19.122_1_f64) },
AtomicScatteringFactor { energy: 2.377_66_f64, f1: Some(55.941_8_f64), f2: Some(18.695_6_f64) },
AtomicScatteringFactor { energy: 2.416_11_f64, f1: Some(56.108_2_f64), f2: Some(18.277_4_f64) },
AtomicScatteringFactor { energy: 2.455_19_f64, f1: Some(56.262_4_f64), f2: Some(17.867_5_f64) },
AtomicScatteringFactor { energy: 2.494_9_f64, f1: Some(56.405_1_f64), f2: Some(17.465_5_f64) },
AtomicScatteringFactor { energy: 2.535_26_f64, f1: Some(56.537_f64), f2: Some(17.071_6_f64) },
AtomicScatteringFactor { energy: 2.576_26_f64, f1: Some(56.658_6_f64), f2: Some(16.685_6_f64) },
AtomicScatteringFactor { energy: 2.617_93_f64, f1: Some(56.770_3_f64), f2: Some(16.307_2_f64) },
AtomicScatteringFactor { energy: 2.660_27_f64, f1: Some(56.873_f64), f2: Some(15.936_7_f64) },
AtomicScatteringFactor { energy: 2.703_3_f64, f1: Some(56.966_4_f64), f2: Some(15.573_3_f64) },
AtomicScatteringFactor { energy: 2.747_03_f64, f1: Some(57.051_5_f64), f2: Some(15.218_f64) },
AtomicScatteringFactor { energy: 2.791_46_f64, f1: Some(57.128_6_f64), f2: Some(14.869_4_f64) },
AtomicScatteringFactor { energy: 2.836_61_f64, f1: Some(57.198_1_f64), f2: Some(14.528_7_f64) },
AtomicScatteringFactor { energy: 2.882_49_f64, f1: Some(57.259_9_f64), f2: Some(14.194_4_f64) },
AtomicScatteringFactor { energy: 2.929_11_f64, f1: Some(57.315_f64), f2: Some(13.868_1_f64) },
AtomicScatteringFactor { energy: 2.976_48_f64, f1: Some(57.363_8_f64), f2: Some(13.548_1_f64) },
AtomicScatteringFactor { energy: 3.024_63_f64, f1: Some(57.406_1_f64), f2: Some(13.234_9_f64) },
AtomicScatteringFactor { energy: 3.073_55_f64, f1: Some(57.442_f64), f2: Some(12.927_9_f64) },
AtomicScatteringFactor { energy: 3.123_26_f64, f1: Some(57.471_6_f64), f2: Some(12.627_9_f64) },
AtomicScatteringFactor { energy: 3.173_78_f64, f1: Some(57.496_f64), f2: Some(12.334_8_f64) },
AtomicScatteringFactor { energy: 3.225_11_f64, f1: Some(57.515_1_f64), f2: Some(12.047_6_f64) },
AtomicScatteringFactor { energy: 3.277_27_f64, f1: Some(57.528_8_f64), f2: Some(11.766_8_f64) },
AtomicScatteringFactor { energy: 3.330_28_f64, f1: Some(57.537_5_f64), f2: Some(11.492_f64) },
AtomicScatteringFactor { energy: 3.384_15_f64, f1: Some(57.541_4_f64), f2: Some(11.223_2_f64) },
AtomicScatteringFactor { energy: 3.438_88_f64, f1: Some(57.540_5_f64), f2: Some(10.960_3_f64) },
AtomicScatteringFactor { energy: 3.494_5_f64, f1: Some(57.535_f64), f2: Some(10.703_3_f64) },
AtomicScatteringFactor { energy: 3.551_02_f64, f1: Some(57.525_1_f64), f2: Some(10.451_9_f64) },
AtomicScatteringFactor { energy: 3.608_46_f64, f1: Some(57.510_8_f64), f2: Some(10.206_f64) },
AtomicScatteringFactor { energy: 3.666_82_f64, f1: Some(57.492_3_f64), f2: Some(9.965_65_f64) },
AtomicScatteringFactor { energy: 3.726_13_f64, f1: Some(57.469_6_f64), f2: Some(9.730_66_f64) },
AtomicScatteringFactor { energy: 3.786_4_f64, f1: Some(57.442_8_f64), f2: Some(9.500_83_f64) },
AtomicScatteringFactor { energy: 3.847_64_f64, f1: Some(57.411_9_f64), f2: Some(9.276_2_f64) },
AtomicScatteringFactor { energy: 3.909_87_f64, f1: Some(57.377_f64), f2: Some(9.056_59_f64) },
AtomicScatteringFactor { energy: 3.973_11_f64, f1: Some(57.338_f64), f2: Some(8.841_91_f64) },
AtomicScatteringFactor { energy: 4.037_38_f64, f1: Some(57.295_1_f64), f2: Some(8.632_1_f64) },
AtomicScatteringFactor { energy: 4.102_68_f64, f1: Some(57.248_2_f64), f2: Some(8.427_03_f64) },
AtomicScatteringFactor { energy: 4.169_03_f64, f1: Some(57.197_2_f64), f2: Some(8.226_42_f64) },
AtomicScatteringFactor { energy: 4.236_46_f64, f1: Some(57.142_f64), f2: Some(8.030_52_f64) },
AtomicScatteringFactor { energy: 4.304_98_f64, f1: Some(57.082_6_f64), f2: Some(7.838_91_f64) },
AtomicScatteringFactor { energy: 4.374_62_f64, f1: Some(57.018_8_f64), f2: Some(7.651_74_f64) },
AtomicScatteringFactor { energy: 4.445_37_f64, f1: Some(56.950_5_f64), f2: Some(7.468_77_f64) },
AtomicScatteringFactor { energy: 4.517_27_f64, f1: Some(56.877_4_f64), f2: Some(7.289_94_f64) },
AtomicScatteringFactor { energy: 4.590_33_f64, f1: Some(56.799_5_f64), f2: Some(7.115_27_f64) },
AtomicScatteringFactor { energy: 4.664_58_f64, f1: Some(56.716_4_f64), f2: Some(6.944_41_f64) },
AtomicScatteringFactor { energy: 4.740_03_f64, f1: Some(56.627_7_f64), f2: Some(6.777_52_f64) },
AtomicScatteringFactor { energy: 4.816_69_f64, f1: Some(56.533_1_f64), f2: Some(6.614_43_f64) },
AtomicScatteringFactor { energy: 4.894_6_f64, f1: Some(56.432_2_f64), f2: Some(6.454_99_f64) },
AtomicScatteringFactor { energy: 4.973_77_f64, f1: Some(56.324_4_f64), f2: Some(6.299_34_f64) },
AtomicScatteringFactor { energy: 5.054_21_f64, f1: Some(56.209_1_f64), f2: Some(6.147_16_f64) },
AtomicScatteringFactor { energy: 5.135_96_f64, f1: Some(56.085_4_f64), f2: Some(5.998_37_f64) },
AtomicScatteringFactor { energy: 5.219_03_f64, f1: Some(55.952_5_f64), f2: Some(5.853_03_f64) },
AtomicScatteringFactor { energy: 5.303_44_f64, f1: Some(55.809_2_f64), f2: Some(5.711_04_f64) },
AtomicScatteringFactor { energy: 5.389_22_f64, f1: Some(55.654_2_f64), f2: Some(5.572_32_f64) },
AtomicScatteringFactor { energy: 5.476_39_f64, f1: Some(55.485_8_f64), f2: Some(5.436_66_f64) },
AtomicScatteringFactor { energy: 5.564_97_f64, f1: Some(55.301_8_f64), f2: Some(5.304_22_f64) },
AtomicScatteringFactor { energy: 5.654_98_f64, f1: Some(55.099_6_f64), f2: Some(5.174_68_f64) },
AtomicScatteringFactor { energy: 5.746_44_f64, f1: Some(54.875_7_f64), f2: Some(5.048_28_f64) },
AtomicScatteringFactor { energy: 5.839_39_f64, f1: Some(54.625_5_f64), f2: Some(4.924_57_f64) },
AtomicScatteringFactor { energy: 5.933_83_f64, f1: Some(54.342_7_f64), f2: Some(4.803_78_f64) },
AtomicScatteringFactor { energy: 6.029_81_f64, f1: Some(54.018_4_f64), f2: Some(4.685_75_f64) },
AtomicScatteringFactor { energy: 6.127_33_f64, f1: Some(53.639_5_f64), f2: Some(4.570_18_f64) },
AtomicScatteringFactor { energy: 6.226_44_f64, f1: Some(53.185_2_f64), f2: Some(4.457_44_f64) },
AtomicScatteringFactor { energy: 6.327_15_f64, f1: Some(52.620_5_f64), f2: Some(4.347_28_f64) },
AtomicScatteringFactor { energy: 6.429_48_f64, f1: Some(51.876_8_f64), f2: Some(4.239_65_f64) },
AtomicScatteringFactor { energy: 6.533_48_f64, f1: Some(50.789_2_f64), f2: Some(4.134_39_f64) },
AtomicScatteringFactor { energy: 6.639_15_f64, f1: Some(48.728_5_f64), f2: Some(4.031_68_f64) },
AtomicScatteringFactor { energy: 6.716_1_f64, f1: Some(32.868_2_f64), f2: Some(3.959_5_f64) },
AtomicScatteringFactor { energy: 6.716_3_f64, f1: Some(32.869_3_f64), f2: Some(11.487_6_f64) },
AtomicScatteringFactor { energy: 6.746_54_f64, f1: Some(46.600_5_f64), f2: Some(11.389_f64) },
AtomicScatteringFactor { energy: 6.855_65_f64, f1: Some(50.196_4_f64), f2: Some(11.043_5_f64) },
AtomicScatteringFactor { energy: 6.966_54_f64, f1: Some(51.379_6_f64), f2: Some(10.708_3_f64) },
AtomicScatteringFactor { energy: 7.079_22_f64, f1: Some(51.865_5_f64), f2: Some(10.383_3_f64) },
AtomicScatteringFactor { energy: 7.193_72_f64, f1: Some(51.745_6_f64), f2: Some(10.068_1_f64) },
AtomicScatteringFactor { energy: 7.310_07_f64, f1: Some(47.229_6_f64), f2: Some(9.762_39_f64) },
AtomicScatteringFactor { energy: 7.311_7_f64, f1: Some(43.822_9_f64), f2: Some(9.758_23_f64) },
AtomicScatteringFactor { energy: 7.311_9_f64, f1: Some(43.824_2_f64), f2: Some(13.524_3_f64) },
AtomicScatteringFactor { energy: 7.428_31_f64, f1: Some(52.675_2_f64), f2: Some(13.128_1_f64) },
AtomicScatteringFactor { energy: 7.548_45_f64, f1: Some(53.694_5_f64), f2: Some(12.737_5_f64) },
AtomicScatteringFactor { energy: 7.670_54_f64, f1: Some(53.995_3_f64), f2: Some(12.358_4_f64) },
AtomicScatteringFactor { energy: 7.736_7_f64, f1: Some(50.867_6_f64), f2: Some(12.160_1_f64) },
AtomicScatteringFactor { energy: 7.736_9_f64, f1: Some(50.870_5_f64), f2: Some(13.921_7_f64) },
AtomicScatteringFactor { energy: 7.794_61_f64, f1: Some(54.529_4_f64), f2: Some(13.775_4_f64) },
AtomicScatteringFactor { energy: 7.920_68_f64, f1: Some(55.717_4_f64), f2: Some(13.464_6_f64) },
AtomicScatteringFactor { energy: 8.048_79_f64, f1: Some(56.484_3_f64), f2: Some(13.157_8_f64) },
AtomicScatteringFactor { energy: 8.178_98_f64, f1: Some(57.092_2_f64), f2: Some(12.855_8_f64) },
AtomicScatteringFactor { energy: 8.311_26_f64, f1: Some(57.604_6_f64), f2: Some(12.558_3_f64) },
AtomicScatteringFactor { energy: 8.445_69_f64, f1: Some(58.049_2_f64), f2: Some(12.265_4_f64) },
AtomicScatteringFactor { energy: 8.582_29_f64, f1: Some(58.441_3_f64), f2: Some(11.976_8_f64) },
AtomicScatteringFactor { energy: 8.721_11_f64, f1: Some(58.791_f64), f2: Some(11.693_1_f64) },
AtomicScatteringFactor { energy: 8.862_16_f64, f1: Some(59.105_6_f64), f2: Some(11.414_5_f64) },
AtomicScatteringFactor { energy: 9.005_5_f64, f1: Some(59.390_3_f64), f2: Some(11.140_5_f64) },
AtomicScatteringFactor { energy: 9.151_16_f64, f1: Some(59.648_6_f64), f2: Some(10.871_2_f64) },
AtomicScatteringFactor { energy: 9.299_17_f64, f1: Some(59.883_8_f64), f2: Some(10.606_9_f64) },
AtomicScatteringFactor { energy: 9.449_58_f64, f1: Some(60.098_8_f64), f2: Some(10.347_7_f64) },
AtomicScatteringFactor { energy: 9.602_42_f64, f1: Some(60.295_5_f64), f2: Some(10.093_3_f64) },
AtomicScatteringFactor { energy: 9.757_73_f64, f1: Some(60.475_7_f64), f2: Some(9.843_61_f64) },
AtomicScatteringFactor { energy: 9.915_55_f64, f1: Some(60.640_8_f64), f2: Some(9.599_12_f64) },
AtomicScatteringFactor { energy: 10.075_9_f64, f1: Some(60.792_5_f64), f2: Some(9.359_27_f64) },
AtomicScatteringFactor { energy: 10.238_9_f64, f1: Some(60.931_5_f64), f2: Some(9.124_26_f64) },
AtomicScatteringFactor { energy: 10.404_5_f64, f1: Some(61.058_9_f64), f2: Some(8.894_08_f64) },
AtomicScatteringFactor { energy: 10.572_8_f64, f1: Some(61.175_8_f64), f2: Some(8.668_66_f64) },
AtomicScatteringFactor { energy: 10.743_8_f64, f1: Some(61.282_9_f64), f2: Some(8.448_f64) },
AtomicScatteringFactor { energy: 10.917_6_f64, f1: Some(61.380_8_f64), f2: Some(8.232_04_f64) },
AtomicScatteringFactor { energy: 11.094_2_f64, f1: Some(61.470_4_f64), f2: Some(8.020_74_f64) },
AtomicScatteringFactor { energy: 11.273_6_f64, f1: Some(61.552_1_f64), f2: Some(7.814_05_f64) },
AtomicScatteringFactor { energy: 11.455_9_f64, f1: Some(61.626_4_f64), f2: Some(7.611_92_f64) },
AtomicScatteringFactor { energy: 11.641_2_f64, f1: Some(61.694_f64), f2: Some(7.414_29_f64) },
AtomicScatteringFactor { energy: 11.829_5_f64, f1: Some(61.755_2_f64), f2: Some(7.221_11_f64) },
AtomicScatteringFactor { energy: 12.020_8_f64, f1: Some(61.810_5_f64), f2: Some(7.032_31_f64) },
AtomicScatteringFactor { energy: 12.215_3_f64, f1: Some(61.860_3_f64), f2: Some(6.847_85_f64) },
AtomicScatteringFactor { energy: 12.412_8_f64, f1: Some(61.904_9_f64), f2: Some(6.667_65_f64) },
AtomicScatteringFactor { energy: 12.613_6_f64, f1: Some(61.944_6_f64), f2: Some(6.491_65_f64) },
AtomicScatteringFactor { energy: 12.817_6_f64, f1: Some(61.979_8_f64), f2: Some(6.319_79_f64) },
AtomicScatteringFactor { energy: 13.025_f64, f1: Some(62.010_7_f64), f2: Some(6.151_99_f64) },
AtomicScatteringFactor { energy: 13.235_6_f64, f1: Some(62.037_6_f64), f2: Some(5.988_2_f64) },
AtomicScatteringFactor { energy: 13.449_7_f64, f1: Some(62.060_8_f64), f2: Some(5.828_34_f64) },
AtomicScatteringFactor { energy: 13.667_2_f64, f1: Some(62.080_5_f64), f2: Some(5.672_35_f64) },
AtomicScatteringFactor { energy: 13.888_3_f64, f1: Some(62.096_9_f64), f2: Some(5.520_16_f64) },
AtomicScatteringFactor { energy: 14.112_9_f64, f1: Some(62.110_3_f64), f2: Some(5.371_69_f64) },
AtomicScatteringFactor { energy: 14.341_2_f64, f1: Some(62.120_8_f64), f2: Some(5.226_88_f64) },
AtomicScatteringFactor { energy: 14.573_1_f64, f1: Some(62.128_5_f64), f2: Some(5.085_66_f64) },
AtomicScatteringFactor { energy: 14.808_9_f64, f1: Some(62.133_8_f64), f2: Some(4.947_96_f64) },
AtomicScatteringFactor { energy: 15.048_4_f64, f1: Some(62.136_6_f64), f2: Some(4.813_71_f64) },
AtomicScatteringFactor { energy: 15.291_8_f64, f1: Some(62.137_3_f64), f2: Some(4.682_84_f64) },
AtomicScatteringFactor { energy: 15.539_1_f64, f1: Some(62.135_9_f64), f2: Some(4.555_28_f64) },
AtomicScatteringFactor { energy: 15.790_4_f64, f1: Some(62.132_5_f64), f2: Some(4.430_97_f64) },
AtomicScatteringFactor { energy: 16.045_8_f64, f1: Some(62.127_3_f64), f2: Some(4.309_84_f64) },
AtomicScatteringFactor { energy: 16.305_4_f64, f1: Some(62.120_4_f64), f2: Some(4.191_81_f64) },
AtomicScatteringFactor { energy: 16.569_1_f64, f1: Some(62.111_9_f64), f2: Some(4.076_83_f64) },
AtomicScatteringFactor { energy: 16.837_1_f64, f1: Some(62.102_f64), f2: Some(3.964_82_f64) },
AtomicScatteringFactor { energy: 17.109_4_f64, f1: Some(62.090_6_f64), f2: Some(3.855_73_f64) },
AtomicScatteringFactor { energy: 17.386_1_f64, f1: Some(62.078_f64), f2: Some(3.749_49_f64) },
AtomicScatteringFactor { energy: 17.667_4_f64, f1: Some(62.064_1_f64), f2: Some(3.646_02_f64) },
AtomicScatteringFactor { energy: 17.953_1_f64, f1: Some(62.049_1_f64), f2: Some(3.545_28_f64) },
AtomicScatteringFactor { energy: 18.243_5_f64, f1: Some(62.033_1_f64), f2: Some(3.447_2_f64) },
AtomicScatteringFactor { energy: 18.538_6_f64, f1: Some(62.016_1_f64), f2: Some(3.351_72_f64) },
AtomicScatteringFactor { energy: 18.838_4_f64, f1: Some(61.998_1_f64), f2: Some(3.258_77_f64) },
AtomicScatteringFactor { energy: 19.143_1_f64, f1: Some(61.979_4_f64), f2: Some(3.168_3_f64) },
AtomicScatteringFactor { energy: 19.452_7_f64, f1: Some(61.959_8_f64), f2: Some(3.080_25_f64) },
AtomicScatteringFactor { energy: 19.767_4_f64, f1: Some(61.939_4_f64), f2: Some(2.994_56_f64) },
AtomicScatteringFactor { energy: 20.087_1_f64, f1: Some(61.918_4_f64), f2: Some(2.911_18_f64) },
AtomicScatteringFactor { energy: 20.412_f64, f1: Some(61.896_8_f64), f2: Some(2.830_04_f64) },
AtomicScatteringFactor { energy: 20.742_1_f64, f1: Some(61.874_5_f64), f2: Some(2.751_1_f64) },
AtomicScatteringFactor { energy: 21.077_6_f64, f1: Some(61.851_7_f64), f2: Some(2.674_3_f64) },
AtomicScatteringFactor { energy: 21.418_5_f64, f1: Some(61.828_3_f64), f2: Some(2.599_6_f64) },
AtomicScatteringFactor { energy: 21.765_f64, f1: Some(61.804_5_f64), f2: Some(2.526_92_f64) },
AtomicScatteringFactor { energy: 22.117_f64, f1: Some(61.780_2_f64), f2: Some(2.456_24_f64) },
AtomicScatteringFactor { energy: 22.474_7_f64, f1: Some(61.755_5_f64), f2: Some(2.387_49_f64) },
AtomicScatteringFactor { energy: 22.838_2_f64, f1: Some(61.730_3_f64), f2: Some(2.320_63_f64) },
AtomicScatteringFactor { energy: 23.207_6_f64, f1: Some(61.704_8_f64), f2: Some(2.255_61_f64) },
AtomicScatteringFactor { energy: 23.583_f64, f1: Some(61.678_9_f64), f2: Some(2.192_38_f64) },
AtomicScatteringFactor { energy: 23.964_4_f64, f1: Some(61.652_6_f64), f2: Some(2.130_9_f64) },
AtomicScatteringFactor { energy: 24.352_f64, f1: Some(61.626_f64), f2: Some(2.071_12_f64) },
AtomicScatteringFactor { energy: 24.745_9_f64, f1: Some(61.599_f64), f2: Some(2.013_f64) },
AtomicScatteringFactor { energy: 25.146_2_f64, f1: Some(61.571_8_f64), f2: Some(1.956_5_f64) },
AtomicScatteringFactor { energy: 25.552_9_f64, f1: Some(61.544_1_f64), f2: Some(1.901_57_f64) },
AtomicScatteringFactor { energy: 25.966_2_f64, f1: Some(61.516_2_f64), f2: Some(1.848_17_f64) },
AtomicScatteringFactor { energy: 26.386_1_f64, f1: Some(61.487_9_f64), f2: Some(1.796_27_f64) },
AtomicScatteringFactor { energy: 26.812_9_f64, f1: Some(61.459_3_f64), f2: Some(1.745_82_f64) },
AtomicScatteringFactor { energy: 27.246_6_f64, f1: Some(61.430_4_f64), f2: Some(1.696_78_f64) },
AtomicScatteringFactor { energy: 27.687_3_f64, f1: Some(61.401_f64), f2: Some(1.649_12_f64) },
AtomicScatteringFactor { energy: 28.135_1_f64, f1: Some(61.371_3_f64), f2: Some(1.602_81_f64) },
AtomicScatteringFactor { energy: 28.590_2_f64, f1: Some(61.341_3_f64), f2: Some(1.557_79_f64) },
AtomicScatteringFactor { energy: 29.052_6_f64, f1: Some(61.311_1_f64), f2: Some(1.514_05_f64) },
AtomicScatteringFactor { energy: 29.522_5_f64, f1: Some(61.284_3_f64), f2: Some(1.471_54_f64) },
AtomicScatteringFactor { energy: 30.0_f64, f1: Some(61.235_6_f64), f2: Some(1.430_24_f64) },
]
}),
neutron_scattering: Some(NeutronScatteringFactor {
b_c: UncertainFloat::new(0.0_f64, 0.5_f64),
b_p: None,
b_m: None,
bound_coherent_scattering_xs: Some(UncertainFloat::new(0.422_f64, 0.009_f64)),
bound_incoherent_scattering_xs: Some(UncertainFloat::new(39.0_f64, 3.0_f64)),
total_bound_scattering_xs: Some(UncertainFloat::new(39.4_f64, 3.0_f64)),
absorption_xs: Some(UncertainFloat::new(5_922.0_f64, 56.0_f64)),
}),
isotopes: vec![
Isotope {
mass_number: 130,
mass: UncertainFloat::new(129.948_63_f64, 0.000_97_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 131,
mass: UncertainFloat::new(130.945_89_f64, 0.000_97_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 132,
mass: UncertainFloat::new(131.940_82_f64, 0.000_75_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 133,
mass: UncertainFloat::new(132.938_73_f64, 0.000_64_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 134,
mass: UncertainFloat::new(133.934_02_f64, 0.000_54_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 135,
mass: UncertainFloat::new(134.932_35_f64, 0.000_54_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 136,
mass: UncertainFloat::new(135.928_3_f64, 0.004_3_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 137,
mass: UncertainFloat::new(136.927_05_f64, 0.000_12_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 138,
mass: UncertainFloat::new(137.923_54_f64, 0.000_32_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 139,
mass: UncertainFloat::new(138.922_302_f64, 0.000_016_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 140,
mass: UncertainFloat::new(139.918_991_f64, 0.000_016_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 141,
mass: UncertainFloat::new(140.918_469_f64, 0.000_013_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 142,
mass: UncertainFloat::new(141.915_193_f64, 0.000_011_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 143,
mass: UncertainFloat::new(142.914_624_f64, 0.000_004_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 144,
mass: UncertainFloat::new(143.911_995_f64, 0.000_004_f64),
abundance: UncertainFloat::new(3.07_f64, 0.07_f64),
xray_scattering: None,
neutron_scattering: Some(NeutronScatteringFactor {
b_c: UncertainFloat::new(-3.0_f64, 4.0_f64),
b_p: None,
b_m: None,
bound_coherent_scattering_xs: Some(UncertainFloat::new(1.0_f64, 3.0_f64)),
bound_incoherent_scattering_xs: Some(UncertainFloat::new(0.0, 0.0)),
total_bound_scattering_xs: Some(UncertainFloat::new(1.0_f64, 3.0_f64)),
absorption_xs: Some(UncertainFloat::new(0.7_f64, 0.3_f64)),
}),
},
Isotope {
mass_number: 145,
mass: UncertainFloat::new(144.913_406_f64, 0.000_004_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 146,
mass: UncertainFloat::new(145.913_037_f64, 0.000_004_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 147,
mass: UncertainFloat::new(146.914_893_f64, 0.000_003_f64),
abundance: UncertainFloat::new(14.99_f64, 0.18_f64),
xray_scattering: None,
neutron_scattering: Some(NeutronScatteringFactor {
b_c: UncertainFloat::new(14.0_f64, 3.0_f64),
b_p: None,
b_m: None,
bound_coherent_scattering_xs: Some(UncertainFloat::new(25.0_f64, 11.0_f64)),
bound_incoherent_scattering_xs: Some(UncertainFloat::new(14.0_f64, 19.0_f64)),
total_bound_scattering_xs: Some(UncertainFloat::new(39.0_f64, 16.0_f64)),
absorption_xs: Some(UncertainFloat::new(57.0_f64, 3.0_f64)),
}),
},
Isotope {
mass_number: 148,
mass: UncertainFloat::new(147.914_818_f64, 0.000_003_f64),
abundance: UncertainFloat::new(11.24_f64, 0.10_f64),
xray_scattering: None,
neutron_scattering: Some(NeutronScatteringFactor {
b_c: UncertainFloat::new(-3.0_f64, 4.0_f64),
b_p: None,
b_m: None,
bound_coherent_scattering_xs: Some(UncertainFloat::new(1.0_f64, 3.0_f64)),
bound_incoherent_scattering_xs: Some(UncertainFloat::new(0.0, 0.0)),
total_bound_scattering_xs: Some(UncertainFloat::new(1.0_f64, 3.0_f64)),
absorption_xs: Some(UncertainFloat::new(2.4_f64, 0.6_f64)),
}),
},
Isotope {
mass_number: 149,
mass: UncertainFloat::new(148.917_18_f64, 0.000_03_f64),
abundance: UncertainFloat::new(13.82_f64, 0.07_f64),
xray_scattering: None,
neutron_scattering: Some(NeutronScatteringFactor {
b_c: UncertainFloat::new(18.7_f64, 0.28_f64),
b_p: None,
b_m: None,
bound_coherent_scattering_xs: Some(UncertainFloat::new(63.5_f64, 0.6_f64)),
bound_incoherent_scattering_xs: Some(UncertainFloat::new(137.0_f64, 5.0_f64)),
total_bound_scattering_xs: Some(UncertainFloat::new(200.0_f64, 5.0_f64)),
absorption_xs: Some(UncertainFloat::new(42_080.0_f64, 400.0_f64)),
}),
},
Isotope {
mass_number: 150,
mass: UncertainFloat::new(149.917_271_f64, 0.000_003_f64),
abundance: UncertainFloat::new(7.38_f64, 0.01_f64),
xray_scattering: None,
neutron_scattering: Some(NeutronScatteringFactor {
b_c: UncertainFloat::new(14.0_f64, 3.0_f64),
b_p: None,
b_m: None,
bound_coherent_scattering_xs: Some(UncertainFloat::new(25.0_f64, 11.0_f64)),
bound_incoherent_scattering_xs: Some(UncertainFloat::new(0.0, 0.0)),
total_bound_scattering_xs: Some(UncertainFloat::new(25.0_f64, 11.0_f64)),
absorption_xs: Some(UncertainFloat::new(104.0_f64, 4.0_f64)),
}),
},
Isotope {
mass_number: 151,
mass: UncertainFloat::new(150.919_928_f64, 0.000_003_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 152,
mass: UncertainFloat::new(151.919_728_f64, 0.000_003_f64),
abundance: UncertainFloat::new(26.75_f64, 0.16_f64),
xray_scattering: None,
neutron_scattering: Some(NeutronScatteringFactor {
b_c: UncertainFloat::new(-5.0_f64, 0.6_f64),
b_p: None,
b_m: None,
bound_coherent_scattering_xs: Some(UncertainFloat::new(3.1_f64, 0.8_f64)),
bound_incoherent_scattering_xs: Some(UncertainFloat::new(0.0, 0.0)),
total_bound_scattering_xs: Some(UncertainFloat::new(3.1_f64, 0.8_f64)),
absorption_xs: Some(UncertainFloat::new(206.0_f64, 6.0_f64)),
}),
},
Isotope {
mass_number: 153,
mass: UncertainFloat::new(152.922_094_f64, 0.000_003_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 154,
mass: UncertainFloat::new(153.922_205_f64, 0.000_003_f64),
abundance: UncertainFloat::new(22.75_f64, 0.29_f64),
xray_scattering: None,
neutron_scattering: Some(NeutronScatteringFactor {
b_c: UncertainFloat::new(8.0_f64, 1.0_f64),
b_p: None,
b_m: None,
bound_coherent_scattering_xs: Some(UncertainFloat::new(11.0_f64, 2.0_f64)),
bound_incoherent_scattering_xs: Some(UncertainFloat::new(0.0, 0.0)),
total_bound_scattering_xs: Some(UncertainFloat::new(11.0_f64, 2.0_f64)),
absorption_xs: Some(UncertainFloat::new(8.4_f64, 0.5_f64)),
}),
},
Isotope {
mass_number: 155,
mass: UncertainFloat::new(154.924_636_f64, 0.000_003_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 156,
mass: UncertainFloat::new(155.925_526_f64, 0.000_010_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 157,
mass: UncertainFloat::new(156.928_35_f64, 0.000_50_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 158,
mass: UncertainFloat::new(157.929_99_f64, 0.000_80_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 159,
mass: UncertainFloat::new(158.933_2_f64, 0.003_2_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 160,
mass: UncertainFloat::new(159.935_14_f64, 0.000_43_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 161,
mass: UncertainFloat::new(160.938_83_f64, 0.000_54_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 162,
mass: UncertainFloat::new(161.941_22_f64, 0.000_64_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 163,
mass: UncertainFloat::new(162.945_36_f64, 0.000_75_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 164,
mass: UncertainFloat::new(163.948_28_f64, 0.000_86_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
Isotope {
mass_number: 165,
mass: UncertainFloat::new(164.952_98_f64, 0.000_97_f64),
abundance: UncertainFloat::new(0.0, 0.0),
xray_scattering: None,
neutron_scattering: None
},
]
}
}
| 85.059172 | 115 | 0.617976 |
e60eaf873d400bd7f3e0e06a9e09e898fa92e66a | 3,828 | //! Checks if the process is running, kills a runnig process if it is.
use crate::{config::Config, errors::AtomicServerResult};
/// Checks if the server is running. If it is, kill that process. Also creates creates a new PID.
pub fn terminate_existing_processes(config: &Config) -> AtomicServerResult<()> {
let pid_maybe = match std::fs::read_to_string(pid_path(config)) {
Ok(content) => str::parse::<i32>(&content).ok(),
Err(_e) => None,
};
if let Some(pid) = pid_maybe {
use sysinfo::{ProcessExt, SystemExt};
let mut s = sysinfo::System::new_all();
let retry_secs = 1;
let mut tries_left = 30;
// either friendly (Terminate) or not friendly (Kill)
let mut signal = sysinfo::Signal::Term;
if let Some(process) = s.process(pid) {
tracing::warn!(
"Terminating existing running instance of atomic-server (process ID: {})...",
process.pid()
);
process.kill(sysinfo::Signal::Term);
tracing::info!("Checking if other server has succesfully terminated...",);
loop {
s.refresh_processes();
if let Some(_process) = s.process(pid) {
if tries_left > 1 {
tries_left -= 1;
tracing::info!(
"Other instance is still running, checking again in {} seconds, for {} more times ",
retry_secs,
tries_left
);
std::thread::sleep(std::time::Duration::from_secs(retry_secs));
} else {
if signal == sysinfo::Signal::Kill {
tracing::error!("Could not terminate other atomic-server, exiting...");
std::process::exit(1);
}
tracing::warn!(
"Terminate signal did not work, let's try again with Kill...",
);
_process.kill(sysinfo::Signal::Kill);
tries_left = 15;
signal = sysinfo::Signal::Kill;
}
continue;
};
tracing::info!("No other atomic-server is running, continuing start-up",);
break;
}
}
}
create_pid(config)
}
/// Removes the process id file in the config directory meant for signaling this instance is running.
pub fn remove_pid(config: &Config) -> AtomicServerResult<()> {
if std::fs::remove_file(pid_path(config)).is_err() {
tracing::warn!(
"Could not remove process file at {}",
pid_path(config).to_str().unwrap()
)
} else {
tracing::info!(
"Removed process file at {}",
pid_path(config).to_str().unwrap()
);
}
Ok(())
}
const PID_NAME: &str = "atomic_server_process_id";
fn pid_path(config: &Config) -> std::path::PathBuf {
std::path::Path::join(&config.config_dir, PID_NAME)
}
/// Writes a `pid` file in the config directory to signal which instance is running.
fn create_pid(config: &Config) -> AtomicServerResult<()> {
use std::io::Write;
let pid = sysinfo::get_current_pid()
.map_err(|_| "Failed to get process info required to create process ID")?;
let mut pid_file = std::fs::File::create(pid_path(config)).map_err(|e| {
format!(
"Could not create process file at {}. {}",
pid_path(config).to_str().unwrap(),
e
)
})?;
pid_file
.write_all(pid.to_string().as_bytes())
.map_err(|e| format!("failed to write process file. {}", e))?;
Ok(())
}
| 39.463918 | 112 | 0.522205 |
38f76eb54774b451b35352635ae0dce9bad6172a | 6,235 | use super::subscriber::*;
use super::pubsub_core::*;
use super::message_publisher::*;
use futures::future::{BoxFuture};
use std::sync::*;
use std::collections::{HashMap, VecDeque};
///
/// An 'expiring' publisher is one that responds to backpressure from its subscribers by
/// expiring the most recent message.
///
/// Usually when a subscriber stalls in processing, a publisher will refuse to accept
/// further messages and block. This will avoid blocking by instead expiring messages
/// that cannot be processed.
///
/// This is useful in a few situations. One important example is distributing state: say
/// you want to indicate to another thread what your current state is, but if it's busy
/// you don't want to wait for it to consume the previous state before you can finish
/// updating the latest state.
///
/// Another example is signalling. An ExpiringPublisher<()> can be used to signal that an
/// event has occurred but will not block if all subscribers have not responded in the
/// case where the event occurs multiple times.
///
pub struct ExpiringPublisher<Message> {
/// The shared core of this publisher
core: Arc<Mutex<PubCore<Message>>>
}
impl<Message: Clone> ExpiringPublisher<Message> {
///
/// Creates a new expiring publisher with a particular buffer size
///
/// Once a subscriber has buffer_size messages, this publisher will start to drop the
/// oldest messages.
///
pub fn new(buffer_size: usize) -> ExpiringPublisher<Message> {
// Create the core
let core = PubCore {
next_subscriber_id: 0,
publisher_count: 1,
subscribers: HashMap::new(),
notify_closed: HashMap::new(),
waiting: vec![],
max_queue_size: buffer_size
};
// Build the publisher itself
ExpiringPublisher {
core: Arc::new(Mutex::new(core))
}
}
///
/// Counts the number of subscribers in this publisher
///
pub fn count_subscribers(&self) -> usize {
self.core.lock().unwrap().subscribers.len()
}
///
/// Creates a duplicate publisher that can be used to publish to the same streams as this object
///
pub fn republish(&self) -> Self {
self.core.lock().unwrap().publisher_count += 1;
ExpiringPublisher {
core: Arc::clone(&self.core)
}
}
}
impl<Message: 'static+Send+Clone> MessagePublisher for ExpiringPublisher<Message> {
type Message = Message;
///
/// Subscribes to this publisher
///
/// Subscribers only receive messages sent to the publisher after they are created.
///
fn subscribe(&mut self) -> Subscriber<Message> {
// Assign a subscriber ID
let subscriber_id = {
let mut core = self.core.lock().unwrap();
let id = core.next_subscriber_id;
core.next_subscriber_id += 1;
id
};
// Create the subscriber core
let sub_core = SubCore {
id: subscriber_id,
published: true,
waiting: VecDeque::new(),
reserved: 0,
notify_waiting: vec![],
notify_ready: vec![],
notify_complete: vec![]
};
// The new subscriber needs a reference to the sub_core and the pub_core
let sub_core = Arc::new(Mutex::new(sub_core));
let pub_core = Arc::downgrade(&self.core);
// Register the subscriber with the core, so it will start receiving messages
{
let mut core = self.core.lock().unwrap();
core.subscribers.insert(subscriber_id, Arc::clone(&sub_core));
}
// Create the subscriber
Subscriber::new(pub_core, sub_core)
}
///
/// Reserves a space for a message with the subscribers, returning when it's ready
///
fn when_ready(&mut self) -> BoxFuture<'static, MessageSender<Message>> {
let when_ready = PubCore::send_all_expiring_oldest(&self.core);
Box::pin(when_ready)
}
///
/// Waits until all subscribers have consumed all pending messages
///
fn when_empty(&mut self) -> BoxFuture<'static, ()> {
let when_empty = PubCore::when_empty(&self.core);
Box::pin(when_empty)
}
///
/// Returns true if this publisher is closed (will not publish any further messages to its subscribers)
///
fn is_closed(&self) -> bool { false }
///
/// Future that returns when this publisher is closed
///
fn when_closed(&self) -> BoxFuture<'static, ()> {
Box::pin(CoreClosedFuture::new(Arc::clone(&self.core)))
}
}
impl<Message> Drop for ExpiringPublisher<Message> {
fn drop(&mut self) {
let to_notify = {
// Lock the core
let mut pub_core = self.core.lock().unwrap();
// Check that this is the last publisher on this core
pub_core.publisher_count -= 1;
if pub_core.publisher_count == 0 {
// Mark all the subscribers as unpublished and notify them so that they close
let mut to_notify = pub_core.notify_closed.drain()
.map(|(_id, waker)| waker)
.collect::<Vec<_>>();
for subscriber in pub_core.subscribers.values() {
let mut subscriber = subscriber.lock().unwrap();
// Unpublish the subscriber (so that it hits the end of the stream)
subscriber.published = false;
subscriber.notify_ready = vec![];
// Add to the things to notify once the lock is released
to_notify.extend(subscriber.notify_waiting.drain(..));
}
// Return the notifications outside of the lock
to_notify
} else {
// This is not the last core
vec![]
}
};
// Notify any subscribers that are waiting that we're unpublished
to_notify.into_iter().for_each(|notify| notify.wake());
}
}
| 33.521505 | 107 | 0.58765 |
098db8729cb40079ffbed592d76bc1e7439fcf96 | 14,120 | use crate::contact_info::ContactInfo;
use bincode::{serialize, serialized_size};
use solana_sdk::{
clock::Slot,
hash::Hash,
pubkey::Pubkey,
signature::{Keypair, Signable, Signature},
transaction::Transaction,
};
use std::{
borrow::{Borrow, Cow},
collections::{BTreeSet, HashSet},
fmt,
};
pub type VoteIndex = u8;
pub const MAX_VOTES: VoteIndex = 32;
pub type EpochSlotIndex = u8;
/// CrdsValue that is replicated across the cluster
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct CrdsValue {
pub signature: Signature,
pub data: CrdsData,
}
impl Signable for CrdsValue {
fn pubkey(&self) -> Pubkey {
self.pubkey()
}
fn signable_data(&self) -> Cow<[u8]> {
Cow::Owned(serialize(&self.data).expect("failed to serialize CrdsData"))
}
fn get_signature(&self) -> Signature {
self.signature
}
fn set_signature(&mut self, signature: Signature) {
self.signature = signature
}
fn verify(&self) -> bool {
let sig_check = self
.get_signature()
.verify(&self.pubkey().as_ref(), self.signable_data().borrow());
let data_check = match &self.data {
CrdsData::Vote(ix, _) => *ix < MAX_VOTES,
_ => true,
};
sig_check && data_check
}
}
/// CrdsData that defines the different types of items CrdsValues can hold
/// * Merge Strategy - Latest wallclock is picked
#[allow(clippy::large_enum_variant)]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum CrdsData {
ContactInfo(ContactInfo),
Vote(VoteIndex, Vote),
EpochSlots(EpochSlotIndex, EpochSlots),
SnapshotHash(SnapshotHash),
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum CompressionType {
Uncompressed,
GZip,
BZip2,
}
impl Default for CompressionType {
fn default() -> Self {
Self::Uncompressed
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub struct EpochIncompleteSlots {
pub first: Slot,
pub compression: CompressionType,
pub compressed_list: Vec<u8>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct SnapshotHash {
pub from: Pubkey,
pub hashes: Vec<(Slot, Hash)>,
pub wallclock: u64,
}
impl SnapshotHash {
pub fn new(from: Pubkey, hashes: Vec<(Slot, Hash)>, wallclock: u64) -> Self {
Self {
from,
hashes,
wallclock,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct EpochSlots {
pub from: Pubkey,
pub root: Slot,
pub lowest: Slot,
pub slots: BTreeSet<Slot>,
pub stash: Vec<EpochIncompleteSlots>,
pub wallclock: u64,
}
impl EpochSlots {
pub fn new(
from: Pubkey,
root: Slot,
lowest: Slot,
slots: BTreeSet<Slot>,
stash: Vec<EpochIncompleteSlots>,
wallclock: u64,
) -> Self {
Self {
from,
root,
lowest,
slots,
stash,
wallclock,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Vote {
pub from: Pubkey,
pub transaction: Transaction,
pub wallclock: u64,
}
impl Vote {
pub fn new(from: &Pubkey, transaction: Transaction, wallclock: u64) -> Self {
Self {
from: *from,
transaction,
wallclock,
}
}
}
/// Type of the replicated value
/// These are labels for values in a record that is associated with `Pubkey`
#[derive(PartialEq, Hash, Eq, Clone, Debug)]
pub enum CrdsValueLabel {
ContactInfo(Pubkey),
Vote(VoteIndex, Pubkey),
EpochSlots(Pubkey),
SnapshotHash(Pubkey),
}
impl fmt::Display for CrdsValueLabel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CrdsValueLabel::ContactInfo(_) => write!(f, "ContactInfo({})", self.pubkey()),
CrdsValueLabel::Vote(ix, _) => write!(f, "Vote({}, {})", ix, self.pubkey()),
CrdsValueLabel::EpochSlots(_) => write!(f, "EpochSlots({})", self.pubkey()),
CrdsValueLabel::SnapshotHash(_) => write!(f, "SnapshotHash({})", self.pubkey()),
}
}
}
impl CrdsValueLabel {
pub fn pubkey(&self) -> Pubkey {
match self {
CrdsValueLabel::ContactInfo(p) => *p,
CrdsValueLabel::Vote(_, p) => *p,
CrdsValueLabel::EpochSlots(p) => *p,
CrdsValueLabel::SnapshotHash(p) => *p,
}
}
}
impl CrdsValue {
pub fn new_unsigned(data: CrdsData) -> Self {
Self {
signature: Signature::default(),
data,
}
}
pub fn new_signed(data: CrdsData, keypair: &Keypair) -> Self {
let mut value = Self::new_unsigned(data);
value.sign(keypair);
value
}
/// Totally unsecure unverfiable wallclock of the node that generated this message
/// Latest wallclock is always picked.
/// This is used to time out push messages.
pub fn wallclock(&self) -> u64 {
match &self.data {
CrdsData::ContactInfo(contact_info) => contact_info.wallclock,
CrdsData::Vote(_, vote) => vote.wallclock,
CrdsData::EpochSlots(_, vote) => vote.wallclock,
CrdsData::SnapshotHash(hash) => hash.wallclock,
}
}
pub fn pubkey(&self) -> Pubkey {
match &self.data {
CrdsData::ContactInfo(contact_info) => contact_info.id,
CrdsData::Vote(_, vote) => vote.from,
CrdsData::EpochSlots(_, slots) => slots.from,
CrdsData::SnapshotHash(hash) => hash.from,
}
}
pub fn label(&self) -> CrdsValueLabel {
match &self.data {
CrdsData::ContactInfo(_) => CrdsValueLabel::ContactInfo(self.pubkey()),
CrdsData::Vote(ix, _) => CrdsValueLabel::Vote(*ix, self.pubkey()),
CrdsData::EpochSlots(_, _) => CrdsValueLabel::EpochSlots(self.pubkey()),
CrdsData::SnapshotHash(_) => CrdsValueLabel::SnapshotHash(self.pubkey()),
}
}
pub fn contact_info(&self) -> Option<&ContactInfo> {
match &self.data {
CrdsData::ContactInfo(contact_info) => Some(contact_info),
_ => None,
}
}
pub fn vote(&self) -> Option<&Vote> {
match &self.data {
CrdsData::Vote(_, vote) => Some(vote),
_ => None,
}
}
pub fn vote_index(&self) -> Option<VoteIndex> {
match &self.data {
CrdsData::Vote(ix, _) => Some(*ix),
_ => None,
}
}
pub fn epoch_slots(&self) -> Option<&EpochSlots> {
match &self.data {
CrdsData::EpochSlots(_, slots) => Some(slots),
_ => None,
}
}
pub fn snapshot_hash(&self) -> Option<&SnapshotHash> {
match &self.data {
CrdsData::SnapshotHash(slots) => Some(slots),
_ => None,
}
}
/// Return all the possible labels for a record identified by Pubkey.
pub fn record_labels(key: &Pubkey) -> Vec<CrdsValueLabel> {
let mut labels = vec![
CrdsValueLabel::ContactInfo(*key),
CrdsValueLabel::EpochSlots(*key),
CrdsValueLabel::SnapshotHash(*key),
];
labels.extend((0..MAX_VOTES).map(|ix| CrdsValueLabel::Vote(ix, *key)));
labels
}
/// Returns the size (in bytes) of a CrdsValue
pub fn size(&self) -> u64 {
serialized_size(&self).expect("unable to serialize contact info")
}
pub fn compute_vote_index(tower_index: usize, mut votes: Vec<&CrdsValue>) -> VoteIndex {
let mut available: HashSet<VoteIndex> = (0..MAX_VOTES).collect();
votes.iter().filter_map(|v| v.vote_index()).for_each(|ix| {
available.remove(&ix);
});
// free index
if !available.is_empty() {
return *available.iter().next().unwrap();
}
assert!(votes.len() == MAX_VOTES as usize);
votes.sort_by_key(|v| v.vote().expect("all values must be votes").wallclock);
// If Tower is full, oldest removed first
if tower_index + 1 == MAX_VOTES as usize {
return votes[0].vote_index().expect("all values must be votes");
}
// If Tower is not full, the early votes have expired
assert!(tower_index < MAX_VOTES as usize);
votes[tower_index]
.vote_index()
.expect("all values must be votes")
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::contact_info::ContactInfo;
use bincode::deserialize;
use solana_perf::test_tx::test_tx;
use solana_sdk::signature::{Keypair, Signer};
use solana_sdk::timing::timestamp;
#[test]
fn test_labels() {
let mut hits = [false; 3 + MAX_VOTES as usize];
// this method should cover all the possible labels
for v in &CrdsValue::record_labels(&Pubkey::default()) {
match v {
CrdsValueLabel::ContactInfo(_) => hits[0] = true,
CrdsValueLabel::EpochSlots(_) => hits[1] = true,
CrdsValueLabel::SnapshotHash(_) => hits[2] = true,
CrdsValueLabel::Vote(ix, _) => hits[*ix as usize + 3] = true,
}
}
assert!(hits.iter().all(|x| *x));
}
#[test]
fn test_keys_and_values() {
let v = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo::default()));
assert_eq!(v.wallclock(), 0);
let key = v.clone().contact_info().unwrap().id;
assert_eq!(v.label(), CrdsValueLabel::ContactInfo(key));
let v = CrdsValue::new_unsigned(CrdsData::Vote(
0,
Vote::new(&Pubkey::default(), test_tx(), 0),
));
assert_eq!(v.wallclock(), 0);
let key = v.clone().vote().unwrap().from;
assert_eq!(v.label(), CrdsValueLabel::Vote(0, key));
let v = CrdsValue::new_unsigned(CrdsData::EpochSlots(
0,
EpochSlots::new(Pubkey::default(), 0, 0, BTreeSet::new(), vec![], 0),
));
assert_eq!(v.wallclock(), 0);
let key = v.clone().epoch_slots().unwrap().from;
assert_eq!(v.label(), CrdsValueLabel::EpochSlots(key));
}
#[test]
fn test_signature() {
let keypair = Keypair::new();
let wrong_keypair = Keypair::new();
let mut v = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo::new_localhost(
&keypair.pubkey(),
timestamp(),
)));
verify_signatures(&mut v, &keypair, &wrong_keypair);
v = CrdsValue::new_unsigned(CrdsData::Vote(
0,
Vote::new(&keypair.pubkey(), test_tx(), timestamp()),
));
verify_signatures(&mut v, &keypair, &wrong_keypair);
let btreeset: BTreeSet<Slot> = vec![1, 2, 3, 6, 8].into_iter().collect();
v = CrdsValue::new_unsigned(CrdsData::EpochSlots(
0,
EpochSlots::new(keypair.pubkey(), 0, 0, btreeset, vec![], timestamp()),
));
verify_signatures(&mut v, &keypair, &wrong_keypair);
}
#[test]
fn test_max_vote_index() {
let keypair = Keypair::new();
let vote = CrdsValue::new_signed(
CrdsData::Vote(
MAX_VOTES,
Vote::new(&keypair.pubkey(), test_tx(), timestamp()),
),
&keypair,
);
assert!(!vote.verify());
}
#[test]
fn test_compute_vote_index_empty() {
for i in 0..MAX_VOTES {
let votes = vec![];
assert!(CrdsValue::compute_vote_index(i as usize, votes) < MAX_VOTES);
}
}
#[test]
fn test_compute_vote_index_one() {
let keypair = Keypair::new();
let vote = CrdsValue::new_unsigned(CrdsData::Vote(
0,
Vote::new(&keypair.pubkey(), test_tx(), 0),
));
for i in 0..MAX_VOTES {
let votes = vec![&vote];
assert!(CrdsValue::compute_vote_index(i as usize, votes) > 0);
let votes = vec![&vote];
assert!(CrdsValue::compute_vote_index(i as usize, votes) < MAX_VOTES);
}
}
#[test]
fn test_compute_vote_index_full() {
let keypair = Keypair::new();
let votes: Vec<_> = (0..MAX_VOTES)
.map(|x| {
CrdsValue::new_unsigned(CrdsData::Vote(
x,
Vote::new(&keypair.pubkey(), test_tx(), x as u64),
))
})
.collect();
let vote_refs = votes.iter().collect();
//pick the oldest vote when full
assert_eq!(CrdsValue::compute_vote_index(31, vote_refs), 0);
//pick the index
let vote_refs = votes.iter().collect();
assert_eq!(CrdsValue::compute_vote_index(0, vote_refs), 0);
let vote_refs = votes.iter().collect();
assert_eq!(CrdsValue::compute_vote_index(30, vote_refs), 30);
}
fn serialize_deserialize_value(value: &mut CrdsValue, keypair: &Keypair) {
let num_tries = 10;
value.sign(keypair);
let original_signature = value.get_signature();
for _ in 0..num_tries {
let serialized_value = serialize(value).unwrap();
let deserialized_value: CrdsValue = deserialize(&serialized_value).unwrap();
// Signatures shouldn't change
let deserialized_signature = deserialized_value.get_signature();
assert_eq!(original_signature, deserialized_signature);
// After deserializing, check that the signature is still the same
assert!(deserialized_value.verify());
}
}
fn verify_signatures(
value: &mut CrdsValue,
correct_keypair: &Keypair,
wrong_keypair: &Keypair,
) {
assert!(!value.verify());
value.sign(&correct_keypair);
assert!(value.verify());
value.sign(&wrong_keypair);
assert!(!value.verify());
serialize_deserialize_value(value, correct_keypair);
}
}
| 30.829694 | 93 | 0.573654 |
1d8eb3b3731344c8fa5f90e72c17af497c271dec | 4,951 | use std::borrow::Cow;
use std::convert::TryFrom;
#[cfg(feature = "sender")]
use crate::sender;
pub struct Uri<'a> {
pub(crate) address: bitcoin::Address,
pub(crate) amount: bitcoin::Amount,
pub(crate) endpoint: Cow<'a, str>,
pub(crate) disable_output_substitution: bool,
}
impl<'a> Uri<'a> {
pub fn address(&self) -> &bitcoin::Address {
&self.address
}
pub fn amount(&self) -> bitcoin::Amount {
self.amount
}
pub fn is_output_substitution_disabled(&self) -> bool {
self.disable_output_substitution
}
#[cfg(feature = "sender")]
pub fn create_request(self, psbt: bitcoin::util::psbt::PartiallySignedTransaction, params: sender::Params) -> Result<(sender::Request, sender::Context), sender::CreateRequestError> {
sender::from_psbt_and_uri(psbt, self, params)
}
pub fn into_static(self) -> Uri<'static> {
Uri {
address: self.address,
amount: self.amount,
endpoint: Cow::Owned(self.endpoint.into()),
disable_output_substitution: self.disable_output_substitution,
}
}
}
impl<'a> TryFrom<&'a str> for Uri<'a> {
type Error = ParseUriError;
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
fn match_kv<'a, T, E: Into<ParseUriError>, F: FnOnce(&'a str) -> Result<T, E>>(kv: &'a str, prefix: &'static str, out: &mut Option<T>, fun: F) -> Result<(), ParseUriError> where ParseUriError: From<E> {
if kv.starts_with(prefix) {
let value = fun(&kv[prefix.len()..])?;
if out.is_some() {
return Err(InternalBip21Error::DuplicateKey(prefix).into());
}
*out = Some(value);
}
Ok(())
}
let prefix = "bitcoin:";
if !s.chars().zip(prefix.chars()).all(|(left, right)| left.to_ascii_lowercase() == right) {
return Err(InternalBip21Error::BadSchema(s.into()).into())
}
let uri_without_prefix = &s[prefix.len()..];
let question_mark_pos = uri_without_prefix.find('?').ok_or(ParseUriError::PjNotPresent)?;
let address = uri_without_prefix[..question_mark_pos].parse().map_err(InternalBip21Error::Address)?;
let mut amount = None;
let mut endpoint = None;
let mut disable_pjos = None;
for kv in uri_without_prefix[(question_mark_pos + 1)..].split('&') {
match_kv(kv, "amount=", &mut amount, |s| bitcoin::Amount::from_str_in(s, bitcoin::Denomination::Bitcoin).map_err(InternalBip21Error::Amount))?;
match_kv(kv, "pjos=", &mut disable_pjos, |s| if s == "0" { Ok(true) } else if s == "1" { Ok(false) } else { Err(InternalPjParseError::BadPjos(s.into())) })?;
match_kv(kv, "pj=", &mut endpoint, |s| if s.starts_with("https://") || s.starts_with("http://") { Ok(s) } else { Err(InternalPjParseError::BadSchema(s.into())) })?;
}
match (amount, endpoint, disable_pjos) {
(_, None, None) => Err(ParseUriError::PjNotPresent),
(Some(amount), Some(endpoint), disable_pjos) => Ok(Uri { address, amount, endpoint: endpoint.into(), disable_output_substitution: disable_pjos.unwrap_or(false), }),
(None, Some(_), _) => Err(ParseUriError::PayJoin(PjParseError(InternalPjParseError::MissingAmount))),
(None, None, Some(_)) => Err(ParseUriError::PayJoin(PjParseError(InternalPjParseError::MissingAmountAndEndpoint))),
(Some(_), None, Some(_)) => Err(ParseUriError::PayJoin(PjParseError(InternalPjParseError::MissingEndpoint))),
}
}
}
impl std::str::FromStr for Uri<'static> {
type Err = ParseUriError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Uri::try_from(s).map(Uri::into_static)
}
}
#[derive(Debug)]
pub enum ParseUriError {
PjNotPresent,
Bip21(Bip21Error),
PayJoin(PjParseError),
}
#[derive(Debug)]
pub struct Bip21Error(InternalBip21Error);
#[derive(Debug)]
pub struct PjParseError(InternalPjParseError);
#[derive(Debug)]
enum InternalBip21Error {
Amount(bitcoin::util::amount::ParseAmountError),
DuplicateKey(&'static str),
BadSchema(String),
Address(bitcoin::util::address::Error),
}
#[derive(Debug)]
enum InternalPjParseError {
BadPjos(String),
BadSchema(String),
MissingAmount,
MissingAmountAndEndpoint,
MissingEndpoint,
}
impl From<Bip21Error> for ParseUriError {
fn from(value: Bip21Error) -> Self {
ParseUriError::Bip21(value)
}
}
impl From<PjParseError> for ParseUriError {
fn from(value: PjParseError) -> Self {
ParseUriError::PayJoin(value)
}
}
impl From<InternalBip21Error> for ParseUriError {
fn from(value: InternalBip21Error) -> Self {
Bip21Error(value).into()
}
}
impl From<InternalPjParseError> for ParseUriError {
fn from(value: InternalPjParseError) -> Self {
PjParseError(value).into()
}
}
| 34.381944 | 210 | 0.62654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.