hexsha
stringlengths
40
40
size
int64
2
1.05M
content
stringlengths
2
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
146123b14b9fb358008d1ec85f6c0f14c944faa3
106
//! All HTTP handlers dealing with the assignments. pub mod edit; pub mod file; pub mod get; pub mod new;
17.666667
51
0.735849
9cedf86f35056aaed7b313a2fe03b9a6575bb651
771
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::uint; struct dog { food: uint, } impl dog { pub fn chase_cat(&mut self) { let _f = || { let p: &'static mut uint = &mut self.food; //~ ERROR cannot infer an appropriate lifetime due to conflicting requirements *p = 3u; }; } } fn main() { }
27.535714
133
0.661479
6254eb7c41eb487da9b76e587ac52241f9b8daf0
2,968
use ra_syntax::{ ast::{self, AstNode, AttrsOwner}, SyntaxKind::{COMMENT, WHITESPACE}, TextSize, }; use crate::{Assist, AssistCtx, AssistId}; // Assist: add_derive // // Adds a new `#[derive()]` clause to a struct or enum. // // ``` // struct Point { // x: u32, // y: u32,<|> // } // ``` // -> // ``` // #[derive()] // struct Point { // x: u32, // y: u32, // } // ``` pub(crate) fn add_derive(ctx: AssistCtx) -> Option<Assist> { let nominal = ctx.find_node_at_offset::<ast::NominalDef>()?; let node_start = derive_insertion_offset(&nominal)?; ctx.add_assist(AssistId("add_derive"), "Add `#[derive]`", |edit| { let derive_attr = nominal .attrs() .filter_map(|x| x.as_simple_call()) .filter(|(name, _arg)| name == "derive") .map(|(_name, arg)| arg) .next(); let offset = match derive_attr { None => { edit.insert(node_start, "#[derive()]\n"); node_start + TextSize::of("#[derive(") } Some(tt) => tt.syntax().text_range().end() - TextSize::of(')'), }; edit.target(nominal.syntax().text_range()); edit.set_cursor(offset) }) } // Insert `derive` after doc comments. fn derive_insertion_offset(nominal: &ast::NominalDef) -> Option<TextSize> { let non_ws_child = nominal .syntax() .children_with_tokens() .find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?; Some(non_ws_child.text_range().start()) } #[cfg(test)] mod tests { use super::*; use crate::helpers::{check_assist, check_assist_target}; #[test] fn add_derive_new() { check_assist( add_derive, "struct Foo { a: i32, <|>}", "#[derive(<|>)]\nstruct Foo { a: i32, }", ); check_assist( add_derive, "struct Foo { <|> a: i32, }", "#[derive(<|>)]\nstruct Foo { a: i32, }", ); } #[test] fn add_derive_existing() { check_assist( add_derive, "#[derive(Clone)]\nstruct Foo { a: i32<|>, }", "#[derive(Clone<|>)]\nstruct Foo { a: i32, }", ); } #[test] fn add_derive_new_with_doc_comment() { check_assist( add_derive, " /// `Foo` is a pretty important struct. /// It does stuff. struct Foo { a: i32<|>, } ", " /// `Foo` is a pretty important struct. /// It does stuff. #[derive(<|>)] struct Foo { a: i32, } ", ); } #[test] fn add_derive_target() { check_assist_target( add_derive, " struct SomeThingIrrelevant; /// `Foo` is a pretty important struct. /// It does stuff. struct Foo { a: i32<|>, } struct EvenMoreIrrelevant; ", "/// `Foo` is a pretty important struct. /// It does stuff. struct Foo { a: i32, }", ); } }
24.528926
75
0.507412
91d96adb0eb5d46c23445f7695096b38b503d490
3,714
use alloc::vec::Vec; use core::time::Duration; /// Erase plan of (opcode, size, base address, typical duration) to erase a range of memory. #[derive(Clone, Debug)] pub(crate) struct ErasePlan(pub Vec<(u8, usize, u32, Option<Duration>)>); impl ErasePlan { pub fn new(insts: &[(usize, u8, Option<Duration>)], start: usize, length: usize) -> Self { log::trace!("Creating erase plan, start={} length={}", start, length); let mut plan = Vec::new(); // Sort instructions by smallest area of effect first. let mut insts = insts.to_vec(); insts.sort(); // We compute the number of useful bytes erased for each operation, // then from those with the same maximum number of useful bytes erased, // we select the smallest operation, and repeat until all bytes are erased. let end = start + length; let mut pos = start; while pos < end { log::trace!("Evaluating candidates, pos={} end={}", pos, end); // Current candidate, (bytes, size, opcode, base). let mut candidate = (0, usize::MAX, 0, 0, None); for (erase_size, opcode, duration) in insts.iter() { let erase_base = pos - (pos % erase_size); let erase_end = erase_base + erase_size - 1; let mut bytes = erase_size - (pos - erase_base); if erase_end > end { bytes -= erase_end - end + 1; } log::trace!( " Candidate 0x{:02X} ({} bytes): base={} end={} bytes={}", opcode, erase_size, erase_base, erase_end, bytes ); if bytes > candidate.0 || (bytes == candidate.0 && *erase_size < candidate.1) { candidate = (bytes, *erase_size, *opcode, erase_base, *duration); } } log::trace!("Candidate selected: {:?}", candidate); pos += candidate.0; plan.push((candidate.2, candidate.1, candidate.3 as u32, candidate.4)); } log::debug!("Erase plan: {:?}", plan); ErasePlan(plan) } #[cfg(feature = "std")] pub fn total_size(&self) -> usize { self.0.iter().map(|x| x.1).sum() } } #[test] fn test_erase_plan() { let insts = &[(4, 1, None), (32, 2, None), (64, 3, None)]; // Use a single 4kB erase to erase an aligned 4kB block. assert_eq!(ErasePlan::new(insts, 0, 4).0, alloc::vec![(1, 4, 0, None)]); // Use a single 64kB erase to erase an aligned 64kB block. assert_eq!( ErasePlan::new(insts, 0, 64).0, alloc::vec![(3, 64, 0, None)] ); // Use three 64kB erases to erase an aligned 192kB block. assert_eq!( ErasePlan::new(insts, 0, 192).0, alloc::vec![(3, 64, 0, None), (3, 64, 64, None), (3, 64, 128, None)] ); // Use 64kB followed by 32kB to erase an aligned 70kB block. assert_eq!( ErasePlan::new(insts, 0, 70).0, alloc::vec![(3, 64, 0, None), (2, 32, 64, None)] ); // Use 64kB followed by 4kB to erase an aligned 66kB block. assert_eq!( ErasePlan::new(insts, 0, 66).0, alloc::vec![(3, 64, 0, None), (1, 4, 64, None)] ); // Use 4kB followed by 64kB to erase a misaligned 64kB block. assert_eq!( ErasePlan::new(insts, 62, 64).0, alloc::vec![(1, 4, 60, None), (3, 64, 64, None)] ); // Use a 4kB, 64kB, 4kB to erase a misaligned 68kB block. assert_eq!( ErasePlan::new(insts, 62, 68).0, alloc::vec![(1, 4, 60, None), (3, 64, 64, None), (1, 4, 128, None)] ); }
37.897959
95
0.530964
7932f114204d9150fb92f8c1254c971354d13baa
1,887
use iron::error::HttpError; use iron::Listening; use iron::prelude::*; use persistent::State; use router::Router; use provider::Provider; use routes; use utils; use types::ProviderState; pub fn start_server<T>(prov: Box<T>) -> Result<Listening, HttpError> where T: Provider + 'static + Send + Sync, { // create a chain with a route map let mut chain = Chain::new(setup_route_map::<T>()); let provider_state = ProviderState { prov }; // this object manages thread-safe access to the shared provider state let safe_provider_state = State::<ProviderState<T>>::one(provider_state); // add a "before" middleware for injecting our provider state chain.link_before(safe_provider_state); // start the web server let port = utils::get_env_integral("PORT", Ok(3000u16)); Iron::new(chain).http(format!("0.0.0.0:{}", port)) } fn setup_route_map<T>() -> Router where T: Provider + 'static + Send + Sync, { router!( index: get "/" => routes::default, create_pod: post "/createPod" => routes::create_pod::<T>, update_pod: put "/updatePod" => routes::update_pod::<T>, delete_pod: delete "/deletePod" => routes::delete_pod::<T>, get_pod: get "/getPod" => routes::get_pod::<T>, get_container_logs: get "/getContainerLogs" => routes::get_container_logs::<T>, get_pod_status: get "/getPodStatus" => routes::get_pod_status::<T>, get_pods: get "/getPods" => routes::get_pods::<T>, capacity: get "/capacity" => routes::capacity::<T>, node_conditions: get "/nodeConditions" => routes::node_conditions::<T>, node_addresses: get "/nodeAddresses" => routes::node_addresses::<T>, node_daemon_endpoints: get "/nodeDaemonEndpoints" => routes::node_daemon_endpoints::<T>, operating_system: get "/operatingSystem" => routes::operating_system::<T>, ) }
36.288462
96
0.657658
089dbc9084a454f09248d3f229e1366099f95a85
2,094
//! Utility module for converting between hir_def ids and code_model wrappers. //! //! It's unclear if we need this long-term, but it's definitelly useful while we //! are splitting the hir. use hir_def::{AdtId, EnumVariantId, ModuleDefId}; use crate::{Adt, EnumVariant, ModuleDef}; macro_rules! from_id { ($(($id:path, $ty:path)),*) => {$( impl From<$id> for $ty { fn from(id: $id) -> $ty { $ty { id } } } )*} } from_id![ (hir_def::ModuleId, crate::Module), (hir_def::StructId, crate::Struct), (hir_def::UnionId, crate::Union), (hir_def::EnumId, crate::Enum), (hir_def::TypeAliasId, crate::TypeAlias), (hir_def::TraitId, crate::Trait), (hir_def::StaticId, crate::Static), (hir_def::ConstId, crate::Const), (hir_def::FunctionId, crate::Function), (hir_expand::MacroDefId, crate::MacroDef) ]; impl From<AdtId> for Adt { fn from(id: AdtId) -> Self { match id { AdtId::StructId(it) => Adt::Struct(it.into()), AdtId::UnionId(it) => Adt::Union(it.into()), AdtId::EnumId(it) => Adt::Enum(it.into()), } } } impl From<EnumVariantId> for EnumVariant { fn from(id: EnumVariantId) -> Self { EnumVariant { parent: id.parent.into(), id: id.local_id } } } impl From<ModuleDefId> for ModuleDef { fn from(id: ModuleDefId) -> Self { match id { ModuleDefId::ModuleId(it) => ModuleDef::Module(it.into()), ModuleDefId::FunctionId(it) => ModuleDef::Function(it.into()), ModuleDefId::AdtId(it) => ModuleDef::Adt(it.into()), ModuleDefId::EnumVariantId(it) => ModuleDef::EnumVariant(it.into()), ModuleDefId::ConstId(it) => ModuleDef::Const(it.into()), ModuleDefId::StaticId(it) => ModuleDef::Static(it.into()), ModuleDefId::TraitId(it) => ModuleDef::Trait(it.into()), ModuleDefId::TypeAliasId(it) => ModuleDef::TypeAlias(it.into()), ModuleDefId::BuiltinType(it) => ModuleDef::BuiltinType(it), } } }
32.71875
80
0.586437
716b0bbe77294deed07ef1166d3f0cb5aa80bf3c
1,061
// Copyright 2016 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. macro_rules! log { ( $ctx:expr, $( $args:expr),* ) => { if $ctx.trace { //~^ no field `trace` on type `&T` println!( $( $args, )* ); } } } // Create a structure. struct Foo { trace: bool, } // Generic wrapper calls log! with a structure. fn wrap<T>(context: &T) -> () { log!(context, "entered wrapper"); //~^ in this expansion of log! } fn main() { // Create a structure. let x = Foo { trace: true }; log!(x, "run started"); // Apply a closure which accesses internal fields. wrap(&x); log!(x, "run finished"); }
26.525
68
0.62017
71c32dafa676f47a5f612dc2c842d7f50d24cdff
812
/* * * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://openapi-generator.tech */ /// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum LolChatLeagueTier { #[serde(rename = "NONE")] NONE, #[serde(rename = "IRON")] IRON, #[serde(rename = "BRONZE")] BRONZE, #[serde(rename = "SILVER")] SILVER, #[serde(rename = "GOLD")] GOLD, #[serde(rename = "PLATINUM")] PLATINUM, #[serde(rename = "DIAMOND")] DIAMOND, #[serde(rename = "MASTER")] MASTER, #[serde(rename = "GRANDMASTER")] GRANDMASTER, #[serde(rename = "CHALLENGER")] CHALLENGER, }
19.804878
109
0.607143
cc094aeef02f3b82815a981b903cd9af4bcc5d43
5,116
// Copyright 2018-2019 Joe Neeman. // // 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. // // See the LICENSE-APACHE or LICENSE-MIT files at the top-level directory // of this distribution. // Allow missing docs in this module, for now, because we need to think more about the types of // errors we're exposing. #![allow(missing_docs)] use serde_yaml; use std::ffi::OsString; use std::path::PathBuf; use std::{self, fmt, io}; use crate::{NodeId, PatchId}; #[derive(Debug)] pub enum PatchIdError { Base64Decode(base64::DecodeError), InvalidLength(usize), Collision(crate::PatchId), } impl From<base64::DecodeError> for PatchIdError { fn from(e: base64::DecodeError) -> PatchIdError { PatchIdError::Base64Decode(e) } } impl fmt::Display for PatchIdError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::PatchIdError::*; match self { Base64Decode(e) => e.fmt(f), InvalidLength(n) => write!(f, "Found the wrong number of bytes: {}", n), Collision(p) => write!( f, "Encountered a collision between patch hashes: {}", p.to_base64() ), } } } impl std::error::Error for PatchIdError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { use self::PatchIdError::*; match self { Base64Decode(e) => Some(e), _ => None, } } } #[derive(Debug)] pub enum Error { BranchExists(String), CurrentBranch(String), DbCorruption, Encoding(std::string::FromUtf8Error), IdMismatch(PatchId, PatchId), Io(io::Error, String), MissingDep(PatchId), NoFilename(PathBuf), NoParent(PathBuf), NonUtfFilename(OsString), NotOrdered, PatchId(PatchIdError), RepoExists(PathBuf), RepoNotFound(PathBuf), Serde(serde_yaml::Error), UnknownBranch(String), UnknownNode(NodeId), UnknownPatch(PatchId), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::BranchExists(b) => write!(f, "The branch \"{}\" already exists", b), Error::CurrentBranch(b) => write!(f, "\"{}\" is the current branch", b), Error::DbCorruption => write!(f, "Found corruption in the database"), Error::Encoding(e) => e.fmt(f), Error::IdMismatch(actual, expected) => write!( f, "Expected {}, found {}", expected.to_base64(), actual.to_base64() ), Error::Io(e, msg) => write!(f, "I/O error: {}. Details: {}", msg, e), Error::MissingDep(id) => write!(f, "Missing a dependency: {}", id.to_base64()), Error::NoFilename(p) => write!(f, "This path didn't end in a filename: {:?}", p), Error::NoParent(p) => write!(f, "I could not find the parent directory of: {:?}", p), Error::NonUtfFilename(p) => { write!(f, "This filename couldn't be converted to UTF-8: {:?}", p) } Error::NotOrdered => write!(f, "The data does not represent a totally ordered file"), Error::PatchId(e) => write!(f, "Found a broken PatchId\n\tcaused by: {}", e), Error::RepoExists(p) => write!(f, "There is already a repository in {:?}", p), Error::RepoNotFound(p) => write!( f, "I could not find a repository tracking this path: {:?}", p ), Error::Serde(e) => e.fmt(f), Error::UnknownBranch(b) => write!(f, "There is no branch named {:?}", b), Error::UnknownNode(n) => write!(f, "There is no node with id {:?}", n), Error::UnknownPatch(p) => write!(f, "There is no patch with hash {:?}", p.to_base64()), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Encoding(e) => Some(e), Error::Io(e, _) => Some(e), Error::PatchId(e) => Some(e), Error::Serde(e) => Some(e), _ => None, } } } impl From<PatchIdError> for Error { fn from(e: PatchIdError) -> Error { Error::PatchId(e) } } impl From<io::Error> for Error { fn from(e: io::Error) -> Error { Error::Io(e, "".to_owned()) } } impl From<(io::Error, &'static str)> for Error { fn from((e, msg): (io::Error, &'static str)) -> Error { Error::Io(e, msg.to_owned()) } } impl From<serde_yaml::Error> for Error { fn from(e: serde_yaml::Error) -> Error { Error::Serde(e) } } impl From<std::string::FromUtf8Error> for Error { fn from(e: std::string::FromUtf8Error) -> Error { Error::Encoding(e) } }
31.580247
99
0.560399
fb66f240d405a537f6ff0a9fac8634841a60d06e
14,021
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Test utilities for starting a pkgfs server. use { anyhow::{Context as _, Error}, fdio::{SpawnAction, SpawnOptions}, fidl::endpoints::ClientEnd, fidl_fuchsia_io::{DirectoryMarker, DirectoryProxy}, fuchsia_runtime::{HandleInfo, HandleType}, fuchsia_zircon::{AsHandleRef, Task}, std::ffi::{CStr, CString}, }; pub use blobfs_ramdisk::BlobfsRamdisk; /// A helper to construct PkgfsRamdisk instances. pub struct PkgfsRamdiskBuilder { blobfs: Option<BlobfsRamdisk>, system_image_merkle: Option<String>, } impl PkgfsRamdiskBuilder { /// Creates a new PkgfsRamdiskBuilder with no configured `blobfs` instance or `system_image_merkle`. fn new() -> Self { Self { blobfs: None, system_image_merkle: None } } /// Use the given blobfs when constructing the PkgfsRamdisk. pub fn blobfs(mut self, blobfs: BlobfsRamdisk) -> Self { self.blobfs = Some(blobfs); self } /// Use the given system_image_merkle when constructing the PkgfsRamdisk. pub fn system_image_merkle(mut self, system_image_merkle: impl Into<String>) -> Self { self.system_image_merkle = Some(system_image_merkle.into()); self } /// Attempt to start the PkgfsRamdisk, consuming this builder. pub fn start(self) -> Result<PkgfsRamdisk, Error> { let blobfs = if let Some(blobfs) = self.blobfs { blobfs } else { BlobfsRamdisk::start()? }; PkgfsRamdisk::start_with_blobfs(blobfs, self.system_image_merkle) } } /// A running pkgfs server backed by a ramdisk-backed blobfs instance. /// /// Make sure to call PkgfsRamdisk.stop() to shut it down properly and receive shutdown errors. /// /// If dropped, only the ramdisk and dynamic index are deleted. pub struct PkgfsRamdisk { blobfs: BlobfsRamdisk, proxy: DirectoryProxy, process: KillOnDrop<fuchsia_zircon::Process>, system_image_merkle: Option<String>, } impl PkgfsRamdisk { /// Creates a new PkgfsRamdiskBuilder with no configured `blobfs` instance or `system_image_merkle`. pub fn builder() -> PkgfsRamdiskBuilder { PkgfsRamdiskBuilder::new() } /// Start a pkgfs server. pub fn start() -> Result<Self, Error> { Self::builder().start() } /// Starts a package server backed by the provided blobfs. /// /// If system_image_merkle is Some, uses that as the starting system_image package. pub fn start_with_blobfs( blobfs: BlobfsRamdisk, system_image_merkle: Option<impl Into<String>>, ) -> Result<Self, Error> { let system_image_merkle = system_image_merkle.map(|m| m.into()); let pkgfs_root_handle_info = HandleInfo::new(HandleType::User0, 0); let (proxy, pkgfs_root_server_end) = fidl::endpoints::create_proxy::<DirectoryMarker>()?; let pkgsvr_bin = CString::new("/pkg/bin/pkgsvr").unwrap(); let system_image_flag = system_image_merkle.as_ref().map(|s| CString::new(s.clone()).unwrap()); let mut argv: Vec<&CStr> = vec![&pkgsvr_bin]; if let Some(system_image_flag) = system_image_flag.as_ref() { argv.push(system_image_flag) } let process = fdio::spawn_etc( &fuchsia_runtime::job_default(), SpawnOptions::CLONE_ALL, &pkgsvr_bin, &argv, None, &mut [ SpawnAction::add_handle( pkgfs_root_handle_info, pkgfs_root_server_end.into_channel().into(), ), SpawnAction::add_namespace_entry( &CString::new("/blob").unwrap(), blobfs.root_dir_handle().context("getting blobfs root dir handle")?.into(), ), ], ) .map_err(|(status, _)| status) .context("spawning 'pkgsvr'")?; Ok(PkgfsRamdisk { blobfs, proxy, process: process.into(), system_image_merkle }) } /// Returns a reference to the [`BlobfsRamdisk`] backing this pkgfs. pub fn blobfs(&self) -> &BlobfsRamdisk { &self.blobfs } /// Returns a new connection to pkgfs's root directory as a raw zircon channel. pub fn root_dir_handle(&self) -> Result<ClientEnd<DirectoryMarker>, Error> { let (root_clone, server_end) = fuchsia_zircon::Channel::create()?; self.proxy.clone(fidl_fuchsia_io::CLONE_FLAG_SAME_RIGHTS, server_end.into())?; Ok(root_clone.into()) } /// Returns a new connection to pkgfs's root directory as a DirectoryProxy. pub fn root_dir_proxy(&self) -> Result<DirectoryProxy, Error> { Ok(self.root_dir_handle()?.into_proxy()?) } /// Returns a new connetion to pkgfs's root directory as a openat::Dir. pub fn root_dir(&self) -> Result<openat::Dir, Error> { use std::os::unix::io::{FromRawFd, IntoRawFd}; let f = fdio::create_fd(self.root_dir_handle()?.into()).unwrap(); let dir = { let fd = f.into_raw_fd(); // Convert our raw file descriptor into an openat::Dir. This is enclosed in an unsafe // block because a RawFd may or may not be owned, and it is only safe to construct an // owned handle from an owned RawFd, which this does. unsafe { openat::Dir::from_raw_fd(fd) } }; Ok(dir) } /// Kills the pkgfs process and waits for it to terminate. fn kill_pkgfs(&self) -> Result<(), Error> { self.process.kill().context("killing pkgfs")?; self.process .wait_handle( fuchsia_zircon::Signals::PROCESS_TERMINATED, fuchsia_zircon::Time::after(fuchsia_zircon::Duration::from_seconds(30)), ) .context("waiting for 'pkgfs' to terminate")?; Ok(()) } /// Restarts pkgfs with the same backing blobfs. pub fn restart(self) -> Result<Self, Error> { self.kill_pkgfs()?; drop(self.proxy); Self::start_with_blobfs(self.blobfs, self.system_image_merkle) } /// Shuts down the pkgfs server and all the backing infrastructure. /// /// This also shuts down blobfs and deletes the backing ramdisk. pub async fn stop(self) -> Result<(), Error> { self.kill_pkgfs()?; self.blobfs.stop().await } } /// An owned zircon job or process that is silently killed when dropped. struct KillOnDrop<T: Task> { task: T, } impl<T: Task> Drop for KillOnDrop<T> { fn drop(&mut self) { let _ = self.task.kill(); } } impl<T: Task> std::ops::Deref for KillOnDrop<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.task } } impl<T: Task> From<T> for KillOnDrop<T> { fn from(task: T) -> Self { Self { task } } } #[cfg(test)] mod tests { use { super::*, fuchsia_pkg::{CreationManifest, MetaPackage}, maplit::{btreemap, hashset}, matches::assert_matches, std::{ collections::HashSet, fs, io::{Read, Write}, path::Path, }, }; #[fuchsia_async::run_singlethreaded(test)] async fn clean_start_and_stop() { let pkgfs = PkgfsRamdisk::start().unwrap(); let proxy = pkgfs.root_dir_proxy().unwrap(); drop(proxy); pkgfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn activate_package() { let pkgfs = PkgfsRamdisk::builder().start().unwrap(); let root = pkgfs.root_dir().unwrap(); let package_merkle = install_test_package(&root); assert_eq!(list_dir(&root.sub_dir("versions").unwrap()), vec![package_merkle]); drop(root); pkgfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn restart_forgets_ephemeral_packages() { let mut pkgfs = PkgfsRamdisk::start().unwrap(); let package_merkle = install_test_package(&pkgfs.root_dir().unwrap()); pkgfs = pkgfs.restart().unwrap(); // after a restart, there are no known packages (since this pkgfs did not have a system // image containing a static or cache index). let root = pkgfs.root_dir().unwrap(); assert_eq!(list_dir(&root.sub_dir("versions").unwrap()), Vec::<String>::new()); // but the backing blobfs is the same, so attempting to create the package will re-import // it without having to write any data. assert_matches!( root.new_file(&format!("install/pkg/{}", package_merkle), 0600), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists ); assert_eq!(list_dir(&root.sub_dir("versions").unwrap()), vec![package_merkle]); drop(root); pkgfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn start_with_system_image_exposes_base_package() { let (pkg_meta_far, pkg_blobs) = make_test_package(); let package_merkle = fuchsia_merkle::MerkleTree::from_reader(pkg_meta_far.as_slice()) .unwrap() .root() .to_string(); let (system_image_far, system_image_blobs) = make_system_image_package(format!("pkgfs-ramdisk-tests/0={}", package_merkle)); let blobfs = BlobfsRamdisk::start().unwrap(); let blobfs_root = blobfs.root_dir().unwrap(); write_blob(&blobfs_root, ".", pkg_meta_far.as_slice()); for blob in pkg_blobs { write_blob(&blobfs_root, ".", blob.as_slice()); } let system_image_merkle_root = write_blob(&blobfs_root, ".", system_image_far.as_slice()); for blob in system_image_blobs { write_blob(&blobfs_root, ".", blob.as_slice()); } drop(blobfs_root); let mut pkgfs = PkgfsRamdisk::builder() .blobfs(blobfs) .system_image_merkle(system_image_merkle_root.clone()) .start() .unwrap(); let expected_active_merkles = hashset![system_image_merkle_root, package_merkle]; // both packages appear in versions assert_eq!( list_dir(&pkgfs.root_dir().unwrap().sub_dir("versions").unwrap()) .into_iter() .collect::<HashSet<_>>(), expected_active_merkles ); // even after a restart pkgfs = pkgfs.restart().unwrap(); assert_eq!( list_dir(&pkgfs.root_dir().unwrap().sub_dir("versions").unwrap()) .into_iter() .collect::<HashSet<_>>(), expected_active_merkles ); pkgfs.stop().await.unwrap(); } /// Makes a test package, producing a tuple of the meta far bytes and a vec of content blob /// bytes. fn make_test_package() -> (Vec<u8>, Vec<Vec<u8>>) { let mut meta_far = vec![]; fuchsia_pkg::build( &CreationManifest::from_external_and_far_contents( btreemap! { "test/pkgfs-ramdisk-lib-test".to_string() => "/pkg/test/pkgfs-ramdisk-lib-test".to_string(), }, btreemap! { "meta/pkgfs-ramdisk-lib-test.cmx".to_string() => "/pkg/meta/pkgfs-ramdisk-lib-test.cmx".to_string(), }, ) .unwrap(), &MetaPackage::from_name_and_variant("pkgfs-ramdisk-tests", "0").unwrap(), &mut meta_far, ) .unwrap(); (meta_far, vec![fs::read("/pkg/test/pkgfs-ramdisk-lib-test").unwrap()]) } /// Makes a test system_image package containing the given literal static_index contents, /// producing a tuple of the meta far bytes and a vec of content blob bytes. fn make_system_image_package(static_index: String) -> (Vec<u8>, Vec<Vec<u8>>) { let tmp = tempfile::tempdir().unwrap(); std::fs::write(tmp.path().join("static_index"), static_index.as_bytes()).unwrap(); let mut meta_far = vec![]; fuchsia_pkg::build( &CreationManifest::from_external_and_far_contents( btreemap! { "data/static_packages".to_string() => tmp.path().join("static_index").into_os_string().into_string().unwrap(), }, btreemap! {}, ) .unwrap(), &MetaPackage::from_name_and_variant("system_image", "0").unwrap(), &mut meta_far, ) .unwrap(); (meta_far, vec![static_index.into_bytes()]) } /// Installs the test package (see make_test_package) to a pkgfs instance. fn install_test_package(pkgfs: &openat::Dir) -> String { let (meta_far, blobs) = make_test_package(); let meta_far_merkle = write_blob(&pkgfs, "install/pkg", meta_far.as_slice()); for blob in blobs { write_blob(&pkgfs, "install/blob", blob.as_slice()); } meta_far_merkle } /// Writes a blob in the given directory and path, returning the computed merkle root of the blob. fn write_blob(dir: &openat::Dir, subdir: impl AsRef<Path>, mut payload: impl Read) -> String { let mut buf = vec![]; payload.read_to_end(&mut buf).unwrap(); let merkle = fuchsia_merkle::MerkleTree::from_reader(buf.as_slice()).unwrap().root().to_string(); let mut f = dir.new_file(&subdir.as_ref().join(&merkle), 0600).unwrap(); f.set_len(buf.len() as u64).unwrap(); f.write_all(&buf).unwrap(); merkle } /// Returns an unsorted list of nodes in the given dir. fn list_dir(dir: &openat::Dir) -> Vec<String> { dir.list_dir(".") .unwrap() .map(|entry| entry.unwrap().file_name().to_owned().into_string().unwrap()) .collect() } }
35.31738
104
0.603167
91d6f168413466e0962eaeb3e3d243e4d651470a
3,899
use std::cmp::Ordering::{Less, Equal, Greater}; use std::collections::HashMap; use std::collections::VecDeque; use std::rc::Rc; pub struct Promise { id: u32, generator: fn () -> u32, } impl Promise { // https://users.rust-lang.org/t/three-way-comparison-in-rust/2648 pub fn compare(left: [u32; 2], right: [u32; 2]) -> std::cmp::Ordering { if left[0] < right[0] { return Less } if left[0] > right[0] { return Greater } if left[1] < right[1] { return Less } if left[1] > right[1] { return Greater } return Equal } pub fn create(&self) -> [u32; 2] { [ self.id, (self.generator)() ] } } #[derive(PartialEq, Debug)] pub struct Entry { version: u64, node: u32, index: u32, value: u32, } pub struct Log { minimum: HashMap<u32, u64>, entries: Vec<Rc<Entry>>, consumer: VecDeque<Rc<Entry>>, } impl Log { pub fn new(consumer: VecDeque<Rc<Entry>>) -> Log { Log { minimum: HashMap::new(), entries: vec![], consumer: consumer, } } fn check(&mut self) { let mut min = self.minimum(); for (_, value) in &self.minimum { if value < &min { min = *value; } } let mut i = 0; loop { if self.entries[i].version == min { break; } i += 1; } self.entries.splice(..i, []); } pub fn minimum(&self) -> u64 { self.entries[0].version } pub fn maximum(&self) -> u64 { self.entries[self.entries.len() - 1].version } pub fn arrive(&mut self, node: u32) { self.minimum.insert(node, 0); } pub fn push(&mut self, entry: Rc<Entry>) { self.entries.push(entry); } pub fn advance(&mut self, node: u32, version: u64) { self.minimum.insert(node, version); self.check(); } pub fn len(& self) -> usize { self.consumer.len() } pub fn replay(&self, version: u64, node: u32, index: u32, consumer: &mut VecDeque<Rc<Entry>>) { let mut i = 0; loop { let entry = &self.entries[i]; if entry.version == version && entry.node == node && entry.index == index { break; } i += 1; } i += 1; loop { if i == self.entries.len() { break } consumer.push_back(self.entries[i].clone()); i += 1 } } } #[cfg(test)] mod tests { use crate::Log; use crate::Entry; use crate::Promise; use std::collections::VecDeque; use std::rc::Rc; use std::cmp::Ordering::{Equal}; #[test] fn it_logs() { let mut log = Log::new(VecDeque::new()); log.arrive(0); log.push(Rc::new(Entry{ version: 0, node: 0, index: 0, value: 0 })); assert_eq!(log.minimum(), 0); log.arrive(1); log.push(Rc::new(Entry{ version: 1, node: 0, index: 0, value: 1 })); log.push(Rc::new(Entry{ version: 1, node: 0, index: 1, value: 2 })); log.arrive(2); log.push(Rc::new(Entry{ version: 2, node: 0, index: 0, value: 3 })); log.advance(2, 1); log.advance(0, 0); log.advance(1, 0); assert_eq!(log.minimum(), 0); let mut replay: VecDeque<Rc<Entry>> = VecDeque::new(); log.replay(1, 0, 0, &mut replay); assert_eq!(*replay.pop_front().unwrap(), Entry { version: 1, node: 0, index: 1, value: 2 }); assert_eq!(log.len(), 0); } #[test] fn is_promises() { let promise = Promise { id: 0, generator: || 0 }; assert_eq!(promise.create(), [ 0, 0 ]); assert_eq!(Promise::compare([ 0, 0, ], [ 0, 0 ]), Equal); } }
25.154839
100
0.489613
fb2ed53e5b0e81c288637ff501c5b6f910eae8b5
52
codeblockutil.SliderBlueprint codeblockutil.CSlider
17.333333
29
0.923077
b9a413efcd5b4111945b92368acb343dbb907755
5,980
#![cfg(feature = "serialization")] extern crate futures; extern crate env_logger; extern crate serde_json; extern crate serde_state as serde; extern crate gluon; use std::fs::File; use std::io::Read; use futures::Future; use serde::ser::SerializeState; use gluon::vm::api::{Hole, OpaqueValue}; use gluon::vm::serialization::{DeSeed, SeSeed}; use gluon::vm::thread::{RootedThread, RootedValue, Thread, ThreadInternal}; use gluon::vm::Variants; use gluon::{new_vm, Compiler}; fn serialize_value(value: Variants) { let mut buffer = Vec::new(); { let mut ser = serde_json::Serializer::pretty(&mut buffer); let ser_state = SeSeed::new(); value.serialize_state(&mut ser, &ser_state).unwrap(); } String::from_utf8(buffer).unwrap(); } fn roundtrip<'t>( thread: &'t RootedThread, value: &OpaqueValue<&Thread, Hole>, ) -> RootedValue<&'t Thread> { use std::str::from_utf8; let value = value.get_variant(); let mut buffer = Vec::new(); { let mut ser = serde_json::Serializer::pretty(&mut buffer); let ser_state = SeSeed::new(); value.serialize_state(&mut ser, &ser_state).unwrap(); } let buffer = from_utf8(&buffer).unwrap(); let mut de = serde_json::Deserializer::from_str(buffer); let deserialize_value = DeSeed::new(thread) .deserialize(&mut de) .unwrap_or_else(|err| panic!("{}\n{}", err, buffer)); let deserialize_value = thread.root_value(unsafe { Variants::new(&deserialize_value) }); // We can't compare functions for equality so serialize again and check that for equality with // the first serialization let mut buffer2 = Vec::new(); { let mut ser = serde_json::Serializer::pretty(&mut buffer2); let ser_state = SeSeed::new(); value.serialize_state(&mut ser, &ser_state).unwrap(); } assert_eq!(buffer, from_utf8(&buffer2).unwrap()); deserialize_value } #[test] fn roundtrip_module() { let thread = new_vm(); let (value, _) = Compiler::new() .run_expr::<OpaqueValue<&Thread, Hole>>(&thread, "test", r#" { x = 1, y = "test" } "#) .unwrap(); let deserialize_value = roundtrip(&thread, &value); assert_eq!(deserialize_value, value.into_inner()); } #[test] fn roundtrip_recursive_closure() { let thread = new_vm(); let expr = r#" let f x = g x and g x = f x { f, g } "#; let (value, _) = Compiler::new() .run_expr::<OpaqueValue<&Thread, Hole>>(&thread, "test", expr) .unwrap(); roundtrip(&thread, &value); } #[test] fn roundtrip_std_prelude() { let thread = new_vm(); let expr = r#" import! std.prelude "#; let (value, _) = Compiler::new() .run_expr::<OpaqueValue<&Thread, Hole>>(&thread, "test", expr) .unwrap(); roundtrip(&thread, &value); } #[test] fn roundtrip_std_libs() { let _ = env_logger::try_init(); let thread = new_vm(); let mut expr = "{\n".to_string(); for entry in std::fs::read_dir("std").unwrap() { let path = entry.unwrap().path(); // Can't check the extension since vim swap files ".glu.swp" will report ".glu" as the // extension let file_stem = path.file_stem().unwrap().to_str(); if path.to_str().unwrap().ends_with(".glu") && file_stem != Some("repl") && file_stem != Some("stream") // floats cannot be roundtripped with serde json // https://github.com/serde-rs/json/issues/128 && file_stem != Some("float") { expr.push_str(&format!( " {} = import! {:?},\n", path.file_stem().unwrap().to_str().unwrap(), path.display() )); } } expr.push_str("}\n"); let (value, _) = Compiler::new() .run_expr::<OpaqueValue<&Thread, Hole>>(&thread, "test", &expr) .unwrap_or_else(|err| panic!("{}", err)); roundtrip(&thread, &value); } #[test] fn precompile() { use gluon::compiler_pipeline::*; let thread = new_vm(); let mut text = String::new(); File::open("std/map.glu") .expect("Unable to open map.glu") .read_to_string(&mut text) .unwrap(); let mut buffer = Vec::new(); { let mut serializer = serde_json::Serializer::new(&mut buffer); Compiler::new() .compile_to_bytecode(&thread, "test", &text, &mut serializer) .unwrap() } let precompiled_result = { let mut deserializer = serde_json::Deserializer::from_slice(&buffer); Precompiled(&mut deserializer) .run_expr(&mut Compiler::new(), &*thread, "test", "", ()) .wait() .unwrap() }; let thread2 = new_vm(); assert_eq!( serialize_value( text.run_expr(&mut Compiler::new(), &*thread2, "test", &text, None) .wait() .unwrap() .value .get_variant() ), serialize_value(precompiled_result.value.get_variant()) ); } #[test] fn roundtrip_reference() { let thread = new_vm(); let expr = r#" import! std.reference "#; let (value, _) = Compiler::new() .run_expr::<OpaqueValue<&Thread, Hole>>(&thread, "test", &expr) .unwrap_or_else(|err| panic!("{}", err)); roundtrip(&thread, &value); } #[test] fn roundtrip_lazy() { let thread = new_vm(); let expr = r#" import! std.lazy "#; let (value, _) = Compiler::new() .run_expr::<OpaqueValue<&Thread, Hole>>(&thread, "test", &expr) .unwrap_or_else(|err| panic!("{}", err)); roundtrip(&thread, &value); } #[test] fn roundtrip_thread() { let thread = new_vm(); let expr = r#" import! std.thread "#; let (value, _) = Compiler::new() .run_expr::<OpaqueValue<&Thread, Hole>>(&thread, "test", &expr) .unwrap_or_else(|err| panic!("{}", err)); roundtrip(&thread, &value); }
29.458128
98
0.578428
e9bebadeb7cd753249f881ea6f3467a243e2f888
1,299
const NULL_DATA_PACKET: [u8; 24] = [ 0x48, 0x11, 0x02, 0x01, 0x00, 0x01, 0xe3, 0x41, 0xbd, 0x6e, 0x00, 0x16, 0xbc, 0x3d, 0xaa, 0x57, 0x00, 0x01, 0xe3, 0x41, 0xbd, 0x6e, 0xf0, 0x03, ]; #[test] fn test_null_data_packet() { // Receiver address: Siemens_41:bd:6e (00:01:e3:41:bd:6e) // Transmitter address: NokiaDan_3d:aa:57 (00:16:bc:3d:aa:57) // Destination address: Siemens_41:bd:6e (00:01:e3:41:bd:6e) // Source address: NokiaDan_3d:aa:57 (00:16:bc:3d:aa:57) // BSS Id: Siemens_41:bd:6e (00:01:e3:41:bd:6e) // STA address: NokiaDan_3d:aa:57 (00:16:bc:3d:aa:57) test_test_item(TestItem { bytes: &NULL_DATA_PACKET, subtype: Some(FrameSubtype::Data(DataSubtype::Null)), ds_status: Some(DSStatus::FromSTAToDS), pwr_mgt: true, duration_id: Some(DurationID::Duration(258)), receiver_address: "00:01:e3:41:bd:6e".parse().unwrap(), transmitter_address: Some("00:16:bc:3d:aa:57".parse().unwrap()), destination_address: Some("00:01:e3:41:bd:6e".parse().unwrap()), source_address: Some("00:16:bc:3d:aa:57".parse().unwrap()), bssid_address: Some("00:01:e3:41:bd:6e".parse().unwrap()), station_address: Some("00:16:bc:3d:aa:57".parse().unwrap()), fragment_number: Some(0), sequence_number: Some(63), ..Default::default() }); }
33.307692
97
0.661278
4851e637d3a62eeb3f440bba63776549497b7107
25,753
use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use crate::infer::{InferCtxt, InferOk}; use crate::traits; use rustc_data_structures::sync::Lrc; use rustc_data_structures::vec_map::VecMap; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::subst::{GenericArgKind, Subst}; use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeVisitor}; use rustc_span::Span; use std::ops::ControlFlow; pub type OpaqueTypeMap<'tcx> = VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>; /// Information about the opaque types whose values we /// are inferring in this function (these are the `impl Trait` that /// appear in the return type). #[derive(Copy, Clone, Debug)] pub struct OpaqueTypeDecl<'tcx> { /// The opaque type (`ty::Opaque`) for this declaration. pub opaque_type: Ty<'tcx>, /// The span of this particular definition of the opaque type. So /// for example: /// /// ```ignore (incomplete snippet) /// type Foo = impl Baz; /// fn bar() -> Foo { /// // ^^^ This is the span we are looking for! /// } /// ``` /// /// In cases where the fn returns `(impl Trait, impl Trait)` or /// other such combinations, the result is currently /// over-approximated, but better than nothing. pub definition_span: Span, /// The type variable that represents the value of the opaque type /// that we require. In other words, after we compile this function, /// we will be created a constraint like: /// /// Foo<'a, T> = ?C /// /// where `?C` is the value of this type variable. =) It may /// naturally refer to the type and lifetime parameters in scope /// in this function, though ultimately it should only reference /// those that are arguments to `Foo` in the constraint above. (In /// other words, `?C` should not include `'b`, even though it's a /// lifetime parameter on `foo`.) pub concrete_ty: Ty<'tcx>, /// The origin of the opaque type. pub origin: hir::OpaqueTyOrigin, } impl<'a, 'tcx> InferCtxt<'a, 'tcx> { /// Replaces all opaque types in `value` with fresh inference variables /// and creates appropriate obligations. For example, given the input: /// /// impl Iterator<Item = impl Debug> /// /// this method would create two type variables, `?0` and `?1`. It would /// return the type `?0` but also the obligations: /// /// ?0: Iterator<Item = ?1> /// ?1: Debug /// /// Moreover, it returns an `OpaqueTypeMap` that would map `?0` to /// info about the `impl Iterator<..>` type and `?1` to info about /// the `impl Debug` type. /// /// # Parameters /// /// - `parent_def_id` -- the `DefId` of the function in which the opaque type /// is defined /// - `body_id` -- the body-id with which the resulting obligations should /// be associated /// - `param_env` -- the in-scope parameter environment to be used for /// obligations /// - `value` -- the value within which we are instantiating opaque types /// - `value_span` -- the span where the value came from, used in error reporting pub fn instantiate_opaque_types<T: TypeFoldable<'tcx>>( &self, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, value: T, value_span: Span, ) -> InferOk<'tcx, T> { debug!( "instantiate_opaque_types(value={:?}, body_id={:?}, \ param_env={:?}, value_span={:?})", value, body_id, param_env, value_span, ); let mut instantiator = Instantiator { infcx: self, body_id, param_env, value_span, obligations: vec![] }; let value = instantiator.instantiate_opaque_types_in_map(value); InferOk { value, obligations: instantiator.obligations } } /// Given the map `opaque_types` containing the opaque /// `impl Trait` types whose underlying, hidden types are being /// inferred, this method adds constraints to the regions /// appearing in those underlying hidden types to ensure that they /// at least do not refer to random scopes within the current /// function. These constraints are not (quite) sufficient to /// guarantee that the regions are actually legal values; that /// final condition is imposed after region inference is done. /// /// # The Problem /// /// Let's work through an example to explain how it works. Assume /// the current function is as follows: /// /// ```text /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>) /// ``` /// /// Here, we have two `impl Trait` types whose values are being /// inferred (the `impl Bar<'a>` and the `impl /// Bar<'b>`). Conceptually, this is sugar for a setup where we /// define underlying opaque types (`Foo1`, `Foo2`) and then, in /// the return type of `foo`, we *reference* those definitions: /// /// ```text /// type Foo1<'x> = impl Bar<'x>; /// type Foo2<'x> = impl Bar<'x>; /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. } /// // ^^^^ ^^ /// // | | /// // | substs /// // def_id /// ``` /// /// As indicating in the comments above, each of those references /// is (in the compiler) basically a substitution (`substs`) /// applied to the type of a suitable `def_id` (which identifies /// `Foo1` or `Foo2`). /// /// Now, at this point in compilation, what we have done is to /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with /// fresh inference variables C1 and C2. We wish to use the values /// of these variables to infer the underlying types of `Foo1` and /// `Foo2`. That is, this gives rise to higher-order (pattern) unification /// constraints like: /// /// ```text /// for<'a> (Foo1<'a> = C1) /// for<'b> (Foo1<'b> = C2) /// ``` /// /// For these equation to be satisfiable, the types `C1` and `C2` /// can only refer to a limited set of regions. For example, `C1` /// can only refer to `'static` and `'a`, and `C2` can only refer /// to `'static` and `'b`. The job of this function is to impose that /// constraint. /// /// Up to this point, C1 and C2 are basically just random type /// inference variables, and hence they may contain arbitrary /// regions. In fact, it is fairly likely that they do! Consider /// this possible definition of `foo`: /// /// ```text /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) { /// (&*x, &*y) /// } /// ``` /// /// Here, the values for the concrete types of the two impl /// traits will include inference variables: /// /// ```text /// &'0 i32 /// &'1 i32 /// ``` /// /// Ordinarily, the subtyping rules would ensure that these are /// sufficiently large. But since `impl Bar<'a>` isn't a specific /// type per se, we don't get such constraints by default. This /// is where this function comes into play. It adds extra /// constraints to ensure that all the regions which appear in the /// inferred type are regions that could validly appear. /// /// This is actually a bit of a tricky constraint in general. We /// want to say that each variable (e.g., `'0`) can only take on /// values that were supplied as arguments to the opaque type /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in /// scope. We don't have a constraint quite of this kind in the current /// region checker. /// /// # The Solution /// /// We generally prefer to make `<=` constraints, since they /// integrate best into the region solver. To do that, we find the /// "minimum" of all the arguments that appear in the substs: that /// is, some region which is less than all the others. In the case /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after /// all). Then we apply that as a least bound to the variables /// (e.g., `'a <= '0`). /// /// In some cases, there is no minimum. Consider this example: /// /// ```text /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... } /// ``` /// /// Here we would report a more complex "in constraint", like `'r /// in ['a, 'b, 'static]` (where `'r` is some region appearing in /// the hidden type). /// /// # Constrain regions, not the hidden concrete type /// /// Note that generating constraints on each region `Rc` is *not* /// the same as generating an outlives constraint on `Tc` iself. /// For example, if we had a function like this: /// /// ```rust /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> { /// (x, y) /// } /// /// // Equivalent to: /// type FooReturn<'a, T> = impl Foo<'a>; /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. } /// ``` /// /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0` /// is an inference variable). If we generated a constraint that /// `Tc: 'a`, then this would incorrectly require that `T: 'a` -- /// but this is not necessary, because the opaque type we /// create will be allowed to reference `T`. So we only generate a /// constraint that `'0: 'a`. /// /// # The `free_region_relations` parameter /// /// The `free_region_relations` argument is used to find the /// "minimum" of the regions supplied to a given opaque type. /// It must be a relation that can answer whether `'a <= 'b`, /// where `'a` and `'b` are regions that appear in the "substs" /// for the opaque type references (the `<'a>` in `Foo1<'a>`). /// /// Note that we do not impose the constraints based on the /// generic regions from the `Foo1` definition (e.g., `'x`). This /// is because the constraints we are imposing here is basically /// the concern of the one generating the constraining type C1, /// which is the current function. It also means that we can /// take "implied bounds" into account in some cases: /// /// ```text /// trait SomeTrait<'a, 'b> { } /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. } /// ``` /// /// Here, the fact that `'b: 'a` is known only because of the /// implied bounds from the `&'a &'b u32` parameter, and is not /// "inherent" to the opaque type definition. /// /// # Parameters /// /// - `opaque_types` -- the map produced by `instantiate_opaque_types` /// - `free_region_relations` -- something that can be used to relate /// the free regions (`'a`) that appear in the impl trait. #[instrument(level = "debug", skip(self))] pub fn constrain_opaque_type( &self, opaque_type_key: OpaqueTypeKey<'tcx>, opaque_defn: &OpaqueTypeDecl<'tcx>, ) { let def_id = opaque_type_key.def_id; let tcx = self.tcx; let concrete_ty = self.resolve_vars_if_possible(opaque_defn.concrete_ty); debug!(?concrete_ty); let first_own_region = match opaque_defn.origin { hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => { // We lower // // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm> // // into // // type foo::<'p0..'pn>::Foo<'q0..'qm> // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>. // // For these types we only iterate over `'l0..lm` below. tcx.generics_of(def_id).parent_count } // These opaque type inherit all lifetime parameters from their // parent, so we have to check them all. hir::OpaqueTyOrigin::TyAlias => 0, }; // For a case like `impl Foo<'a, 'b>`, we would generate a constraint // `'r in ['a, 'b, 'static]` for each region `'r` that appears in the // hidden type (i.e., it must be equal to `'a`, `'b`, or `'static`). // // `conflict1` and `conflict2` are the two region bounds that we // detected which were unrelated. They are used for diagnostics. // Create the set of choice regions: each region in the hidden // type can be equal to any of the region parameters of the // opaque type definition. let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new( opaque_type_key.substs[first_own_region..] .iter() .filter_map(|arg| match arg.unpack() { GenericArgKind::Lifetime(r) => Some(r), GenericArgKind::Type(_) | GenericArgKind::Const(_) => None, }) .chain(std::iter::once(self.tcx.lifetimes.re_static)) .collect(), ); concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor { op: |r| { self.member_constraint( opaque_type_key.def_id, opaque_defn.definition_span, concrete_ty, r, &choice_regions, ) }, }); } fn opaque_type_origin(&self, def_id: LocalDefId) -> Option<hir::OpaqueTyOrigin> { let tcx = self.tcx; let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(def_id); let parent_def_id = self.defining_use_anchor?; let item_kind = &tcx.hir().expect_item(def_id).kind; let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item_kind else { span_bug!( tcx.def_span(def_id), "weird opaque type: {:#?}", item_kind ) }; let in_definition_scope = match *origin { // Async `impl Trait` hir::OpaqueTyOrigin::AsyncFn(parent) => parent == parent_def_id, // Anonymous `impl Trait` hir::OpaqueTyOrigin::FnReturn(parent) => parent == parent_def_id, // Named `type Foo = impl Bar;` hir::OpaqueTyOrigin::TyAlias => { may_define_opaque_type(tcx, parent_def_id, opaque_hir_id) } }; in_definition_scope.then_some(*origin) } } // Visitor that requires that (almost) all regions in the type visited outlive // `least_region`. We cannot use `push_outlives_components` because regions in // closure signatures are not included in their outlives components. We need to // ensure all regions outlive the given bound so that we don't end up with, // say, `ReVar` appearing in a return type and causing ICEs when other // functions end up with region constraints involving regions from other // functions. // // We also cannot use `for_each_free_region` because for closures it includes // the regions parameters from the enclosing item. // // We ignore any type parameters because impl trait values are assumed to // capture all the in-scope type parameters. struct ConstrainOpaqueTypeRegionVisitor<OP> { op: OP, } impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<OP> where OP: FnMut(ty::Region<'tcx>), { fn visit_binder<T: TypeFoldable<'tcx>>( &mut self, t: &ty::Binder<'tcx, T>, ) -> ControlFlow<Self::BreakTy> { t.as_ref().skip_binder().visit_with(self); ControlFlow::CONTINUE } fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> { match *r { // ignore bound regions, keep visiting ty::ReLateBound(_, _) => ControlFlow::CONTINUE, _ => { (self.op)(r); ControlFlow::CONTINUE } } } fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { // We're only interested in types involving regions if !ty.flags().intersects(ty::TypeFlags::HAS_FREE_REGIONS) { return ControlFlow::CONTINUE; } match ty.kind() { ty::Closure(_, ref substs) => { // Skip lifetime parameters of the enclosing item(s) substs.as_closure().tupled_upvars_ty().visit_with(self); substs.as_closure().sig_as_fn_ptr_ty().visit_with(self); } ty::Generator(_, ref substs, _) => { // Skip lifetime parameters of the enclosing item(s) // Also skip the witness type, because that has no free regions. substs.as_generator().tupled_upvars_ty().visit_with(self); substs.as_generator().return_ty().visit_with(self); substs.as_generator().yield_ty().visit_with(self); substs.as_generator().resume_ty().visit_with(self); } _ => { ty.super_visit_with(self); } } ControlFlow::CONTINUE } } struct Instantiator<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, value_span: Span, obligations: Vec<traits::PredicateObligation<'tcx>>, } impl<'a, 'tcx> Instantiator<'a, 'tcx> { fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T { let tcx = self.infcx.tcx; value.fold_with(&mut BottomUpFolder { tcx, ty_op: |ty| { if ty.references_error() { return tcx.ty_error(); } else if let ty::Opaque(def_id, substs) = ty.kind() { // Check that this is `impl Trait` type is // declared by `parent_def_id` -- i.e., one whose // value we are inferring. At present, this is // always true during the first phase of // type-check, but not always true later on during // NLL. Once we support named opaque types more fully, // this same scenario will be able to arise during all phases. // // Here is an example using type alias `impl Trait` // that indicates the distinction we are checking for: // // ```rust // mod a { // pub type Foo = impl Iterator; // pub fn make_foo() -> Foo { .. } // } // // mod b { // fn foo() -> a::Foo { a::make_foo() } // } // ``` // // Here, the return type of `foo` references an // `Opaque` indeed, but not one whose value is // presently being inferred. You can get into a // similar situation with closure return types // today: // // ```rust // fn foo() -> impl Iterator { .. } // fn bar() { // let x = || foo(); // returns the Opaque assoc with `foo` // } // ``` if let Some(def_id) = def_id.as_local() { if let Some(origin) = self.infcx.opaque_type_origin(def_id) { let opaque_type_key = OpaqueTypeKey { def_id: def_id.to_def_id(), substs }; return self.fold_opaque_ty(ty, opaque_type_key, origin); } debug!( "instantiate_opaque_types_in_map: \ encountered opaque outside its definition scope \ def_id={:?}", def_id, ); } } ty }, lt_op: |lt| lt, ct_op: |ct| ct, }) } #[instrument(skip(self), level = "debug")] fn fold_opaque_ty( &mut self, ty: Ty<'tcx>, opaque_type_key: OpaqueTypeKey<'tcx>, origin: hir::OpaqueTyOrigin, ) -> Ty<'tcx> { let infcx = self.infcx; let tcx = infcx.tcx; let OpaqueTypeKey { def_id, substs } = opaque_type_key; // Use the same type variable if the exact same opaque type appears more // than once in the return type (e.g., if it's passed to a type alias). if let Some(opaque_defn) = infcx.inner.borrow().opaque_types.get(&opaque_type_key) { debug!("re-using cached concrete type {:?}", opaque_defn.concrete_ty.kind()); return opaque_defn.concrete_ty; } let ty_var = infcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span: self.value_span, }); // Ideally, we'd get the span where *this specific `ty` came // from*, but right now we just use the span from the overall // value being folded. In simple cases like `-> impl Foo`, // these are the same span, but not in cases like `-> (impl // Foo, impl Bar)`. let definition_span = self.value_span; { let mut infcx = self.infcx.inner.borrow_mut(); infcx.opaque_types.insert( OpaqueTypeKey { def_id, substs }, OpaqueTypeDecl { opaque_type: ty, definition_span, concrete_ty: ty_var, origin }, ); infcx.opaque_types_vars.insert(ty_var, ty); } debug!("generated new type inference var {:?}", ty_var.kind()); let item_bounds = tcx.explicit_item_bounds(def_id); self.obligations.reserve(item_bounds.len()); for (predicate, _) in item_bounds { debug!(?predicate); let predicate = predicate.subst(tcx, substs); debug!(?predicate); let predicate = predicate.fold_with(&mut BottomUpFolder { tcx, ty_op: |ty| match *ty.kind() { // Replace all other mentions of the same opaque type with the hidden type, // as the bounds must hold on the hidden type after all. ty::Opaque(def_id2, substs2) if def_id == def_id2 && substs == substs2 => { ty_var } // Instantiate nested instances of `impl Trait`. ty::Opaque(..) => self.instantiate_opaque_types_in_map(ty), _ => ty, }, lt_op: |lt| lt, ct_op: |ct| ct, }); // We can't normalize associated types from `rustc_infer`, but we can eagerly register inference variables for them. let predicate = predicate.fold_with(&mut BottomUpFolder { tcx, ty_op: |ty| match ty.kind() { ty::Projection(projection_ty) => infcx.infer_projection( self.param_env, *projection_ty, traits::ObligationCause::misc(self.value_span, self.body_id), 0, &mut self.obligations, ), _ => ty, }, lt_op: |lt| lt, ct_op: |ct| ct, }); debug!(?predicate); if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() { if projection.term.references_error() { return tcx.ty_error(); } } let cause = traits::ObligationCause::new(self.value_span, self.body_id, traits::OpaqueType); // Require that the predicate holds for the concrete type. debug!(?predicate); self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate)); } ty_var } } /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`. /// /// Example: /// ```rust /// pub mod foo { /// pub mod bar { /// pub trait Bar { .. } /// /// pub type Baz = impl Bar; /// /// fn f1() -> Baz { .. } /// } /// /// fn f2() -> bar::Baz { .. } /// } /// ``` /// /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`), /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`. /// For the above example, this function returns `true` for `f1` and `false` for `f2`. fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool { let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id); // Named opaque types can be defined by any siblings or children of siblings. let scope = tcx.hir().get_defining_scope(opaque_hir_id); // We walk up the node tree until we hit the root or the scope of the opaque type. while hir_id != scope && hir_id != hir::CRATE_HIR_ID { hir_id = tcx.hir().local_def_id_to_hir_id(tcx.hir().get_parent_item(hir_id)); } // Syntactically, we are allowed to define the concrete type if: let res = hir_id == scope; trace!( "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}", tcx.hir().find(hir_id), tcx.hir().get(opaque_hir_id), res ); res }
40.051322
128
0.551975
1143e9b264b793658aa5b9990f6267132f3cf796
1,902
use necsim_core::cogs::{ DispersalSampler, EmigrationExit, Habitat, MathsCore, PrimeableRng, SpeciationProbability, TurnoverRate, }; use necsim_core::lineage::{GlobalLineageReference, Lineage}; use necsim_core_bond::NonNegativeF64; use crate::cogs::{ active_lineage_sampler::singular::SingularActiveLineageSampler, coalescence_sampler::independent::IndependentCoalescenceSampler, event_sampler::independent::IndependentEventSampler, immigration_entry::never::NeverImmigrationEntry, lineage_store::independent::IndependentLineageStore, }; use super::{EventTimeSampler, IndependentActiveLineageSampler}; impl< M: MathsCore, H: Habitat<M>, G: PrimeableRng<M>, X: EmigrationExit<M, H, G, GlobalLineageReference, IndependentLineageStore<M, H>>, D: DispersalSampler<M, H, G>, T: TurnoverRate<M, H>, N: SpeciationProbability<M, H>, J: EventTimeSampler<M, H, G, T>, > SingularActiveLineageSampler< M, H, G, GlobalLineageReference, IndependentLineageStore<M, H>, X, D, IndependentCoalescenceSampler<M, H>, T, N, IndependentEventSampler<M, H, G, X, D, T, N>, NeverImmigrationEntry, > for IndependentActiveLineageSampler<M, H, G, X, D, T, N, J> { #[must_use] #[inline] fn replace_active_lineage(&mut self, active_lineage: Option<Lineage>) -> Option<Lineage> { // `core::mem::replace()` would be semantically better // - but `clone()` does not spill to local memory let old_active_lineage = self.active_lineage.clone(); self.active_lineage = active_lineage; self.last_event_time = match &self.active_lineage { None => NonNegativeF64::zero(), Some(lineage) => lineage.last_event_time, }; old_active_lineage } }
31.180328
94
0.656677
113c48f22eeaf8a5636d7f18bcb9212e3e585934
6,331
//! [`egui`] bindings for [`glow`](https://github.com/grovesNL/glow). //! //! The main type you want to use is [`EguiGlow`]. //! //! This library is an [`epi`] backend. //! If you are writing an app, you may want to look at [`eframe`](https://docs.rs/eframe) instead. // Forbid warnings in release builds: #![cfg_attr(not(debug_assertions), deny(warnings))] #![deny(unsafe_code)] #![warn( clippy::all, clippy::await_holding_lock, clippy::char_lit_as_u8, clippy::checked_conversions, clippy::dbg_macro, clippy::debug_assert_with_mut_call, clippy::disallowed_method, clippy::doc_markdown, clippy::empty_enum, clippy::enum_glob_use, clippy::exit, clippy::expl_impl_clone_on_copy, clippy::explicit_deref_methods, clippy::explicit_into_iter_loop, clippy::fallible_impl_from, clippy::filter_map_next, clippy::flat_map_option, clippy::float_cmp_const, clippy::fn_params_excessive_bools, clippy::from_iter_instead_of_collect, clippy::if_let_mutex, clippy::implicit_clone, clippy::imprecise_flops, clippy::inefficient_to_string, clippy::invalid_upcast_comparisons, clippy::large_digit_groups, clippy::large_stack_arrays, clippy::large_types_passed_by_value, clippy::let_unit_value, clippy::linkedlist, clippy::lossy_float_literal, clippy::macro_use_imports, clippy::manual_ok_or, clippy::map_err_ignore, clippy::map_flatten, clippy::map_unwrap_or, clippy::match_on_vec_items, clippy::match_same_arms, clippy::match_wild_err_arm, clippy::match_wildcard_for_single_variants, clippy::mem_forget, clippy::mismatched_target_os, clippy::missing_errors_doc, clippy::missing_safety_doc, clippy::mut_mut, clippy::mutex_integer, clippy::needless_borrow, clippy::needless_continue, clippy::needless_for_each, clippy::needless_pass_by_value, clippy::option_option, clippy::path_buf_push_overwrite, clippy::ptr_as_ptr, clippy::ref_option_ref, clippy::rest_pat_in_fully_bound_structs, clippy::same_functions_in_if_condition, clippy::semicolon_if_nothing_returned, clippy::single_match_else, clippy::string_add_assign, clippy::string_add, clippy::string_lit_as_bytes, clippy::string_to_string, clippy::todo, clippy::trait_duplication_in_bounds, clippy::unimplemented, clippy::unnested_or_patterns, clippy::unused_self, clippy::useless_transmute, clippy::verbose_file_reads, clippy::zero_sized_map_values, future_incompatible, nonstandard_style, rust_2018_idioms, rustdoc::missing_crate_level_docs )] #![allow(clippy::float_cmp)] #![allow(clippy::manual_range_contains)] pub mod painter; pub use glow; pub use painter::Painter; #[cfg(feature = "winit")] mod epi_backend; mod misc_util; mod post_process; mod shader_version; mod vao_emulate; #[cfg(not(target_arch = "wasm32"))] #[cfg(feature = "egui_winit")] pub use egui_winit; #[cfg(all(feature = "epi", feature = "winit"))] pub use epi_backend::{run, NativeOptions}; // ---------------------------------------------------------------------------- /// Use [`egui`] from a [`glow`] app. #[cfg(feature = "winit")] pub struct EguiGlow { pub egui_ctx: egui::Context, pub egui_winit: egui_winit::State, pub painter: crate::Painter, shapes: Vec<egui::epaint::ClippedShape>, textures_delta: egui::TexturesDelta, } #[cfg(feature = "winit")] impl EguiGlow { pub fn new( gl_window: &glutin::WindowedContext<glutin::PossiblyCurrent>, gl: &glow::Context, ) -> Self { Self { egui_ctx: Default::default(), egui_winit: egui_winit::State::new(gl_window.window()), painter: crate::Painter::new(gl, None, "") .map_err(|error| { eprintln!("some error occurred in initializing painter\n{}", error); }) .unwrap(), shapes: Default::default(), textures_delta: Default::default(), } } /// Returns `true` if egui wants exclusive use of this event /// (e.g. a mouse click on an egui window, or entering text into a text field). /// For instance, if you use egui for a game, you want to first call this /// and only when this returns `false` pass on the events to your game. /// /// Note that egui uses `tab` to move focus between elements, so this will always return `true` for tabs. pub fn on_event(&mut self, event: &glutin::event::WindowEvent<'_>) -> bool { self.egui_winit.on_event(&self.egui_ctx, event) } /// Returns `true` if egui requests a repaint. /// /// Call [`Self::paint`] later to paint. pub fn run( &mut self, window: &glutin::window::Window, run_ui: impl FnMut(&egui::Context), ) -> bool { let raw_input = self.egui_winit.take_egui_input(window); let (egui_output, shapes) = self.egui_ctx.run(raw_input, run_ui); let needs_repaint = egui_output.needs_repaint; let textures_delta = self .egui_winit .handle_output(window, &self.egui_ctx, egui_output); self.shapes = shapes; self.textures_delta.append(textures_delta); needs_repaint } /// Paint the results of the last call to [`Self::run`]. pub fn paint( &mut self, gl_window: &glutin::WindowedContext<glutin::PossiblyCurrent>, gl: &glow::Context, ) { let shapes = std::mem::take(&mut self.shapes); let mut textures_delta = std::mem::take(&mut self.textures_delta); for (id, image) in textures_delta.set { self.painter.set_texture(gl, id, &image); } let clipped_meshes = self.egui_ctx.tessellate(shapes); let dimensions: [u32; 2] = gl_window.window().inner_size().into(); self.painter.paint_meshes( gl, dimensions, self.egui_ctx.pixels_per_point(), clipped_meshes, ); for id in textures_delta.free.drain(..) { self.painter.free_texture(gl, id); } } /// Call to release the allocated graphics resources. pub fn destroy(&mut self, gl: &glow::Context) { self.painter.destroy(gl); } }
31.497512
109
0.650134
ccf564408461b11c0e5a0b5780367f5727dd0dfb
79,204
use crate::msgs::enums::{ProtocolVersion, HandshakeType}; use crate::msgs::enums::{CipherSuite, Compression, ExtensionType, ECPointFormat}; use crate::msgs::enums::{HashAlgorithm, SignatureAlgorithm, ServerNameType}; use crate::msgs::enums::{SignatureScheme, KeyUpdateRequest, NamedGroup}; use crate::msgs::enums::{ClientCertificateType, CertificateStatusType, CachedInformationType}; use crate::msgs::enums::ECCurveType; use crate::msgs::enums::PSKKeyExchangeMode; use crate::msgs::base::{Payload, PayloadU8, PayloadU16, PayloadU24}; use crate::msgs::codec; use crate::msgs::codec::{Codec, Reader}; use crate::key; #[cfg(feature = "logging")] use crate::log::warn; use std::fmt; use std::io::Write; use std::collections; use std::mem; use webpki; macro_rules! declare_u8_vec( ($name:ident, $itemtype:ty) => { pub type $name = Vec<$itemtype>; impl Codec for $name { fn encode(&self, bytes: &mut Vec<u8>) { codec::encode_vec_u8(bytes, self); } fn read(r: &mut Reader) -> Option<$name> { codec::read_vec_u8::<$itemtype>(r) } } } ); macro_rules! declare_u16_vec( ($name:ident, $itemtype:ty) => { pub type $name = Vec<$itemtype>; impl Codec for $name { fn encode(&self, bytes: &mut Vec<u8>) { codec::encode_vec_u16(bytes, self); } fn read(r: &mut Reader) -> Option<$name> { codec::read_vec_u16::<$itemtype>(r) } } } ); declare_u16_vec!(VecU16OfPayloadU8, PayloadU8); declare_u16_vec!(VecU16OfPayloadU16, PayloadU16); #[derive(Debug, PartialEq, Clone)] pub struct Random([u8; 32]); static HELLO_RETRY_REQUEST_RANDOM: Random = Random([ 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c, ]); static ZERO_RANDOM: Random = Random([0u8; 32]); impl Codec for Random { fn encode(&self, bytes: &mut Vec<u8>) { bytes.extend_from_slice(&self.0); } fn read(r: &mut Reader) -> Option<Random> { let bytes = r.take(32)?; let mut opaque = [0; 32]; opaque.clone_from_slice(bytes); Some(Random(opaque)) } } impl Random { pub fn from_slice(bytes: &[u8]) -> Random { let mut rd = Reader::init(bytes); Random::read(&mut rd).unwrap() } pub fn write_slice(&self, mut bytes: &mut [u8]) { let buf = self.get_encoding(); bytes.write_all(&buf).unwrap(); } } #[derive(Copy, Clone)] pub struct SessionID { len: usize, data: [u8; 32], } impl fmt::Debug for SessionID { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut t = f.debug_tuple("SessionID"); for i in 0..self.len() { t.field(&self.data[i]); } t.finish() } } impl PartialEq for SessionID { fn eq(&self, other: &Self) -> bool { if self.len != other.len { return false; } let mut diff = 0u8; for i in 0..self.len { diff |= self.data[i] ^ other.data[i] } diff == 0u8 } } impl Codec for SessionID { fn encode(&self, bytes: &mut Vec<u8>) { debug_assert!(self.len <= 32); bytes.push(self.len as u8); bytes.extend_from_slice(&self.data[..self.len]); } fn read(r: &mut Reader) -> Option<SessionID> { let len = u8::read(r)? as usize; if len > 32 { return None; } let bytes = r.take(len)?; let mut out = [0u8; 32]; out[..len].clone_from_slice(&bytes[..len]); Some(SessionID { data: out, len, }) } } impl SessionID { pub fn new(bytes: &[u8]) -> SessionID { debug_assert!(bytes.len() <= 32); let mut d = [0u8; 32]; d[..bytes.len()].clone_from_slice(&bytes[..]); SessionID { data: d, len: bytes.len(), } } pub fn empty() -> SessionID { SessionID { data: [0u8; 32], len: 0, } } pub fn len(&self) -> usize { self.len } pub fn is_empty(&self) -> bool { self.len == 0 } } #[derive(Clone, Debug)] pub struct UnknownExtension { pub typ: ExtensionType, pub payload: Payload, } impl UnknownExtension { fn encode(&self, bytes: &mut Vec<u8>) { self.payload.encode(bytes); } fn read(typ: ExtensionType, r: &mut Reader) -> Option<UnknownExtension> { let payload = Payload::read(r)?; Some(UnknownExtension { typ, payload, }) } } declare_u8_vec!(ECPointFormatList, ECPointFormat); pub trait SupportedPointFormats { fn supported() -> ECPointFormatList; } impl SupportedPointFormats for ECPointFormatList { fn supported() -> ECPointFormatList { vec![ECPointFormat::Uncompressed] } } declare_u16_vec!(NamedGroups, NamedGroup); declare_u16_vec!(SupportedSignatureSchemes, SignatureScheme); pub trait DecomposedSignatureScheme { fn sign(&self) -> SignatureAlgorithm; fn make(alg: SignatureAlgorithm, hash: HashAlgorithm) -> SignatureScheme; } impl DecomposedSignatureScheme for SignatureScheme { fn sign(&self) -> SignatureAlgorithm { match *self { SignatureScheme::RSA_PKCS1_SHA1 | SignatureScheme::RSA_PKCS1_SHA256 | SignatureScheme::RSA_PKCS1_SHA384 | SignatureScheme::RSA_PKCS1_SHA512 | SignatureScheme::RSA_PSS_SHA256 | SignatureScheme::RSA_PSS_SHA384 | SignatureScheme::RSA_PSS_SHA512 => SignatureAlgorithm::RSA, SignatureScheme::ECDSA_NISTP256_SHA256 | SignatureScheme::ECDSA_NISTP384_SHA384 | SignatureScheme::ECDSA_NISTP521_SHA512 => SignatureAlgorithm::ECDSA, _ => SignatureAlgorithm::Unknown(0), } } fn make(alg: SignatureAlgorithm, hash: HashAlgorithm) -> SignatureScheme { use crate::msgs::enums::SignatureAlgorithm::{RSA, ECDSA}; use crate::msgs::enums::HashAlgorithm::{SHA1, SHA256, SHA384, SHA512}; match (alg, hash) { (RSA, SHA1) => SignatureScheme::RSA_PKCS1_SHA1, (RSA, SHA256) => SignatureScheme::RSA_PKCS1_SHA256, (RSA, SHA384) => SignatureScheme::RSA_PKCS1_SHA384, (RSA, SHA512) => SignatureScheme::RSA_PKCS1_SHA512, (ECDSA, SHA256) => SignatureScheme::ECDSA_NISTP256_SHA256, (ECDSA, SHA384) => SignatureScheme::ECDSA_NISTP384_SHA384, (ECDSA, SHA512) => SignatureScheme::ECDSA_NISTP521_SHA512, (_, _) => unreachable!(), } } } #[derive(Clone, Debug)] pub enum ServerNamePayload { HostName(webpki::DNSName), Unknown(Payload), } impl ServerNamePayload { fn read_hostname(r: &mut Reader) -> Option<ServerNamePayload> { let len = u16::read(r)? as usize; let name = r.take(len)?; let dns_name = match webpki::DNSNameRef::try_from_ascii(name) { Ok(dns_name) => dns_name, Err(_) => { warn!("Illegal SNI hostname received {:?}", name); return None; } }; Some(ServerNamePayload::HostName(dns_name.into())) } fn encode_hostname(name: webpki::DNSNameRef, bytes: &mut Vec<u8>) { let dns_name_str: &str = name.into(); (dns_name_str.len() as u16).encode(bytes); bytes.extend_from_slice(dns_name_str.as_bytes()); } fn encode(&self, bytes: &mut Vec<u8>) { match *self { ServerNamePayload::HostName(ref r) => ServerNamePayload::encode_hostname(r.as_ref(), bytes), ServerNamePayload::Unknown(ref r) => r.encode(bytes), } } } #[derive(Clone, Debug)] pub struct ServerName { pub typ: ServerNameType, pub payload: ServerNamePayload, } impl Codec for ServerName { fn encode(&self, bytes: &mut Vec<u8>) { self.typ.encode(bytes); self.payload.encode(bytes); } fn read(r: &mut Reader) -> Option<ServerName> { let typ = ServerNameType::read(r)?; let payload = match typ { ServerNameType::HostName => ServerNamePayload::read_hostname(r)?, _ => ServerNamePayload::Unknown(Payload::read(r).unwrap()), }; Some(ServerName { typ, payload, }) } } declare_u16_vec!(ServerNameRequest, ServerName); pub trait ConvertServerNameList { fn has_duplicate_names_for_type(&self) -> bool; fn get_single_hostname(&self) -> Option<webpki::DNSNameRef>; } impl ConvertServerNameList for ServerNameRequest { /// RFC6066: "The ServerNameList MUST NOT contain more than one name of the same name_type." fn has_duplicate_names_for_type(&self) -> bool { let mut seen = collections::HashSet::new(); for name in self { if !seen.insert(name.typ.get_u8()) { return true; } } false } fn get_single_hostname(&self) -> Option<webpki::DNSNameRef> { fn only_dns_hostnames(name: &ServerName) -> Option<webpki::DNSNameRef> { if let ServerNamePayload::HostName(ref dns) = name.payload { Some(dns.as_ref()) } else { None } } self.iter() .filter_map(only_dns_hostnames) .nth(0) } } pub type ProtocolNameList = VecU16OfPayloadU8; pub trait ConvertProtocolNameList { fn from_slices(names: &[&[u8]]) -> Self; fn to_slices(&self) -> Vec<&[u8]>; fn as_single_slice(&self) -> Option<&[u8]>; } impl ConvertProtocolNameList for ProtocolNameList { fn from_slices(names: &[&[u8]]) -> ProtocolNameList { let mut ret = Vec::new(); for name in names { ret.push(PayloadU8::new(name.to_vec())); } ret } fn to_slices(&self) -> Vec<&[u8]> { self.iter() .map(|proto| -> &[u8] { &proto.0 }) .collect::<Vec<&[u8]>>() } fn as_single_slice(&self) -> Option<&[u8]> { if self.len() == 1 { Some(&self[0].0) } else { None } } } // --- TLS 1.3 Key shares --- #[derive(Clone, Debug)] pub struct KeyShareEntry { pub group: NamedGroup, pub payload: PayloadU16, } impl KeyShareEntry { pub fn new(group: NamedGroup, payload: &[u8]) -> KeyShareEntry { KeyShareEntry { group, payload: PayloadU16::new(payload.to_vec()), } } } impl Codec for KeyShareEntry { fn encode(&self, bytes: &mut Vec<u8>) { self.group.encode(bytes); self.payload.encode(bytes); } fn read(r: &mut Reader) -> Option<KeyShareEntry> { let group = NamedGroup::read(r)?; let payload = PayloadU16::read(r)?; Some(KeyShareEntry { group, payload, }) } } // --- TLS 1.3 PresharedKey offers --- #[derive(Clone, Debug)] pub struct PresharedKeyIdentity { pub identity: PayloadU16, pub obfuscated_ticket_age: u32, } impl PresharedKeyIdentity { pub fn new(id: Vec<u8>, age: u32) -> PresharedKeyIdentity { PresharedKeyIdentity { identity: PayloadU16::new(id), obfuscated_ticket_age: age, } } } impl Codec for PresharedKeyIdentity { fn encode(&self, bytes: &mut Vec<u8>) { self.identity.encode(bytes); self.obfuscated_ticket_age.encode(bytes); } fn read(r: &mut Reader) -> Option<PresharedKeyIdentity> { Some(PresharedKeyIdentity { identity: PayloadU16::read(r)?, obfuscated_ticket_age: u32::read(r)?, }) } } declare_u16_vec!(PresharedKeyIdentities, PresharedKeyIdentity); pub type PresharedKeyBinder = PayloadU8; pub type PresharedKeyBinders = VecU16OfPayloadU8; #[derive(Clone, Debug)] pub struct PresharedKeyOffer { pub identities: PresharedKeyIdentities, pub binders: PresharedKeyBinders, } impl PresharedKeyOffer { /// Make a new one with one entry. pub fn new(id: PresharedKeyIdentity, binder: Vec<u8>) -> PresharedKeyOffer { PresharedKeyOffer { identities: vec![ id ], binders: vec![ PresharedKeyBinder::new(binder) ], } } } impl Codec for PresharedKeyOffer { fn encode(&self, bytes: &mut Vec<u8>) { self.identities.encode(bytes); self.binders.encode(bytes); } fn read(r: &mut Reader) -> Option<PresharedKeyOffer> { Some(PresharedKeyOffer { identities: PresharedKeyIdentities::read(r)?, binders: PresharedKeyBinders::read(r)?, }) } } // --- RFC6066 certificate status request --- type ResponderIDs = VecU16OfPayloadU16; #[derive(Clone, Debug)] pub struct OCSPCertificateStatusRequest { pub responder_ids: ResponderIDs, pub extensions: PayloadU16, } impl Codec for OCSPCertificateStatusRequest { fn encode(&self, bytes: &mut Vec<u8>) { CertificateStatusType::OCSP.encode(bytes); self.responder_ids.encode(bytes); self.extensions.encode(bytes); } fn read(r: &mut Reader) -> Option<OCSPCertificateStatusRequest> { Some(OCSPCertificateStatusRequest { responder_ids: ResponderIDs::read(r)?, extensions: PayloadU16::read(r)?, }) } } #[derive(Clone, Debug)] pub enum CertificateStatusRequest { OCSP(OCSPCertificateStatusRequest), Unknown((CertificateStatusType, Payload)) } impl Codec for CertificateStatusRequest { fn encode(&self, bytes: &mut Vec<u8>) { match *self { CertificateStatusRequest::OCSP(ref r) => r.encode(bytes), CertificateStatusRequest::Unknown((typ, ref payload)) => { typ.encode(bytes); payload.encode(bytes); } } } fn read(r: &mut Reader) -> Option<CertificateStatusRequest> { let typ = CertificateStatusType::read(r)?; match typ { CertificateStatusType::OCSP => { let ocsp_req = OCSPCertificateStatusRequest::read(r)?; Some(CertificateStatusRequest::OCSP(ocsp_req)) } _ => { let data = Payload::read(r)?; Some(CertificateStatusRequest::Unknown((typ, data))) } } } } impl CertificateStatusRequest { pub fn build_ocsp() -> CertificateStatusRequest { let ocsp = OCSPCertificateStatusRequest { responder_ids: ResponderIDs::new(), extensions: PayloadU16::empty(), }; CertificateStatusRequest::OCSP(ocsp) } } // --- // SCTs pub type SCTList = VecU16OfPayloadU16; // --- declare_u8_vec!(PSKKeyExchangeModes, PSKKeyExchangeMode); declare_u16_vec!(KeyShareEntries, KeyShareEntry); declare_u8_vec!(ProtocolVersions, ProtocolVersion); /// https://tools.ietf.org/html/rfc7924#section-3 #[derive(Clone, Debug)] pub struct CachedObject { pub typ: CachedInformationType, pub hash_value: PayloadU8, } impl Codec for CachedObject { fn encode(&self, bytes: &mut Vec<u8>) { self.typ.encode(bytes); self.hash_value.encode(bytes); } fn read(r: &mut Reader) -> Option<Self> { let typ = CachedInformationType::read(r)?; let hash_value = PayloadU8::read(r)?; Some(CachedObject {typ, hash_value}) } } declare_u16_vec!(CachedInfo, CachedObject); declare_u16_vec!(CachedInfoTypes, CachedInformationType); #[derive(Clone, Debug)] pub struct ProactiveCiphertextOffer { pub certificate_hash: PayloadU8, pub ciphertext: PayloadU16, } impl Codec for ProactiveCiphertextOffer { fn encode(&self, bytes: &mut Vec<u8>) { self.certificate_hash.encode(bytes); self.ciphertext.encode(bytes); } fn read(r: &mut Reader) -> Option<Self> { let certificate_hash = PayloadU8::read(r)?; let ciphertext = PayloadU16::read(r)?; Some(ProactiveCiphertextOffer { certificate_hash, ciphertext }) } } #[derive(Clone, Debug)] pub enum ClientExtension { ECPointFormats(ECPointFormatList), NamedGroups(NamedGroups), SignatureAlgorithms(SupportedSignatureSchemes), ServerName(ServerNameRequest), SessionTicketRequest, SessionTicketOffer(Payload), Protocols(ProtocolNameList), SupportedVersions(ProtocolVersions), KeyShare(KeyShareEntries), PresharedKeyModes(PSKKeyExchangeModes), PresharedKey(PresharedKeyOffer), Cookie(PayloadU16), ExtendedMasterSecretRequest, CertificateStatusRequest(CertificateStatusRequest), SignedCertificateTimestampRequest, TransportParameters(Vec<u8>), EarlyData, Unknown(UnknownExtension), CachedInformation(CachedInfo), ProactiveCiphertext(ProactiveCiphertextOffer), ProactiveClientAuth, } impl ClientExtension { pub fn get_type(&self) -> ExtensionType { match *self { ClientExtension::ECPointFormats(_) => ExtensionType::ECPointFormats, ClientExtension::NamedGroups(_) => ExtensionType::EllipticCurves, ClientExtension::SignatureAlgorithms(_) => ExtensionType::SignatureAlgorithms, ClientExtension::ServerName(_) => ExtensionType::ServerName, ClientExtension::SessionTicketRequest | ClientExtension::SessionTicketOffer(_) => ExtensionType::SessionTicket, ClientExtension::Protocols(_) => ExtensionType::ALProtocolNegotiation, ClientExtension::SupportedVersions(_) => ExtensionType::SupportedVersions, ClientExtension::KeyShare(_) => ExtensionType::KeyShare, ClientExtension::PresharedKeyModes(_) => ExtensionType::PSKKeyExchangeModes, ClientExtension::PresharedKey(_) => ExtensionType::PreSharedKey, ClientExtension::Cookie(_) => ExtensionType::Cookie, ClientExtension::ExtendedMasterSecretRequest => ExtensionType::ExtendedMasterSecret, ClientExtension::CertificateStatusRequest(_) => ExtensionType::StatusRequest, ClientExtension::SignedCertificateTimestampRequest => ExtensionType::SCT, ClientExtension::TransportParameters(_) => ExtensionType::TransportParameters, ClientExtension::EarlyData => ExtensionType::EarlyData, ClientExtension::CachedInformation(_) => ExtensionType::CachedInformation, ClientExtension::ProactiveCiphertext(_) => ExtensionType::ProactiveCiphertext, ClientExtension::ProactiveClientAuth => ExtensionType::ProactiveClientAuth, ClientExtension::Unknown(ref r) => r.typ, } } } impl Codec for ClientExtension { fn encode(&self, bytes: &mut Vec<u8>) { self.get_type().encode(bytes); let mut sub: Vec<u8> = Vec::new(); match *self { ClientExtension::ECPointFormats(ref r) => r.encode(&mut sub), ClientExtension::NamedGroups(ref r) => r.encode(&mut sub), ClientExtension::SignatureAlgorithms(ref r) => r.encode(&mut sub), ClientExtension::ServerName(ref r) => r.encode(&mut sub), ClientExtension::SessionTicketRequest | ClientExtension::ExtendedMasterSecretRequest | ClientExtension::SignedCertificateTimestampRequest | ClientExtension::ProactiveClientAuth | ClientExtension::EarlyData => (), ClientExtension::SessionTicketOffer(ref r) => r.encode(&mut sub), ClientExtension::Protocols(ref r) => r.encode(&mut sub), ClientExtension::SupportedVersions(ref r) => r.encode(&mut sub), ClientExtension::KeyShare(ref r) => r.encode(&mut sub), ClientExtension::PresharedKeyModes(ref r) => r.encode(&mut sub), ClientExtension::PresharedKey(ref r) => r.encode(&mut sub), ClientExtension::Cookie(ref r) => r.encode(&mut sub), ClientExtension::CertificateStatusRequest(ref r) => r.encode(&mut sub), ClientExtension::TransportParameters(ref r) => sub.extend_from_slice(r), ClientExtension::Unknown(ref r) => r.encode(&mut sub), ClientExtension::CachedInformation(ref obj) => obj.encode(&mut sub), ClientExtension::ProactiveCiphertext(ref r) => r.encode(&mut sub), } (sub.len() as u16).encode(bytes); bytes.append(&mut sub); } fn read(r: &mut Reader) -> Option<ClientExtension> { let typ = ExtensionType::read(r)?; let len = u16::read(r)? as usize; let mut sub = r.sub(len)?; Some(match typ { ExtensionType::ECPointFormats => { ClientExtension::ECPointFormats(ECPointFormatList::read(&mut sub)?) } ExtensionType::EllipticCurves => { ClientExtension::NamedGroups(NamedGroups::read(&mut sub)?) } ExtensionType::SignatureAlgorithms => { let schemes = SupportedSignatureSchemes::read(&mut sub)?; ClientExtension::SignatureAlgorithms(schemes) } ExtensionType::ServerName => { ClientExtension::ServerName(ServerNameRequest::read(&mut sub)?) } ExtensionType::SessionTicket => { if sub.any_left() { let contents = Payload::read(&mut sub).unwrap(); ClientExtension::SessionTicketOffer(contents) } else { ClientExtension::SessionTicketRequest } } ExtensionType::ALProtocolNegotiation => { ClientExtension::Protocols(ProtocolNameList::read(&mut sub)?) } ExtensionType::SupportedVersions => { ClientExtension::SupportedVersions(ProtocolVersions::read(&mut sub)?) } ExtensionType::KeyShare => { ClientExtension::KeyShare(KeyShareEntries::read(&mut sub)?) } ExtensionType::PSKKeyExchangeModes => { ClientExtension::PresharedKeyModes(PSKKeyExchangeModes::read(&mut sub)?) } ExtensionType::PreSharedKey => { ClientExtension::PresharedKey(PresharedKeyOffer::read(&mut sub)?) } ExtensionType::Cookie => ClientExtension::Cookie(PayloadU16::read(&mut sub)?), ExtensionType::ExtendedMasterSecret if !sub.any_left() => { ClientExtension::ExtendedMasterSecretRequest } ExtensionType::StatusRequest => { let csr = CertificateStatusRequest::read(&mut sub)?; ClientExtension::CertificateStatusRequest(csr) } ExtensionType::SCT if !sub.any_left() => { ClientExtension::SignedCertificateTimestampRequest } ExtensionType::TransportParameters => { ClientExtension::TransportParameters(sub.rest().to_vec()) }, ExtensionType::ProactiveCiphertext => { ClientExtension::ProactiveCiphertext(ProactiveCiphertextOffer::read(&mut sub)?) } ExtensionType::EarlyData if !sub.any_left() => { ClientExtension::EarlyData }, ExtensionType::ProactiveClientAuth if !sub.any_left() => { ClientExtension::ProactiveClientAuth }, ExtensionType::CachedInformation => ClientExtension::CachedInformation(CachedInfo::read(&mut sub)?), _ => ClientExtension::Unknown(UnknownExtension::read(typ, &mut sub)?), }) } } fn trim_hostname_trailing_dot_for_sni(dns_name: webpki::DNSNameRef) -> webpki::DNSName { let dns_name_str: &str = dns_name.into(); // RFC6066: "The hostname is represented as a byte string using // ASCII encoding without a trailing dot" if dns_name_str.ends_with('.') { let trimmed = &dns_name_str[0..dns_name_str.len()-1]; webpki::DNSNameRef::try_from_ascii_str(trimmed) .unwrap() .to_owned() } else { dns_name.to_owned() } } impl ClientExtension { /// Make a basic SNI ServerNameRequest quoting `hostname`. pub fn make_sni(dns_name: webpki::DNSNameRef) -> ClientExtension { let name = ServerName { typ: ServerNameType::HostName, payload: ServerNamePayload::HostName( trim_hostname_trailing_dot_for_sni(dns_name)), }; ClientExtension::ServerName(vec![ name ]) } /// Mark a cached certificate /// see https://tools.ietf.org/html/rfc7924#section-3 pub fn make_cached_certs(certs: &[key::Certificate]) -> ClientExtension { let mut objs = Vec::with_capacity(certs.len()); for hash_value in certs.iter().map(|crt| crt.hash()) { let typ = CachedInformationType::Cert; let hash_value = PayloadU8::new(hash_value); objs.push(CachedObject { typ, hash_value }) } ClientExtension::CachedInformation(objs) } // KEMTLS-PDK proactively encapsulate // XXX this doesn't do proper validation of the certificate so anything in the cache is trusted // Also this doesn't account for any of the settings of the client or server in regards to acceptable algorithms pub fn make_proactive_ciphertext(certs: &[key::Certificate], hostname: webpki::DNSNameRef) -> Option<(ClientExtension, oqs::kem::SharedSecret)> { for cert in certs.iter() { let eecert = webpki::EndEntityCert::from(&cert.0); if let Ok(eecert) = eecert { if eecert.is_kem_cert() && eecert.verify_is_valid_for_dns_name(hostname).is_ok() { let (ct, ss) = eecert.encapsulate().ok()?; return Some( (ClientExtension::ProactiveCiphertext( ProactiveCiphertextOffer { certificate_hash: PayloadU8::new(cert.hash()), ciphertext: PayloadU16::new(ct.as_ref().to_vec()) } ), ss)); } } } None } } #[derive(Clone, Debug)] pub enum ServerExtension { ECPointFormats(ECPointFormatList), ServerNameAck, SessionTicketAck, RenegotiationInfo(PayloadU8), Protocols(ProtocolNameList), KeyShare(KeyShareEntry), PresharedKey(u16), ExtendedMasterSecretAck, CertificateStatusAck, SignedCertificateTimestamp(SCTList), SupportedVersions(ProtocolVersion), TransportParameters(Vec<u8>), EarlyData, ProactiveCiphertextAccepted(PayloadU8), CachedInformation(CachedInfoTypes), Unknown(UnknownExtension), } impl ServerExtension { pub fn get_type(&self) -> ExtensionType { match *self { ServerExtension::ECPointFormats(_) => ExtensionType::ECPointFormats, ServerExtension::ServerNameAck => ExtensionType::ServerName, ServerExtension::SessionTicketAck => ExtensionType::SessionTicket, ServerExtension::RenegotiationInfo(_) => ExtensionType::RenegotiationInfo, ServerExtension::Protocols(_) => ExtensionType::ALProtocolNegotiation, ServerExtension::KeyShare(_) => ExtensionType::KeyShare, ServerExtension::PresharedKey(_) => ExtensionType::PreSharedKey, ServerExtension::ExtendedMasterSecretAck => ExtensionType::ExtendedMasterSecret, ServerExtension::CertificateStatusAck => ExtensionType::StatusRequest, ServerExtension::SignedCertificateTimestamp(_) => ExtensionType::SCT, ServerExtension::SupportedVersions(_) => ExtensionType::SupportedVersions, ServerExtension::TransportParameters(_) => ExtensionType::TransportParameters, ServerExtension::EarlyData => ExtensionType::EarlyData, ServerExtension::Unknown(ref r) => r.typ, ServerExtension::CachedInformation(_) => ExtensionType::CachedInformation, ServerExtension::ProactiveCiphertextAccepted(_) => ExtensionType::ProactiveCiphertext, } } } impl Codec for ServerExtension { fn encode(&self, bytes: &mut Vec<u8>) { self.get_type().encode(bytes); let mut sub: Vec<u8> = Vec::new(); match *self { ServerExtension::ECPointFormats(ref r) => r.encode(&mut sub), ServerExtension::ServerNameAck | ServerExtension::SessionTicketAck | ServerExtension::ExtendedMasterSecretAck | ServerExtension::CertificateStatusAck | ServerExtension::EarlyData => (), ServerExtension::RenegotiationInfo(ref r) => r.encode(&mut sub), ServerExtension::Protocols(ref r) => r.encode(&mut sub), ServerExtension::KeyShare(ref r) => r.encode(&mut sub), ServerExtension::PresharedKey(r) => r.encode(&mut sub), ServerExtension::SignedCertificateTimestamp(ref r) => r.encode(&mut sub), ServerExtension::SupportedVersions(ref r) => r.encode(&mut sub), ServerExtension::TransportParameters(ref r) => sub.extend_from_slice(r), ServerExtension::CachedInformation(ref r) => r.encode(&mut sub), ServerExtension::ProactiveCiphertextAccepted(ref r) => r.encode(&mut sub), ServerExtension::Unknown(ref r) => r.encode(&mut sub), } (sub.len() as u16).encode(bytes); bytes.append(&mut sub); } fn read(r: &mut Reader) -> Option<ServerExtension> { let typ = ExtensionType::read(r)?; let len = u16::read(r)? as usize; let mut sub = r.sub(len)?; Some(match typ { ExtensionType::ECPointFormats => { ServerExtension::ECPointFormats(ECPointFormatList::read(&mut sub)?) } ExtensionType::ServerName => ServerExtension::ServerNameAck, ExtensionType::SessionTicket => ServerExtension::SessionTicketAck, ExtensionType::StatusRequest => ServerExtension::CertificateStatusAck, ExtensionType::RenegotiationInfo => { ServerExtension::RenegotiationInfo(PayloadU8::read(&mut sub)?) } ExtensionType::ALProtocolNegotiation => { ServerExtension::Protocols(ProtocolNameList::read(&mut sub)?) } ExtensionType::KeyShare => { ServerExtension::KeyShare(KeyShareEntry::read(&mut sub)?) } ExtensionType::PreSharedKey => { ServerExtension::PresharedKey(u16::read(&mut sub)?) } ExtensionType::ExtendedMasterSecret => ServerExtension::ExtendedMasterSecretAck, ExtensionType::SCT => { let scts = SCTList::read(&mut sub)?; ServerExtension::SignedCertificateTimestamp(scts) } ExtensionType::SupportedVersions => { ServerExtension::SupportedVersions(ProtocolVersion::read(&mut sub)?) } ExtensionType::TransportParameters => { ServerExtension::TransportParameters(sub.rest().to_vec()) }, ExtensionType::CachedInformation => ServerExtension::CachedInformation(CachedInfoTypes::read(&mut sub)?), ExtensionType::ProactiveCiphertext => ServerExtension::ProactiveCiphertextAccepted(PayloadU8::read(&mut sub)?), ExtensionType::EarlyData => ServerExtension::EarlyData, _ => ServerExtension::Unknown(UnknownExtension::read(typ, &mut sub)?), }) } } impl ServerExtension { pub fn make_alpn(proto: &[&[u8]]) -> ServerExtension { ServerExtension::Protocols(ProtocolNameList::from_slices(proto)) } pub fn make_empty_renegotiation_info() -> ServerExtension { let empty = Vec::new(); ServerExtension::RenegotiationInfo(PayloadU8::new(empty)) } pub fn make_sct(sctl: Vec<u8>) -> ServerExtension { let scts = SCTList::read_bytes(&sctl) .expect("invalid SCT list"); ServerExtension::SignedCertificateTimestamp(scts) } } #[derive(Debug, Clone)] pub struct ClientHelloPayload { pub client_version: ProtocolVersion, pub random: Random, pub session_id: SessionID, pub cipher_suites: Vec<CipherSuite>, pub compression_methods: Vec<Compression>, pub extensions: Vec<ClientExtension>, } impl Codec for ClientHelloPayload { fn encode(&self, bytes: &mut Vec<u8>) { self.client_version.encode(bytes); self.random.encode(bytes); self.session_id.encode(bytes); codec::encode_vec_u16(bytes, &self.cipher_suites); codec::encode_vec_u8(bytes, &self.compression_methods); if !self.extensions.is_empty() { codec::encode_vec_u16(bytes, &self.extensions); } } fn read(r: &mut Reader) -> Option<ClientHelloPayload> { let mut ret = ClientHelloPayload { client_version: ProtocolVersion::read(r)?, random: Random::read(r)?, session_id: SessionID::read(r)?, cipher_suites: codec::read_vec_u16::<CipherSuite>(r)?, compression_methods: codec::read_vec_u8::<Compression>(r)?, extensions: Vec::new(), }; if r.any_left() { ret.extensions = codec::read_vec_u16::<ClientExtension>(r)?; } Some(ret) } } impl ClientHelloPayload { /// Returns true if there is more than one extension of a given /// type. pub fn has_duplicate_extension(&self) -> bool { let mut seen = collections::HashSet::new(); for ext in &self.extensions { let typ = ext.get_type().get_u16(); if seen.contains(&typ) { return true; } seen.insert(typ); } false } pub fn find_extension(&self, ext: ExtensionType) -> Option<&ClientExtension> { self.extensions.iter().find(|x| x.get_type() == ext) } pub fn get_sni_extension(&self) -> Option<&ServerNameRequest> { let ext = self.find_extension(ExtensionType::ServerName)?; match *ext { ClientExtension::ServerName(ref req) => Some(req), _ => None, } } pub fn get_sigalgs_extension(&self) -> Option<&SupportedSignatureSchemes> { let ext = self.find_extension(ExtensionType::SignatureAlgorithms)?; match *ext { ClientExtension::SignatureAlgorithms(ref req) => Some(req), _ => None, } } pub fn get_namedgroups_extension(&self) -> Option<&NamedGroups> { let ext = self.find_extension(ExtensionType::EllipticCurves)?; match *ext { ClientExtension::NamedGroups(ref req) => Some(req), _ => None, } } pub fn get_ecpoints_extension(&self) -> Option<&ECPointFormatList> { let ext = self.find_extension(ExtensionType::ECPointFormats)?; match *ext { ClientExtension::ECPointFormats(ref req) => Some(req), _ => None, } } pub fn get_alpn_extension(&self) -> Option<&ProtocolNameList> { let ext = self.find_extension(ExtensionType::ALProtocolNegotiation)?; match *ext { ClientExtension::Protocols(ref req) => Some(req), _ => None, } } pub fn get_quic_params_extension(&self) -> Option<Vec<u8>> { let ext = self.find_extension(ExtensionType::TransportParameters)?; match *ext { ClientExtension::TransportParameters(ref bytes) => Some(bytes.to_vec()), _ => None, } } pub fn get_ticket_extension(&self) -> Option<&ClientExtension> { self.find_extension(ExtensionType::SessionTicket) } pub fn get_versions_extension(&self) -> Option<&ProtocolVersions> { let ext = self.find_extension(ExtensionType::SupportedVersions)?; match *ext { ClientExtension::SupportedVersions(ref vers) => Some(vers), _ => None, } } pub fn get_keyshare_extension(&self) -> Option<&KeyShareEntries> { let ext = self.find_extension(ExtensionType::KeyShare)?; match *ext { ClientExtension::KeyShare(ref shares) => Some(shares), _ => None, } } pub fn has_keyshare_extension_with_duplicates(&self) -> bool { let entries = self.get_keyshare_extension(); if entries.is_none() { return false; } let mut seen = collections::HashSet::new(); for kse in entries.unwrap() { let grp = kse.group.get_u16(); if seen.contains(&grp) { return true; } seen.insert(grp); } false } pub fn get_psk(&self) -> Option<&PresharedKeyOffer> { let ext = self.find_extension(ExtensionType::PreSharedKey)?; match *ext { ClientExtension::PresharedKey(ref psk) => Some(psk), _ => None, } } pub fn check_psk_ext_is_last(&self) -> bool { self.extensions .last() .map_or(false, |ext| ext.get_type() == ExtensionType::PreSharedKey) } pub fn get_psk_modes(&self) -> Option<&PSKKeyExchangeModes> { let ext = self.find_extension(ExtensionType::PSKKeyExchangeModes)?; match *ext { ClientExtension::PresharedKeyModes(ref psk_modes) => Some(psk_modes), _ => None, } } pub fn psk_mode_offered(&self, mode: PSKKeyExchangeMode) -> bool { self.get_psk_modes() .map(|modes| modes.contains(&mode)) .or(Some(false)) .unwrap() } pub fn set_psk_binder(&mut self, binder: Vec<u8>) { let last_extension = self.extensions.last_mut().unwrap(); if let ClientExtension::PresharedKey(ref mut offer) = *last_extension { offer.binders[0] = PresharedKeyBinder::new(binder); } } pub fn ems_support_offered(&self) -> bool { self.find_extension(ExtensionType::ExtendedMasterSecret) .is_some() } pub fn early_data_extension_offered(&self) -> bool { self.find_extension(ExtensionType::EarlyData).is_some() } pub fn cached_information(&self) -> Option<&Vec<CachedObject>> { self.find_extension(ExtensionType::CachedInformation) .and_then(|ext| { match ext { ClientExtension::CachedInformation(ref obj) => { Some(obj) }, _ => None, } }) } pub fn get_proactive_ciphertext(&self, cert: &key::Certificate) -> Option<&ProactiveCiphertextOffer> { self.find_extension(ExtensionType::ProactiveCiphertext) .and_then(|ext| { match ext { ClientExtension::ProactiveCiphertext(ref obj) if obj.certificate_hash.0 == cert.hash() => { Some(obj) }, _ => None, } }) } } #[derive(Debug)] pub enum HelloRetryExtension { KeyShare(NamedGroup), Cookie(PayloadU16), SupportedVersions(ProtocolVersion), Unknown(UnknownExtension), } impl HelloRetryExtension { pub fn get_type(&self) -> ExtensionType { match *self { HelloRetryExtension::KeyShare(_) => ExtensionType::KeyShare, HelloRetryExtension::Cookie(_) => ExtensionType::Cookie, HelloRetryExtension::SupportedVersions(_) => ExtensionType::SupportedVersions, HelloRetryExtension::Unknown(ref r) => r.typ, } } } impl Codec for HelloRetryExtension { fn encode(&self, bytes: &mut Vec<u8>) { self.get_type().encode(bytes); let mut sub: Vec<u8> = Vec::new(); match *self { HelloRetryExtension::KeyShare(ref r) => r.encode(&mut sub), HelloRetryExtension::Cookie(ref r) => r.encode(&mut sub), HelloRetryExtension::SupportedVersions(ref r) => r.encode(&mut sub), HelloRetryExtension::Unknown(ref r) => r.encode(&mut sub), } (sub.len() as u16).encode(bytes); bytes.append(&mut sub); } fn read(r: &mut Reader) -> Option<HelloRetryExtension> { let typ = ExtensionType::read(r)?; let len = u16::read(r)? as usize; let mut sub = r.sub(len)?; Some(match typ { ExtensionType::KeyShare => { HelloRetryExtension::KeyShare(NamedGroup::read(&mut sub)?) } ExtensionType::Cookie => { HelloRetryExtension::Cookie(PayloadU16::read(&mut sub)?) } ExtensionType::SupportedVersions => { HelloRetryExtension::SupportedVersions(ProtocolVersion::read(&mut sub)?) } _ => HelloRetryExtension::Unknown(UnknownExtension::read(typ, &mut sub)?), }) } } #[derive(Debug)] pub struct HelloRetryRequest { pub legacy_version: ProtocolVersion, pub session_id: SessionID, pub cipher_suite: CipherSuite, pub extensions: Vec<HelloRetryExtension>, } impl Codec for HelloRetryRequest { fn encode(&self, bytes: &mut Vec<u8>) { self.legacy_version.encode(bytes); HELLO_RETRY_REQUEST_RANDOM.encode(bytes); self.session_id.encode(bytes); self.cipher_suite.encode(bytes); Compression::Null.encode(bytes); codec::encode_vec_u16(bytes, &self.extensions); } fn read(r: &mut Reader) -> Option<HelloRetryRequest> { let session_id = SessionID::read(r)?; let cipher_suite = CipherSuite::read(r)?; let compression = Compression::read(r)?; if compression != Compression::Null { return None; } Some(HelloRetryRequest { legacy_version: ProtocolVersion::Unknown(0), session_id, cipher_suite, extensions: codec::read_vec_u16::<HelloRetryExtension>(r)?, }) } } impl HelloRetryRequest { /// Returns true if there is more than one extension of a given /// type. pub fn has_duplicate_extension(&self) -> bool { let mut seen = collections::HashSet::new(); for ext in &self.extensions { let typ = ext.get_type().get_u16(); if seen.contains(&typ) { return true; } seen.insert(typ); } false } pub fn has_unknown_extension(&self) -> bool { self.extensions .iter() .any(|ext| { ext.get_type() != ExtensionType::KeyShare && ext.get_type() != ExtensionType::SupportedVersions && ext.get_type() != ExtensionType::Cookie }) } fn find_extension(&self, ext: ExtensionType) -> Option<&HelloRetryExtension> { self.extensions.iter().find(|x| x.get_type() == ext) } pub fn get_requested_key_share_group(&self) -> Option<NamedGroup> { let ext = self.find_extension(ExtensionType::KeyShare)?; match *ext { HelloRetryExtension::KeyShare(grp) => Some(grp), _ => None, } } pub fn get_cookie(&self) -> Option<&PayloadU16> { let ext = self.find_extension(ExtensionType::Cookie)?; match *ext { HelloRetryExtension::Cookie(ref ck) => Some(ck), _ => None, } } pub fn get_supported_versions(&self) -> Option<ProtocolVersion> { let ext = self.find_extension(ExtensionType::SupportedVersions)?; match *ext { HelloRetryExtension::SupportedVersions(ver) => Some(ver), _ => None, } } } #[derive(Debug)] pub struct ServerHelloPayload { pub legacy_version: ProtocolVersion, pub random: Random, pub session_id: SessionID, pub cipher_suite: CipherSuite, pub compression_method: Compression, pub extensions: Vec<ServerExtension>, } impl Codec for ServerHelloPayload { fn encode(&self, bytes: &mut Vec<u8>) { self.legacy_version.encode(bytes); self.random.encode(bytes); self.session_id.encode(bytes); self.cipher_suite.encode(bytes); self.compression_method.encode(bytes); if !self.extensions.is_empty() { codec::encode_vec_u16(bytes, &self.extensions); } } // minus version and random, which have already been read. fn read(r: &mut Reader) -> Option<ServerHelloPayload> { let session_id = SessionID::read(r)?; let suite = CipherSuite::read(r)?; let compression = Compression::read(r)?; let mut ret = ServerHelloPayload { legacy_version: ProtocolVersion::Unknown(0), random: ZERO_RANDOM.clone(), session_id, cipher_suite: suite, compression_method: compression, extensions: Vec::new(), }; if r.any_left() { ret.extensions = codec::read_vec_u16::<ServerExtension>(r)?; } Some(ret) } } impl HasServerExtensions for ServerHelloPayload { fn get_extensions(&self) -> &[ServerExtension] { &self.extensions } } impl ServerHelloPayload { pub fn get_key_share(&self) -> Option<&KeyShareEntry> { let ext = self.find_extension(ExtensionType::KeyShare)?; match *ext { ServerExtension::KeyShare(ref share) => Some(share), _ => None, } } pub fn get_psk_index(&self) -> Option<u16> { let ext = self.find_extension(ExtensionType::PreSharedKey)?; match *ext { ServerExtension::PresharedKey(ref index) => Some(*index), _ => None, } } pub fn get_ecpoints_extension(&self) -> Option<&ECPointFormatList> { let ext = self.find_extension(ExtensionType::ECPointFormats)?; match *ext { ServerExtension::ECPointFormats(ref fmts) => Some(fmts), _ => None, } } pub fn ems_support_acked(&self) -> bool { self.find_extension(ExtensionType::ExtendedMasterSecret) .is_some() } pub fn get_sct_list(&self) -> Option<&SCTList> { let ext = self.find_extension(ExtensionType::SCT)?; match *ext { ServerExtension::SignedCertificateTimestamp(ref sctl) => Some(sctl), _ => None, } } pub fn get_supported_versions(&self) -> Option<ProtocolVersion> { let ext = self.find_extension(ExtensionType::SupportedVersions)?; match *ext { ServerExtension::SupportedVersions(vers) => Some(vers), _ => None, } } pub fn get_accepted_ciphertext(&self) -> Option<&PayloadU8> { let ext = self.find_extension(ExtensionType::ProactiveCiphertext)?; match ext { ServerExtension::ProactiveCiphertextAccepted(obj) => Some(obj), _ => None, } } } pub type CertificatePayload = Vec<key::Certificate>; impl Codec for CertificatePayload { fn encode(&self, bytes: &mut Vec<u8>) { codec::encode_vec_u24(bytes, self); } fn read(r: &mut Reader) -> Option<CertificatePayload> { // 64KB of certificates is plenty, 16MB is obviously silly // EXCEPT IS IT. codec::read_vec_u24_limited(r, 2usize.pow(20)) } } // TLS1.3 changes the Certificate payload encoding. // That's annoying. It means the parsing is not // context-free any more. #[derive(Debug, Clone)] pub enum CertificateExtension { CertificateStatus(CertificateStatus), SignedCertificateTimestamp(SCTList), Unknown(UnknownExtension), } impl CertificateExtension { pub fn get_type(&self) -> ExtensionType { match *self { CertificateExtension::CertificateStatus(_) => ExtensionType::StatusRequest, CertificateExtension::SignedCertificateTimestamp(_) => ExtensionType::SCT, CertificateExtension::Unknown(ref r) => r.typ, } } pub fn make_sct(sct_list: Vec<u8>) -> CertificateExtension { let sctl = SCTList::read_bytes(&sct_list) .expect("invalid SCT list"); CertificateExtension::SignedCertificateTimestamp(sctl) } pub fn get_cert_status(&self) -> Option<&Vec<u8>> { match *self { CertificateExtension::CertificateStatus(ref cs) => Some(&cs.ocsp_response.0), _ => None } } pub fn get_sct_list(&self) -> Option<&SCTList> { match *self { CertificateExtension::SignedCertificateTimestamp(ref sctl) => Some(sctl), _ => None } } } impl Codec for CertificateExtension { fn encode(&self, bytes: &mut Vec<u8>) { self.get_type().encode(bytes); let mut sub: Vec<u8> = Vec::new(); match *self { CertificateExtension::CertificateStatus(ref r) => r.encode(&mut sub), CertificateExtension::SignedCertificateTimestamp(ref r) => r.encode(&mut sub), CertificateExtension::Unknown(ref r) => r.encode(&mut sub), } (sub.len() as u16).encode(bytes); bytes.append(&mut sub); } fn read(r: &mut Reader) -> Option<CertificateExtension> { let typ = ExtensionType::read(r)?; let len = u16::read(r)? as usize; let mut sub = r.sub(len)?; Some(match typ { ExtensionType::StatusRequest => { let st = CertificateStatus::read(&mut sub)?; CertificateExtension::CertificateStatus(st) } ExtensionType::SCT => { let scts = SCTList::read(&mut sub)?; CertificateExtension::SignedCertificateTimestamp(scts) } _ => CertificateExtension::Unknown(UnknownExtension::read(typ, &mut sub)?), }) } } declare_u16_vec!(CertificateExtensions, CertificateExtension); #[derive(Debug, Clone)] pub struct CertificateEntry { pub cert: key::Certificate, pub exts: CertificateExtensions, } impl Codec for CertificateEntry { fn encode(&self, bytes: &mut Vec<u8>) { self.cert.encode(bytes); self.exts.encode(bytes); } fn read(r: &mut Reader) -> Option<CertificateEntry> { Some(CertificateEntry { cert: key::Certificate::read(r)?, exts: CertificateExtensions::read(r)?, }) } } impl CertificateEntry { pub fn new(cert: key::Certificate) -> CertificateEntry { CertificateEntry { cert, exts: Vec::new(), } } pub fn has_duplicate_extension(&self) -> bool { let mut seen = collections::HashSet::new(); for ext in &self.exts { let typ = ext.get_type().get_u16(); if seen.contains(&typ) { return true; } seen.insert(typ); } false } pub fn has_unknown_extension(&self) -> bool { self.exts .iter() .any(|ext| { ext.get_type() != ExtensionType::StatusRequest && ext.get_type() != ExtensionType::SCT }) } pub fn get_ocsp_response(&self) -> Option<&Vec<u8>> { self.exts .iter() .find(|ext| ext.get_type() == ExtensionType::StatusRequest) .and_then(CertificateExtension::get_cert_status) } pub fn get_scts(&self) -> Option<&SCTList> { self.exts .iter() .find(|ext| ext.get_type() == ExtensionType::SCT) .and_then(CertificateExtension::get_sct_list) } } #[derive(Debug, Clone)] pub struct CertificatePayloadTLS13 { pub context: PayloadU8, pub entries: Vec<CertificateEntry>, } impl Codec for CertificatePayloadTLS13 { fn encode(&self, bytes: &mut Vec<u8>) { self.context.encode(bytes); codec::encode_vec_u24(bytes, &self.entries); } fn read(r: &mut Reader) -> Option<CertificatePayloadTLS13> { Some(CertificatePayloadTLS13 { context: PayloadU8::read(r)?, entries: codec::read_vec_u24_limited::<CertificateEntry>(r, 2usize.pow(23))?, }) } } impl CertificatePayloadTLS13 { pub fn new(entries: Vec<CertificateEntry>) -> CertificatePayloadTLS13 { CertificatePayloadTLS13 { context: PayloadU8::empty(), entries, } } pub fn any_entry_has_duplicate_extension(&self) -> bool { for entry in &self.entries { if entry.has_duplicate_extension() { return true; } } false } pub fn any_entry_has_unknown_extension(&self) -> bool { for entry in &self.entries { if entry.has_unknown_extension() { return true; } } false } pub fn any_entry_has_extension(&self) -> bool { for entry in &self.entries { if !entry.exts.is_empty() { return true; } } false } pub fn get_end_entity_ocsp(&self) -> Vec<u8> { self.entries.first() .and_then(CertificateEntry::get_ocsp_response) .cloned() .unwrap_or_else( Vec::new) } pub fn get_end_entity_scts(&self) -> Option<SCTList> { self.entries.first() .and_then(CertificateEntry::get_scts) .cloned() } pub fn convert(&self) -> CertificatePayload { let mut ret = Vec::new(); for entry in &self.entries { ret.push(entry.cert.clone()); } ret } pub fn replace_cached_entries(&mut self, cached_certs: &[key::Certificate]) { let cached_certificate_hashes = cached_certs.iter().map(|crt| crt.hash()).collect::<Vec<_>>(); for entry in self.entries.iter_mut() { if let Some(pos) = cached_certificate_hashes.iter().position(|x| x == &entry.cert.0) { entry.cert = cached_certs[pos].clone(); } } } } #[derive(Debug)] pub enum KeyExchangeAlgorithm { BulkOnly, DH, DHE, RSA, ECDH, ECDHE, } // We don't support arbitrary curves. It's a terrible // idea and unnecessary attack surface. Please, // get a grip. #[derive(Debug)] pub struct ECParameters { pub curve_type: ECCurveType, pub named_group: NamedGroup, } impl Codec for ECParameters { fn encode(&self, bytes: &mut Vec<u8>) { self.curve_type.encode(bytes); self.named_group.encode(bytes); } fn read(r: &mut Reader) -> Option<ECParameters> { let ct = ECCurveType::read(r)?; if ct != ECCurveType::NamedCurve { return None; } let grp = NamedGroup::read(r)?; Some(ECParameters { curve_type: ct, named_group: grp, }) } } #[derive(Debug, Clone)] pub struct DigitallySignedStruct { pub scheme: SignatureScheme, pub sig: PayloadU16, } impl DigitallySignedStruct { pub fn new(scheme: SignatureScheme, sig: Vec<u8>) -> DigitallySignedStruct { DigitallySignedStruct { scheme, sig: PayloadU16::new(sig), } } } impl Codec for DigitallySignedStruct { fn encode(&self, bytes: &mut Vec<u8>) { self.scheme.encode(bytes); self.sig.encode(bytes); } fn read(r: &mut Reader) -> Option<DigitallySignedStruct> { let scheme = SignatureScheme::read(r)?; let sig = PayloadU16::read(r)?; Some(DigitallySignedStruct { scheme, sig, }) } } #[derive(Debug)] pub struct ClientECDHParams { pub public: PayloadU8, } impl Codec for ClientECDHParams { fn encode(&self, bytes: &mut Vec<u8>) { self.public.encode(bytes); } fn read(r: &mut Reader) -> Option<ClientECDHParams> { let pb = PayloadU8::read(r)?; Some(ClientECDHParams { public: pb }) } } #[derive(Debug)] pub struct ServerECDHParams { pub curve_params: ECParameters, pub public: PayloadU8, } impl ServerECDHParams { pub fn new(named_group: NamedGroup, pubkey: &[u8]) -> ServerECDHParams { ServerECDHParams { curve_params: ECParameters { curve_type: ECCurveType::NamedCurve, named_group, }, public: PayloadU8::new(pubkey.to_vec()), } } } impl Codec for ServerECDHParams { fn encode(&self, bytes: &mut Vec<u8>) { self.curve_params.encode(bytes); self.public.encode(bytes); } fn read(r: &mut Reader) -> Option<ServerECDHParams> { let cp = ECParameters::read(r)?; let pb = PayloadU8::read(r)?; Some(ServerECDHParams { curve_params: cp, public: pb, }) } } #[derive(Debug)] pub struct ECDHEServerKeyExchange { pub params: ServerECDHParams, pub dss: DigitallySignedStruct, } impl Codec for ECDHEServerKeyExchange { fn encode(&self, bytes: &mut Vec<u8>) { self.params.encode(bytes); self.dss.encode(bytes); } fn read(r: &mut Reader) -> Option<ECDHEServerKeyExchange> { let params = ServerECDHParams::read(r)?; let dss = DigitallySignedStruct::read(r)?; Some(ECDHEServerKeyExchange { params, dss, }) } } #[derive(Debug)] pub enum ServerKeyExchangePayload { ECDHE(ECDHEServerKeyExchange), Unknown(Payload), } impl Codec for ServerKeyExchangePayload { fn encode(&self, bytes: &mut Vec<u8>) { match *self { ServerKeyExchangePayload::ECDHE(ref x) => x.encode(bytes), ServerKeyExchangePayload::Unknown(ref x) => x.encode(bytes), } } fn read(r: &mut Reader) -> Option<ServerKeyExchangePayload> { // read as Unknown, fully parse when we know the // KeyExchangeAlgorithm Payload::read(r).map(ServerKeyExchangePayload::Unknown) } } impl ServerKeyExchangePayload { pub fn unwrap_given_kxa(&self, kxa: &KeyExchangeAlgorithm) -> Option<ServerKeyExchangePayload> { if let ServerKeyExchangePayload::Unknown(ref unk) = *self { let mut rd = Reader::init(&unk.0); let result = match *kxa { KeyExchangeAlgorithm::ECDHE => { ECDHEServerKeyExchange::read(&mut rd) .map(ServerKeyExchangePayload::ECDHE) } _ => None, }; if !rd.any_left() { return result; }; } None } pub fn encode_params(&self, bytes: &mut Vec<u8>) { bytes.clear(); if let ServerKeyExchangePayload::ECDHE(ref x) = *self { x.params.encode(bytes); } } pub fn get_sig(&self) -> Option<DigitallySignedStruct> { match *self { ServerKeyExchangePayload::ECDHE(ref x) => Some(x.dss.clone()), _ => None, } } } // -- EncryptedExtensions (TLS1.3 only) -- declare_u16_vec!(EncryptedExtensions, ServerExtension); pub trait HasServerExtensions { fn get_extensions(&self) -> &[ServerExtension]; /// Returns true if there is more than one extension of a given /// type. fn has_duplicate_extension(&self) -> bool { let mut seen = collections::HashSet::new(); for ext in self.get_extensions() { let typ = ext.get_type().get_u16(); if seen.contains(&typ) { return true; } seen.insert(typ); } false } fn find_extension(&self, ext: ExtensionType) -> Option<&ServerExtension> { self.get_extensions().iter().find(|x| x.get_type() == ext) } fn get_alpn_protocol(&self) -> Option<&[u8]> { let ext = self.find_extension(ExtensionType::ALProtocolNegotiation)?; match *ext { ServerExtension::Protocols(ref protos) => protos.as_single_slice(), _ => None, } } fn get_quic_params_extension(&self) -> Option<Vec<u8>> { let ext = self.find_extension(ExtensionType::TransportParameters)?; match *ext { ServerExtension::TransportParameters(ref bytes) => Some(bytes.to_vec()), _ => None, } } fn early_data_extension_offered(&self) -> bool { self.find_extension(ExtensionType::EarlyData).is_some() } } impl HasServerExtensions for EncryptedExtensions { fn get_extensions(&self) -> &[ServerExtension] { self } } // -- CertificateRequest and sundries -- declare_u8_vec!(ClientCertificateTypes, ClientCertificateType); pub type DistinguishedName = PayloadU16; pub type DistinguishedNames = VecU16OfPayloadU16; #[derive(Debug)] pub struct CertificateRequestPayload { pub certtypes: ClientCertificateTypes, pub sigschemes: SupportedSignatureSchemes, pub canames: DistinguishedNames, } impl Codec for CertificateRequestPayload { fn encode(&self, bytes: &mut Vec<u8>) { self.certtypes.encode(bytes); self.sigschemes.encode(bytes); self.canames.encode(bytes); } fn read(r: &mut Reader) -> Option<CertificateRequestPayload> { let certtypes = ClientCertificateTypes::read(r)?; let sigschemes = SupportedSignatureSchemes::read(r)?; let canames = DistinguishedNames::read(r)?; if sigschemes.is_empty() { warn!("meaningless CertificateRequest message"); None } else { Some(CertificateRequestPayload { certtypes, sigschemes, canames, }) } } } #[derive(Debug)] pub enum CertReqExtension { SignatureAlgorithms(SupportedSignatureSchemes), AuthorityNames(DistinguishedNames), Unknown(UnknownExtension), } impl CertReqExtension { pub fn get_type(&self) -> ExtensionType { match *self { CertReqExtension::SignatureAlgorithms(_) => ExtensionType::SignatureAlgorithms, CertReqExtension::AuthorityNames(_) => ExtensionType::CertificateAuthorities, CertReqExtension::Unknown(ref r) => r.typ, } } } impl Codec for CertReqExtension { fn encode(&self, bytes: &mut Vec<u8>) { self.get_type().encode(bytes); let mut sub: Vec<u8> = Vec::new(); match *self { CertReqExtension::SignatureAlgorithms(ref r) => r.encode(&mut sub), CertReqExtension::AuthorityNames(ref r) => r.encode(&mut sub), CertReqExtension::Unknown(ref r) => r.encode(&mut sub), } (sub.len() as u16).encode(bytes); bytes.append(&mut sub); } fn read(r: &mut Reader) -> Option<CertReqExtension> { let typ = ExtensionType::read(r)?; let len = u16::read(r)? as usize; let mut sub = r.sub(len)?; Some(match typ { ExtensionType::SignatureAlgorithms => { let schemes = SupportedSignatureSchemes::read(&mut sub)?; if schemes.is_empty() { return None; } CertReqExtension::SignatureAlgorithms(schemes) } ExtensionType::CertificateAuthorities => { let cas = DistinguishedNames::read(&mut sub)?; CertReqExtension::AuthorityNames(cas) } _ => CertReqExtension::Unknown(UnknownExtension::read(typ, &mut sub)?), }) } } declare_u16_vec!(CertReqExtensions, CertReqExtension); #[derive(Debug)] pub struct CertificateRequestPayloadTLS13 { pub context: PayloadU8, pub extensions: CertReqExtensions, } impl Codec for CertificateRequestPayloadTLS13 { fn encode(&self, bytes: &mut Vec<u8>) { self.context.encode(bytes); self.extensions.encode(bytes); } fn read(r: &mut Reader) -> Option<CertificateRequestPayloadTLS13> { let context = PayloadU8::read(r)?; let extensions = CertReqExtensions::read(r)?; Some(CertificateRequestPayloadTLS13 { context, extensions, }) } } impl CertificateRequestPayloadTLS13 { pub fn find_extension(&self, ext: ExtensionType) -> Option<&CertReqExtension> { self.extensions.iter().find(|x| x.get_type() == ext) } pub fn get_sigalgs_extension(&self) -> Option<&SupportedSignatureSchemes> { let ext = self.find_extension(ExtensionType::SignatureAlgorithms)?; match *ext { CertReqExtension::SignatureAlgorithms(ref sa) => Some(sa), _ => None, } } pub fn get_authorities_extension(&self) -> Option<&DistinguishedNames> { let ext = self.find_extension(ExtensionType::CertificateAuthorities)?; match *ext { CertReqExtension::AuthorityNames(ref an) => Some(an), _ => None, } } } // -- NewSessionTicket -- #[derive(Debug)] pub struct NewSessionTicketPayload { pub lifetime_hint: u32, pub ticket: PayloadU16, } impl NewSessionTicketPayload { pub fn new(lifetime_hint: u32, ticket: Vec<u8>) -> NewSessionTicketPayload { NewSessionTicketPayload { lifetime_hint, ticket: PayloadU16::new(ticket), } } } impl Codec for NewSessionTicketPayload { fn encode(&self, bytes: &mut Vec<u8>) { self.lifetime_hint.encode(bytes); self.ticket.encode(bytes); } fn read(r: &mut Reader) -> Option<NewSessionTicketPayload> { let lifetime = u32::read(r)?; let ticket = PayloadU16::read(r)?; Some(NewSessionTicketPayload { lifetime_hint: lifetime, ticket, }) } } // -- NewSessionTicket electric boogaloo -- #[derive(Debug)] pub enum NewSessionTicketExtension { EarlyData(u32), Unknown(UnknownExtension), } impl NewSessionTicketExtension { pub fn get_type(&self) -> ExtensionType { match *self { NewSessionTicketExtension::EarlyData(_) => ExtensionType::EarlyData, NewSessionTicketExtension::Unknown(ref r) => r.typ, } } } impl Codec for NewSessionTicketExtension { fn encode(&self, bytes: &mut Vec<u8>) { self.get_type().encode(bytes); let mut sub: Vec<u8> = Vec::new(); match *self { NewSessionTicketExtension::EarlyData(r) => r.encode(&mut sub), NewSessionTicketExtension::Unknown(ref r) => r.encode(&mut sub), } (sub.len() as u16).encode(bytes); bytes.append(&mut sub); } fn read(r: &mut Reader) -> Option<NewSessionTicketExtension> { let typ = ExtensionType::read(r)?; let len = u16::read(r)? as usize; let mut sub = r.sub(len)?; Some(match typ { ExtensionType::EarlyData => NewSessionTicketExtension::EarlyData(u32::read(&mut sub)?), _ => { NewSessionTicketExtension::Unknown(UnknownExtension::read(typ, &mut sub)?) } }) } } declare_u16_vec!(NewSessionTicketExtensions, NewSessionTicketExtension); #[derive(Debug)] pub struct NewSessionTicketPayloadTLS13 { pub lifetime: u32, pub age_add: u32, pub nonce: PayloadU8, pub ticket: PayloadU16, pub exts: NewSessionTicketExtensions, } impl NewSessionTicketPayloadTLS13 { pub fn new(lifetime: u32, age_add: u32, nonce: Vec<u8>, ticket: Vec<u8>) -> NewSessionTicketPayloadTLS13 { NewSessionTicketPayloadTLS13 { lifetime, age_add, nonce: PayloadU8::new(nonce), ticket: PayloadU16::new(ticket), exts: vec![], } } pub fn find_extension(&self, ext: ExtensionType) -> Option<&NewSessionTicketExtension> { self.exts.iter().find(|x| x.get_type() == ext) } pub fn get_max_early_data_size(&self) -> Option<u32> { let ext = self.find_extension(ExtensionType::EarlyData)?; match *ext { NewSessionTicketExtension::EarlyData(ref sz) => Some(*sz), _ => None } } } impl Codec for NewSessionTicketPayloadTLS13 { fn encode(&self, bytes: &mut Vec<u8>) { self.lifetime.encode(bytes); self.age_add.encode(bytes); self.nonce.encode(bytes); self.ticket.encode(bytes); self.exts.encode(bytes); } fn read(r: &mut Reader) -> Option<NewSessionTicketPayloadTLS13> { let lifetime = u32::read(r)?; let age_add = u32::read(r)?; let nonce = PayloadU8::read(r)?; let ticket = PayloadU16::read(r)?; let exts = NewSessionTicketExtensions::read(r)?; Some(NewSessionTicketPayloadTLS13 { lifetime, age_add, nonce, ticket, exts, }) } } // -- RFC6066 certificate status types /// Only supports OCSP #[derive(Debug, Clone)] pub struct CertificateStatus { pub ocsp_response: PayloadU24 } impl Codec for CertificateStatus { fn encode(&self, bytes: &mut Vec<u8>) { CertificateStatusType::OCSP.encode(bytes); self.ocsp_response.encode(bytes); } fn read(r: &mut Reader) -> Option<CertificateStatus> { let typ = CertificateStatusType::read(r)?; match typ { CertificateStatusType::OCSP => { Some(CertificateStatus { ocsp_response: PayloadU24::read(r)? }) } _ => None } } } impl CertificateStatus { pub fn new(ocsp: Vec<u8>) -> CertificateStatus { CertificateStatus { ocsp_response: PayloadU24::new(ocsp) } } pub fn take_ocsp_response(&mut self) -> Vec<u8> { let new = PayloadU24::new(Vec::new()); mem::replace(&mut self.ocsp_response, new).0 } } #[derive(Debug)] pub enum HandshakePayload { HelloRequest, ClientHello(ClientHelloPayload), ServerHello(ServerHelloPayload), HelloRetryRequest(HelloRetryRequest), Certificate(CertificatePayload), CertificateTLS13(CertificatePayloadTLS13), ServerKeyExchange(ServerKeyExchangePayload), CertificateRequest(CertificateRequestPayload), CertificateRequestTLS13(CertificateRequestPayloadTLS13), CertificateVerify(DigitallySignedStruct), ServerHelloDone, EarlyData, EndOfEarlyData, ClientKeyExchange(Payload), NewSessionTicket(NewSessionTicketPayload), NewSessionTicketTLS13(NewSessionTicketPayloadTLS13), EncryptedExtensions(EncryptedExtensions), KeyUpdate(KeyUpdateRequest), Finished(Payload), CertificateStatus(CertificateStatus), MessageHash(Payload), ServerKemCiphertext(Payload), ClientKemCiphertext(Payload), Unknown(Payload), } impl HandshakePayload { fn encode(&self, bytes: &mut Vec<u8>) { match *self { HandshakePayload::HelloRequest | HandshakePayload::ServerHelloDone | HandshakePayload::EarlyData | HandshakePayload::EndOfEarlyData => {} HandshakePayload::ClientHello(ref x) => x.encode(bytes), HandshakePayload::ServerHello(ref x) => x.encode(bytes), HandshakePayload::HelloRetryRequest(ref x) => x.encode(bytes), HandshakePayload::Certificate(ref x) => x.encode(bytes), HandshakePayload::CertificateTLS13(ref x) => x.encode(bytes), HandshakePayload::ServerKeyExchange(ref x) => x.encode(bytes), HandshakePayload::ClientKeyExchange(ref x) => x.encode(bytes), HandshakePayload::CertificateRequest(ref x) => x.encode(bytes), HandshakePayload::CertificateRequestTLS13(ref x) => x.encode(bytes), HandshakePayload::CertificateVerify(ref x) => x.encode(bytes), HandshakePayload::NewSessionTicket(ref x) => x.encode(bytes), HandshakePayload::NewSessionTicketTLS13(ref x) => x.encode(bytes), HandshakePayload::EncryptedExtensions(ref x) => x.encode(bytes), HandshakePayload::KeyUpdate(ref x) => x.encode(bytes), HandshakePayload::Finished(ref x) => x.encode(bytes), HandshakePayload::CertificateStatus(ref x) => x.encode(bytes), HandshakePayload::MessageHash(ref x) => x.encode(bytes), HandshakePayload::Unknown(ref x) => x.encode(bytes), HandshakePayload::ServerKemCiphertext(ref x) => {x.encode(bytes)} HandshakePayload::ClientKemCiphertext(ref x) => {x.encode(bytes)} } } } #[derive(Debug)] pub struct HandshakeMessagePayload { pub typ: HandshakeType, pub payload: HandshakePayload, } impl Codec for HandshakeMessagePayload { fn encode(&self, bytes: &mut Vec<u8>) { // encode payload to learn length let mut sub: Vec<u8> = Vec::new(); self.payload.encode(&mut sub); // output type, length, and encoded payload match self.typ { HandshakeType::HelloRetryRequest => HandshakeType::ServerHello, _ => self.typ, }.encode(bytes); codec::u24(sub.len() as u32).encode(bytes); bytes.append(&mut sub); } fn read(r: &mut Reader) -> Option<HandshakeMessagePayload> { HandshakeMessagePayload::read_version(r, ProtocolVersion::TLSv1_2) } } impl HandshakeMessagePayload { pub fn length(&self) -> usize { let mut buf = Vec::new(); self.encode(&mut buf); buf.len() } pub fn read_version(r: &mut Reader, vers: ProtocolVersion) -> Option<HandshakeMessagePayload> { let mut typ = HandshakeType::read(r)?; let len = codec::u24::read(r)?.0 as usize; let mut sub = r.sub(len)?; let payload = match typ { HandshakeType::HelloRequest if sub.left() == 0 => HandshakePayload::HelloRequest, HandshakeType::ClientHello => { HandshakePayload::ClientHello(ClientHelloPayload::read(&mut sub)?) } HandshakeType::ServerHello => { let version = ProtocolVersion::read(&mut sub)?; let random = Random::read(&mut sub)?; if random == HELLO_RETRY_REQUEST_RANDOM { let mut hrr = HelloRetryRequest::read(&mut sub)?; hrr.legacy_version = version; typ = HandshakeType::HelloRetryRequest; HandshakePayload::HelloRetryRequest(hrr) } else { let mut shp = ServerHelloPayload::read(&mut sub)?; shp.legacy_version = version; shp.random = random; HandshakePayload::ServerHello(shp) } } HandshakeType::Certificate if vers == ProtocolVersion::TLSv1_3 => { let p = CertificatePayloadTLS13::read(&mut sub)?; HandshakePayload::CertificateTLS13(p) } HandshakeType::Certificate => { HandshakePayload::Certificate(CertificatePayload::read(&mut sub)?) } HandshakeType::ServerKeyExchange => { let p = ServerKeyExchangePayload::read(&mut sub)?; HandshakePayload::ServerKeyExchange(p) } HandshakeType::ServerHelloDone => { if sub.any_left() { return None; } HandshakePayload::ServerHelloDone } HandshakeType::ClientKeyExchange => { HandshakePayload::ClientKeyExchange(Payload::read(&mut sub).unwrap()) } HandshakeType::CertificateRequest if vers == ProtocolVersion::TLSv1_3 => { let p = CertificateRequestPayloadTLS13::read(&mut sub)?; HandshakePayload::CertificateRequestTLS13(p) } HandshakeType::CertificateRequest => { let p = CertificateRequestPayload::read(&mut sub)?; HandshakePayload::CertificateRequest(p) } HandshakeType::CertificateVerify => { HandshakePayload::CertificateVerify(DigitallySignedStruct::read(&mut sub)?) } HandshakeType::NewSessionTicket if vers == ProtocolVersion::TLSv1_3 => { let p = NewSessionTicketPayloadTLS13::read(&mut sub)?; HandshakePayload::NewSessionTicketTLS13(p) } HandshakeType::NewSessionTicket => { let p = NewSessionTicketPayload::read(&mut sub)?; HandshakePayload::NewSessionTicket(p) } HandshakeType::EncryptedExtensions => { HandshakePayload::EncryptedExtensions(EncryptedExtensions::read(&mut sub)?) } HandshakeType::KeyUpdate => { HandshakePayload::KeyUpdate(KeyUpdateRequest::read(&mut sub)?) } HandshakeType::Finished => { HandshakePayload::Finished(Payload::read(&mut sub).unwrap()) } HandshakeType::CertificateStatus => { HandshakePayload::CertificateStatus(CertificateStatus::read(&mut sub)?) } HandshakeType::MessageHash => { // does not appear on the wire return None; } HandshakeType::HelloRetryRequest => { // not legal on wire return None; } HandshakeType::ServerKemCiphertext => { HandshakePayload::ServerKemCiphertext(Payload::read(&mut sub).unwrap()) } HandshakeType::ClientKemCiphertext => { HandshakePayload::ClientKemCiphertext(Payload::read(&mut sub).unwrap()) } _ => HandshakePayload::Unknown(Payload::read(&mut sub).unwrap()), }; if sub.any_left() { None } else { Some(HandshakeMessagePayload { typ, payload, }) } } pub fn build_key_update_notify() -> HandshakeMessagePayload { HandshakeMessagePayload { typ: HandshakeType::KeyUpdate, payload: HandshakePayload::KeyUpdate(KeyUpdateRequest::UpdateNotRequested), } } pub fn get_encoding_for_binder_signing(&self) -> Vec<u8> { let mut ret = self.get_encoding(); let binder_len = match self.payload { HandshakePayload::ClientHello(ref ch) => { let offer = ch.get_psk().unwrap(); let mut binders_encoding = Vec::new(); offer.binders.encode(&mut binders_encoding); binders_encoding.len() } _ => 0, }; let ret_len = ret.len() - binder_len; ret.truncate(ret_len); ret } pub fn build_handshake_hash(hash: &[u8]) -> HandshakeMessagePayload { HandshakeMessagePayload { typ: HandshakeType::MessageHash, payload: HandshakePayload::MessageHash(Payload::new(hash.to_vec())) } } }
31.89851
149
0.598884
f79dc421ff75964b2f8a368f233521e8fac703f3
3,751
#![allow(unused_imports)] use cursive::direction::Orientation; use cursive::event::{AnyCb, Event, EventResult, Key}; use cursive::traits::{Boxable, Finder, Identifiable, View}; use cursive::view::{IntoBoxedView, Selector, ViewNotFound, ViewWrapper}; use cursive::views::{EditView, NamedView, ViewRef}; use cursive::{Cursive, Printer, Vec2}; use std::cell::RefCell; use std::sync::{Arc, Mutex, RwLock}; use crate::command::{Command, MoveMode}; use crate::commands::CommandResult; use crate::events::EventManager; use crate::library::Library; use crate::model::album::Album; use crate::model::artist::Artist; use crate::model::episode::Episode; use crate::model::playlist::Playlist; use crate::model::show::Show; use crate::model::track::Track; use crate::queue::Queue; use crate::spotify::{Spotify, UriType}; use crate::traits::{ListItem, ViewExt}; use crate::ui::layout::Layout; use crate::ui::listview::ListView; use crate::ui::pagination::Pagination; use crate::ui::search_results::SearchResultsView; use crate::ui::tabview::TabView; use rspotify::model::search::SearchResult; pub struct SearchView { edit: NamedView<EditView>, edit_focused: bool, } pub const EDIT_ID: &str = "search_edit"; impl SearchView { pub fn new(events: EventManager, queue: Arc<Queue>, library: Arc<Library>) -> SearchView { let searchfield = EditView::new() .on_submit(move |s, input| { if !input.is_empty() { let results = SearchResultsView::new( input.to_string(), events.clone(), queue.clone(), library.clone(), ); s.call_on_name("main", move |v: &mut Layout| v.push_view(Box::new(results))); } }) .with_name(EDIT_ID); SearchView { edit: searchfield, edit_focused: true, } } pub fn clear(&mut self) { self.edit .call_on(&Selector::Name(EDIT_ID), |v: &mut EditView| { v.set_content(""); }); } } impl View for SearchView { fn draw(&self, printer: &Printer<'_, '_>) { let printer = &printer .offset((0, 0)) .cropped((printer.size.x, 1)) .focused(self.edit_focused); self.edit.draw(printer); } fn layout(&mut self, size: Vec2) { self.edit.layout(Vec2::new(size.x, 1)); } fn on_event(&mut self, event: Event) -> EventResult { if event == Event::Key(Key::Tab) { self.edit_focused = !self.edit_focused; return EventResult::Consumed(None); } else if self.edit_focused && event == Event::Key(Key::Esc) { self.clear(); } if self.edit_focused { self.edit.on_event(event) } else { EventResult::Ignored } } fn call_on_any<'a>(&mut self, selector: &Selector<'_>, callback: AnyCb<'a>) { self.edit.call_on_any(selector, &mut |v| callback(v)); } fn focus_view(&mut self, selector: &Selector<'_>) -> Result<(), ViewNotFound> { if let Selector::Name(s) = selector { self.edit_focused = s == &"search_edit"; Ok(()) } else { Err(ViewNotFound) } } } impl ViewExt for SearchView { fn title(&self) -> String { "Search".to_string() } fn on_command(&mut self, _s: &mut Cursive, cmd: &Command) -> Result<CommandResult, String> { if let Command::Focus(_) = cmd { self.edit_focused = true; self.clear(); return Ok(CommandResult::Consumed(None)); } Ok(CommandResult::Ignored) } }
29.769841
97
0.575047
8a07c6f21e9488aff54d3b6aa52a6452062fb041
2,791
// Copyright 2020 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_exception::Result; use common_meta_types::CreateDatabaseReply; use common_meta_types::MetaId; use common_meta_types::MetaVersion; use common_meta_types::TableInfo; use common_meta_types::UpsertTableOptionReply; use common_planners::CreateDatabasePlan; use common_planners::CreateTablePlan; use common_planners::DropDatabasePlan; use common_planners::DropTablePlan; use crate::catalogs::Database; use crate::catalogs::Table; use crate::catalogs::TableFunction; use crate::datasources::table_func_engine::TableArgs; /// Catalog is the global view of all the databases of the user. /// The global view has many engine type: Local-Database(engine=Local), Remote-Database(engine=Remote) /// or others(like MySQL-Database, engine=MySQL) /// When we create a new database, we first to get the engine from the registered engines, /// and use the engine to create them. pub trait Catalog { // Get all the databases. fn get_databases(&self) -> Result<Vec<Arc<dyn Database>>>; // Get the database by name. fn get_database(&self, db_name: &str) -> Result<Arc<dyn Database>>; // Get one table by db and table name. fn get_table(&self, db_name: &str, table_name: &str) -> Result<Arc<dyn Table>>; fn get_tables(&self, db_name: &str) -> Result<Vec<Arc<dyn Table>>>; fn create_table(&self, plan: CreateTablePlan) -> Result<()>; fn drop_table(&self, plan: DropTablePlan) -> Result<()>; /// Build a `Arc<dyn Table>` from `TableInfo`. fn build_table(&self, table_info: &TableInfo) -> Result<Arc<dyn Table>>; // Get function by name. fn get_table_function( &self, _func_name: &str, _tbl_args: TableArgs, ) -> Result<Arc<dyn TableFunction>> { unimplemented!() } fn upsert_table_option( &self, table_id: MetaId, table_version: MetaVersion, table_option_key: String, table_option_value: String, ) -> common_exception::Result<UpsertTableOptionReply>; // Operation with database. fn create_database(&self, plan: CreateDatabasePlan) -> Result<CreateDatabaseReply>; fn drop_database(&self, plan: DropDatabasePlan) -> Result<()>; }
35.329114
102
0.713723
f851e0d8cd3c5f51e97c47ab4c7ff9059d8aab2e
2,622
// SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2022 Andre Richter <[email protected]> //! A panic handler that infinitely waits. use crate::{bsp, cpu}; use core::{fmt, panic::PanicInfo}; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- fn _panic_print(args: fmt::Arguments) { use fmt::Write; unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; } /// Prints with a newline - only use from the panic handler. /// /// Carbon copy from <https://doc.rust-lang.org/src/std/macros.rs.html> #[macro_export] macro_rules! panic_println { ($($arg:tt)*) => ({ _panic_print(format_args_nl!($($arg)*)); }) } /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { use crate::time::interface::TimeManager; // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let timestamp = crate::time::time_manager().uptime(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; panic_println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", timestamp.as_secs(), timestamp.subsec_micros(), location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() }
30.488372
100
0.588482
091614b6bc74c17163d408d67d07925afbb8cbc1
83,975
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * * # Compilation of match statements * * I will endeavor to explain the code as best I can. I have only a loose * understanding of some parts of it. * * ## Matching * * The basic state of the code is maintained in an array `m` of `Match` * objects. Each `Match` describes some list of patterns, all of which must * match against the current list of values. If those patterns match, then * the arm listed in the match is the correct arm. A given arm may have * multiple corresponding match entries, one for each alternative that * remains. As we proceed these sets of matches are adjusted by the various * `enter_XXX()` functions, each of which adjusts the set of options given * some information about the value which has been matched. * * So, initially, there is one value and N matches, each of which have one * constituent pattern. N here is usually the number of arms but may be * greater, if some arms have multiple alternatives. For example, here: * * enum Foo { A, B(int), C(uint, uint) } * match foo { * A => ..., * B(x) => ..., * C(1u, 2) => ..., * C(_) => ... * } * * The value would be `foo`. There would be four matches, each of which * contains one pattern (and, in one case, a guard). We could collect the * various options and then compile the code for the case where `foo` is an * `A`, a `B`, and a `C`. When we generate the code for `C`, we would (1) * drop the two matches that do not match a `C` and (2) expand the other two * into two patterns each. In the first case, the two patterns would be `1u` * and `2`, and the in the second case the _ pattern would be expanded into * `_` and `_`. The two values are of course the arguments to `C`. * * Here is a quick guide to the various functions: * * - `compile_submatch()`: The main workhouse. It takes a list of values and * a list of matches and finds the various possibilities that could occur. * * - `enter_XXX()`: modifies the list of matches based on some information * about the value that has been matched. For example, * `enter_rec_or_struct()` adjusts the values given that a record or struct * has been matched. This is an infallible pattern, so *all* of the matches * must be either wildcards or record/struct patterns. `enter_opt()` * handles the fallible cases, and it is correspondingly more complex. * * ## Bindings * * We store information about the bound variables for each arm as part of the * per-arm `ArmData` struct. There is a mapping from identifiers to * `BindingInfo` structs. These structs contain the mode/id/type of the * binding, but they also contain up to two LLVM values, called `llmatch` and * `llbinding` respectively (the `llbinding`, as will be described shortly, is * optional and only present for by-value bindings---therefore it is bundled * up as part of the `TransBindingMode` type). Both point at allocas. * * The `llmatch` binding always stores a pointer into the value being matched * which points at the data for the binding. If the value being matched has * type `T`, then, `llmatch` will point at an alloca of type `T*` (and hence * `llmatch` has type `T**`). So, if you have a pattern like: * * let a: A = ...; * let b: B = ...; * match (a, b) { (ref c, d) => { ... } } * * For `c` and `d`, we would generate allocas of type `C*` and `D*` * respectively. These are called the `llmatch`. As we match, when we come * up against an identifier, we store the current pointer into the * corresponding alloca. * * In addition, for each by-value binding (copy or move), we will create a * second alloca (`llbinding`) that will hold the final value. In this * example, that means that `d` would have this second alloca of type `D` (and * hence `llbinding` has type `D*`). * * Once a pattern is completely matched, and assuming that there is no guard * pattern, we will branch to a block that leads to the body itself. For any * by-value bindings, this block will first load the ptr from `llmatch` (the * one of type `D*`) and copy/move the value into `llbinding` (the one of type * `D`). The second alloca then becomes the value of the local variable. For * by ref bindings, the value of the local variable is simply the first * alloca. * * So, for the example above, we would generate a setup kind of like this: * * +-------+ * | Entry | * +-------+ * | * +-------------------------------------------+ * | llmatch_c = (addr of first half of tuple) | * | llmatch_d = (addr of first half of tuple) | * +-------------------------------------------+ * | * +--------------------------------------+ * | *llbinding_d = **llmatch_dlbinding_d | * +--------------------------------------+ * * If there is a guard, the situation is slightly different, because we must * execute the guard code. Moreover, we need to do so once for each of the * alternatives that lead to the arm, because if the guard fails, they may * have different points from which to continue the search. Therefore, in that * case, we generate code that looks more like: * * +-------+ * | Entry | * +-------+ * | * +-------------------------------------------+ * | llmatch_c = (addr of first half of tuple) | * | llmatch_d = (addr of first half of tuple) | * +-------------------------------------------+ * | * +-------------------------------------------------+ * | *llbinding_d = **llmatch_dlbinding_d | * | check condition | * | if false { free *llbinding_d, goto next case } | * | if true { goto body } | * +-------------------------------------------------+ * * The handling for the cleanups is a bit... sensitive. Basically, the body * is the one that invokes `add_clean()` for each binding. During the guard * evaluation, we add temporary cleanups and revoke them after the guard is * evaluated (it could fail, after all). Presuming the guard fails, we drop * the various values we copied explicitly. Note that guards and moves are * just plain incompatible. * * Some relevant helper functions that manage bindings: * - `create_bindings_map()` * - `store_non_ref_bindings()` * - `insert_lllocals()` * * * ## Notes on vector pattern matching. * * Vector pattern matching is surprisingly tricky. The problem is that * the structure of the vector isn't fully known, and slice matches * can be done on subparts of it. * * The way that vector pattern matches are dealt with, then, is as * follows. First, we make the actual condition associated with a * vector pattern simply a vector length comparison. So the pattern * [1, .. x] gets the condition "vec len >= 1", and the pattern * [.. x] gets the condition "vec len >= 0". The problem here is that * having the condition "vec len >= 1" hold clearly does not mean that * only a pattern that has exactly that condition will match. This * means that it may well be the case that a condition holds, but none * of the patterns matching that condition match; to deal with this, * when doing vector length matches, we have match failures proceed to * the next condition to check. * * There are a couple more subtleties to deal with. While the "actual" * condition associated with vector length tests is simply a test on * the vector length, the actual vec_len Opt entry contains more * information used to restrict which matches are associated with it. * So that all matches in a submatch are matching against the same * values from inside the vector, they are split up by how many * elements they match at the front and at the back of the vector. In * order to make sure that arms are properly checked in order, even * with the overmatching conditions, each vec_len Opt entry is * associated with a range of matches. * Consider the following: * * match &[1, 2, 3] { * [1, 1, .. _] => 0, * [1, 2, 2, .. _] => 1, * [1, 2, 3, .. _] => 2, * [1, 2, .. _] => 3, * _ => 4 * } * The proper arm to match is arm 2, but arms 0 and 3 both have the * condition "len >= 2". If arm 3 was lumped in with arm 0, then the * wrong branch would be taken. Instead, vec_len Opts are associated * with a contiguous range of matches that have the same "shape". * This is sort of ugly and requires a bunch of special handling of * vec_len options. * */ use back::abi; use lib::llvm::{llvm, ValueRef, BasicBlockRef}; use middle::const_eval; use middle::borrowck::root_map_key; use middle::lang_items::{UniqStrEqFnLangItem, StrEqFnLangItem}; use middle::pat_util::*; use middle::resolve::DefMap; use middle::trans::adt; use middle::trans::base::*; use middle::trans::build::*; use middle::trans::callee; use middle::trans::common::*; use middle::trans::consts; use middle::trans::controlflow; use middle::trans::datum; use middle::trans::datum::*; use middle::trans::expr::Dest; use middle::trans::expr; use middle::trans::glue; use middle::trans::tvec; use middle::trans::type_of; use middle::trans::debuginfo; use middle::ty; use util::common::indenter; use util::ppaux::{Repr, vec_map_to_str}; use std::hashmap::HashMap; use std::vec; use syntax::ast; use syntax::ast::Ident; use syntax::ast_util::path_to_ident; use syntax::ast_util; use syntax::codemap::{Span, dummy_sp}; // An option identifying a literal: either a unit-like struct or an // expression. enum Lit { UnitLikeStructLit(ast::NodeId), // the node ID of the pattern ExprLit(@ast::Expr), ConstLit(ast::DefId), // the def ID of the constant } #[deriving(Eq)] pub enum VecLenOpt { vec_len_eq, vec_len_ge(/* length of prefix */uint) } // An option identifying a branch (either a literal, a enum variant or a // range) enum Opt { lit(Lit), var(ty::Disr, @adt::Repr), range(@ast::Expr, @ast::Expr), vec_len(/* length */ uint, VecLenOpt, /*range of matches*/(uint, uint)) } fn opt_eq(tcx: ty::ctxt, a: &Opt, b: &Opt) -> bool { match (a, b) { (&lit(a), &lit(b)) => { match (a, b) { (UnitLikeStructLit(a), UnitLikeStructLit(b)) => a == b, _ => { let a_expr; match a { ExprLit(existing_a_expr) => a_expr = existing_a_expr, ConstLit(a_const) => { let e = const_eval::lookup_const_by_id(tcx, a_const); a_expr = e.unwrap(); } UnitLikeStructLit(_) => { fail!("UnitLikeStructLit should have been handled \ above") } } let b_expr; match b { ExprLit(existing_b_expr) => b_expr = existing_b_expr, ConstLit(b_const) => { let e = const_eval::lookup_const_by_id(tcx, b_const); b_expr = e.unwrap(); } UnitLikeStructLit(_) => { fail!("UnitLikeStructLit should have been handled \ above") } } match const_eval::compare_lit_exprs(tcx, a_expr, b_expr) { Some(val1) => val1 == 0, None => fail!("compare_list_exprs: type mismatch"), } } } } (&range(a1, a2), &range(b1, b2)) => { let m1 = const_eval::compare_lit_exprs(tcx, a1, b1); let m2 = const_eval::compare_lit_exprs(tcx, a2, b2); match (m1, m2) { (Some(val1), Some(val2)) => (val1 == 0 && val2 == 0), _ => fail!("compare_list_exprs: type mismatch"), } } (&var(a, _), &var(b, _)) => a == b, (&vec_len(a1, a2, _), &vec_len(b1, b2, _)) => a1 == b1 && a2 == b2, _ => false } } pub enum opt_result { single_result(Result), lower_bound(Result), range_result(Result, Result), } fn trans_opt(bcx: @mut Block, o: &Opt) -> opt_result { let _icx = push_ctxt("match::trans_opt"); let ccx = bcx.ccx(); let bcx = bcx; match *o { lit(ExprLit(lit_expr)) => { let datumblock = expr::trans_to_datum(bcx, lit_expr); return single_result(datumblock.to_result()); } lit(UnitLikeStructLit(pat_id)) => { let struct_ty = ty::node_id_to_type(bcx.tcx(), pat_id); let datumblock = datum::scratch_datum(bcx, struct_ty, "", true); return single_result(datumblock.to_result(bcx)); } lit(ConstLit(lit_id)) => { let (llval, _) = consts::get_const_val(bcx.ccx(), lit_id); return single_result(rslt(bcx, llval)); } var(disr_val, repr) => { return adt::trans_case(bcx, repr, disr_val); } range(l1, l2) => { let (l1, _) = consts::const_expr(ccx, l1); let (l2, _) = consts::const_expr(ccx, l2); return range_result(rslt(bcx, l1), rslt(bcx, l2)); } vec_len(n, vec_len_eq, _) => { return single_result(rslt(bcx, C_int(ccx, n as int))); } vec_len(n, vec_len_ge(_), _) => { return lower_bound(rslt(bcx, C_int(ccx, n as int))); } } } fn variant_opt(bcx: @mut Block, pat_id: ast::NodeId) -> Opt { let ccx = bcx.ccx(); match ccx.tcx.def_map.get_copy(&pat_id) { ast::DefVariant(enum_id, var_id, _) => { let variants = ty::enum_variants(ccx.tcx, enum_id); for v in (*variants).iter() { if var_id == v.id { return var(v.disr_val, adt::represent_node(bcx, pat_id)) } } unreachable!(); } ast::DefFn(..) | ast::DefStruct(_) => { return lit(UnitLikeStructLit(pat_id)); } _ => { ccx.sess.bug("non-variant or struct in variant_opt()"); } } } #[deriving(Clone)] enum TransBindingMode { TrByValue(/*llbinding:*/ ValueRef), TrByRef, } /** * Information about a pattern binding: * - `llmatch` is a pointer to a stack slot. The stack slot contains a * pointer into the value being matched. Hence, llmatch has type `T**` * where `T` is the value being matched. * - `trmode` is the trans binding mode * - `id` is the node id of the binding * - `ty` is the Rust type of the binding */ #[deriving(Clone)] struct BindingInfo { llmatch: ValueRef, trmode: TransBindingMode, id: ast::NodeId, span: Span, ty: ty::t, } type BindingsMap = HashMap<Ident, BindingInfo>; #[deriving(Clone)] struct ArmData<'a> { bodycx: @mut Block, arm: &'a ast::Arm, bindings_map: @BindingsMap } /** * Info about Match. * If all `pats` are matched then arm `data` will be executed. * As we proceed `bound_ptrs` are filled with pointers to values to be bound, * these pointers are stored in llmatch variables just before executing `data` arm. */ #[deriving(Clone)] struct Match<'a> { pats: ~[@ast::Pat], data: ArmData<'a>, bound_ptrs: ~[(Ident, ValueRef)] } impl<'a> Repr for Match<'a> { fn repr(&self, tcx: ty::ctxt) -> ~str { if tcx.sess.verbose() { // for many programs, this just take too long to serialize self.pats.repr(tcx) } else { format!("{} pats", self.pats.len()) } } } fn has_nested_bindings(m: &[Match], col: uint) -> bool { for br in m.iter() { match br.pats[col].node { ast::PatIdent(_, _, Some(_)) => return true, _ => () } } return false; } fn expand_nested_bindings<'r>(bcx: @mut Block, m: &[Match<'r>], col: uint, val: ValueRef) -> ~[Match<'r>] { debug!("expand_nested_bindings(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); m.map(|br| { match br.pats[col].node { ast::PatIdent(_, ref path, Some(inner)) => { let pats = vec::append( br.pats.slice(0u, col).to_owned(), vec::append(~[inner], br.pats.slice(col + 1u, br.pats.len()))); let mut res = Match { pats: pats, data: br.data.clone(), bound_ptrs: br.bound_ptrs.clone() }; res.bound_ptrs.push((path_to_ident(path), val)); res } _ => (*br).clone(), } }) } fn assert_is_binding_or_wild(bcx: @mut Block, p: @ast::Pat) { if !pat_is_binding_or_wild(bcx.tcx().def_map, p) { bcx.sess().span_bug( p.span, format!("Expected an identifier pattern but found p: {}", p.repr(bcx.tcx()))); } } type enter_pat<'a> = 'a |@ast::Pat| -> Option<~[@ast::Pat]>; fn enter_match<'r>(bcx: @mut Block, dm: DefMap, m: &[Match<'r>], col: uint, val: ValueRef, e: enter_pat) -> ~[Match<'r>] { debug!("enter_match(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); let mut result = ~[]; for br in m.iter() { match e(br.pats[col]) { Some(sub) => { let pats = vec::append( vec::append(sub, br.pats.slice(0u, col)), br.pats.slice(col + 1u, br.pats.len())); let this = br.pats[col]; let mut bound_ptrs = br.bound_ptrs.clone(); match this.node { ast::PatIdent(_, ref path, None) => { if pat_is_binding(dm, this) { bound_ptrs.push((path_to_ident(path), val)); } } _ => {} } result.push(Match { pats: pats, data: br.data.clone(), bound_ptrs: bound_ptrs }); } None => () } } debug!("result={}", result.repr(bcx.tcx())); return result; } fn enter_default<'r>(bcx: @mut Block, dm: DefMap, m: &[Match<'r>], col: uint, val: ValueRef, chk: FailureHandler) -> ~[Match<'r>] { debug!("enter_default(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); // Collect all of the matches that can match against anything. let matches = enter_match(bcx, dm, m, col, val, |p| { match p.node { ast::PatWild | ast::PatWildMulti | ast::PatTup(_) => Some(~[]), ast::PatIdent(_, _, None) if pat_is_binding(dm, p) => Some(~[]), _ => None } }); // Ok, now, this is pretty subtle. A "default" match is a match // that needs to be considered if none of the actual checks on the // value being considered succeed. The subtlety lies in that sometimes // identifier/wildcard matches are *not* default matches. Consider: // "match x { _ if something => foo, true => bar, false => baz }". // There is a wildcard match, but it is *not* a default case. The boolean // case on the value being considered is exhaustive. If the case is // exhaustive, then there are no defaults. // // We detect whether the case is exhaustive in the following // somewhat kludgy way: if the last wildcard/binding match has a // guard, then by non-redundancy, we know that there aren't any // non guarded matches, and thus by exhaustiveness, we know that // we don't need any default cases. If the check *isn't* nonexhaustive // (because chk is Some), then we need the defaults anyways. let is_exhaustive = match matches.last_opt() { Some(m) if m.data.arm.guard.is_some() && chk.is_infallible() => true, _ => false }; if is_exhaustive { ~[] } else { matches } } // <pcwalton> nmatsakis: what does enter_opt do? // <pcwalton> in trans/match // <pcwalton> trans/match.rs is like stumbling around in a dark cave // <nmatsakis> pcwalton: the enter family of functions adjust the set of // patterns as needed // <nmatsakis> yeah, at some point I kind of achieved some level of // understanding // <nmatsakis> anyhow, they adjust the patterns given that something of that // kind has been found // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I // said // <nmatsakis> enter_match() kind of embodies the generic code // <nmatsakis> it is provided with a function that tests each pattern to see // if it might possibly apply and so forth // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _ // <nmatsakis> then _ would be expanded to (_, _) // <nmatsakis> one spot for each of the sub-patterns // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible // cases // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they // are infallible patterns // <nmatsakis> so all patterns must either be records (resp. tuples) or // wildcards fn enter_opt<'r>(bcx: @mut Block, m: &[Match<'r>], opt: &Opt, col: uint, variant_size: uint, val: ValueRef) -> ~[Match<'r>] { debug!("enter_opt(bcx={}, m={}, opt={:?}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), *opt, col, bcx.val_to_str(val)); let _indenter = indenter(); let tcx = bcx.tcx(); let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()}; let mut i = 0; enter_match(bcx, tcx.def_map, m, col, val, |p| { let answer = match p.node { ast::PatEnum(..) | ast::PatIdent(_, _, None) if pat_is_const(tcx.def_map, p) => { let const_def = tcx.def_map.get_copy(&p.id); let const_def_id = ast_util::def_id_of_def(const_def); if opt_eq(tcx, &lit(ConstLit(const_def_id)), opt) { Some(~[]) } else { None } } ast::PatEnum(_, ref subpats) => { if opt_eq(tcx, &variant_opt(bcx, p.id), opt) { // XXX: Must we clone? match *subpats { None => Some(vec::from_elem(variant_size, dummy)), _ => (*subpats).clone(), } } else { None } } ast::PatIdent(_, _, None) if pat_is_variant_or_struct(tcx.def_map, p) => { if opt_eq(tcx, &variant_opt(bcx, p.id), opt) { Some(~[]) } else { None } } ast::PatLit(l) => { if opt_eq(tcx, &lit(ExprLit(l)), opt) {Some(~[])} else {None} } ast::PatRange(l1, l2) => { if opt_eq(tcx, &range(l1, l2), opt) {Some(~[])} else {None} } ast::PatStruct(_, ref field_pats, _) => { if opt_eq(tcx, &variant_opt(bcx, p.id), opt) { // Look up the struct variant ID. let struct_id; match tcx.def_map.get_copy(&p.id) { ast::DefVariant(_, found_struct_id, _) => { struct_id = found_struct_id; } _ => { tcx.sess.span_bug(p.span, "expected enum variant def"); } } // Reorder the patterns into the same order they were // specified in the struct definition. Also fill in // unspecified fields with dummy. let mut reordered_patterns = ~[]; let r = ty::lookup_struct_fields(tcx, struct_id); for field in r.iter() { match field_pats.iter().find(|p| p.ident.name == field.name) { None => reordered_patterns.push(dummy), Some(fp) => reordered_patterns.push(fp.pat) } } Some(reordered_patterns) } else { None } } ast::PatVec(ref before, slice, ref after) => { let (lo, hi) = match *opt { vec_len(_, _, (lo, hi)) => (lo, hi), _ => tcx.sess.span_bug(p.span, "vec pattern but not vec opt") }; match slice { Some(slice) if i >= lo && i <= hi => { let n = before.len() + after.len(); let this_opt = vec_len(n, vec_len_ge(before.len()), (lo, hi)); if opt_eq(tcx, &this_opt, opt) { Some(vec::append_one((*before).clone(), slice) + *after) } else { None } } None if i >= lo && i <= hi => { let n = before.len(); if opt_eq(tcx, &vec_len(n, vec_len_eq, (lo,hi)), opt) { Some((*before).clone()) } else { None } } _ => None } } _ => { assert_is_binding_or_wild(bcx, p); // In most cases, a binding/wildcard match be // considered to match against any Opt. However, when // doing vector pattern matching, submatches are // considered even if the eventual match might be from // a different submatch. Thus, when a submatch fails // when doing a vector match, we proceed to the next // submatch. Thus, including a default match would // cause the default match to fire spuriously. match *opt { vec_len(..) => None, _ => Some(vec::from_elem(variant_size, dummy)) } } }; i += 1; answer }) } fn enter_rec_or_struct<'r>(bcx: @mut Block, dm: DefMap, m: &[Match<'r>], col: uint, fields: &[ast::Ident], val: ValueRef) -> ~[Match<'r>] { debug!("enter_rec_or_struct(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()}; enter_match(bcx, dm, m, col, val, |p| { match p.node { ast::PatStruct(_, ref fpats, _) => { let mut pats = ~[]; for fname in fields.iter() { match fpats.iter().find(|p| p.ident.name == fname.name) { None => pats.push(dummy), Some(pat) => pats.push(pat.pat) } } Some(pats) } _ => { assert_is_binding_or_wild(bcx, p); Some(vec::from_elem(fields.len(), dummy)) } } }) } fn enter_tup<'r>(bcx: @mut Block, dm: DefMap, m: &[Match<'r>], col: uint, val: ValueRef, n_elts: uint) -> ~[Match<'r>] { debug!("enter_tup(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()}; enter_match(bcx, dm, m, col, val, |p| { match p.node { ast::PatTup(ref elts) => Some((*elts).clone()), _ => { assert_is_binding_or_wild(bcx, p); Some(vec::from_elem(n_elts, dummy)) } } }) } fn enter_tuple_struct<'r>(bcx: @mut Block, dm: DefMap, m: &[Match<'r>], col: uint, val: ValueRef, n_elts: uint) -> ~[Match<'r>] { debug!("enter_tuple_struct(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()}; enter_match(bcx, dm, m, col, val, |p| { match p.node { ast::PatEnum(_, Some(ref elts)) => Some((*elts).clone()), _ => { assert_is_binding_or_wild(bcx, p); Some(vec::from_elem(n_elts, dummy)) } } }) } fn enter_box<'r>(bcx: @mut Block, dm: DefMap, m: &[Match<'r>], col: uint, val: ValueRef) -> ~[Match<'r>] { debug!("enter_box(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()}; enter_match(bcx, dm, m, col, val, |p| { match p.node { ast::PatBox(sub) => { Some(~[sub]) } _ => { assert_is_binding_or_wild(bcx, p); Some(~[dummy]) } } }) } fn enter_uniq<'r>(bcx: @mut Block, dm: DefMap, m: &[Match<'r>], col: uint, val: ValueRef) -> ~[Match<'r>] { debug!("enter_uniq(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()}; enter_match(bcx, dm, m, col, val, |p| { match p.node { ast::PatUniq(sub) => { Some(~[sub]) } _ => { assert_is_binding_or_wild(bcx, p); Some(~[dummy]) } } }) } fn enter_region<'r>(bcx: @mut Block, dm: DefMap, m: &[Match<'r>], col: uint, val: ValueRef) -> ~[Match<'r>] { debug!("enter_region(bcx={}, m={}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), col, bcx.val_to_str(val)); let _indenter = indenter(); let dummy = @ast::Pat { id: 0, node: ast::PatWild, span: dummy_sp() }; enter_match(bcx, dm, m, col, val, |p| { match p.node { ast::PatRegion(sub) => { Some(~[sub]) } _ => { assert_is_binding_or_wild(bcx, p); Some(~[dummy]) } } }) } // Returns the options in one column of matches. An option is something that // needs to be conditionally matched at runtime; for example, the discriminant // on a set of enum variants or a literal. fn get_options(bcx: @mut Block, m: &[Match], col: uint) -> ~[Opt] { let ccx = bcx.ccx(); fn add_to_set(tcx: ty::ctxt, set: &mut ~[Opt], val: Opt) { if set.iter().any(|l| opt_eq(tcx, l, &val)) {return;} set.push(val); } // Vector comparisions are special in that since the actual // conditions over-match, we need to be careful about them. This // means that in order to properly handle things in order, we need // to not always merge conditions. fn add_veclen_to_set(set: &mut ~[Opt], i: uint, len: uint, vlo: VecLenOpt) { match set.last_opt() { // If the last condition in the list matches the one we want // to add, then extend its range. Otherwise, make a new // vec_len with a range just covering the new entry. Some(&vec_len(len2, vlo2, (start, end))) if len == len2 && vlo == vlo2 => set[set.len() - 1] = vec_len(len, vlo, (start, end+1)), _ => set.push(vec_len(len, vlo, (i, i))) } } let mut found = ~[]; for (i, br) in m.iter().enumerate() { let cur = br.pats[col]; match cur.node { ast::PatLit(l) => { add_to_set(ccx.tcx, &mut found, lit(ExprLit(l))); } ast::PatIdent(..) => { // This is one of: an enum variant, a unit-like struct, or a // variable binding. match ccx.tcx.def_map.find(&cur.id) { Some(&ast::DefVariant(..)) => { add_to_set(ccx.tcx, &mut found, variant_opt(bcx, cur.id)); } Some(&ast::DefStruct(..)) => { add_to_set(ccx.tcx, &mut found, lit(UnitLikeStructLit(cur.id))); } Some(&ast::DefStatic(const_did, false)) => { add_to_set(ccx.tcx, &mut found, lit(ConstLit(const_did))); } _ => {} } } ast::PatEnum(..) | ast::PatStruct(..) => { // This could be one of: a tuple-like enum variant, a // struct-like enum variant, or a struct. match ccx.tcx.def_map.find(&cur.id) { Some(&ast::DefFn(..)) | Some(&ast::DefVariant(..)) => { add_to_set(ccx.tcx, &mut found, variant_opt(bcx, cur.id)); } Some(&ast::DefStatic(const_did, false)) => { add_to_set(ccx.tcx, &mut found, lit(ConstLit(const_did))); } _ => {} } } ast::PatRange(l1, l2) => { add_to_set(ccx.tcx, &mut found, range(l1, l2)); } ast::PatVec(ref before, slice, ref after) => { let (len, vec_opt) = match slice { None => (before.len(), vec_len_eq), Some(_) => (before.len() + after.len(), vec_len_ge(before.len())) }; add_veclen_to_set(&mut found, i, len, vec_opt); } _ => {} } } return found; } struct ExtractedBlock { vals: ~[ValueRef], bcx: @mut Block } fn extract_variant_args(bcx: @mut Block, repr: &adt::Repr, disr_val: ty::Disr, val: ValueRef) -> ExtractedBlock { let _icx = push_ctxt("match::extract_variant_args"); let args = vec::from_fn(adt::num_args(repr, disr_val), |i| { adt::trans_field_ptr(bcx, repr, val, disr_val, i) }); ExtractedBlock { vals: args, bcx: bcx } } fn match_datum(bcx: @mut Block, val: ValueRef, pat_id: ast::NodeId) -> Datum { //! Helper for converting from the ValueRef that we pass around in //! the match code, which is always by ref, into a Datum. Eventually //! we should just pass around a Datum and be done with it. let ty = node_id_type(bcx, pat_id); Datum {val: val, ty: ty, mode: datum::ByRef(RevokeClean)} } fn extract_vec_elems(bcx: @mut Block, pat_span: Span, pat_id: ast::NodeId, elem_count: uint, slice: Option<uint>, val: ValueRef, count: ValueRef) -> ExtractedBlock { let _icx = push_ctxt("match::extract_vec_elems"); let vec_datum = match_datum(bcx, val, pat_id); let (bcx, base, len) = vec_datum.get_vec_base_and_len(bcx, pat_span, pat_id, 0); let vt = tvec::vec_types(bcx, node_id_type(bcx, pat_id)); let mut elems = vec::from_fn(elem_count, |i| { match slice { None => GEPi(bcx, base, [i]), Some(n) if i < n => GEPi(bcx, base, [i]), Some(n) if i > n => { InBoundsGEP(bcx, base, [ Sub(bcx, count, C_int(bcx.ccx(), (elem_count - i) as int))]) } _ => unsafe { llvm::LLVMGetUndef(vt.llunit_ty.to_ref()) } } }); if slice.is_some() { let n = slice.unwrap(); let slice_byte_offset = Mul(bcx, vt.llunit_size, C_uint(bcx.ccx(), n)); let slice_begin = tvec::pointer_add_byte(bcx, base, slice_byte_offset); let slice_len_offset = C_uint(bcx.ccx(), elem_count - 1u); let slice_len = Sub(bcx, len, slice_len_offset); let slice_ty = ty::mk_evec(bcx.tcx(), ty::mt {ty: vt.unit_ty, mutbl: ast::MutImmutable}, ty::vstore_slice(ty::ReStatic) ); let scratch = scratch_datum(bcx, slice_ty, "", false); Store(bcx, slice_begin, GEPi(bcx, scratch.val, [0u, abi::slice_elt_base]) ); Store(bcx, slice_len, GEPi(bcx, scratch.val, [0u, abi::slice_elt_len])); elems[n] = scratch.val; scratch.add_clean(bcx); } ExtractedBlock { vals: elems, bcx: bcx } } /// Checks every pattern in `m` at `col` column. /// If there are a struct pattern among them function /// returns list of all fields that are matched in these patterns. /// Function returns None if there is no struct pattern. /// Function doesn't collect fields from struct-like enum variants. /// Function can return empty list if there is only wildcard struct pattern. fn collect_record_or_struct_fields(bcx: @mut Block, m: &[Match], col: uint) -> Option<~[ast::Ident]> { let mut fields: ~[ast::Ident] = ~[]; let mut found = false; for br in m.iter() { match br.pats[col].node { ast::PatStruct(_, ref fs, _) => { match ty::get(node_id_type(bcx, br.pats[col].id)).sty { ty::ty_struct(..) => { extend(&mut fields, *fs); found = true; } _ => () } } _ => () } } if found { return Some(fields); } else { return None; } fn extend(idents: &mut ~[ast::Ident], field_pats: &[ast::FieldPat]) { for field_pat in field_pats.iter() { let field_ident = field_pat.ident; if !idents.iter().any(|x| x.name == field_ident.name) { idents.push(field_ident); } } } } fn pats_require_rooting(bcx: @mut Block, m: &[Match], col: uint) -> bool { m.iter().any(|br| { let pat_id = br.pats[col].id; let key = root_map_key {id: pat_id, derefs: 0u }; bcx.ccx().maps.root_map.contains_key(&key) }) } fn root_pats_as_necessary(mut bcx: @mut Block, m: &[Match], col: uint, val: ValueRef) -> @mut Block { for br in m.iter() { let pat_id = br.pats[col].id; if pat_id != 0 { let datum = Datum {val: val, ty: node_id_type(bcx, pat_id), mode: ByRef(ZeroMem)}; bcx = datum.root_and_write_guard(bcx, br.pats[col].span, pat_id, 0); } } return bcx; } // Macro for deciding whether any of the remaining matches fit a given kind of // pattern. Note that, because the macro is well-typed, either ALL of the // matches should fit that sort of pattern or NONE (however, some of the // matches may be wildcards like _ or identifiers). macro_rules! any_pat ( ($m:expr, $pattern:pat) => ( ($m).iter().any(|br| { match br.pats[col].node { $pattern => true, _ => false } }) ) ) fn any_box_pat(m: &[Match], col: uint) -> bool { any_pat!(m, ast::PatBox(_)) } fn any_uniq_pat(m: &[Match], col: uint) -> bool { any_pat!(m, ast::PatUniq(_)) } fn any_region_pat(m: &[Match], col: uint) -> bool { any_pat!(m, ast::PatRegion(_)) } fn any_tup_pat(m: &[Match], col: uint) -> bool { any_pat!(m, ast::PatTup(_)) } fn any_tuple_struct_pat(bcx: @mut Block, m: &[Match], col: uint) -> bool { m.iter().any(|br| { let pat = br.pats[col]; match pat.node { ast::PatEnum(_, Some(_)) => { match bcx.tcx().def_map.find(&pat.id) { Some(&ast::DefFn(..)) | Some(&ast::DefStruct(..)) => true, _ => false } } _ => false } }) } trait CustomFailureHandler { fn handle_fail(&self) -> BasicBlockRef; } struct DynamicFailureHandler { bcx: @mut Block, sp: Span, msg: @str, finished: @mut Option<BasicBlockRef>, } impl CustomFailureHandler for DynamicFailureHandler { fn handle_fail(&self) -> BasicBlockRef { match *self.finished { Some(bb) => return bb, _ => (), } let fail_cx = sub_block(self.bcx, "case_fallthrough"); controlflow::trans_fail(fail_cx, Some(self.sp), self.msg); *self.finished = Some(fail_cx.llbb); fail_cx.llbb } } /// What to do when the pattern match fails. enum FailureHandler { Infallible, JumpToBasicBlock(BasicBlockRef), CustomFailureHandlerClass(@CustomFailureHandler), } impl FailureHandler { fn is_infallible(&self) -> bool { match *self { Infallible => true, _ => false, } } fn is_fallible(&self) -> bool { !self.is_infallible() } fn handle_fail(&self) -> BasicBlockRef { match *self { Infallible => { fail!("attempted to fail in infallible failure handler!") } JumpToBasicBlock(basic_block) => basic_block, CustomFailureHandlerClass(custom_failure_handler) => { custom_failure_handler.handle_fail() } } } } fn pick_col(m: &[Match]) -> uint { fn score(p: &ast::Pat) -> uint { match p.node { ast::PatLit(_) | ast::PatEnum(_, _) | ast::PatRange(_, _) => 1u, ast::PatIdent(_, _, Some(p)) => score(p), _ => 0u } } let mut scores = vec::from_elem(m[0].pats.len(), 0u); for br in m.iter() { for (i, p) in br.pats.iter().enumerate() { scores[i] += score(*p); } } let mut max_score = 0u; let mut best_col = 0u; for (i, score) in scores.iter().enumerate() { let score = *score; // Irrefutable columns always go first, they'd only be duplicated in // the branches. if score == 0u { return i; } // If no irrefutable ones are found, we pick the one with the biggest // branching factor. if score > max_score { max_score = score; best_col = i; } } return best_col; } #[deriving(Eq)] pub enum branch_kind { no_branch, single, switch, compare, compare_vec_len, } // Compiles a comparison between two things. // // NB: This must produce an i1, not a Rust bool (i8). fn compare_values(cx: @mut Block, lhs: ValueRef, rhs: ValueRef, rhs_t: ty::t) -> Result { let _icx = push_ctxt("compare_values"); if ty::type_is_scalar(rhs_t) { let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq); return rslt(rs.bcx, rs.val); } match ty::get(rhs_t).sty { ty::ty_estr(ty::vstore_uniq) => { let scratch_lhs = alloca(cx, val_ty(lhs), "__lhs"); Store(cx, lhs, scratch_lhs); let scratch_rhs = alloca(cx, val_ty(rhs), "__rhs"); Store(cx, rhs, scratch_rhs); let did = langcall(cx, None, format!("comparison of `{}`", cx.ty_to_str(rhs_t)), UniqStrEqFnLangItem); let result = callee::trans_lang_call(cx, did, [scratch_lhs, scratch_rhs], None); Result { bcx: result.bcx, val: bool_to_i1(result.bcx, result.val) } } ty::ty_estr(_) => { let did = langcall(cx, None, format!("comparison of `{}`", cx.ty_to_str(rhs_t)), StrEqFnLangItem); let result = callee::trans_lang_call(cx, did, [lhs, rhs], None); Result { bcx: result.bcx, val: bool_to_i1(result.bcx, result.val) } } _ => { cx.tcx().sess.bug("only scalars and strings supported in \ compare_values"); } } } fn store_non_ref_bindings(bcx: @mut Block, bindings_map: &BindingsMap, mut opt_temp_cleanups: Option<&mut ~[ValueRef]>) -> @mut Block { /*! * * For each copy/move binding, copy the value from the value * being matched into its final home. This code executes once * one of the patterns for a given arm has completely matched. * It adds temporary cleanups to the `temp_cleanups` array, * if one is provided. */ let mut bcx = bcx; for (_, &binding_info) in bindings_map.iter() { match binding_info.trmode { TrByValue(lldest) => { let llval = Load(bcx, binding_info.llmatch); // get a T* let datum = Datum {val: llval, ty: binding_info.ty, mode: ByRef(ZeroMem)}; bcx = datum.store_to(bcx, INIT, lldest); opt_temp_cleanups.mutate(|temp_cleanups| { add_clean_temp_mem(bcx, lldest, binding_info.ty); temp_cleanups.push(lldest); temp_cleanups }); } TrByRef => {} } } return bcx; } fn insert_lllocals(bcx: @mut Block, bindings_map: &BindingsMap, add_cleans: bool) -> @mut Block { /*! * For each binding in `data.bindings_map`, adds an appropriate entry into * the `fcx.lllocals` map. If add_cleans is true, then adds cleanups for * the bindings. */ let llmap = bcx.fcx.lllocals; for (&ident, &binding_info) in bindings_map.iter() { let llval = match binding_info.trmode { // By value bindings: use the stack slot that we // copied/moved the value into TrByValue(lldest) => { if add_cleans { add_clean(bcx, lldest, binding_info.ty); } lldest } // By ref binding: use the ptr into the matched value TrByRef => { binding_info.llmatch } }; debug!("binding {:?} to {}", binding_info.id, bcx.val_to_str(llval)); llmap.insert(binding_info.id, llval); if bcx.sess().opts.extra_debuginfo { debuginfo::create_match_binding_metadata(bcx, ident, binding_info.id, binding_info.ty, binding_info.span); } } return bcx; } fn compile_guard(bcx: @mut Block, guard_expr: &ast::Expr, data: &ArmData, m: &[Match], vals: &[ValueRef], chk: FailureHandler) -> @mut Block { debug!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})", bcx.to_str(), bcx.expr_to_str(guard_expr), m.repr(bcx.tcx()), vec_map_to_str(vals, |v| bcx.val_to_str(*v))); let _indenter = indenter(); let mut bcx = bcx; let mut temp_cleanups = ~[]; bcx = store_non_ref_bindings(bcx, data.bindings_map, Some(&mut temp_cleanups)); bcx = insert_lllocals(bcx, data.bindings_map, false); let val = unpack_result!(bcx, { with_scope_result(bcx, guard_expr.info(), "guard", |bcx| { expr::trans_to_datum(bcx, guard_expr).to_result() }) }); let val = bool_to_i1(bcx, val); // Revoke the temp cleanups now that the guard successfully executed. for llval in temp_cleanups.iter() { revoke_clean(bcx, *llval); } return with_cond(bcx, Not(bcx, val), |bcx| { // Guard does not match: free the values we copied, // and remove all bindings from the lllocals table let bcx = drop_bindings(bcx, data); compile_submatch(bcx, m, vals, chk); bcx }); fn drop_bindings(bcx: @mut Block, data: &ArmData) -> @mut Block { let mut bcx = bcx; for (_, &binding_info) in data.bindings_map.iter() { match binding_info.trmode { TrByValue(llval) => { bcx = glue::drop_ty(bcx, llval, binding_info.ty); } TrByRef => {} } bcx.fcx.lllocals.remove(&binding_info.id); } return bcx; } } fn compile_submatch(bcx: @mut Block, m: &[Match], vals: &[ValueRef], chk: FailureHandler) { debug!("compile_submatch(bcx={}, m={}, vals={})", bcx.to_str(), m.repr(bcx.tcx()), vec_map_to_str(vals, |v| bcx.val_to_str(*v))); let _indenter = indenter(); /* For an empty match, a fall-through case must exist */ assert!((m.len() > 0u || chk.is_fallible())); let _icx = push_ctxt("match::compile_submatch"); let mut bcx = bcx; if m.len() == 0u { Br(bcx, chk.handle_fail()); return; } if m[0].pats.len() == 0u { let data = &m[0].data; for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() { let llmatch = data.bindings_map.get(ident).llmatch; Store(bcx, *value_ptr, llmatch); } match data.arm.guard { Some(guard_expr) => { bcx = compile_guard(bcx, guard_expr, &m[0].data, m.slice(1, m.len()), vals, chk); } _ => () } Br(bcx, data.bodycx.llbb); return; } let col = pick_col(m); let val = vals[col]; if has_nested_bindings(m, col) { let expanded = expand_nested_bindings(bcx, m, col, val); compile_submatch_continue(bcx, expanded, vals, chk, col, val) } else { compile_submatch_continue(bcx, m, vals, chk, col, val) } } fn compile_submatch_continue(mut bcx: @mut Block, m: &[Match], vals: &[ValueRef], chk: FailureHandler, col: uint, val: ValueRef) { let tcx = bcx.tcx(); let dm = tcx.def_map; let vals_left = vec::append(vals.slice(0u, col).to_owned(), vals.slice(col + 1u, vals.len())); let ccx = bcx.fcx.ccx; let mut pat_id = 0; let mut pat_span = dummy_sp(); for br in m.iter() { // Find a real id (we're adding placeholder wildcard patterns, but // each column is guaranteed to have at least one real pattern) if pat_id == 0 { pat_id = br.pats[col].id; pat_span = br.pats[col].span; } } // If we are not matching against an `@T`, we should not be // required to root any values. assert!(any_box_pat(m, col) || !pats_require_rooting(bcx, m, col)); match collect_record_or_struct_fields(bcx, m, col) { Some(ref rec_fields) => { let pat_ty = node_id_type(bcx, pat_id); let pat_repr = adt::represent_type(bcx.ccx(), pat_ty); expr::with_field_tys(tcx, pat_ty, None, |discr, field_tys| { let rec_vals = rec_fields.map(|field_name| { let ix = ty::field_idx_strict(tcx, field_name.name, field_tys); adt::trans_field_ptr(bcx, pat_repr, val, discr, ix) }); compile_submatch( bcx, enter_rec_or_struct(bcx, dm, m, col, *rec_fields, val), vec::append(rec_vals, vals_left), chk); }); return; } None => {} } if any_tup_pat(m, col) { let tup_ty = node_id_type(bcx, pat_id); let tup_repr = adt::represent_type(bcx.ccx(), tup_ty); let n_tup_elts = match ty::get(tup_ty).sty { ty::ty_tup(ref elts) => elts.len(), _ => ccx.sess.bug("non-tuple type in tuple pattern") }; let tup_vals = vec::from_fn(n_tup_elts, |i| { adt::trans_field_ptr(bcx, tup_repr, val, 0, i) }); compile_submatch(bcx, enter_tup(bcx, dm, m, col, val, n_tup_elts), vec::append(tup_vals, vals_left), chk); return; } if any_tuple_struct_pat(bcx, m, col) { let struct_ty = node_id_type(bcx, pat_id); let struct_element_count; match ty::get(struct_ty).sty { ty::ty_struct(struct_id, _) => { struct_element_count = ty::lookup_struct_fields(tcx, struct_id).len(); } _ => { ccx.sess.bug("non-struct type in tuple struct pattern"); } } let struct_repr = adt::represent_type(bcx.ccx(), struct_ty); let llstructvals = vec::from_fn(struct_element_count, |i| { adt::trans_field_ptr(bcx, struct_repr, val, 0, i) }); compile_submatch(bcx, enter_tuple_struct(bcx, dm, m, col, val, struct_element_count), vec::append(llstructvals, vals_left), chk); return; } // Unbox in case of a box field if any_box_pat(m, col) { bcx = root_pats_as_necessary(bcx, m, col, val); let llbox = Load(bcx, val); let unboxed = GEPi(bcx, llbox, [0u, abi::box_field_body]); compile_submatch(bcx, enter_box(bcx, dm, m, col, val), vec::append(~[unboxed], vals_left), chk); return; } if any_uniq_pat(m, col) { let pat_ty = node_id_type(bcx, pat_id); let llbox = Load(bcx, val); let unboxed = match ty::get(pat_ty).sty { ty::ty_uniq(..) if !ty::type_contents(bcx.tcx(), pat_ty).owns_managed() => llbox, _ => GEPi(bcx, llbox, [0u, abi::box_field_body]) }; compile_submatch(bcx, enter_uniq(bcx, dm, m, col, val), vec::append(~[unboxed], vals_left), chk); return; } if any_region_pat(m, col) { let loaded_val = Load(bcx, val); compile_submatch(bcx, enter_region(bcx, dm, m, col, val), vec::append(~[loaded_val], vals_left), chk); return; } // Decide what kind of branch we need let opts = get_options(bcx, m, col); debug!("options={:?}", opts); let mut kind = no_branch; let mut test_val = val; if opts.len() > 0u { match opts[0] { var(_, repr) => { let (the_kind, val_opt) = adt::trans_switch(bcx, repr, val); kind = the_kind; for &tval in val_opt.iter() { test_val = tval; } } lit(_) => { let pty = node_id_type(bcx, pat_id); test_val = load_if_immediate(bcx, val, pty); kind = if ty::type_is_integral(pty) { switch } else { compare }; } range(_, _) => { test_val = Load(bcx, val); kind = compare; }, vec_len(..) => { let vt = tvec::vec_types(bcx, node_id_type(bcx, pat_id)); let unboxed = load_if_immediate(bcx, val, vt.vec_ty); let (_, len) = tvec::get_base_and_len(bcx, unboxed, vt.vec_ty); test_val = len; kind = compare_vec_len; } } } for o in opts.iter() { match *o { range(_, _) => { kind = compare; break } _ => () } } let else_cx = match kind { no_branch | single => bcx, _ => sub_block(bcx, "match_else") }; let sw = if kind == switch { Switch(bcx, test_val, else_cx.llbb, opts.len()) } else { C_int(ccx, 0) // Placeholder for when not using a switch }; let defaults = enter_default(else_cx, dm, m, col, val, chk); let exhaustive = chk.is_infallible() && defaults.len() == 0u; let len = opts.len(); // Compile subtrees for each option for (i, opt) in opts.iter().enumerate() { // In some cases in vector pattern matching, we need to override // the failure case so that instead of failing, it proceeds to // try more matching. branch_chk, then, is the proper failure case // for the current conditional branch. let mut branch_chk = chk; let mut opt_cx = else_cx; if !exhaustive || i+1 < len { opt_cx = sub_block(bcx, "match_case"); match kind { single => Br(bcx, opt_cx.llbb), switch => { match trans_opt(bcx, opt) { single_result(r) => { unsafe { llvm::LLVMAddCase(sw, r.val, opt_cx.llbb); bcx = r.bcx; } } _ => { bcx.sess().bug( "in compile_submatch, expected \ trans_opt to return a single_result") } } } compare => { let t = node_id_type(bcx, pat_id); let Result {bcx: after_cx, val: matches} = { with_scope_result(bcx, None, "compaReScope", |bcx| { match trans_opt(bcx, opt) { single_result( Result {bcx, val}) => { compare_values(bcx, test_val, val, t) } lower_bound( Result {bcx, val}) => { compare_scalar_types( bcx, test_val, val, t, ast::BiGe) } range_result( Result {val: vbegin, ..}, Result {bcx, val: vend}) => { let Result {bcx, val: llge} = compare_scalar_types( bcx, test_val, vbegin, t, ast::BiGe); let Result {bcx, val: llle} = compare_scalar_types( bcx, test_val, vend, t, ast::BiLe); rslt(bcx, And(bcx, llge, llle)) } } }) }; bcx = sub_block(after_cx, "compare_next"); CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb); } compare_vec_len => { let Result {bcx: after_cx, val: matches} = { with_scope_result(bcx, None, "compare_vec_len_scope", |bcx| { match trans_opt(bcx, opt) { single_result( Result {bcx, val}) => { let value = compare_scalar_values( bcx, test_val, val, signed_int, ast::BiEq); rslt(bcx, value) } lower_bound( Result {bcx, val: val}) => { let value = compare_scalar_values( bcx, test_val, val, signed_int, ast::BiGe); rslt(bcx, value) } range_result( Result {val: vbegin, ..}, Result {bcx, val: vend}) => { let llge = compare_scalar_values( bcx, test_val, vbegin, signed_int, ast::BiGe); let llle = compare_scalar_values( bcx, test_val, vend, signed_int, ast::BiLe); rslt(bcx, And(bcx, llge, llle)) } } }) }; bcx = sub_block(after_cx, "compare_vec_len_next"); // If none of these subcases match, move on to the // next condition. branch_chk = JumpToBasicBlock(bcx.llbb); CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb); } _ => () } } else if kind == compare || kind == compare_vec_len { Br(bcx, else_cx.llbb); } let mut size = 0u; let mut unpacked = ~[]; match *opt { var(disr_val, repr) => { let ExtractedBlock {vals: argvals, bcx: new_bcx} = extract_variant_args(opt_cx, repr, disr_val, val); size = argvals.len(); unpacked = argvals; opt_cx = new_bcx; } vec_len(n, vt, _) => { let (n, slice) = match vt { vec_len_ge(i) => (n + 1u, Some(i)), vec_len_eq => (n, None) }; let args = extract_vec_elems(opt_cx, pat_span, pat_id, n, slice, val, test_val); size = args.vals.len(); unpacked = args.vals.clone(); opt_cx = args.bcx; } lit(_) | range(_, _) => () } let opt_ms = enter_opt(opt_cx, m, opt, col, size, val); let opt_vals = vec::append(unpacked, vals_left); compile_submatch(opt_cx, opt_ms, opt_vals, branch_chk); } // Compile the fall-through case, if any if !exhaustive { if kind == compare || kind == compare_vec_len { Br(bcx, else_cx.llbb); } if kind != single { compile_submatch(else_cx, defaults, vals_left, chk); } } } pub fn trans_match(bcx: @mut Block, match_expr: &ast::Expr, discr_expr: &ast::Expr, arms: &[ast::Arm], dest: Dest) -> @mut Block { let _icx = push_ctxt("match::trans_match"); with_scope(bcx, match_expr.info(), "match", |bcx| { trans_match_inner(bcx, discr_expr, arms, dest) }) } fn create_bindings_map(bcx: @mut Block, pat: @ast::Pat) -> BindingsMap { // Create the bindings map, which is a mapping from each binding name // to an alloca() that will be the value for that local variable. // Note that we use the names because each binding will have many ids // from the various alternatives. let ccx = bcx.ccx(); let tcx = bcx.tcx(); let mut bindings_map = HashMap::new(); pat_bindings(tcx.def_map, pat, |bm, p_id, span, path| { let ident = path_to_ident(path); let variable_ty = node_id_type(bcx, p_id); let llvariable_ty = type_of::type_of(ccx, variable_ty); let llmatch; let trmode; match bm { ast::BindByValue(_) => { // in this case, the final type of the variable will be T, // but during matching we need to store a *T as explained // above llmatch = alloca(bcx, llvariable_ty.ptr_to(), "__llmatch"); trmode = TrByValue(alloca(bcx, llvariable_ty, bcx.ident(ident))); } ast::BindByRef(_) => { llmatch = alloca(bcx, llvariable_ty, bcx.ident(ident)); trmode = TrByRef; } }; bindings_map.insert(ident, BindingInfo { llmatch: llmatch, trmode: trmode, id: p_id, span: span, ty: variable_ty }); }); return bindings_map; } fn trans_match_inner(scope_cx: @mut Block, discr_expr: &ast::Expr, arms: &[ast::Arm], dest: Dest) -> @mut Block { let _icx = push_ctxt("match::trans_match_inner"); let mut bcx = scope_cx; let tcx = bcx.tcx(); let discr_datum = unpack_datum!(bcx, { expr::trans_to_datum(bcx, discr_expr) }); if bcx.unreachable { return bcx; } let mut arm_datas = ~[]; let mut matches = ~[]; for arm in arms.iter() { let body = scope_block(bcx, arm.body.info(), "case_body"); let bindings_map = create_bindings_map(bcx, arm.pats[0]); let arm_data = ArmData { bodycx: body, arm: arm, bindings_map: @bindings_map }; arm_datas.push(arm_data.clone()); for p in arm.pats.iter() { matches.push(Match { pats: ~[*p], data: arm_data.clone(), bound_ptrs: ~[], }); } } let t = node_id_type(bcx, discr_expr.id); let chk = { if ty::type_is_empty(tcx, t) { // Special case for empty types let fail_cx = @mut None; let fail_handler = @DynamicFailureHandler { bcx: scope_cx, sp: discr_expr.span, msg: @"scrutinizing value that can't exist", finished: fail_cx, } as @CustomFailureHandler; CustomFailureHandlerClass(fail_handler) } else { Infallible } }; let lldiscr = discr_datum.to_ref_llval(bcx); compile_submatch(bcx, matches, [lldiscr], chk); let mut arm_cxs = ~[]; for arm_data in arm_datas.iter() { let mut bcx = arm_data.bodycx; // If this arm has a guard, then the various by-value bindings have // already been copied into their homes. If not, we do it here. This // is just to reduce code space. See extensive comment at the start // of the file for more details. if arm_data.arm.guard.is_none() { bcx = store_non_ref_bindings(bcx, arm_data.bindings_map, None); } // insert bindings into the lllocals map and add cleanups bcx = insert_lllocals(bcx, arm_data.bindings_map, true); bcx = controlflow::trans_block(bcx, arm_data.arm.body, dest); bcx = trans_block_cleanups(bcx, block_cleanups(arm_data.bodycx)); arm_cxs.push(bcx); } bcx = controlflow::join_blocks(scope_cx, arm_cxs); return bcx; } enum IrrefutablePatternBindingMode { // Stores the association between node ID and LLVM value in `lllocals`. BindLocal, // Stores the association between node ID and LLVM value in `llargs`. BindArgument } pub fn store_local(bcx: @mut Block, pat: @ast::Pat, opt_init_expr: Option<@ast::Expr>) -> @mut Block { /*! * Generates code for a local variable declaration like * `let <pat>;` or `let <pat> = <opt_init_expr>`. */ let _icx = push_ctxt("match::store_local"); let mut bcx = bcx; return match opt_init_expr { Some(init_expr) => { // Optimize the "let x = expr" case. This just writes // the result of evaluating `expr` directly into the alloca // for `x`. Often the general path results in similar or the // same code post-optimization, but not always. In particular, // in unsafe code, you can have expressions like // // let x = intrinsics::uninit(); // // In such cases, the more general path is unsafe, because // it assumes it is matching against a valid value. match simple_identifier(pat) { Some(path) => { return mk_binding_alloca( bcx, pat.id, path, BindLocal, |bcx, _, llval| expr::trans_into(bcx, init_expr, expr::SaveIn(llval))); } None => {} } // General path. let init_datum = unpack_datum!( bcx, expr::trans_to_datum(bcx, init_expr)); if ty::type_is_bot(expr_ty(bcx, init_expr)) { create_dummy_locals(bcx, pat) } else { if bcx.sess().asm_comments() { add_comment(bcx, "creating zeroable ref llval"); } let llptr = init_datum.to_ref_llval(bcx); return bind_irrefutable_pat(bcx, pat, llptr, BindLocal); } } None => { create_dummy_locals(bcx, pat) } }; fn create_dummy_locals(mut bcx: @mut Block, pat: @ast::Pat) -> @mut Block { // create dummy memory for the variables if we have no // value to store into them immediately let tcx = bcx.tcx(); pat_bindings(tcx.def_map, pat, |_, p_id, _, path| { bcx = mk_binding_alloca( bcx, p_id, path, BindLocal, |bcx, var_ty, llval| { zero_mem(bcx, llval, var_ty); bcx }); }); bcx } } pub fn store_arg(mut bcx: @mut Block, pat: @ast::Pat, llval: ValueRef) -> @mut Block { /*! * Generates code for argument patterns like `fn foo(<pat>: T)`. * Creates entries in the `llargs` map for each of the bindings * in `pat`. * * # Arguments * * - `pat` is the argument pattern * - `llval` is a pointer to the argument value (in other words, * if the argument type is `T`, then `llval` is a `T*`). In some * cases, this code may zero out the memory `llval` points at. */ let _icx = push_ctxt("match::store_arg"); // We always need to cleanup the argument as we exit the fn scope. // Note that we cannot do it before for fear of a fn like // fn getaddr(~ref x: ~uint) -> *uint {....} // (From test `run-pass/func-arg-ref-pattern.rs`) let arg_ty = node_id_type(bcx, pat.id); add_clean(bcx, llval, arg_ty); // Debug information (the llvm.dbg.declare intrinsic to be precise) always expects to get an // alloca, which only is the case on the general path, so lets disable the optimized path when // debug info is enabled. let fast_path = !bcx.ccx().sess.opts.extra_debuginfo && simple_identifier(pat).is_some(); if fast_path { // Optimized path for `x: T` case. This just adopts // `llval` wholesale as the pointer for `x`, avoiding the // general logic which may copy out of `llval`. bcx.fcx.llargs.insert(pat.id, llval); } else { // General path. Copy out the values that are used in the // pattern. bcx = bind_irrefutable_pat(bcx, pat, llval, BindArgument); } return bcx; } fn mk_binding_alloca(mut bcx: @mut Block, p_id: ast::NodeId, path: &ast::Path, binding_mode: IrrefutablePatternBindingMode, populate: |@mut Block, ty::t, ValueRef| -> @mut Block) -> @mut Block { let var_ty = node_id_type(bcx, p_id); let ident = ast_util::path_to_ident(path); let llval = alloc_ty(bcx, var_ty, bcx.ident(ident)); bcx = populate(bcx, var_ty, llval); let llmap = match binding_mode { BindLocal => bcx.fcx.lllocals, BindArgument => bcx.fcx.llargs }; llmap.insert(p_id, llval); add_clean(bcx, llval, var_ty); return bcx; } fn bind_irrefutable_pat(bcx: @mut Block, pat: @ast::Pat, val: ValueRef, binding_mode: IrrefutablePatternBindingMode) -> @mut Block { /*! * A simple version of the pattern matching code that only handles * irrefutable patterns. This is used in let/argument patterns, * not in match statements. Unifying this code with the code above * sounds nice, but in practice it produces very inefficient code, * since the match code is so much more general. In most cases, * LLVM is able to optimize the code, but it causes longer compile * times and makes the generated code nigh impossible to read. * * # Arguments * - bcx: starting basic block context * - pat: the irrefutable pattern being matched. * - val: a pointer to the value being matched. If pat matches a value * of type T, then this is a T*. If the value is moved from `pat`, * then `*pat` will be zeroed; otherwise, it's existing cleanup * applies. * - binding_mode: is this for an argument or a local variable? */ debug!("bind_irrefutable_pat(bcx={}, pat={}, binding_mode={:?})", bcx.to_str(), pat.repr(bcx.tcx()), binding_mode); if bcx.sess().asm_comments() { add_comment(bcx, format!("bind_irrefutable_pat(pat={})", pat.repr(bcx.tcx()))); } let _indenter = indenter(); let _icx = push_ctxt("alt::bind_irrefutable_pat"); let mut bcx = bcx; let tcx = bcx.tcx(); let ccx = bcx.ccx(); match pat.node { ast::PatIdent(pat_binding_mode, ref path, inner) => { if pat_is_binding(tcx.def_map, pat) { // Allocate the stack slot where the value of this // binding will live and place it into the appropriate // map. bcx = mk_binding_alloca( bcx, pat.id, path, binding_mode, |bcx, variable_ty, llvariable_val| { match pat_binding_mode { ast::BindByValue(_) => { // By value binding: move the value that `val` // points at into the binding's stack slot. let datum = Datum {val: val, ty: variable_ty, mode: ByRef(ZeroMem)}; datum.store_to(bcx, INIT, llvariable_val) } ast::BindByRef(_) => { // By ref binding: the value of the variable // is the pointer `val` itself. Store(bcx, val, llvariable_val); bcx } } }); } for &inner_pat in inner.iter() { bcx = bind_irrefutable_pat(bcx, inner_pat, val, binding_mode); } } ast::PatEnum(_, ref sub_pats) => { match bcx.tcx().def_map.find(&pat.id) { Some(&ast::DefVariant(enum_id, var_id, _)) => { let repr = adt::represent_node(bcx, pat.id); let vinfo = ty::enum_variant_with_id(ccx.tcx, enum_id, var_id); let args = extract_variant_args(bcx, repr, vinfo.disr_val, val); for sub_pat in sub_pats.iter() { for (i, argval) in args.vals.iter().enumerate() { bcx = bind_irrefutable_pat(bcx, sub_pat[i], *argval, binding_mode); } } } Some(&ast::DefFn(..)) | Some(&ast::DefStruct(..)) => { match *sub_pats { None => { // This is a unit-like struct. Nothing to do here. } Some(ref elems) => { // This is the tuple struct case. let repr = adt::represent_node(bcx, pat.id); for (i, elem) in elems.iter().enumerate() { let fldptr = adt::trans_field_ptr(bcx, repr, val, 0, i); bcx = bind_irrefutable_pat(bcx, *elem, fldptr, binding_mode); } } } } Some(&ast::DefStatic(_, false)) => { } _ => { // Nothing to do here. } } } ast::PatStruct(_, ref fields, _) => { let tcx = bcx.tcx(); let pat_ty = node_id_type(bcx, pat.id); let pat_repr = adt::represent_type(bcx.ccx(), pat_ty); expr::with_field_tys(tcx, pat_ty, None, |discr, field_tys| { for f in fields.iter() { let ix = ty::field_idx_strict(tcx, f.ident.name, field_tys); let fldptr = adt::trans_field_ptr(bcx, pat_repr, val, discr, ix); bcx = bind_irrefutable_pat(bcx, f.pat, fldptr, binding_mode); } }) } ast::PatTup(ref elems) => { let repr = adt::represent_node(bcx, pat.id); for (i, elem) in elems.iter().enumerate() { let fldptr = adt::trans_field_ptr(bcx, repr, val, 0, i); bcx = bind_irrefutable_pat(bcx, *elem, fldptr, binding_mode); } } ast::PatBox(inner) | ast::PatUniq(inner) => { let pat_ty = node_id_type(bcx, pat.id); let llbox = Load(bcx, val); let unboxed = match ty::get(pat_ty).sty { ty::ty_uniq(..) if !ty::type_contents(bcx.tcx(), pat_ty).owns_managed() => llbox, _ => GEPi(bcx, llbox, [0u, abi::box_field_body]) }; bcx = bind_irrefutable_pat(bcx, inner, unboxed, binding_mode); } ast::PatRegion(inner) => { let loaded_val = Load(bcx, val); bcx = bind_irrefutable_pat(bcx, inner, loaded_val, binding_mode); } ast::PatVec(..) => { bcx.tcx().sess.span_bug( pat.span, format!("vector patterns are never irrefutable!")); } ast::PatWild | ast::PatWildMulti | ast::PatLit(_) | ast::PatRange(_, _) => () } return bcx; } fn simple_identifier<'a>(pat: &'a ast::Pat) -> Option<&'a ast::Path> { match pat.node { ast::PatIdent(ast::BindByValue(_), ref path, None) => { Some(path) } _ => { None } } }
37.255989
98
0.487919
0a30e4d48c5b3dd68ebc300df56a19fa9164f527
1,320
// This file is part of security-keys-rust. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/security-keys-rust/master/COPYRIGHT. No part of security-keys-rust, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2021 The developers of security-keys-rust. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/security-keys-rust/master/COPYRIGHT. #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] enum TagParseError { OutOfDataForSubsequentByte { subsequent_byte_index: u8, }, ShiftedTooFar { subsequent_byte_index: u8, }, FirstSubsequentByteHasLower7BitsAllZero, } impl Display for TagParseError { #[inline(always)] fn fmt(&self, f: &mut Formatter) -> fmt::Result { Debug::fmt(self, f) } } impl error::Error for TagParseError { #[inline(always)] fn source(&self) -> Option<&(dyn error::Error + 'static)> { use Self::*; match self { OutOfDataForSubsequentByte { .. } => None, ShiftedTooFar { .. } => None, FirstSubsequentByteHasLower7BitsAllZero => None, } } }
28.085106
411
0.733333
d9dd0ff9736c54b2968b9f0bb109c05fb1c17ed2
202
#[cfg(target_os = "windows")] #[path = "win32/mod.rs"] pub mod api; #[cfg(target_os = "linux")] #[path = "linux/mod.rs"] pub mod api; #[cfg(target_os = "macos")] #[path = "cocoa/mod.rs"] pub mod api;
16.833333
29
0.60396
6786b47c441828894ff7e0272932f1f40a205228
21,429
use { crate::{broadcast_stage::BroadcastStage, retransmit_stage::RetransmitStage}, itertools::Itertools, lru::LruCache, rand::{seq::SliceRandom, Rng, SeedableRng}, rand_chacha::ChaChaRng, solana_gossip::{ cluster_info::{compute_retransmit_peers, ClusterInfo}, contact_info::ContactInfo, crds::GossipRoute, crds_gossip_pull::CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS, crds_value::{CrdsData, CrdsValue}, weighted_shuffle::WeightedShuffle, }, solana_ledger::shred::Shred, solana_runtime::bank::Bank, solana_sdk::{ clock::{Epoch, Slot}, feature_set, pubkey::Pubkey, signature::Keypair, timing::timestamp, }, solana_streamer::socket::SocketAddrSpace, std::{ any::TypeId, cmp::Reverse, collections::HashMap, iter::{once, repeat_with}, marker::PhantomData, net::SocketAddr, ops::Deref, sync::{Arc, Mutex}, time::{Duration, Instant}, }, }; #[allow(clippy::large_enum_variant)] enum NodeId { // TVU node obtained through gossip (staked or not). ContactInfo(ContactInfo), // Staked node with no contact-info in gossip table. Pubkey(Pubkey), } pub struct Node { node: NodeId, stake: u64, } pub struct ClusterNodes<T> { pubkey: Pubkey, // The local node itself. // All staked nodes + other known tvu-peers + the node itself; // sorted by (stake, pubkey) in descending order. nodes: Vec<Node>, // Reverse index from nodes pubkey to their index in self.nodes. index: HashMap<Pubkey, /*index:*/ usize>, weighted_shuffle: WeightedShuffle</*stake:*/ u64>, _phantom: PhantomData<T>, } type CacheEntry<T> = Option<(/*as of:*/ Instant, Arc<ClusterNodes<T>>)>; pub struct ClusterNodesCache<T> { // Cache entries are wrapped in Arc<Mutex<...>>, so that, when needed, only // one thread does the computations to update the entry for the epoch. cache: Mutex<LruCache<Epoch, Arc<Mutex<CacheEntry<T>>>>>, ttl: Duration, // Time to live. } impl Node { #[inline] fn pubkey(&self) -> Pubkey { match &self.node { NodeId::Pubkey(pubkey) => *pubkey, NodeId::ContactInfo(node) => node.id, } } #[inline] fn contact_info(&self) -> Option<&ContactInfo> { match &self.node { NodeId::Pubkey(_) => None, NodeId::ContactInfo(node) => Some(node), } } } impl<T> ClusterNodes<T> { pub(crate) fn num_peers(&self) -> usize { self.nodes.len().saturating_sub(1) } // A peer is considered live if they generated their contact info recently. pub(crate) fn num_peers_live(&self, now: u64) -> usize { self.nodes .iter() .filter(|node| node.pubkey() != self.pubkey) .filter_map(|node| node.contact_info()) .filter(|node| { let elapsed = if node.wallclock < now { now - node.wallclock } else { node.wallclock - now }; elapsed < CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS }) .count() } } impl ClusterNodes<BroadcastStage> { pub fn new(cluster_info: &ClusterInfo, stakes: &HashMap<Pubkey, u64>) -> Self { new_cluster_nodes(cluster_info, stakes) } pub(crate) fn get_broadcast_addrs( &self, shred: &Shred, root_bank: &Bank, fanout: usize, socket_addr_space: &SocketAddrSpace, ) -> Vec<SocketAddr> { const MAX_CONTACT_INFO_AGE: Duration = Duration::from_secs(2 * 60); let shred_seed = shred.seed(self.pubkey, root_bank); let mut rng = ChaChaRng::from_seed(shred_seed); let index = match self.weighted_shuffle.first(&mut rng) { None => return Vec::default(), Some(index) => index, }; if let Some(node) = self.nodes[index].contact_info() { let now = timestamp(); let age = Duration::from_millis(now.saturating_sub(node.wallclock)); if age < MAX_CONTACT_INFO_AGE && ContactInfo::is_valid_address(&node.tvu, socket_addr_space) { return vec![node.tvu]; } } let mut rng = ChaChaRng::from_seed(shred_seed); let nodes: Vec<&Node> = self .weighted_shuffle .clone() .shuffle(&mut rng) .map(|index| &self.nodes[index]) .collect(); if nodes.is_empty() { return Vec::default(); } if drop_redundant_turbine_path(shred.slot(), root_bank) { let peers = once(nodes[0]).chain(get_retransmit_peers(fanout, 0, &nodes)); let addrs = peers.filter_map(Node::contact_info).map(|peer| peer.tvu); return addrs .filter(|addr| ContactInfo::is_valid_address(addr, socket_addr_space)) .collect(); } let (neighbors, children) = compute_retransmit_peers(fanout, 0, &nodes); neighbors[..1] .iter() .filter_map(|node| Some(node.contact_info()?.tvu)) .chain( neighbors[1..] .iter() .filter_map(|node| Some(node.contact_info()?.tvu_forwards)), ) .chain( children .iter() .filter_map(|node| Some(node.contact_info()?.tvu)), ) .filter(|addr| ContactInfo::is_valid_address(addr, socket_addr_space)) .collect() } } impl ClusterNodes<RetransmitStage> { pub(crate) fn get_retransmit_addrs( &self, slot_leader: Pubkey, shred: &Shred, root_bank: &Bank, fanout: usize, ) -> Vec<SocketAddr> { let (neighbors, children) = self.get_retransmit_peers(slot_leader, shred, root_bank, fanout); if neighbors.is_empty() { let peers = children.into_iter().filter_map(Node::contact_info); return peers.map(|peer| peer.tvu).collect(); } // If the node is on the critical path (i.e. the first node in each // neighborhood), it should send the packet to tvu socket of its // children and also tvu_forward socket of its neighbors. Otherwise it // should only forward to tvu_forwards socket of its children. if neighbors[0].pubkey() != self.pubkey { return children .iter() .filter_map(|node| Some(node.contact_info()?.tvu_forwards)) .collect(); } // First neighbor is this node itself, so skip it. neighbors[1..] .iter() .filter_map(|node| Some(node.contact_info()?.tvu_forwards)) .chain( children .iter() .filter_map(|node| Some(node.contact_info()?.tvu)), ) .collect() } pub fn get_retransmit_peers( &self, slot_leader: Pubkey, shred: &Shred, root_bank: &Bank, fanout: usize, ) -> ( Vec<&Node>, // neighbors Vec<&Node>, // children ) { let shred_seed = shred.seed(slot_leader, root_bank); let mut weighted_shuffle = self.weighted_shuffle.clone(); // Exclude slot leader from list of nodes. if slot_leader == self.pubkey { error!("retransmit from slot leader: {}", slot_leader); } else if let Some(index) = self.index.get(&slot_leader) { weighted_shuffle.remove_index(*index); }; let mut rng = ChaChaRng::from_seed(shred_seed); let nodes: Vec<_> = weighted_shuffle .shuffle(&mut rng) .map(|index| &self.nodes[index]) .collect(); let self_index = nodes .iter() .position(|node| node.pubkey() == self.pubkey) .unwrap(); if drop_redundant_turbine_path(shred.slot(), root_bank) { let peers = get_retransmit_peers(fanout, self_index, &nodes); return (Vec::default(), peers.collect()); } let (neighbors, children) = compute_retransmit_peers(fanout, self_index, &nodes); // Assert that the node itself is included in the set of neighbors, at // the right offset. debug_assert_eq!(neighbors[self_index % fanout].pubkey(), self.pubkey); (neighbors, children) } } pub fn new_cluster_nodes<T: 'static>( cluster_info: &ClusterInfo, stakes: &HashMap<Pubkey, u64>, ) -> ClusterNodes<T> { let self_pubkey = cluster_info.id(); let nodes = get_nodes(cluster_info, stakes); let index: HashMap<_, _> = nodes .iter() .enumerate() .map(|(ix, node)| (node.pubkey(), ix)) .collect(); let broadcast = TypeId::of::<T>() == TypeId::of::<BroadcastStage>(); let stakes: Vec<u64> = nodes.iter().map(|node| node.stake).collect(); let mut weighted_shuffle = WeightedShuffle::new("cluster-nodes", &stakes); if broadcast { weighted_shuffle.remove_index(index[&self_pubkey]); } ClusterNodes { pubkey: self_pubkey, nodes, index, weighted_shuffle, _phantom: PhantomData::default(), } } // All staked nodes + other known tvu-peers + the node itself; // sorted by (stake, pubkey) in descending order. fn get_nodes(cluster_info: &ClusterInfo, stakes: &HashMap<Pubkey, u64>) -> Vec<Node> { let self_pubkey = cluster_info.id(); // The local node itself. std::iter::once({ let stake = stakes.get(&self_pubkey).copied().unwrap_or_default(); let node = NodeId::from(cluster_info.my_contact_info()); Node { node, stake } }) // All known tvu-peers from gossip. .chain(cluster_info.tvu_peers().into_iter().map(|node| { let stake = stakes.get(&node.id).copied().unwrap_or_default(); let node = NodeId::from(node); Node { node, stake } })) // All staked nodes. .chain( stakes .iter() .filter(|(_, stake)| **stake > 0) .map(|(&pubkey, &stake)| Node { node: NodeId::from(pubkey), stake, }), ) .sorted_by_key(|node| Reverse((node.stake, node.pubkey()))) // Since sorted_by_key is stable, in case of duplicates, this // will keep nodes with contact-info. .dedup_by(|a, b| a.pubkey() == b.pubkey()) .collect() } // root : [0] // 1st layer: [1, 2, ..., fanout] // 2nd layer: [[fanout + 1, ..., fanout * 2], // [fanout * 2 + 1, ..., fanout * 3], // ... // [fanout * fanout + 1, ..., fanout * (fanout + 1)]] // 3rd layer: ... // ... // The leader node broadcasts shreds to the root node. // The root node retransmits the shreds to all nodes in the 1st layer. // Each other node retransmits shreds to fanout many nodes in the next layer. // For example the node k in the 1st layer will retransmit to nodes: // fanout + k, 2*fanout + k, ..., fanout*fanout + k fn get_retransmit_peers<T: Copy>( fanout: usize, index: usize, // Local node's index withing the nodes slice. nodes: &[T], ) -> impl Iterator<Item = T> + '_ { // Node's index within its neighborhood. let offset = index.saturating_sub(1) % fanout; // First node in the neighborhood. let anchor = index - offset; let step = if index == 0 { 1 } else { fanout }; (anchor * fanout + offset + 1..) .step_by(step) .take(fanout) .map(|i| nodes.get(i)) .while_some() .copied() } impl<T> ClusterNodesCache<T> { pub fn new( // Capacity of underlying LRU-cache in terms of number of epochs. cap: usize, // A time-to-live eviction policy is enforced to refresh entries in // case gossip contact-infos are updated. ttl: Duration, ) -> Self { Self { cache: Mutex::new(LruCache::new(cap)), ttl, } } } impl<T: 'static> ClusterNodesCache<T> { fn get_cache_entry(&self, epoch: Epoch) -> Arc<Mutex<CacheEntry<T>>> { let mut cache = self.cache.lock().unwrap(); match cache.get(&epoch) { Some(entry) => Arc::clone(entry), None => { let entry = Arc::default(); cache.put(epoch, Arc::clone(&entry)); entry } } } pub(crate) fn get( &self, shred_slot: Slot, root_bank: &Bank, working_bank: &Bank, cluster_info: &ClusterInfo, ) -> Arc<ClusterNodes<T>> { let epoch = root_bank.get_leader_schedule_epoch(shred_slot); let entry = self.get_cache_entry(epoch); // Hold the lock on the entry here so that, if needed, only // one thread recomputes cluster-nodes for this epoch. let mut entry = entry.lock().unwrap(); if let Some((asof, nodes)) = entry.deref() { if asof.elapsed() < self.ttl { return Arc::clone(nodes); } } let epoch_staked_nodes = [root_bank, working_bank] .iter() .find_map(|bank| bank.epoch_staked_nodes(epoch)); if epoch_staked_nodes.is_none() { inc_new_counter_info!("cluster_nodes-unknown_epoch_staked_nodes", 1); if epoch != root_bank.get_leader_schedule_epoch(root_bank.slot()) { return self.get(root_bank.slot(), root_bank, working_bank, cluster_info); } inc_new_counter_info!("cluster_nodes-unknown_epoch_staked_nodes_root", 1); } let nodes = Arc::new(new_cluster_nodes::<T>( cluster_info, &epoch_staked_nodes.unwrap_or_default(), )); *entry = Some((Instant::now(), Arc::clone(&nodes))); nodes } } impl From<ContactInfo> for NodeId { fn from(node: ContactInfo) -> Self { NodeId::ContactInfo(node) } } impl From<Pubkey> for NodeId { fn from(pubkey: Pubkey) -> Self { NodeId::Pubkey(pubkey) } } pub fn make_test_cluster<R: Rng>( rng: &mut R, num_nodes: usize, unstaked_ratio: Option<(u32, u32)>, ) -> ( Vec<ContactInfo>, HashMap<Pubkey, u64>, // stakes ClusterInfo, ) { let (unstaked_numerator, unstaked_denominator) = unstaked_ratio.unwrap_or((1, 7)); let mut nodes: Vec<_> = repeat_with(|| ContactInfo::new_rand(rng, None)) .take(num_nodes) .collect(); nodes.shuffle(rng); let this_node = nodes[0].clone(); let mut stakes: HashMap<Pubkey, u64> = nodes .iter() .filter_map(|node| { if rng.gen_ratio(unstaked_numerator, unstaked_denominator) { None // No stake for some of the nodes. } else { Some((node.id, rng.gen_range(0, 20))) } }) .collect(); // Add some staked nodes with no contact-info. stakes.extend(repeat_with(|| (Pubkey::new_unique(), rng.gen_range(0, 20))).take(100)); let cluster_info = ClusterInfo::new( this_node, Arc::new(Keypair::new()), SocketAddrSpace::Unspecified, ); { let now = timestamp(); let mut gossip_crds = cluster_info.gossip.crds.write().unwrap(); // First node is pushed to crds table by ClusterInfo constructor. for node in nodes.iter().skip(1) { let node = CrdsData::ContactInfo(node.clone()); let node = CrdsValue::new_unsigned(node); assert_eq!( gossip_crds.insert(node, now, GossipRoute::LocalMessage), Ok(()) ); } } (nodes, stakes, cluster_info) } fn drop_redundant_turbine_path(shred_slot: Slot, root_bank: &Bank) -> bool { let feature_slot = root_bank .feature_set .activated_slot(&feature_set::drop_redundant_turbine_path::id()); match feature_slot { None => false, Some(feature_slot) => { let epoch_schedule = root_bank.epoch_schedule(); let feature_epoch = epoch_schedule.get_epoch(feature_slot); let shred_epoch = epoch_schedule.get_epoch(shred_slot); feature_epoch < shred_epoch } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cluster_nodes_retransmit() { let mut rng = rand::thread_rng(); let (nodes, stakes, cluster_info) = make_test_cluster(&mut rng, 1_000, None); // ClusterInfo::tvu_peers excludes the node itself. assert_eq!(cluster_info.tvu_peers().len(), nodes.len() - 1); let cluster_nodes = new_cluster_nodes::<RetransmitStage>(&cluster_info, &stakes); // All nodes with contact-info should be in the index. // Staked nodes with no contact-info should be included. assert!(cluster_nodes.nodes.len() > nodes.len()); // Assert that all nodes keep their contact-info. // and, all staked nodes are also included. { let cluster_nodes: HashMap<_, _> = cluster_nodes .nodes .iter() .map(|node| (node.pubkey(), node)) .collect(); for node in &nodes { assert_eq!(cluster_nodes[&node.id].contact_info().unwrap().id, node.id); } for (pubkey, stake) in &stakes { if *stake > 0 { assert_eq!(cluster_nodes[pubkey].stake, *stake); } } } } #[test] fn test_cluster_nodes_broadcast() { let mut rng = rand::thread_rng(); let (nodes, stakes, cluster_info) = make_test_cluster(&mut rng, 1_000, None); // ClusterInfo::tvu_peers excludes the node itself. assert_eq!(cluster_info.tvu_peers().len(), nodes.len() - 1); let cluster_nodes = ClusterNodes::<BroadcastStage>::new(&cluster_info, &stakes); // All nodes with contact-info should be in the index. // Excluding this node itself. // Staked nodes with no contact-info should be included. assert!(cluster_nodes.nodes.len() > nodes.len()); // Assert that all nodes keep their contact-info. // and, all staked nodes are also included. { let cluster_nodes: HashMap<_, _> = cluster_nodes .nodes .iter() .map(|node| (node.pubkey(), node)) .collect(); for node in &nodes { assert_eq!(cluster_nodes[&node.id].contact_info().unwrap().id, node.id); } for (pubkey, stake) in &stakes { if *stake > 0 { assert_eq!(cluster_nodes[pubkey].stake, *stake); } } } } #[test] fn test_get_retransmit_peers() { // fanout 2 let index = vec![ 7, // root 6, 10, // 1st layer // 2nd layer 5, 19, // 1st neighborhood 0, 14, // 2nd // 3rd layer 3, 1, // 1st neighborhood 12, 2, // 2nd 11, 4, // 3rd 15, 18, // 4th // 4th layer 13, 16, // 1st neighborhood 17, 9, // 2nd 8, // 3rd ]; let peers = vec![ vec![6, 10], vec![5, 0], vec![19, 14], vec![3, 12], vec![1, 2], vec![11, 15], vec![4, 18], vec![13, 17], vec![16, 9], vec![8], ]; for (k, peers) in peers.into_iter().enumerate() { let retransmit_peers = get_retransmit_peers(/*fanout:*/ 2, k, &index); assert_eq!(retransmit_peers.collect::<Vec<_>>(), peers); } for k in 10..=index.len() { let mut retransmit_peers = get_retransmit_peers(/*fanout:*/ 2, k, &index); assert_eq!(retransmit_peers.next(), None); } // fanout 3 let index = vec![ 19, // root 14, 15, 28, // 1st layer // 2nd layer 29, 4, 5, // 1st neighborhood 9, 16, 7, // 2nd 26, 23, 2, // 3rd // 3rd layer 31, 3, 17, // 1st neighborhood 20, 25, 0, // 2nd 13, 30, 18, // 3rd 35, 21, 22, // 4th 6, 8, 11, // 5th 27, 1, 10, // 6th 12, 24, 34, // 7th 33, 32, // 8th ]; let peers = vec![ vec![14, 15, 28], vec![29, 9, 26], vec![4, 16, 23], vec![5, 7, 2], vec![31, 20, 13], vec![3, 25, 30], vec![17, 0, 18], vec![35, 6, 27], vec![21, 8, 1], vec![22, 11, 10], vec![12, 33], vec![24, 32], vec![34], ]; for (k, peers) in peers.into_iter().enumerate() { let retransmit_peers = get_retransmit_peers(/*fanout:*/ 3, k, &index); assert_eq!(retransmit_peers.collect::<Vec<_>>(), peers); } for k in 13..=index.len() { let mut retransmit_peers = get_retransmit_peers(/*fanout:*/ 3, k, &index); assert_eq!(retransmit_peers.next(), None); } } }
34.2864
90
0.547156
cc021da30b8b9072510b7cd946c5440f43461285
15,486
#![warn(missing_docs)] use crate::architecture::{ arm::{ communication_interface::{ ApInformation::{MemoryAp, Other}, ArmProbeInterface, MemoryApInformation, }, core::{debug_core_start, reset_catch_clear, reset_catch_set}, memory::Component, SwoConfig, }, riscv::communication_interface::RiscvCommunicationInterface, }; use crate::config::{ ChipInfo, MemoryRegion, RawFlashAlgorithm, RegistryError, Target, TargetSelector, }; use crate::core::{Architecture, CoreState, SpecificCoreState}; use crate::{AttachMethod, Core, CoreType, Error, Probe}; use anyhow::anyhow; use std::time::Duration; /// The `Session` struct represents an active debug session. /// /// ## Creating a session /// /// It can be conviently created by calling the [Session::auto_attach()] function, /// which tries to automatically select a probe, and then connect to the target. /// /// For more control, the [Probe::attach()] and [Probe::attach_under_reset()] /// methods can be used to open a `Session` from a specific [Probe]. /// /// # Usage /// To get access to a single [Core] from the `Session`, the [Session::core()] method /// can be used. /// /// You can create and share a session between threads to enable multiple stakeholders (e.g. GDB and RTT) to access the target /// taking turns. If you do so, please make sure that both threads sleep in between tasks such that other shareholders may take their turn. #[derive(Debug)] pub struct Session { target: Target, interface: ArchitectureInterface, cores: Vec<(SpecificCoreState, CoreState)>, } #[derive(Debug)] enum ArchitectureInterface { Arm(Box<dyn ArmProbeInterface + 'static>), Riscv(Box<RiscvCommunicationInterface>), } impl From<ArchitectureInterface> for Architecture { fn from(value: ArchitectureInterface) -> Self { match value { ArchitectureInterface::Arm(_) => Architecture::Arm, ArchitectureInterface::Riscv(_) => Architecture::Riscv, } } } impl ArchitectureInterface { fn attach<'probe>( &'probe mut self, core: &'probe mut SpecificCoreState, core_state: &'probe mut CoreState, ) -> Result<Core<'probe>, Error> { match self { ArchitectureInterface::Arm(state) => { let memory = state.memory_interface(0.into())?; core.attach_arm(core_state, memory) } ArchitectureInterface::Riscv(state) => core.attach_riscv(core_state, state), } } /// Deassert the target reset line /// /// When connecting under reset, /// initial configuration is done with the reset line /// asserted. After initial configuration is done, the /// reset line can be deasserted using this method. /// /// See also [`Probe::target_reset_deassert`]. fn target_reset_deassert(&mut self) -> Result<(), Error> { match self { ArchitectureInterface::Arm(arm_interface) => arm_interface.target_reset_deassert()?, ArchitectureInterface::Riscv(riscv_interface) => { riscv_interface.target_reset_deassert()? } } Ok(()) } } impl Session { /// Open a new session with a given debug target. pub(crate) fn new( probe: Probe, target: impl Into<TargetSelector>, attach_method: AttachMethod, ) -> Result<Self, Error> { let (probe, target) = get_target_from_selector(target, probe)?; let mut session = match target.architecture() { Architecture::Arm => { let core = ( SpecificCoreState::from_core_type(target.core_type), Core::create_state(0), ); let interface = probe.try_into_arm_interface().map_err(|(_, err)| err)?; let mut session = Session { target, interface: ArchitectureInterface::Arm(interface), cores: vec![core], }; // Enable debug mode debug_core_start(&mut session.core(0)?)?; if attach_method == AttachMethod::UnderReset { // we need to halt the chip here reset_catch_set(&mut session.core(0)?)?; // Deassert the reset pin session.interface.target_reset_deassert()?; // Wait for the core to be halted let mut core = session.core(0)?; core.wait_for_core_halted(Duration::from_millis(100))?; reset_catch_clear(&mut core)?; } session } Architecture::Riscv => { // TODO: Handle attach under reset let core = ( SpecificCoreState::from_core_type(target.core_type), Core::create_state(0), ); let interface = probe .try_into_riscv_interface() .map_err(|(_probe, err)| err)?; let mut session = Session { target, interface: ArchitectureInterface::Riscv(Box::new(interface)), cores: vec![core], }; { let mut core = session.core(0)?; core.halt(Duration::from_millis(100))?; } session } }; session.clear_all_hw_breakpoints()?; Ok(session) } /// Automatically creates a session with the first connected probe found. pub fn auto_attach(target: impl Into<TargetSelector>) -> Result<Session, Error> { // Get a list of all available debug probes. let probes = Probe::list_all(); // Use the first probe found. let probe = probes .get(0) .ok_or(Error::UnableToOpenProbe("No probe was found"))? .open()?; // Attach to a chip. probe.attach(target) } /// Lists the available cores with their number and their type. pub fn list_cores(&self) -> Vec<(usize, CoreType)> { self.cores .iter() .map(|(t, _)| CoreType::from(t)) .enumerate() .collect() } /// Attaches to the core with the given number. pub fn core(&mut self, n: usize) -> Result<Core<'_>, Error> { let (core, core_state) = self.cores.get_mut(n).ok_or(Error::CoreNotFound(n))?; self.interface.attach(core, core_state) } /// Returns a list of the flash algotithms on the target. pub(crate) fn flash_algorithms(&self) -> &[RawFlashAlgorithm] { &self.target.flash_algorithms } /// Read available data from the SWO interface without waiting. /// /// This method is only supported for ARM-based targets, and will /// return [Error::ArchitectureRequired] otherwise. pub fn read_swo(&mut self) -> Result<Vec<u8>, Error> { let interface = self.get_arm_interface()?; interface.read_swo() } fn get_arm_interface(&mut self) -> Result<&mut Box<dyn ArmProbeInterface>, Error> { let interface = match &mut self.interface { ArchitectureInterface::Arm(state) => state, _ => return Err(Error::ArchitectureRequired(&["ARMv7", "ARMv8"])), }; Ok(interface) } /// Reads all the available ARM CoresightComponents of the currently attached target. /// /// This will recursively parse the Romtable of the attached target /// and create a list of all the contained components. pub fn get_arm_components(&mut self) -> Result<Vec<Component>, Error> { let interface = self.get_arm_interface()?; let mut components = Vec::new(); for ap_index in 0..(interface.num_access_ports() as u8) { let ap_information = interface .ap_information(ap_index.into()) .ok_or_else(|| anyhow!("AP {} does not exist on chip.", ap_index))?; let component = match ap_information { MemoryAp(MemoryApInformation { port_number: _, only_32bit_data_size: _, debug_base_address: 0, supports_hnonsec: _, }) => Err(Error::Other(anyhow!("AP has a base address of 0"))), MemoryAp(MemoryApInformation { port_number, only_32bit_data_size: _, debug_base_address, supports_hnonsec: _, }) => { let access_port_number = *port_number; let base_address = *debug_base_address; let mut memory = interface.memory_interface(access_port_number.into())?; Component::try_parse(&mut memory, base_address) .map_err(Error::architecture_specific) } Other { port_number } => { // Return an error, only possible to get Component from MemoryAP Err(Error::Other(anyhow!( "AP {} is not a MemoryAP, unable to get ARM component.", port_number ))) } }; match component { Ok(component) => { components.push(component); } Err(e) => { log::info!("Not counting AP {} because of: {}", ap_index, e); } } } Ok(components) } /// Configure the target and probe for serial wire view (SWV) tracing. pub fn setup_swv(&mut self, config: &SwoConfig) -> Result<(), Error> { // Configure SWO on the probe { let interface = self.get_arm_interface()?; interface.enable_swo(config)?; } // Enable tracing on the target { let mut core = self.core(0)?; crate::architecture::arm::component::enable_tracing(&mut core)?; } // Configure SWV on the target let components = self.get_arm_components()?; let mut core = self.core(0)?; crate::architecture::arm::component::setup_swv(&mut core, &components, config) } /// Configure the target to stop emitting SWV trace data. pub fn disable_swv(&mut self) -> Result<(), Error> { crate::architecture::arm::component::disable_swv(&mut self.core(0)?) } /// Begin tracing a memory address over SWV. pub fn add_swv_data_trace(&mut self, unit: usize, address: u32) -> Result<(), Error> { let components = self.get_arm_components()?; let mut core = self.core(0)?; crate::architecture::arm::component::add_swv_data_trace( &mut core, &components, unit, address, ) } /// Stop tracing from a given SWV unit pub fn remove_swv_data_trace(&mut self, unit: usize) -> Result<(), Error> { let components = self.get_arm_components()?; let mut core = self.core(0)?; crate::architecture::arm::component::remove_swv_data_trace(&mut core, &components, unit) } /// Returns the memory map of the target. #[deprecated = "Use the Session::target function instead"] pub fn memory_map(&self) -> &[MemoryRegion] { &self.target.memory_map } /// Get the target description of the connected target. pub fn target(&self) -> &Target { &self.target } /// Return the `Architecture` of the currently connected chip. pub fn architecture(&self) -> Architecture { match self.interface { ArchitectureInterface::Arm(_) => Architecture::Arm, ArchitectureInterface::Riscv(_) => Architecture::Riscv, } } /// Clears all hardware breakpoints on all cores pub fn clear_all_hw_breakpoints(&mut self) -> Result<(), Error> { { 0..self.cores.len() }.try_for_each(|n| { self.core(n) .and_then(|mut core| core.clear_all_hw_breakpoints()) }) } } // This test ensures that [Session] is fully [Send] + [Sync]. static_assertions::assert_impl_all!(Session: Send); impl Drop for Session { fn drop(&mut self) { let result = { 0..self.cores.len() }.try_for_each(|i| { self.core(i) .and_then(|mut core| core.clear_all_set_hw_breakpoints()) }); if let Err(err) = result { log::warn!("Could not clear all hardware breakpoints: {:?}", err); } } } /// Determine the [Target] from a [TargetSelector]. /// /// If the selector is [TargetSelector::Unspecified], the target will be looked up in the registry. /// If it its [TargetSelector::Auto], probe-rs will try to determine the target automatically, based on /// information read from the chip. fn get_target_from_selector( target: impl Into<TargetSelector>, probe: Probe, ) -> Result<(Probe, Target), Error> { let mut probe = probe; let target = match target.into() { TargetSelector::Unspecified(name) => crate::config::get_target_by_name(name)?, TargetSelector::Specified(target) => target, TargetSelector::Auto => { let mut found_chip = None; if probe.has_arm_interface() { match probe.try_into_arm_interface() { Ok(mut interface) => { //let chip_result = try_arm_autodetect(interface); log::debug!("Autodetect: Trying DAP interface..."); let found_arm_chip = interface.read_from_rom_table().unwrap_or_else(|e| { log::info!("Error during auto-detection of ARM chips: {}", e); None }); found_chip = found_arm_chip.map(ChipInfo::from); probe = interface.close(); } Err((returned_probe, err)) => { probe = returned_probe; log::debug!("Error using ARM interface: {}", err); } } } else { log::debug!("No ARM interface was present. Skipping Riscv autodetect."); } if found_chip.is_none() && probe.has_riscv_interface() { match probe.try_into_riscv_interface() { Ok(mut interface) => { let idcode = interface.read_idcode(); log::debug!("ID Code read over JTAG: {:x?}", idcode); probe = interface.close(); } Err((returned_probe, err)) => { log::debug!("Error during autodetection of RISCV chips: {}", err); probe = returned_probe; } } } else { log::debug!("No RISCV interface was present. Skipping Riscv autodetect."); } if let Some(chip) = found_chip { crate::config::get_target_by_chip_info(chip)? } else { return Err(Error::ChipNotFound(RegistryError::ChipAutodetectFailed)); } } }; Ok((probe, target)) }
35.036199
139
0.555469
eda1242cd41d56c8d17615fbe11efa8c0b2cc0de
9,998
use crate::contact_info::ContactInfo; use bincode::serialize; use solana_sdk::pubkey::Pubkey; use solana_sdk::signature::{Keypair, Signable, Signature}; use solana_sdk::transaction::Transaction; use std::borrow::Cow; use std::collections::BTreeSet; use std::fmt; /// CrdsValue that is replicated across the cluster #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub enum CrdsValue { /// * Merge Strategy - Latest wallclock is picked ContactInfo(ContactInfo), /// * Merge Strategy - Latest wallclock is picked Vote(Vote), /// * Merge Strategy - Latest wallclock is picked EpochSlots(EpochSlots), } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct EpochSlots { pub from: Pubkey, pub root: u64, pub slots: BTreeSet<u64>, pub signature: Signature, pub wallclock: u64, } impl EpochSlots { pub fn new(from: Pubkey, root: u64, slots: BTreeSet<u64>, wallclock: u64) -> Self { Self { from, root, slots, signature: Signature::default(), wallclock, } } } impl Signable for EpochSlots { fn pubkey(&self) -> Pubkey { self.from } fn signable_data(&self) -> Cow<[u8]> { #[derive(Serialize)] struct SignData<'a> { root: u64, slots: &'a BTreeSet<u64>, wallclock: u64, } let data = SignData { root: self.root, slots: &self.slots, wallclock: self.wallclock, }; Cow::Owned(serialize(&data).expect("unable to serialize EpochSlots")) } fn get_signature(&self) -> Signature { self.signature } fn set_signature(&mut self, signature: Signature) { self.signature = signature; } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct Vote { pub from: Pubkey, pub transaction: Transaction, pub signature: Signature, pub wallclock: u64, } impl Vote { pub fn new(from: &Pubkey, transaction: Transaction, wallclock: u64) -> Self { Self { from: *from, transaction, signature: Signature::default(), wallclock, } } } impl Signable for Vote { fn pubkey(&self) -> Pubkey { self.from } fn signable_data(&self) -> Cow<[u8]> { #[derive(Serialize)] struct SignData<'a> { transaction: &'a Transaction, wallclock: u64, } let data = SignData { transaction: &self.transaction, wallclock: self.wallclock, }; Cow::Owned(serialize(&data).expect("unable to serialize Vote")) } fn get_signature(&self) -> Signature { self.signature } fn set_signature(&mut self, signature: Signature) { self.signature = signature } } /// 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(Pubkey), EpochSlots(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(_) => write!(f, "Vote({})", self.pubkey()), CrdsValueLabel::EpochSlots(_) => write!(f, "EpochSlots({})", self.pubkey()), } } } impl CrdsValueLabel { pub fn pubkey(&self) -> Pubkey { match self { CrdsValueLabel::ContactInfo(p) => *p, CrdsValueLabel::Vote(p) => *p, CrdsValueLabel::EpochSlots(p) => *p, } } } impl CrdsValue { /// 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 { CrdsValue::ContactInfo(contact_info) => contact_info.wallclock, CrdsValue::Vote(vote) => vote.wallclock, CrdsValue::EpochSlots(vote) => vote.wallclock, } } pub fn label(&self) -> CrdsValueLabel { match self { CrdsValue::ContactInfo(contact_info) => { CrdsValueLabel::ContactInfo(contact_info.pubkey()) } CrdsValue::Vote(vote) => CrdsValueLabel::Vote(vote.pubkey()), CrdsValue::EpochSlots(slots) => CrdsValueLabel::EpochSlots(slots.pubkey()), } } pub fn contact_info(&self) -> Option<&ContactInfo> { match self { CrdsValue::ContactInfo(contact_info) => Some(contact_info), _ => None, } } pub fn vote(&self) -> Option<&Vote> { match self { CrdsValue::Vote(vote) => Some(vote), _ => None, } } pub fn epoch_slots(&self) -> Option<&EpochSlots> { match self { CrdsValue::EpochSlots(slots) => Some(slots), _ => None, } } /// Return all the possible labels for a record identified by Pubkey. pub fn record_labels(key: &Pubkey) -> [CrdsValueLabel; 3] { [ CrdsValueLabel::ContactInfo(*key), CrdsValueLabel::Vote(*key), CrdsValueLabel::EpochSlots(*key), ] } } impl Signable for CrdsValue { fn sign(&mut self, keypair: &Keypair) { match self { CrdsValue::ContactInfo(contact_info) => contact_info.sign(keypair), CrdsValue::Vote(vote) => vote.sign(keypair), CrdsValue::EpochSlots(epoch_slots) => epoch_slots.sign(keypair), }; } fn verify(&self) -> bool { match self { CrdsValue::ContactInfo(contact_info) => contact_info.verify(), CrdsValue::Vote(vote) => vote.verify(), CrdsValue::EpochSlots(epoch_slots) => epoch_slots.verify(), } } fn pubkey(&self) -> Pubkey { match self { CrdsValue::ContactInfo(contact_info) => contact_info.pubkey(), CrdsValue::Vote(vote) => vote.pubkey(), CrdsValue::EpochSlots(epoch_slots) => epoch_slots.pubkey(), } } fn signable_data(&self) -> Cow<[u8]> { unimplemented!() } fn get_signature(&self) -> Signature { match self { CrdsValue::ContactInfo(contact_info) => contact_info.get_signature(), CrdsValue::Vote(vote) => vote.get_signature(), CrdsValue::EpochSlots(epoch_slots) => epoch_slots.get_signature(), } } fn set_signature(&mut self, _: Signature) { unimplemented!() } } #[cfg(test)] mod test { use super::*; use crate::contact_info::ContactInfo; use crate::test_tx::test_tx; use bincode::deserialize; use solana_sdk::signature::{Keypair, KeypairUtil}; use solana_sdk::timing::timestamp; #[test] fn test_labels() { let mut hits = [false; 3]; // this method should cover all the possible labels for v in &CrdsValue::record_labels(&Pubkey::default()) { match v { CrdsValueLabel::ContactInfo(_) => hits[0] = true, CrdsValueLabel::Vote(_) => hits[1] = true, CrdsValueLabel::EpochSlots(_) => hits[2] = true, } } assert!(hits.iter().all(|x| *x)); } #[test] fn test_keys_and_values() { let v = CrdsValue::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::Vote(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(key)); let v = CrdsValue::EpochSlots(EpochSlots::new(Pubkey::default(), 0, BTreeSet::new(), 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::ContactInfo(ContactInfo::new_localhost(&keypair.pubkey(), timestamp())); verify_signatures(&mut v, &keypair, &wrong_keypair); v = CrdsValue::Vote(Vote::new(&keypair.pubkey(), test_tx(), timestamp())); verify_signatures(&mut v, &keypair, &wrong_keypair); let btreeset: BTreeSet<u64> = vec![1, 2, 3, 6, 8].into_iter().collect(); v = CrdsValue::EpochSlots(EpochSlots::new(keypair.pubkey(), 0, btreeset, timestamp())); verify_signatures(&mut v, &keypair, &wrong_keypair); } fn test_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()); test_serialize_deserialize_value(value, correct_keypair); } }
31.341693
97
0.585517
f985260a76e6567ebd06e7f8e16f8a64e42d3460
245
// Copyright 2022 - Nym Technologies SA <[email protected]> // SPDX-License-Identifier: Apache-2.0 use config::defaults::DENOM; use cosmwasm_std::Coin; pub mod events; pub mod messages; pub fn one_ucoin() -> Coin { Coin::new(1, DENOM) }
20.416667
61
0.710204
4a2a7e293fc7f10e316cb431f595703420666bf4
8,569
// Copyright (c) 2018 Alexander Færøy. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use std::cmp::Ordering; use std::collections::HashMap; pub type GuardID = u32; #[derive(Debug, Eq, PartialEq)] pub enum EventType { // Our guard wakes up. GuardAwake, // Our guard falls asleep. GuardAsleep, // New guard begins their shift. GuardBeginsShift(GuardID), } #[derive(Debug, Eq, PartialEq)] pub struct Event { // Our date + time. datetime: DateTime, // Our event type. event_type: EventType, } impl Event { pub fn new(datetime: DateTime, event_type: EventType) -> Event { Event { datetime, event_type, } } pub fn event_type(&self) -> &EventType { &self.event_type } pub fn datetime(&self) -> &DateTime { &self.datetime } } impl Ord for Event { fn cmp(&self, other: &Event) -> Ordering { self.datetime.cmp(&other.datetime) } } impl PartialOrd for Event { fn partial_cmp(&self, other: &Event) -> Option<Ordering> { Some(self.cmp(other)) } } #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Date { // Our year. year: i32, // Our month. month: u32, // Our day. day: u32, } impl Date { pub fn new(year: i32, month: u32, day: u32) -> Date { Date { year, month, day } } pub fn year(&self) -> i32 { self.year } pub fn month(&self) -> u32 { self.month } pub fn day(&self) -> u32 { self.day } } #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Time { // Our hour. hour: u8, // Our minutes. minutes: u8, } impl Time { pub fn new(hour: u8, minutes: u8) -> Time { Time { hour, minutes } } pub fn hour(&self) -> u8 { self.hour } pub fn minutes(&self) -> u8 { self.minutes } } #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct DateTime { // Our date. date: Date, // Our time. time: Time, } impl DateTime { pub fn new(date: Date, time: Time) -> DateTime { DateTime { date, time } } pub fn date(&self) -> &Date { &self.date } pub fn time(&self) -> &Time { &self.time } } pub struct GuardSummary { // The ID of our guard. id: GuardID, // Time slot where the guard was most often asleep. most_missed_timestamp: Time, // Amount of times the guard was asleep at `most_missed_timestamp`. most_missed_timestamp_count: usize, // Total minutes slept. minutes_asleep: usize, } impl GuardSummary { pub fn new( id: GuardID, most_missed_timestamp: Time, most_missed_timestamp_count: usize, minutes_asleep: usize, ) -> GuardSummary { GuardSummary { id, most_missed_timestamp, most_missed_timestamp_count, minutes_asleep, } } pub fn id(&self) -> GuardID { self.id } pub fn most_missed_timestamp(&self) -> &Time { &self.most_missed_timestamp } pub fn most_missed_timestamp_count(&self) -> usize { self.most_missed_timestamp_count } pub fn minutes_asleep(&self) -> usize { self.minutes_asleep } } pub struct EventTracker { // The current guard on duty. current_guard: GuardID, // Tracking of minutes asleep for each guard. sleep_tracker: HashMap<GuardID, SleepTracker>, } impl EventTracker { pub fn new() -> EventTracker { EventTracker { current_guard: 0, sleep_tracker: HashMap::new(), } } pub fn event(&mut self, event: &Event) { match event.event_type() { EventType::GuardAsleep => self.asleep(event.datetime()), EventType::GuardAwake => self.awake(event.datetime()), EventType::GuardBeginsShift(guard) => self.begins_shift(guard), } } fn asleep(&mut self, datetime: &DateTime) { self.sleep_tracker .get_mut(&self.current_guard) .unwrap() .asleep(datetime); } fn awake(&mut self, datetime: &DateTime) { self.sleep_tracker .get_mut(&self.current_guard) .unwrap() .awake(datetime); } fn begins_shift(&mut self, guard: &GuardID) { if !self.sleep_tracker.contains_key(guard) { self.sleep_tracker.insert(*guard, SleepTracker::new()); } self.current_guard = *guard; } pub fn summaries(&self) -> Vec<GuardSummary> { // Our result. let mut result = Vec::new(); for (guard_id, sleep_tracker) in self.sleep_tracker.iter() { // Mapping between `(Hour, Minute) -> Count` used to keep track at which time the given // Guard sleeps the most. let mut asleep_time_freq = HashMap::new(); // The sum of how many hours the guard is asleep at. let mut total_minutes_asleep = 0; // Loop over each minute the given guard was asleep and sum up the count. for minute in sleep_tracker.minutes_asleep().iter() { // Bump the value by 1. *asleep_time_freq.entry(minute.clone()).or_insert(0) += 1; // Bump our sum. total_minutes_asleep += 1; } // Figure out which point in time the guard is mostly asleep. let mut most_missed_timestamp_count = 0; let mut most_missed_timestamp = (0, 0); for (timestamp, count) in asleep_time_freq.iter() { if count > &most_missed_timestamp_count { most_missed_timestamp = timestamp.clone(); most_missed_timestamp_count = count.clone(); } } result.push(GuardSummary::new( *guard_id, Time::new(most_missed_timestamp.0 as u8, most_missed_timestamp.1 as u8), most_missed_timestamp_count, total_minutes_asleep, )); } result } } struct SleepDuration { start: DateTime, duration: u32, } impl SleepDuration { pub fn new(start: DateTime, duration: u32) -> SleepDuration { SleepDuration { start, duration } } pub fn minutes_asleep(&self) -> Vec<(u32, u32)> { let time = self.start.time(); let mut v = Vec::new(); for minute in 0..self.duration { let mut hour = time.hour() as u32; let mut min = time.minutes() as u32 + minute; if min > 59 { hour += 1; min = 0; } v.push((hour, min)); } v } } enum SleepTrackerState { Invalid, Asleep(DateTime), Awake, } pub struct SleepTracker { // Current state. state: SleepTrackerState, // Periods where we are asleep. sleep_periods: Vec<SleepDuration>, } impl SleepTracker { pub fn new() -> SleepTracker { SleepTracker { state: SleepTrackerState::Invalid, sleep_periods: Vec::new(), } } // We fell asleep. pub fn asleep(&mut self, datetime: &DateTime) { self.state = SleepTrackerState::Asleep(datetime.clone()); } // We woke up. pub fn awake(&mut self, other: &DateTime) { if let SleepTrackerState::Asleep(ref datetime) = self.state { // They always work on one day at a time. assert_eq!(datetime.date().year(), other.date().year()); assert_eq!(datetime.date().month(), other.date().month()); assert_eq!(datetime.date().day(), other.date().day()); let delta_minutes = (other.time().hour() - datetime.time().hour()) * 60 + (other.time().minutes() - datetime.time().minutes()); self.sleep_periods .push(SleepDuration::new(datetime.clone(), delta_minutes.into())); } else { // We arrived from a state which was not `Asleep`? Sounds weird. assert!(false); } self.state = SleepTrackerState::Awake; } // Returns a vector of all the minutes we have been asleep at. pub fn minutes_asleep(&self) -> Vec<(u32, u32)> { let mut m = Vec::new(); for x in self.sleep_periods.iter() { m.extend(x.minutes_asleep()); } m } }
23.736842
99
0.560859
1e8d1574d2b02aec590591a4e89bb590a586db4f
12,427
// Copyright 2017 GFX 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. use super::*; use cocoa::foundation::NSUInteger; use objc::runtime::{NO, YES}; #[repr(u64)] #[allow(non_camel_case_types)] #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum MTLBlendFactor { Zero = 0, One = 1, SourceColor = 2, OneMinusSourceColor = 3, SourceAlpha = 4, OneMinusSourceAlpha = 5, DestinationColor = 6, OneMinusDestinationColor = 7, DestinationAlpha = 8, OneMinusDestinationAlpha = 9, SourceAlphaSaturated = 10, BlendColor = 11, OneMinusBlendColor = 12, BlendAlpha = 13, OneMinusBlendAlpha = 14, Source1Color = 15, OneMinusSource1Color = 16, Source1Alpha = 17, OneMinusSource1Alpha = 18, } #[repr(u64)] #[allow(non_camel_case_types)] #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum MTLBlendOperation { Add = 0, Subtract = 1, ReverseSubtract = 2, Min = 3, Max = 4, } bitflags! { pub struct MTLColorWriteMask: NSUInteger { const Red = 0x1 << 3; const Green = 0x1 << 2; const Blue = 0x1 << 1; const Alpha = 0x1 << 0; } } #[repr(u64)] #[allow(non_camel_case_types)] #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum MTLPrimitiveTopologyClass { Unspecified = 0, Point = 1, Line = 2, Triangle = 3, } pub enum MTLRenderPipelineColorAttachmentDescriptor {} foreign_obj_type! { type CType = MTLRenderPipelineColorAttachmentDescriptor; pub struct RenderPipelineColorAttachmentDescriptor; pub struct RenderPipelineColorAttachmentDescriptorRef; } impl RenderPipelineColorAttachmentDescriptorRef { pub fn pixel_format(&self) -> MTLPixelFormat { unsafe { msg_send![self, pixelFormat] } } pub fn set_pixel_format(&self, pixel_format: MTLPixelFormat) { unsafe { msg_send![self, setPixelFormat: pixel_format] } } pub fn is_blending_enabled(&self) -> bool { unsafe { match msg_send![self, isBlendingEnabled] { YES => true, NO => false, _ => unreachable!(), } } } pub fn set_blending_enabled(&self, enabled: bool) { unsafe { msg_send![self, setBlendingEnabled: enabled] } } pub fn source_rgb_blend_factor(&self) -> MTLBlendFactor { unsafe { msg_send![self, sourceRGBBlendFactor] } } pub fn set_source_rgb_blend_factor(&self, blend_factor: MTLBlendFactor) { unsafe { msg_send![self, setSourceRGBBlendFactor: blend_factor] } } pub fn destination_rgb_blend_factor(&self) -> MTLBlendFactor { unsafe { msg_send![self, destinationRGBBlendFactor] } } pub fn set_destination_rgb_blend_factor(&self, blend_factor: MTLBlendFactor) { unsafe { msg_send![self, setDestinationRGBBlendFactor: blend_factor] } } pub fn rgb_blend_operation(&self) -> MTLBlendOperation { unsafe { msg_send![self, rgbBlendOperation] } } pub fn set_rgb_blend_operation(&self, blend_operation: MTLBlendOperation) { unsafe { msg_send![self, setRgbBlendOperation: blend_operation] } } pub fn source_alpha_blend_factor(&self) -> MTLBlendFactor { unsafe { msg_send![self, sourceAlphaBlendFactor] } } pub fn set_source_alpha_blend_factor(&self, blend_factor: MTLBlendFactor) { unsafe { msg_send![self, setSourceAlphaBlendFactor: blend_factor] } } pub fn destination_alpha_blend_factor(&self) -> MTLBlendFactor { unsafe { msg_send![self, destinationAlphaBlendFactor] } } pub fn set_destination_alpha_blend_factor(&self, blend_factor: MTLBlendFactor) { unsafe { msg_send![self, setDestinationAlphaBlendFactor: blend_factor] } } pub fn alpha_blend_operation(&self) -> MTLBlendOperation { unsafe { msg_send![self, alphaBlendOperation] } } pub fn set_alpha_blend_operation(&self, blend_operation: MTLBlendOperation) { unsafe { msg_send![self, setAlphaBlendOperation: blend_operation] } } pub fn write_mask(&self) -> MTLColorWriteMask { unsafe { msg_send![self, writeMask] } } pub fn set_write_mask(&self, mask: MTLColorWriteMask) { unsafe { msg_send![self, setWriteMask: mask] } } } pub enum MTLRenderPipelineReflection {} foreign_obj_type! { type CType = MTLRenderPipelineReflection; pub struct RenderPipelineReflection; pub struct RenderPipelineReflectionRef; } impl RenderPipelineReflection { #[cfg(feature = "private")] pub unsafe fn new( vertex_data: *mut std::ffi::c_void, fragment_data: *mut std::ffi::c_void, vertex_desc: *mut std::ffi::c_void, device: &DeviceRef, options: u64, flags: u64, ) -> Self { let class = class!(MTLRenderPipelineReflection); let this: RenderPipelineReflection = msg_send![class, alloc]; let this_alias: *mut Object = msg_send![this.as_ref(), initWithVertexData:vertex_data fragmentData:fragment_data serializedVertexDescriptor:vertex_desc device:device options:options flags:flags]; if this_alias.is_null() { panic!("[MTLRenderPipelineReflection init] failed"); } this } } impl RenderPipelineReflectionRef { pub fn fragment_arguments(&self) -> &Array<Argument> { unsafe { msg_send![self, fragmentArguments] } } pub fn vertex_arguments(&self) -> &Array<Argument> { unsafe { msg_send![self, vertexArguments] } } } pub enum MTLRenderPipelineDescriptor {} foreign_obj_type! { type CType = MTLRenderPipelineDescriptor; pub struct RenderPipelineDescriptor; pub struct RenderPipelineDescriptorRef; } impl RenderPipelineDescriptor { pub fn new() -> Self { unsafe { let class = class!(MTLRenderPipelineDescriptor); msg_send![class, new] } } } impl RenderPipelineDescriptorRef { pub fn label(&self) -> &str { unsafe { let label = msg_send![self, label]; crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { let nslabel = crate::nsstring_from_str(label); msg_send![self, setLabel: nslabel]; } } pub fn vertex_function(&self) -> Option<&FunctionRef> { unsafe { msg_send![self, vertexFunction] } } pub fn set_vertex_function(&self, function: Option<&FunctionRef>) { unsafe { msg_send![self, setVertexFunction: function] } } pub fn fragment_function(&self) -> Option<&FunctionRef> { unsafe { msg_send![self, fragmentFunction] } } pub fn set_fragment_function(&self, function: Option<&FunctionRef>) { unsafe { msg_send![self, setFragmentFunction: function] } } pub fn vertex_descriptor(&self) -> Option<&VertexDescriptorRef> { unsafe { msg_send![self, vertexDescriptor] } } pub fn set_vertex_descriptor(&self, descriptor: Option<&VertexDescriptorRef>) { unsafe { msg_send![self, setVertexDescriptor: descriptor] } } pub fn sample_count(&self) -> NSUInteger { unsafe { msg_send![self, sampleCount] } } pub fn set_sample_count(&self, count: NSUInteger) { unsafe { msg_send![self, setSampleCount: count] } } pub fn is_alpha_to_coverage_enabled(&self) -> bool { unsafe { match msg_send![self, isAlphaToCoverageEnabled] { YES => true, NO => false, _ => unreachable!(), } } } pub fn set_alpha_to_coverage_enabled(&self, enabled: bool) { unsafe { msg_send![self, setAlphaToCoverageEnabled: enabled] } } pub fn is_alpha_to_one_enabled(&self) -> bool { unsafe { match msg_send![self, isAlphaToOneEnabled] { YES => true, NO => false, _ => unreachable!(), } } } pub fn set_alpha_to_one_enabled(&self, enabled: bool) { unsafe { msg_send![self, setAlphaToOneEnabled: enabled] } } pub fn is_rasterization_enabled(&self) -> bool { unsafe { match msg_send![self, isRasterizationEnabled] { YES => true, NO => false, _ => unreachable!(), } } } pub fn set_rasterization_enabled(&self, enabled: bool) { unsafe { msg_send![self, setRasterizationEnabled: enabled] } } pub fn color_attachments(&self) -> &RenderPipelineColorAttachmentDescriptorArrayRef { unsafe { msg_send![self, colorAttachments] } } pub fn depth_attachment_pixel_format(&self) -> MTLPixelFormat { unsafe { msg_send![self, depthAttachmentPixelFormat] } } pub fn set_depth_attachment_pixel_format(&self, pixel_format: MTLPixelFormat) { unsafe { msg_send![self, setDepthAttachmentPixelFormat: pixel_format] } } pub fn stencil_attachment_pixel_format(&self) -> MTLPixelFormat { unsafe { msg_send![self, stencilAttachmentPixelFormat] } } pub fn set_stencil_attachment_pixel_format(&self, pixel_format: MTLPixelFormat) { unsafe { msg_send![self, setStencilAttachmentPixelFormat: pixel_format] } } pub fn input_primitive_topology(&self) -> MTLPrimitiveTopologyClass { unsafe { msg_send![self, inputPrimitiveTopology] } } pub fn set_input_primitive_topology(&self, topology: MTLPrimitiveTopologyClass) { unsafe { msg_send![self, setInputPrimitiveTopology: topology] } } #[cfg(feature = "private")] pub unsafe fn serialize_vertex_data(&self) -> *mut std::ffi::c_void { use std::ptr; let flags = 0; let err: *mut Object = ptr::null_mut(); msg_send![self, newSerializedVertexDataWithFlags:flags error:err] } #[cfg(feature = "private")] pub unsafe fn serialize_fragment_data(&self) -> *mut std::ffi::c_void { msg_send![self, serializeFragmentData] } pub fn support_indirect_command_buffers(&self) -> bool { unsafe { match msg_send![self, supportIndirectCommandBuffers] { YES => true, NO => false, _ => unreachable!(), } } } pub fn set_support_indirect_command_buffers(&self, support: bool) { unsafe { msg_send![self, setSupportIndirectCommandBuffers: support] } } } pub enum MTLRenderPipelineState {} foreign_obj_type! { type CType = MTLRenderPipelineState; pub struct RenderPipelineState; pub struct RenderPipelineStateRef; } impl RenderPipelineStateRef { pub fn label(&self) -> &str { unsafe { let label = msg_send![self, label]; crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { let nslabel = crate::nsstring_from_str(label); msg_send![self, setLabel: nslabel]; } } } pub enum MTLRenderPipelineColorAttachmentDescriptorArray {} foreign_obj_type! { type CType = MTLRenderPipelineColorAttachmentDescriptorArray; pub struct RenderPipelineColorAttachmentDescriptorArray; pub struct RenderPipelineColorAttachmentDescriptorArrayRef; } impl RenderPipelineColorAttachmentDescriptorArrayRef { pub fn object_at(&self, index: usize) -> Option<&RenderPipelineColorAttachmentDescriptorRef> { unsafe { msg_send![self, objectAtIndexedSubscript: index] } } pub fn set_object_at( &self, index: usize, attachment: Option<&RenderPipelineColorAttachmentDescriptorRef>, ) { unsafe { msg_send![self, setObject:attachment atIndexedSubscript:index] } } }
30.309756
98
0.628148
2272bb1ceb71c429b01620be42fcb9e4cdc46216
8,170
#![allow(non_snake_case)] #![allow(dead_code)] use crate::mlutils; use crate::map2d; use crate::map2d::{Map2d,writeAt,readAt,map2dDrawCircle}; use crate::Misc::{flattenVec2Map, Vec2}; // TODO< draw a object in motion and display result maxima classifications > // TODO< print visualization of the result with the highest ranked category to console > // TODO< discremenate between different classifications my keeping track of max > // TODO< use NN and train NN to filter results from primitive classifier! > // experiment for classification of motion in image // current result: doesn't work because it fids similarity to not moved circle pub fn expMotionClassifier0() { let subImgSize = 16; let mut categories:Vec<Vec<f64>> = vec![]; // vector with flattened map2d's of categories // array of movement directions of background let bgMotionDirs = &[ Vec2{x:0.001,y:0.001}, Vec2{x:0.1,y:0.001}, Vec2{x:-0.1,y:0.001}, Vec2{x:0.001,y:0.1}, Vec2{x:0.001,y:-0.1}]; // fill with uniform movement info without any object in front for iBackgroundMotion in bgMotionDirs { let catMap: Map2d<Vec2> = Map2d{arr:vec![*iBackgroundMotion;16*16],w:16,h:16}; categories.push(flattenVec2Map(&catMap)); } let nBgMotionCats = categories.len() as i32; // number of background motion categories // with with movements when a object is in front for iBgMotionIdx in 0..bgMotionDirs.len() { let iBgMotion = &bgMotionDirs[iBgMotionIdx]; for iFgMotionIdx in 0..bgMotionDirs.len() { let iFgMotion = &bgMotionDirs[iFgMotionIdx]; if iBgMotionIdx != iFgMotionIdx { // we can't differentiate between a object which is moving with the same velocity as the background! let mut catMap: Map2d<Vec2> = Map2d{arr:vec![*iBgMotion;16*16],w:16,h:16}; // draw object, in this case a circle let w = catMap.w; let h = catMap.h; map2dDrawCircle(&mut catMap, w/2,h/2,w/3,*iFgMotion); categories.push(flattenVec2Map(&catMap)); } } } let perceptDirMap:Map2d<Vec2> = Map2d{arr:vec![Vec2{x:0.06,y:0.001};32*32],w:32,h:32}; let mut clfnMaps:Vec<Map2d<f64>> = vec![]; for _i in 0..categories.len() { clfnMaps.push(Map2d::<f64>{arr:vec![0.0;(perceptDirMap.w*perceptDirMap.h) as usize],w:perceptDirMap.w,h:perceptDirMap.h}); } for iy in 0..perceptDirMap.h-subImgSize { for ix in 0..perceptDirMap.w-subImgSize { let iSubImg = map2d::crop(&perceptDirMap, ix, iy, subImgSize, subImgSize); // crop the motion map let iSubImgMapFlat:Vec<f64> = flattenVec2Map(&iSubImg); // flatten map to real vector // classify for this cropped image from the motion map for iCatIdx in 0..categories.len() { let iCat = &categories[iCatIdx]; let vecA:&Vec<f64> = &iSubImgMapFlat; let vecB:&Vec<f64> = iCat; let sim0 = mlutils::calcCosineSim(&vecA,&vecB); /* commented because not necessary because it didn't work // represent as boolean vectors let mut vecABool:Vec<bool> = convRealVecToQuantizedBoolVec(&iSubImgMapFlat); let mut vecBBool:Vec<bool> = convRealVecToQuantizedBoolVec(&vecB); // compute similarity based on quantized bool vectors // the similarity isn't useful with the extreme quantification let sim1:f64 = boolVecSim(&vecABool,&vecBBool); */ //debug //println!("cat[{}] {}", iCatIdx, sim0); writeAt(&mut clfnMaps[iCatIdx], iy,ix, sim0); } } } let threshold = 0.2; let maxima:Vec<ClsnWVal> = max(&clfnMaps, nBgMotionCats, threshold); println!("maxima ="); for iMaxima in maxima { println!(" {:?}", iMaxima); } println!("DONE"); } pub fn main() { expMotionClassifier0(); } // helper to convert real vector to quantized bool vector by cutting the interval [0.0;1.0] into different parts // TODO< refactor: refactor conversion to boolean array with #of ranges > pub fn convRealVecToQuantizedBoolVec(v:&[f64]) -> Vec<bool> { let mut res:Vec<bool> = vec![]; for iv in v { res.push(*iv < 0.5); res.push(*iv > 0.5); } res } // helper to compute similarity between bool vectors pub fn boolVecSim(a: &[bool], b: &[bool]) -> f64 { // compute difference let mut diffCnt:i64 = 0; for idx in 0..a.len() { if a[idx] != b[idx] { diffCnt+=1; } } let sim1:f64 = 1.0 - (diffCnt as f64) / (a.len() as f64); return sim1; } // classification with value #[derive(Debug, Clone, Copy)] pub struct ClsnWVal { pub val:f64, // classification pub cls:i64, pub x:i32, pub y:i32, } // need this for reading of map impl Default for ClsnWVal { fn default() -> ClsnWVal {ClsnWVal{val:0.0,cls:-1,x:-1,y:-1}} } // searches for the maximum classification of different maps // /param nBgMotionCats number of categories of background pub fn max(arr:&Vec<Map2d<f64>>, nBgMotionCats:i32, threshold:f64) -> Vec<ClsnWVal> { let w = arr[0].w; let h = arr[0].h; let mut maxMap = Map2d::<Option<ClsnWVal>>{arr:vec![None;(w*h) as usize],w:w,h:h}; // map with current maxima if nBgMotionCats == 0 { // ignore background categories for iy in 0..h { for ix in 0..w { let v = readAt(&arr[0],iy,ix); writeAt(&mut maxMap, iy,ix, Some(ClsnWVal{val:v,cls:0,x:ix,y:iy})); } } } let mut iClass:i64=1; for iArr in &arr[1..] { if (iClass as i32) > nBgMotionCats { // ignore background categories for iy in 0..h { for ix in 0..w { let r = readAt(&maxMap,iy,ix); let v = readAt(&iArr,iy,ix); if r.is_some() { let rval = r.unwrap().val; if v>rval { writeAt(&mut maxMap, iy,ix, Some(ClsnWVal{val:v,cls:iClass,x:ix,y:iy})); } } else { writeAt(&mut maxMap, iy,ix, Some(ClsnWVal{val:v,cls:iClass,x:ix,y:iy})); } } } } iClass+=1; } // search maxima loop { // loop until it doesn't change anymore let mut wasChanged = false; for iy in 0..h { for ix in 0..w { let maxV:Option<ClsnWVal> = readAt(&maxMap,iy,ix); let maxVX:Option<ClsnWVal> = readAt(&maxMap,iy,ix-1); let maxVY:Option<ClsnWVal> = readAt(&maxMap,iy-1,ix); if maxV.is_some() && maxVX.is_some() { if maxV.unwrap().val > maxVX.unwrap().val { writeAt(&mut maxMap,iy,ix-1,None); wasChanged = true; } else if maxV.unwrap().val < maxVX.unwrap().val { writeAt(&mut maxMap,iy,ix,None); wasChanged = true; } } if maxV.is_some() && maxVY.is_some() { if maxV.unwrap().val > maxVY.unwrap().val { writeAt(&mut maxMap,iy-1,ix,None); wasChanged = true; } else if maxV.unwrap().val < maxVY.unwrap().val { writeAt(&mut maxMap,iy,ix,None); wasChanged = true; } } } } if !wasChanged { break; // terminate if it wasn't changed } } // compute result array maxMap.arr.iter().filter(|v| v.is_some()).filter(|v| v.unwrap().val >= threshold).map(|v| v.unwrap()).collect() }
32.68
146
0.543819
dd8ffeae8c3f7a954d5def7faaad8e21e97d49fc
4,389
extern crate mithril; use std::f64; use std::num::Float; use self::mithril::math::{ Vector, Quaternion }; pub struct Camera { position: Vector, focus_point: Vector, up: Vector, field_of_view: f64, aspect_ratio: f64, far: f64, near: f64, anchor_point: Option<[f64; 2]>, control_point: [f64; 2], } impl Camera { pub fn new(position: Vector, focus_point: Vector, up: Vector) -> Camera { Camera{ position: position, focus_point: focus_point, up: up.normalize(), field_of_view: (90.0 * f64::consts::PI / 180.0), aspect_ratio: 640.0/480.0, far: 100.0, near: 1.0, anchor_point: None, control_point: [0.0; 2], } } pub fn position(&self) -> Vector { self.position } pub fn focus_point(&self) -> Vector { self.focus_point } pub fn go_to(&mut self, position: Vector) { self.position = position; } pub fn update(&mut self) { } pub fn start_control(&mut self, x: f64, y: f64) { self.anchor_point = Some([x, y]); self.control_point[0] = x; self.control_point[1] = y; } pub fn set_control_point(&mut self, x: f64, y: f64) { self.control_point[0] = x; self.control_point[1] = y; } pub fn release_controls(&mut self) { self.anchor_point = None; } pub fn is_controlled(&self) -> bool { self.anchor_point != None } pub fn view_matrix(&self) -> [f32; 16] { let mut z_view = (self.position - self.focus_point).normalize(); let mut x_view = self.up.cross(z_view).normalize(); let mut y_view = z_view.cross(x_view).normalize(); let x_trans = -self.position.dot(x_view); let y_trans = -self.position.dot(y_view); let z_trans = -self.position.dot(z_view); match self.anchor_point { Some(anchor_point) => { let diff = [ (self.control_point[1] - anchor_point[1]) as f32, (anchor_point[0] - self.control_point[0]) as f32, ]; let diff_sq = (diff[0] * diff[0] + diff[1] * diff[1]).sqrt(); if diff_sq > 0.0001 { let diff_length = diff_sq.sqrt(); let rot_axis = (x_view * diff[0] + y_view * diff[1]) / diff_length; let rot_in_radians = diff_length * 2.0; let u_quat = Quaternion::new(0.0, x_view[0], x_view[1], x_view[2]); let v_quat = Quaternion::new(0.0, y_view[0], y_view[1], y_view[2]); let w_quat = Quaternion::new(0.0, z_view[0], z_view[1], z_view[2]); let rot_quat = Quaternion::new_from_rotation(rot_in_radians, rot_axis[0], rot_axis[1], rot_axis[2]); let new_u_quat = rot_quat * u_quat * rot_quat.inverse(); let new_v_quat = rot_quat * v_quat * rot_quat.inverse(); let new_w_quat = rot_quat * w_quat * rot_quat.inverse(); x_view[0] = new_u_quat[1]; x_view[1] = new_u_quat[2]; x_view[2] = new_u_quat[3]; y_view[0] = new_v_quat[1]; y_view[1] = new_v_quat[2]; y_view[2] = new_v_quat[3]; z_view[0] = new_w_quat[1]; z_view[1] = new_w_quat[2]; z_view[2] = new_w_quat[3]; } } None => { // do nothing } } [ x_view[0], x_view[1], x_view[2], x_trans, y_view[0], y_view[1], y_view[2], y_trans, z_view[0], z_view[1], z_view[2], z_trans, 0.0, 0.0, 0.0, 1.0, ] } pub fn projection_matrix(&self) -> [f32; 16] { let m_11 = (1.0 / (self.field_of_view / 2.0).tan()) as f32; let m_22 = m_11 * (self.aspect_ratio as f32); let m_33 = -((self.far + self.near) / (self.far - self.near)) as f32; let m_43 = -((2.0 * self.far * self.near) / (self.far - self.near)) as f32; [ m_11, 0.0, 0.0, 0.0, 0.0, m_22, 0.0, 0.0, 0.0, 0.0, m_33, m_43, 0.0, 0.0, -1.0, 0.0, ] } }
31.804348
120
0.494874
fc2ac0163ce3a60c592f5853e91f71a22afb1723
10,362
// DO NOT EDIT ! // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! //! This documentation was generated from *datastore* crate version *1.0.14+20200524*, where *20200524* is the exact revision of the *datastore:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.14*. //! //! Everything else about the *datastore* *v1* API can be found at the //! [official documentation site](https://cloud.google.com/datastore/). //! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/datastore1). //! # Features //! //! Handle the following *Resources* with ease from the central [hub](Datastore) ... //! //! * projects //! * [*allocate ids*](api::ProjectAllocateIdCall), [*begin transaction*](api::ProjectBeginTransactionCall), [*commit*](api::ProjectCommitCall), [*export*](api::ProjectExportCall), [*import*](api::ProjectImportCall), [*indexes create*](api::ProjectIndexeCreateCall), [*indexes delete*](api::ProjectIndexeDeleteCall), [*indexes get*](api::ProjectIndexeGetCall), [*indexes list*](api::ProjectIndexeListCall), [*lookup*](api::ProjectLookupCall), [*operations cancel*](api::ProjectOperationCancelCall), [*operations delete*](api::ProjectOperationDeleteCall), [*operations get*](api::ProjectOperationGetCall), [*operations list*](api::ProjectOperationListCall), [*reserve ids*](api::ProjectReserveIdCall), [*rollback*](api::ProjectRollbackCall) and [*run query*](api::ProjectRunQueryCall) //! //! //! //! //! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](http://byron.github.io/google-apis-rs). //! //! # Structure of this Library //! //! The API is structured into the following primary items: //! //! * **[Hub](Datastore)** //! * a central object to maintain state and allow accessing all *Activities* //! * creates [*Method Builders*](client::MethodsBuilder) which in turn //! allow access to individual [*Call Builders*](client::CallBuilder) //! * **[Resources](client::Resource)** //! * primary types that you can apply *Activities* to //! * a collection of properties and *Parts* //! * **[Parts](client::Part)** //! * a collection of properties //! * never directly used in *Activities* //! * **[Activities](client::CallBuilder)** //! * operations to apply to *Resources* //! //! All *structures* are marked with applicable traits to further categorize them and ease browsing. //! //! Generally speaking, you can invoke *Activities* like this: //! //! ```Rust,ignore //! let r = hub.resource().activity(...).doit() //! ``` //! //! Or specifically ... //! //! ```ignore //! let r = hub.projects().indexes_create(...).doit() //! let r = hub.projects().indexes_delete(...).doit() //! let r = hub.projects().operations_get(...).doit() //! let r = hub.projects().export(...).doit() //! let r = hub.projects().import(...).doit() //! ``` //! //! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` //! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be //! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. //! The `doit()` method performs the actual communication with the server and returns the respective result. //! //! # Usage //! //! ## Setting up your Project //! //! To use this library, you would put the following lines into your `Cargo.toml` file: //! //! ```toml //! [dependencies] //! google-datastore1 = "*" //! # This project intentionally uses an old version of Hyper. See //! # https://github.com/Byron/google-apis-rs/issues/173 for more //! # information. //! hyper = "^0.14" //! hyper-rustls = "^0.22" //! serde = "^1.0" //! serde_json = "^1.0" //! yup-oauth2 = "^5.0" //! ``` //! //! ## A complete example //! //! ```test_harness,no_run //! extern crate hyper; //! extern crate hyper_rustls; //! extern crate yup_oauth2 as oauth2; //! extern crate google_datastore1 as datastore1; //! use datastore1::api::GoogleDatastoreAdminV1Index; //! use datastore1::{Result, Error}; //! # #[test] fn egal() { //! use std::default::Default; //! use oauth2; //! use datastore1::Datastore; //! //! // Get an ApplicationSecret instance by some means. It contains the `client_id` and //! // `client_secret`, among other things. //! let secret: ApplicationSecret = Default::default(); //! // Instantiate the authenticator. It will choose a suitable authentication flow for you, //! // unless you replace `None` with the desired Flow. //! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about //! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and //! // retrieve them from storage. //! let auth = yup_oauth2::InstalledFlowAuthenticator::builder( //! secret, //! yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect, //! ).build().await.unwrap(); //! let mut hub = Datastore::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth); //! // As the method needs a request, you would usually fill it with the desired information //! // into the respective structure. Some of the parts shown here might not be applicable ! //! // Values shown here are possibly random and not representative ! //! let mut req = GoogleDatastoreAdminV1Index::default(); //! //! // You can configure optional parameters by calling the respective setters at will, and //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.projects().indexes_create(req, "projectId") //! .doit(); //! //! match result { //! Err(e) => match e { //! // The Error enum provides details about what exactly happened. //! // You can also just use its `Debug`, `Display` or `Error` traits //! Error::HttpError(_) //! |Error::MissingAPIKey //! |Error::MissingToken(_) //! |Error::Cancelled //! |Error::UploadSizeLimitExceeded(_, _) //! |Error::Failure(_) //! |Error::BadRequest(_) //! |Error::FieldClash(_) //! |Error::JsonDecodeError(_, _) => println!("{}", e), //! }, //! Ok(res) => println!("Success: {:?}", res), //! } //! # } //! ``` //! ## Handling Errors //! //! All errors produced by the system are provided either as [Result](client::Result) enumeration as return value of //! the doit() methods, or handed as possibly intermediate results to either the //! [Hub Delegate](client::Delegate), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html). //! //! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This //! makes the system potentially resilient to all kinds of errors. //! //! ## Uploads and Downloads //! If a method supports downloads, the response body, which is part of the [Result](client::Result), should be //! read by you to obtain the media. //! If such a method also supports a [Response Result](client::ResponseResult), it will return that by default. //! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making //! this call: `.param("alt", "media")`. //! //! Methods supporting uploads can do so using up to 2 different protocols: //! *simple* and *resumable*. The distinctiveness of each is represented by customized //! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. //! //! ## Customization and Callbacks //! //! You may alter the way an `doit()` method is called by providing a [delegate](client::Delegate) to the //! [Method Builder](client::CallBuilder) before making the final `doit()` call. //! Respective methods will be called to provide progress information, as well as determine whether the system should //! retry on failure. //! //! The [delegate trait](client::Delegate) is default-implemented, allowing you to customize it with minimal effort. //! //! ## Optional Parts in Server-Requests //! //! All structures provided by this library are made to be [encodable](client::RequestValue) and //! [decodable](client::ResponseResult) via *json*. Optionals are used to indicate that partial requests are responses //! are valid. //! Most optionals are are considered [Parts](client::Part) which are identifiable by name, which will be sent to //! the server to indicate either the set parts of the request or the desired parts in the response. //! //! ## Builder Arguments //! //! Using [method builders](client::CallBuilder), you are able to prepare an action call by repeatedly calling it's methods. //! These will always take a single argument, for which the following statements are true. //! //! * [PODs][wiki-pod] are handed by copy //! * strings are passed as `&str` //! * [request values](client::RequestValue) are moved //! //! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. //! //! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure //! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern //! [google-go-api]: https://github.com/google/google-api-go-client //! //! // Unused attributes happen thanks to defined, but unused structures // We don't warn about this, as depending on the API, some data structures or facilities are never used. // Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any // unused imports in fully featured APIs. Same with unused_mut ... . #![allow(unused_imports, unused_mut, dead_code)] // DO NOT EDIT ! // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! #[macro_use] extern crate serde_derive; extern crate hyper; extern crate serde; extern crate serde_json; extern crate yup_oauth2 as oauth2; extern crate mime; extern crate url; pub mod api; pub mod client; // Re-export the hub type and some basic client structs pub use api::Datastore; pub use client::{Result, Error, Delegate};
47.751152
784
0.68674
fbea68cb7f2ff069dc4c58ca83e3c990511263c7
9,779
use crate::interactive::{ sorted_entries, widgets::{MainWindow, MainWindowProps}, ByteVisualization, CursorDirection, CursorMode, DisplayOptions, EntryDataBundle, MarkEntryMode, SortMode, }; use anyhow::Result; use crosstermion::input::{key_input_channel, Key}; use dua::{ traverse::{Traversal, TreeIndex}, WalkOptions, WalkResult, }; use std::{collections::BTreeMap, path::PathBuf}; use tui::backend::Backend; use tui_react::Terminal; #[derive(Copy, Clone)] pub enum FocussedPane { Main, Help, Mark, } impl Default for FocussedPane { fn default() -> Self { FocussedPane::Main } } #[derive(Default)] pub struct AppState { pub root: TreeIndex, pub selected: Option<TreeIndex>, pub entries: Vec<EntryDataBundle>, pub sorting: SortMode, pub message: Option<String>, pub focussed: FocussedPane, pub bookmarks: BTreeMap<TreeIndex, TreeIndex>, pub is_scanning: bool, } pub enum ProcessingResult { Finished(WalkResult), ExitRequested(WalkResult), } impl AppState { pub fn draw<B>( &mut self, window: &mut MainWindow, traversal: &Traversal, display: DisplayOptions, terminal: &mut Terminal<B>, ) -> Result<()> where B: Backend, { let props = MainWindowProps { traversal: &traversal, display, state: &self, }; draw_window(window, props, terminal) } pub fn process_events<B>( &mut self, window: &mut MainWindow, traversal: &mut Traversal, display: &mut DisplayOptions, terminal: &mut Terminal<B>, keys: impl Iterator<Item = Key>, ) -> Result<ProcessingResult> where B: Backend, { use crosstermion::input::Key::*; use FocussedPane::*; self.draw(window, traversal, *display, terminal)?; for key in keys { self.reset_message(); match key { Char('?') => self.toggle_help_pane(window), Char('\t') => { self.cycle_focus(window); } Ctrl('c') => { return Ok(ProcessingResult::ExitRequested(WalkResult { num_errors: traversal.io_errors, })) } Char('q') | Esc => match self.focussed { Main => { return Ok(ProcessingResult::ExitRequested(WalkResult { num_errors: traversal.io_errors, })) } Mark => self.focussed = Main, Help => { self.focussed = Main; window.help_pane = None } }, _ => {} } match self.focussed { FocussedPane::Mark => { self.dispatch_to_mark_pane(key, window, traversal, *display, terminal) } FocussedPane::Help => { window.help_pane.as_mut().expect("help pane").key(key); } FocussedPane::Main => match key { Char('O') => self.open_that(traversal), Char(' ') => self.mark_entry( CursorMode::KeepPosition, MarkEntryMode::Toggle, window, traversal, ), Char('d') => self.mark_entry( CursorMode::Advance, MarkEntryMode::Toggle, window, traversal, ), Char('x') => self.mark_entry( CursorMode::Advance, MarkEntryMode::MarkForDeletion, window, traversal, ), Char('u') | Char('h') | Backspace | Left => { self.exit_node_with_traversal(traversal) } Char('o') | Char('l') | Char('\n') | Right => { self.enter_node_with_traversal(traversal) } Ctrl('u') | PageUp => self.change_entry_selection(CursorDirection::PageUp), Char('k') | Up => self.change_entry_selection(CursorDirection::Up), Char('j') | Down => self.change_entry_selection(CursorDirection::Down), Ctrl('d') | PageDown => self.change_entry_selection(CursorDirection::PageDown), Char('s') => self.cycle_sorting(traversal), Char('g') => display.byte_vis.cycle(), _ => {} }, }; self.draw(window, traversal, *display, terminal)?; } Ok(ProcessingResult::Finished(WalkResult { num_errors: traversal.io_errors, })) } } pub fn draw_window<B>( window: &mut MainWindow, props: MainWindowProps, terminal: &mut Terminal<B>, ) -> Result<()> where B: Backend, { let area = terminal.pre_render()?; window.render(props, area, terminal.current_buffer_mut()); terminal.post_render()?; Ok(()) } /// State and methods representing the interactive disk usage analyser for the terminal pub struct TerminalApp { pub traversal: Traversal, pub display: DisplayOptions, pub state: AppState, pub window: MainWindow, } type KeyboardInputAndApp = (std::sync::mpsc::Receiver<Key>, TerminalApp); impl TerminalApp { pub fn process_events<B>( &mut self, terminal: &mut Terminal<B>, keys: impl Iterator<Item = Key>, ) -> Result<WalkResult> where B: Backend, { match self.state.process_events( &mut self.window, &mut self.traversal, &mut self.display, terminal, keys, )? { ProcessingResult::Finished(res) | ProcessingResult::ExitRequested(res) => Ok(res), } } pub fn initialize<B>( terminal: &mut Terminal<B>, options: WalkOptions, input: Vec<PathBuf>, mode: Interaction, ) -> Result<Option<KeyboardInputAndApp>> where B: Backend, { terminal.hide_cursor()?; terminal.clear()?; let mut display: DisplayOptions = options.clone().into(); display.byte_vis = ByteVisualization::PercentageAndBar; let mut window = MainWindow::default(); let keys_rx = match mode { Interaction::None => { let (_, keys_rx) = std::sync::mpsc::channel(); keys_rx } Interaction::Full => key_input_channel(), }; let fetch_buffered_key_events = || { let mut keys = Vec::new(); while let Ok(key) = keys_rx.try_recv() { keys.push(key); } keys }; let mut state = None::<AppState>; let traversal = Traversal::from_walk(options, input, |traversal| { let s = match state.as_mut() { Some(s) => { s.entries = sorted_entries(&traversal.tree, s.root, s.sorting); s } None => { state = Some({ let sorting = Default::default(); let entries = sorted_entries(&traversal.tree, traversal.root_index, sorting); AppState { root: traversal.root_index, sorting, selected: entries.get(0).map(|b| b.index), entries, is_scanning: true, ..Default::default() } }); state.as_mut().expect("state to be present, we just set it") } }; s.reset_message(); // force "scanning" to appear let should_exit = match s.process_events( &mut window, traversal, &mut display, terminal, fetch_buffered_key_events().into_iter(), )? { ProcessingResult::ExitRequested(_) => true, ProcessingResult::Finished(_) => false, }; Ok(should_exit) })?; let traversal = match traversal { Some(t) => t, None => return Ok(None), }; Ok(Some(( keys_rx, TerminalApp { state: { let mut s = state.unwrap_or_else(|| { let sorting = Default::default(); let root = traversal.root_index; let entries = sorted_entries(&traversal.tree, root, sorting); AppState { root, sorting, entries, ..Default::default() } }); s.is_scanning = false; s.entries = sorted_entries(&traversal.tree, s.root, s.sorting); s.selected = s.selected.or_else(|| s.entries.get(0).map(|b| b.index)); s }, display, traversal, window, }, ))) } } pub enum Interaction { Full, #[allow(dead_code)] None, }
31.85342
99
0.472032
399ea131934d302b9bf692822f178ae75f1b00df
2,768
use super::context::Context; use super::timer; use crate::process::PROCESSOR; use crate::kernel::syscall_handler; use crate::memory::*; use crate::sbi::console_getchar; use crate::fs::STDIN; use riscv::register::{ scause::{Exception, Interrupt, Scause, Trap}, stvec, sie }; global_asm!(include_str!("../asm/interrupt.asm")); /// 初始化中断处理 /// /// 把中断入口 `__interrupt` 写入 `stvec` 中,并且开启中断使能 pub fn init() { unsafe { extern "C" { /// `interrupt.asm` 中的中断入口 fn __interrupt(); } // 使用 Direct 模式,将中断入口设置为 `__interrupt` stvec::write(__interrupt as usize, stvec::TrapMode::Direct); // 开启外部中断使能 sie::set_sext(); // 在 OpenSBI 中开启外部中断 *PhysicalAddress(0x0c00_2080).deref_kernel() = 1 << 10; // 在 OpenSBI 中开启串口 *PhysicalAddress(0x1000_0004).deref_kernel() = 0x0bu8; *PhysicalAddress(0x1000_0001).deref_kernel() = 0x01u8; } } /// 中断的处理入口 /// /// `interrupt.asm` 首先保存寄存器至 Context,其作为参数和 scause 以及 stval 一并传入此函数 /// 具体的中断类型需要根据 scause 来推断,然后分别处理 #[no_mangle] pub fn handle_interrupt(context: &mut Context, scause: Scause, stval: usize) -> *mut Context { match scause.cause() { // 断点中断(ebreak) Trap::Exception(Exception::Breakpoint) => breakpoint(context), // 系统调用 Trap::Exception(Exception::UserEnvCall) => syscall_handler(context), // 时钟中断 Trap::Interrupt(Interrupt::SupervisorTimer) => supervisor_timer(context), // 外部中断(键盘输入) Trap::Interrupt(Interrupt::SupervisorExternal) => supervisor_external(context), // 其他情况,终止当前线程 _ => fault(context, scause, stval), } } /// 处理 ebreak 断点 /// /// 继续执行,其中 `sepc` 增加 2 字节,以跳过当前这条 `ebreak` 指令 fn breakpoint(context: &mut Context) -> *mut Context { println!("Breakpoint at 0x{:x}", context.sepc); context.sepc += 2; context } /// 处理时钟中断 fn supervisor_timer(context: &mut Context) -> *mut Context { timer::tick(); context // liyiwei disables preemptive scheduling // PROCESSOR.get().park_current_thread(context); // PROCESSOR.get().prepare_next_thread() } /// 出现未能解决的异常,终止当前线程 fn fault(_context: &mut Context, scause: Scause, stval: usize) -> *mut Context { println!( "{:x?} terminated with {:x?}", PROCESSOR.get().current_thread(), scause.cause() ); println!("stval: {:x}", stval); PROCESSOR.get().kill_current_thread(); // 跳转到 PROCESSOR 调度的下一个线程 PROCESSOR.get().prepare_next_thread() } /// 处理外部中断,只实现了键盘输入 fn supervisor_external(context: &mut Context) -> *mut Context { let mut c = console_getchar(); if c <= 255 { if c == '\r' as usize { c = '\n' as usize; } STDIN.push(c as u8); } context }
27.959596
94
0.620303
ff40e20e535ce26ec6f1a61024b09a257cfdd17d
46,379
use crate::POOL; use num::{Bounded, Num, NumCast, ToPrimitive, Zero}; use rayon::prelude::*; use arrow::types::{simd::Simd, NativeType}; #[cfg(feature = "object")] use crate::chunked_array::object::extension::create_extension; use crate::frame::groupby::GroupsIdx; #[cfg(feature = "object")] use crate::frame::groupby::GroupsIndicator; use crate::prelude::*; use crate::series::implementations::SeriesWrap; use polars_arrow::kernels::take_agg::*; use polars_arrow::prelude::QuantileInterpolOptions; use polars_arrow::trusted_len::PushUnchecked; use std::ops::Deref; fn slice_from_offsets<T>(ca: &ChunkedArray<T>, first: u32, len: u32) -> ChunkedArray<T> where ChunkedArray<T>: ChunkOps, { ca.slice(first as i64, len as usize) } // helper that combines the groups into a parallel iterator over `(first, all): (u32, &Vec<u32>)` fn agg_helper_idx<T, F>(groups: &GroupsIdx, f: F) -> Option<Series> where F: Fn((u32, &Vec<u32>)) -> Option<T::Native> + Send + Sync, T: PolarsNumericType, ChunkedArray<T>: IntoSeries, { let ca: ChunkedArray<T> = POOL.install(|| groups.into_par_iter().map(f).collect()); Some(ca.into_series()) } // helper that iterates on the `all: Vec<Vec<u32>` collection // this doesn't have traverse the `first: Vec<u32>` memory and is therefore faster fn agg_helper_idx_on_all<T, F>(groups: &GroupsIdx, f: F) -> Option<Series> where F: Fn(&Vec<u32>) -> Option<T::Native> + Send + Sync, T: PolarsNumericType, ChunkedArray<T>: IntoSeries, { let ca: ChunkedArray<T> = POOL.install(|| groups.all().into_par_iter().map(f).collect()); Some(ca.into_series()) } fn agg_helper_slice<T, F>(groups: &[[u32; 2]], f: F) -> Option<Series> where F: Fn([u32; 2]) -> Option<T::Native> + Send + Sync, T: PolarsNumericType, ChunkedArray<T>: IntoSeries, { let ca: ChunkedArray<T> = POOL.install(|| groups.par_iter().copied().map(f).collect()); Some(ca.into_series()) } impl BooleanChunked { pub(crate) fn agg_min(&self, groups: &GroupsProxy) -> Option<Series> { self.cast(&DataType::UInt32).unwrap().agg_min(groups) } pub(crate) fn agg_max(&self, groups: &GroupsProxy) -> Option<Series> { self.cast(&DataType::UInt32).unwrap().agg_max(groups) } pub(crate) fn agg_sum(&self, groups: &GroupsProxy) -> Option<Series> { self.cast(&DataType::UInt32).unwrap().agg_sum(groups) } } // implemented on the series because we don't need types impl Series { fn slice_from_offsets(&self, first: u32, len: u32) -> Self { self.slice(first as i64, len as usize) } fn restore_logical(&self, out: Series) -> Series { if self.is_logical() { out.cast(self.dtype()).unwrap() } else { out } } #[cfg(feature = "private")] pub fn agg_valid_count(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<UInt32Type, _>(groups, |idx| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { None } else if !self.has_validity() { Some(idx.len() as u32) } else { let take = unsafe { self.take_iter_unchecked(&mut idx.iter().map(|i| *i as usize)) }; Some((take.len() - take.null_count()) as u32) } }), GroupsProxy::Slice(groups) => { agg_helper_slice::<UInt32Type, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); if len == 0 { None } else if !self.has_validity() { Some(len) } else { let take = self.slice_from_offsets(first, len); Some((take.len() - take.null_count()) as u32) } }) } } } #[cfg(feature = "private")] pub fn agg_first(&self, groups: &GroupsProxy) -> Series { let out = match groups { GroupsProxy::Idx(groups) => { let mut iter = groups.iter().map(|(first, idx)| { if idx.is_empty() { None } else { Some(first as usize) } }); // Safety: // groups are always in bounds unsafe { self.take_opt_iter_unchecked(&mut iter) } } GroupsProxy::Slice(groups) => { let mut iter = groups.iter().map( |&[first, len]| { if len == 0 { None } else { Some(first as usize) } }, ); // Safety: // groups are always in bounds unsafe { self.take_opt_iter_unchecked(&mut iter) } } }; self.restore_logical(out) } #[cfg(feature = "private")] pub fn agg_n_unique(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<UInt32Type, _>(groups, |idx| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { None } else { let take = unsafe { self.take_iter_unchecked(&mut idx.iter().map(|i| *i as usize)) }; take.n_unique().ok().map(|v| v as u32) } }), GroupsProxy::Slice(groups) => { agg_helper_slice::<UInt32Type, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); if len == 0 { None } else { let take = self.slice_from_offsets(first, len); take.n_unique().ok().map(|v| v as u32) } }) } } } #[cfg(feature = "private")] pub fn agg_last(&self, groups: &GroupsProxy) -> Series { let out = match groups { GroupsProxy::Idx(groups) => { let mut iter = groups.all().iter().map(|idx| { if idx.is_empty() { None } else { Some(idx[idx.len() - 1] as usize) } }); unsafe { self.take_opt_iter_unchecked(&mut iter) } } GroupsProxy::Slice(groups) => { let mut iter = groups.iter().map(|&[first, len]| { if len == 0 { None } else { Some((first + len - 1) as usize) } }); unsafe { self.take_opt_iter_unchecked(&mut iter) } } }; self.restore_logical(out) } } impl<T> ChunkedArray<T> where T: PolarsNumericType + Sync, T::Native: NativeType + PartialOrd + Num + NumCast + Zero + Simd + Bounded + std::iter::Sum<T::Native>, <T::Native as Simd>::Simd: std::ops::Add<Output = <T::Native as Simd>::Simd> + arrow::compute::aggregate::Sum<T::Native> + arrow::compute::aggregate::SimdOrd<T::Native>, ChunkedArray<T>: IntoSeries, { pub(crate) fn agg_min(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx::<T, _>(groups, |(first, idx)| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { None } else if idx.len() == 1 { self.get(first as usize) } else { match (self.has_validity(), self.chunks.len()) { (false, 1) => Some(unsafe { take_agg_no_null_primitive_iter_unchecked( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| if a < b { a } else { b }, T::Native::max_value(), ) }), (_, 1) => unsafe { take_agg_primitive_iter_unchecked::<T::Native, _, _>( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| if a < b { a } else { b }, T::Native::max_value(), ) }, _ => { let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.min() } } } }), GroupsProxy::Slice(groups) => agg_helper_slice::<T, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.min() } } }), } } pub(crate) fn agg_max(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx::<T, _>(groups, |(first, idx)| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { None } else if idx.len() == 1 { self.get(first as usize) } else { match (self.has_validity(), self.chunks.len()) { (false, 1) => Some(unsafe { take_agg_no_null_primitive_iter_unchecked( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| if a > b { a } else { b }, T::Native::min_value(), ) }), (_, 1) => unsafe { take_agg_primitive_iter_unchecked::<T::Native, _, _>( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| if a > b { a } else { b }, T::Native::min_value(), ) }, _ => { let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.max() } } } }), GroupsProxy::Slice(groups) => agg_helper_slice::<T, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.max() } } }), } } pub(crate) fn agg_sum(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx::<T, _>(groups, |(first, idx)| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { None } else if idx.len() == 1 { self.get(first as usize) } else { match (self.has_validity(), self.chunks.len()) { (false, 1) => Some(unsafe { take_agg_no_null_primitive_iter_unchecked( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| a + b, T::Native::zero(), ) }), (_, 1) => unsafe { take_agg_primitive_iter_unchecked::<T::Native, _, _>( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| a + b, T::Native::zero(), ) }, _ => { let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.sum() } } } }), GroupsProxy::Slice(groups) => agg_helper_slice::<T, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.sum() } } }), } } } impl<T> SeriesWrap<ChunkedArray<T>> where T: PolarsFloatType, ChunkedArray<T>: IntoSeries + ChunkVar<T::Native> + VarAggSeries + ChunkQuantile<T::Native> + QuantileAggSeries, T::Native: NativeType + PartialOrd + Num + NumCast + Simd + std::iter::Sum<T::Native>, <T::Native as Simd>::Simd: std::ops::Add<Output = <T::Native as Simd>::Simd> + arrow::compute::aggregate::Sum<T::Native> + arrow::compute::aggregate::SimdOrd<T::Native>, { pub(crate) fn agg_mean(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => { agg_helper_idx::<T, _>(groups, |(first, idx)| { // this can fail due to a bug in lazy code. // here users can create filters in aggregations // and thereby creating shorter columns than the original group tuples. // the group tuples are modified, but if that's done incorrect there can be out of bounds // access debug_assert!(idx.len() <= self.len()); let out = if idx.is_empty() { None } else if idx.len() == 1 { self.get(first as usize).map(|sum| sum.to_f64().unwrap()) } else { match (self.has_validity(), self.chunks.len()) { (false, 1) => unsafe { take_agg_no_null_primitive_iter_unchecked( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| a + b, T::Native::zero(), ) } .to_f64() .map(|sum| sum / idx.len() as f64), (_, 1) => unsafe { take_agg_primitive_iter_unchecked_count_nulls::<T::Native, _, _>( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| a + b, T::Native::zero(), ) } .map(|(sum, null_count)| { sum.to_f64() .map(|sum| sum / (idx.len() as f64 - null_count as f64)) .unwrap() }), _ => { let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; let opt_sum: Option<T::Native> = take.sum(); opt_sum.map(|sum| sum.to_f64().unwrap() / idx.len() as f64) } } }; out.map(|flt| NumCast::from(flt).unwrap()) }) } GroupsProxy::Slice(groups) => agg_helper_slice::<T, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.mean().map(|flt| NumCast::from(flt).unwrap()) } } }), } } pub(crate) fn agg_var(&self, groups: &GroupsProxy) -> Option<Series> { let ca = &self.0; match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| { debug_assert!(idx.len() <= ca.len()); if idx.is_empty() { return None; } let take = unsafe { ca.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.var_as_series().unpack::<T>().unwrap().get(0) }), GroupsProxy::Slice(groups) => agg_helper_slice::<T, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.var().map(|flt| NumCast::from(flt).unwrap()) } } }), } } pub(crate) fn agg_std(&self, groups: &GroupsProxy) -> Option<Series> { let ca = &self.0; match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| { debug_assert!(idx.len() <= ca.len()); if idx.is_empty() { return None; } let take = unsafe { ca.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.std_as_series().unpack::<T>().unwrap().get(0) }), GroupsProxy::Slice(groups) => agg_helper_slice::<T, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.std().map(|flt| NumCast::from(flt).unwrap()) } } }), } } pub(crate) fn agg_quantile( &self, groups: &GroupsProxy, quantile: f64, interpol: QuantileInterpolOptions, ) -> Option<Series> { let ca = &self.0; let invalid_quantile = !(0.0..=1.0).contains(&quantile); match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| { debug_assert!(idx.len() <= ca.len()); if idx.is_empty() | invalid_quantile { return None; } let take = unsafe { ca.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.quantile_as_series(quantile, interpol) .unwrap() // checked with invalid quantile check .unpack::<T>() .unwrap() .get(0) }), GroupsProxy::Slice(groups) => agg_helper_slice::<T, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize), _ => { let arr_group = slice_from_offsets(self, first, len); // unwrap checked with invalid quantile check arr_group .quantile(quantile, interpol) .unwrap() .map(|flt| NumCast::from(flt).unwrap()) } } }), } } pub(crate) fn agg_median(&self, groups: &GroupsProxy) -> Option<Series> { let ca = &self.0; match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| { debug_assert!(idx.len() <= ca.len()); if idx.is_empty() { return None; } let take = unsafe { ca.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.median_as_series().unpack::<T>().unwrap().get(0) }), GroupsProxy::Slice(groups) => agg_helper_slice::<T, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.median().map(|flt| NumCast::from(flt).unwrap()) } } }), } } } impl<T> ChunkedArray<T> where T: PolarsIntegerType, ChunkedArray<T>: IntoSeries, T::Native: NativeType + PartialOrd + Num + NumCast + Zero + Simd + Bounded + std::iter::Sum<T::Native>, <T::Native as Simd>::Simd: std::ops::Add<Output = <T::Native as Simd>::Simd> + arrow::compute::aggregate::Sum<T::Native> + arrow::compute::aggregate::SimdOrd<T::Native>, { pub(crate) fn agg_mean(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => { agg_helper_idx::<Float64Type, _>(groups, |(first, idx)| { // this can fail due to a bug in lazy code. // here users can create filters in aggregations // and thereby creating shorter columns than the original group tuples. // the group tuples are modified, but if that's done incorrect there can be out of bounds // access debug_assert!(idx.len() <= self.len()); if idx.is_empty() { None } else if idx.len() == 1 { self.get(first as usize).map(|sum| sum.to_f64().unwrap()) } else { match (self.has_validity(), self.chunks.len()) { (false, 1) => unsafe { take_agg_no_null_primitive_iter_unchecked( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| a + b, T::Native::zero(), ) } .to_f64() .map(|sum| sum / idx.len() as f64), (_, 1) => unsafe { take_agg_primitive_iter_unchecked_count_nulls::<T::Native, _, _>( self.downcast_iter().next().unwrap(), idx.iter().map(|i| *i as usize), |a, b| a + b, T::Native::zero(), ) } .map(|(sum, null_count)| { sum.to_f64() .map(|sum| sum / (idx.len() as f64 - null_count as f64)) .unwrap() }), _ => { let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; let opt_sum: Option<T::Native> = take.sum(); opt_sum.map(|sum| sum.to_f64().unwrap() / idx.len() as f64) } } } }) } GroupsProxy::Slice(groups) => { agg_helper_slice::<Float64Type, _>(groups, |[first, len]| { debug_assert!(len < self.len() as u32); match first - len { 0 => None, 1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.mean() } } }) } } } pub(crate) fn agg_var(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<Float64Type, _>(groups, |idx| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { return None; } let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.var_as_series().unpack::<Float64Type>().unwrap().get(0) }), GroupsProxy::Slice(groups) => { agg_helper_slice::<Float64Type, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.var() } } }) } } } pub(crate) fn agg_std(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<Float64Type, _>(groups, |idx| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { return None; } let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.std_as_series().unpack::<Float64Type>().unwrap().get(0) }), GroupsProxy::Slice(groups) => { agg_helper_slice::<Float64Type, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.std() } } }) } } } pub(crate) fn agg_quantile( &self, groups: &GroupsProxy, quantile: f64, interpol: QuantileInterpolOptions, ) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<Float64Type, _>(groups, |idx| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { return None; } let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.quantile_as_series(quantile, interpol) .unwrap() .unpack::<Float64Type>() .unwrap() .get(0) }), GroupsProxy::Slice(groups) => { agg_helper_slice::<Float64Type, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.quantile(quantile, interpol).unwrap() } } }) } } } pub(crate) fn agg_median(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<Float64Type, _>(groups, |idx| { debug_assert!(idx.len() <= self.len()); if idx.is_empty() { return None; } let take = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; take.median_as_series() .unpack::<Float64Type>() .unwrap() .get(0) }), GroupsProxy::Slice(groups) => { agg_helper_slice::<Float64Type, _>(groups, |[first, len]| { debug_assert!(len <= self.len() as u32); match len { 0 => None, 1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()), _ => { let arr_group = slice_from_offsets(self, first, len); arr_group.median() } } }) } } } } impl<T> ChunkedArray<T> where ChunkedArray<T>: ChunkTake + IntoSeries {} pub trait AggList { fn agg_list(&self, _groups: &GroupsProxy) -> Option<Series> { None } } impl<T> AggList for ChunkedArray<T> where T: PolarsNumericType, ChunkedArray<T>: IntoSeries, { fn agg_list(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => { let mut can_fast_explode = true; let arr = match self.cont_slice() { Ok(values) => { let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1); let mut length_so_far = 0i64; offsets.push(length_so_far); let mut list_values = Vec::<T::Native>::with_capacity(self.len()); groups.iter().for_each(|(_, idx)| { let idx_len = idx.len(); if idx_len == 0 { can_fast_explode = false; } length_so_far += idx_len as i64; // Safety: // group tuples are in bounds unsafe { list_values.extend(idx.iter().map(|idx| { debug_assert!((*idx as usize) < values.len()); *values.get_unchecked(*idx as usize) })); // Safety: // we know that offsets has allocated enough slots offsets.push_unchecked(length_so_far); } }); let array = PrimitiveArray::from_data( T::get_dtype().to_arrow(), list_values.into(), None, ); let data_type = ListArray::<i64>::default_datatype(T::get_dtype().to_arrow()); ListArray::<i64>::from_data( data_type, offsets.into(), Arc::new(array), None, ) } _ => { let mut builder = ListPrimitiveChunkedBuilder::<T::Native>::new( self.name(), groups.len(), self.len(), self.dtype().clone(), ); for idx in groups.all().iter() { let s = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) .into_series() }; builder.append_series(&s); } return Some(builder.finish().into_series()); } }; let mut ca = ListChunked::from_chunks(self.name(), vec![Arc::new(arr)]); if can_fast_explode { ca.set_fast_explode() } Some(ca.into()) } GroupsProxy::Slice(groups) => { let mut can_fast_explode = true; let arr = match self.cont_slice() { Ok(values) => { let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1); let mut length_so_far = 0i64; offsets.push(length_so_far); let mut list_values = Vec::<T::Native>::with_capacity(self.len()); groups.iter().for_each(|&[first, len]| { if len == 0 { can_fast_explode = false; } length_so_far += len as i64; list_values .extend_from_slice(&values[first as usize..(first + len) as usize]); unsafe { // Safety: // we know that offsets has allocated enough slots offsets.push_unchecked(length_so_far); } }); let array = PrimitiveArray::from_data( T::get_dtype().to_arrow(), list_values.into(), None, ); let data_type = ListArray::<i64>::default_datatype(T::get_dtype().to_arrow()); ListArray::<i64>::from_data( data_type, offsets.into(), Arc::new(array), None, ) } _ => { let mut builder = ListPrimitiveChunkedBuilder::<T::Native>::new( self.name(), groups.len(), self.len(), self.dtype().clone(), ); for &[first, len] in groups { let s = self.slice(first as i64, len as usize).into_series(); builder.append_series(&s); } return Some(builder.finish().into_series()); } }; let mut ca = ListChunked::from_chunks(self.name(), vec![Arc::new(arr)]); if can_fast_explode { ca.set_fast_explode() } Some(ca.into()) } } } } impl AggList for BooleanChunked { fn agg_list(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => { let mut builder = ListBooleanChunkedBuilder::new(self.name(), groups.len(), self.len()); for idx in groups.all().iter() { let ca = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; builder.append(&ca) } Some(builder.finish().into_series()) } GroupsProxy::Slice(groups) => { let mut builder = ListBooleanChunkedBuilder::new(self.name(), groups.len(), self.len()); for [first, len] in groups { let ca = self.slice(*first as i64, *len as usize); builder.append(&ca) } Some(builder.finish().into_series()) } } } } impl AggList for Utf8Chunked { fn agg_list(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => { let mut builder = ListUtf8ChunkedBuilder::new(self.name(), groups.len(), self.len()); for idx in groups.all().iter() { let ca = unsafe { self.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; builder.append(&ca) } Some(builder.finish().into_series()) } GroupsProxy::Slice(groups) => { let mut builder = ListUtf8ChunkedBuilder::new(self.name(), groups.len(), self.len()); for [first, len] in groups { let ca = self.slice(*first as i64, *len as usize); builder.append(&ca) } Some(builder.finish().into_series()) } } } } fn agg_list_list<F: Fn(&ListChunked, bool, &mut Vec<i64>, &mut i64, &mut Vec<ArrayRef>) -> bool>( ca: &ListChunked, groups_len: usize, func: F, ) -> Option<Series> { let can_fast_explode = true; let mut offsets = Vec::<i64>::with_capacity(groups_len + 1); let mut length_so_far = 0i64; offsets.push(length_so_far); let mut list_values = Vec::with_capacity(groups_len); let can_fast_explode = func( ca, can_fast_explode, &mut offsets, &mut length_so_far, &mut list_values, ); if groups_len == 0 { list_values.push(ca.chunks[0].slice(0, 0).into()) } let arrays = list_values.iter().map(|arr| &**arr).collect::<Vec<_>>(); let list_values: ArrayRef = arrow::compute::concatenate::concatenate(&arrays) .unwrap() .into(); let data_type = ListArray::<i64>::default_datatype(list_values.data_type().clone()); let arr = Arc::new(ListArray::<i64>::from_data( data_type, offsets.into(), list_values, None, )) as ArrayRef; let mut listarr = ListChunked::from_chunks(ca.name(), vec![arr]); if can_fast_explode { listarr.set_fast_explode() } Some(listarr.into_series()) } impl AggList for ListChunked { fn agg_list(&self, groups: &GroupsProxy) -> Option<Series> { match groups { GroupsProxy::Idx(groups) => { let func = |ca: &ListChunked, mut can_fast_explode: bool, offsets: &mut Vec<i64>, length_so_far: &mut i64, list_values: &mut Vec<ArrayRef>| { groups.iter().for_each(|(_, idx)| { let idx_len = idx.len(); if idx_len == 0 { can_fast_explode = false; } *length_so_far += idx_len as i64; // Safety: // group tuples are in bounds unsafe { let mut s = ca.take_unchecked((idx.iter().map(|idx| *idx as usize)).into()); let arr = s.chunks.pop().unwrap(); list_values.push(arr); // Safety: // we know that offsets has allocated enough slots offsets.push_unchecked(*length_so_far); } }); can_fast_explode }; agg_list_list(self, groups.len(), func) } GroupsProxy::Slice(groups) => { let func = |ca: &ListChunked, mut can_fast_explode: bool, offsets: &mut Vec<i64>, length_so_far: &mut i64, list_values: &mut Vec<ArrayRef>| { groups.iter().for_each(|&[first, len]| { if len == 0 { can_fast_explode = false; } *length_so_far += len as i64; let mut s = ca.slice(first as i64, len as usize); let arr = s.chunks.pop().unwrap(); list_values.push(arr); unsafe { // Safety: // we know that offsets has allocated enough slots offsets.push_unchecked(*length_so_far); } }); can_fast_explode }; agg_list_list(self, groups.len(), func) } } } } impl AggList for CategoricalChunked { fn agg_list(&self, groups: &GroupsProxy) -> Option<Series> { match self.deref().agg_list(groups) { None => None, Some(s) => { let ca = s.list().unwrap(); let mut out = ListChunked::from_chunks(ca.name(), ca.chunks.clone()); out.field = Arc::new(Field::new( ca.name(), DataType::List(Box::new(DataType::Categorical)), )); out.categorical_map = self.categorical_map.clone(); out.bit_settings = ca.bit_settings; Some(out.into_series()) } } } } #[cfg(feature = "object")] impl<T: PolarsObject> AggList for ObjectChunked<T> { fn agg_list(&self, groups: &GroupsProxy) -> Option<Series> { let mut can_fast_explode = true; let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1); let mut length_so_far = 0i64; offsets.push(length_so_far); // we know that iterators length let iter = unsafe { groups .iter() .flat_map(|indicator| { let (group_vals, len) = match indicator { GroupsIndicator::Idx((_first, idx)) => { // Safety: // group tuples always in bounds let group_vals = self.take_unchecked((idx.iter().map(|idx| *idx as usize)).into()); (group_vals, idx.len() as u32) } GroupsIndicator::Slice([first, len]) => { let group_vals = slice_from_offsets(self, first, len); (group_vals, len) } }; if len == 0 { can_fast_explode = false; } length_so_far += len as i64; // Safety: // we know that offsets has allocated enough slots offsets.push_unchecked(length_so_far); let arr = group_vals.downcast_iter().next().unwrap().clone(); arr.into_iter_cloned() }) .trust_my_length(self.len()) }; let mut pe = create_extension(iter); // Safety: // this is safe because we just created the PolarsExtension // meaning that the sentinel is heap allocated and the dereference of the // pointer does not fail unsafe { pe.set_to_series_fn::<T>() }; let extension_array = Arc::new(pe.take_and_forget()) as ArrayRef; let extension_dtype = extension_array.data_type(); let data_type = ListArray::<i64>::default_datatype(extension_dtype.clone()); let arr = Arc::new(ListArray::<i64>::from_data( data_type, offsets.into(), extension_array, None, )) as ArrayRef; let mut listarr = ListChunked::from_chunks(self.name(), vec![arr]); if can_fast_explode { listarr.set_fast_explode() } Some(listarr.into_series()) } }
41.189165
109
0.413722
f5b01aeec7a3b20f8791654c07344c1e69733b70
17,120
//! Provides the core configuration functionality. use crate::config::extended_hashmap::ExtendedMap; use crate::config::tree::{parse_conf, ConfigNode}; use crate::logger::LogLevel; use crate::proxy::{EqMutex, LoadBalancer}; use crate::rand::Lcg; use std::collections::HashMap; use std::env::{args, var}; use std::fs::File; use std::io::Read; use std::net::IpAddr; use std::path::Path; use std::time::Duration; /// Represents the parsed and validated configuration. #[derive(Debug, PartialEq)] pub struct Config { /// Where the configuration was located. pub source: ConfigSource, /// The address to host the server on pub address: String, /// The port to host the server on pub port: u16, /// The number of threads to host the server on pub threads: usize, /// The TLS configuration to use #[cfg(feature = "tls")] pub tls_config: Option<TlsConfig>, /// Address to forward WebSocket connections to, unless otherwise specified by the route pub default_websocket_proxy: Option<String>, /// The configuration for different hosts pub hosts: Vec<HostConfig>, /// The configuration for the default host pub default_host: HostConfig, /// The configuration for any plugins #[cfg(feature = "plugins")] pub plugins: Vec<PluginConfig>, /// Logging configuration pub logging: LoggingConfig, /// Cache configuration pub cache: CacheConfig, /// Blacklist configuration pub blacklist: BlacklistConfig, /// The amount of time to wait between requests pub connection_timeout: Option<Duration>, } /// Represents the configuration for a specific host. #[derive(Debug, PartialEq)] pub struct HostConfig { /// Wildcard string specifying what hosts to match, e.g. `*.example.com` pub matches: String, /// The routes to use for this host pub routes: Vec<RouteConfig>, } /// Represents the type of a route. #[derive(Copy, Clone, Debug, PartialEq)] pub enum RouteType { /// Serve a single file. File, /// Serve a directory of files. Directory, /// Proxy requests to this route to another server. Proxy, /// Redirect clients to another server. Redirect, } /// Represents configuration for a specific route. #[derive(Debug, PartialEq)] pub struct RouteConfig { /// The type of the route pub route_type: RouteType, /// The URL to match pub matches: String, /// The path to the file, directory or redirect target pub path: Option<String>, /// The load balancer to use for proxying pub load_balancer: Option<EqMutex<LoadBalancer>>, /// The WebSocket proxy target for WebSocket connections to this route pub websocket_proxy: Option<String>, } /// Represents configuration for the logger. #[derive(Clone, Debug, PartialEq, Eq)] pub struct LoggingConfig { /// The level of logging pub level: LogLevel, /// Whether to log to the console pub console: bool, /// The path to the log file pub file: Option<String>, } /// Represents configuration for the cache. #[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] pub struct CacheConfig { /// The maximum size of the cache, in bytes pub size_limit: usize, /// The maximum time to cache an item for, in seconds pub time_limit: usize, } /// Represents configuration for the blacklist. #[derive(Clone, Debug, PartialEq, Eq)] pub struct BlacklistConfig { /// The list of addresses to block pub list: Vec<IpAddr>, /// The way in which the blacklist is enforced pub mode: BlacklistMode, } /// Represents configuration for TLS. #[cfg(feature = "tls")] #[derive(Clone, Debug, PartialEq, Eq)] pub struct TlsConfig { /// The TLS certificate file path. pub cert_file: String, /// The TLS key file path. pub key_file: String, /// Whether to force clients to use HTTPS. pub force: bool, } /// Represents configuration for a plugin. #[cfg(feature = "plugins")] #[derive(Clone, Debug, PartialEq, Eq)] pub struct PluginConfig { /// The name of the plugin. pub name: String, /// The path to the shared library file. pub library: String, /// The configuration for the plugin. pub config: HashMap<String, String>, } /// Represents an algorithm for load balancing. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum LoadBalancerMode { /// Evenly distributes load in a repeating pattern RoundRobin, /// Randomly distributes load Random, } /// Represents a method of applying the blacklist. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum BlacklistMode { /// Does not allow any access from blacklisted addresses Block, /// Returns 400 Forbidden to every request, only available in static mode Forbidden, } /// Represents the source of the configuration. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ConfigSource { /// The configuration was found at a path specified in a command-line argument. Argument, /// The configuration was found at a path specified in the environment variable `HUMPHREY_CONF`. EnvironmentVariable, /// The configuration was found in the current directory at `humphrey.conf`. CurrentDirectory, /// The configuration was not found, so the default configuration was used. Default, } impl Config { /// Attempts to load the configuration. pub fn load() -> Result<Self, String> { let (path, source) = if let Some(arg_path) = args().nth(1) { (arg_path, ConfigSource::Argument) } else if Path::new("humphrey.conf").exists() { ("humphrey.conf".into(), ConfigSource::CurrentDirectory) } else if let Ok(env_path) = var("HUMPHREY_CONF") { (env_path, ConfigSource::EnvironmentVariable) } else { ("".into(), ConfigSource::Default) }; if let Ok((filename, config_string)) = load_config_file(path) { let tree = parse_conf(&config_string, &filename).map_err(|e| e.to_string())?; let mut config = Self::from_tree(tree)?; config.source = source; Ok(config) } else { Ok(Config::default()) } } /// Parses the config from the config tree. pub fn from_tree(tree: ConfigNode) -> Result<Self, &'static str> { let mut hashmap: HashMap<String, ConfigNode> = HashMap::new(); tree.flatten(&mut hashmap, &Vec::new()); // Get and validate the specified address, port and threads let address = hashmap.get_optional("server.address", "0.0.0.0".into()); let port: u16 = hashmap.get_optional_parsed("server.port", 80, "Invalid port")?; let threads: usize = hashmap.get_optional_parsed("server.threads", 32, "Invalid number of threads")?; let default_websocket_proxy = hashmap.get_owned("server.websocket"); let connection_timeout_seconds: u64 = hashmap.get_optional_parsed("server.timeout", 0, "Invalid connection timeout")?; let connection_timeout = if connection_timeout_seconds > 0 { Some(Duration::from_secs(connection_timeout_seconds)) } else { None }; if threads < 1 { return Err("You cannot specify less than 1 thread"); } // Get and validate the blacklist file and mode let blacklist = { let blacklist_strings: Vec<String> = load_list_file(hashmap.get_owned("server.blacklist.file"))?; let mut blacklist: Vec<IpAddr> = Vec::with_capacity(blacklist_strings.len()); for ip in blacklist_strings { blacklist.push( ip.parse::<IpAddr>() .map_err(|_| "Could not parse IP address in blacklist file")?, ); } let blacklist_mode = hashmap.get_optional("server.blacklist.mode", "block".into()); let blacklist_mode = match blacklist_mode.as_ref() { "block" => BlacklistMode::Block, "forbidden" => BlacklistMode::Forbidden, _ => return Err("Invalid blacklist mode"), }; BlacklistConfig { list: blacklist, mode: blacklist_mode, } }; #[cfg(feature = "tls")] let tls_config = { let cert_file = hashmap.get_owned("server.tls.cert_file"); let key_file = hashmap.get_owned("server.tls.key_file"); let force = hashmap.get_optional("server.tls.force", "false".into()); if force == "true" && threads < 2 { return Err("A minimum of two threads are required to force HTTPS"); } if force == "true" && port != 443 { return Err("Forcing HTTPS redirects requires the port to be 443"); } if let Some(cert_file) = cert_file { if let Some(key_file) = key_file { Some(TlsConfig { cert_file, key_file, force: force == "true", }) } else { return Err("Missing key file for TLS"); } } else { None } }; // Get and validate the logging configuration let logging = { let log_level = hashmap.get_optional_parsed( "server.log.level", LogLevel::Warn, "Invalid log level", )?; let log_file = hashmap.get_owned("server.log.file"); let log_console = hashmap.get_optional_parsed( "server.log.console", true, "server.log.console must be a boolean", )?; LoggingConfig { level: log_level, console: log_console, file: log_file, } }; // Get and validate the cache configuration let cache = { let cache_size = hashmap.get_optional_parsed("server.cache.size", 0_usize, "Invalid cache size")?; let cache_time = hashmap.get_optional_parsed("server.cache.time", 0_usize, "Invalid cache time")?; CacheConfig { size_limit: cache_size, time_limit: cache_time, } }; // Get and validate the configuration for the different routes let default_host = parse_host("*", &tree)?; let hosts = { let hosts_map = tree.get_hosts(); let mut hosts: Vec<HostConfig> = Vec::with_capacity(hosts_map.len()); for (host, conf) in hosts_map { hosts.push(parse_host(&host, &conf)?); } hosts }; // Get and validate plugin configuration #[cfg(feature = "plugins")] let plugins = { let plugins_map = tree.get_plugins(); let mut plugins: Vec<PluginConfig> = Vec::new(); for (name, conf) in plugins_map { let library = conf.get_compulsory("library", "Plugin library not specified")?; let mut additional_config: HashMap<String, String> = conf .clone() .iter() .map(|(k, v)| (k.clone(), v.get_string().unwrap())) .collect(); additional_config.remove("library").unwrap(); plugins.push(PluginConfig { name, library, config: additional_config, }) } plugins }; Ok(Config { source: ConfigSource::Default, address, port, threads, #[cfg(feature = "tls")] tls_config, default_websocket_proxy, default_host, hosts, #[cfg(feature = "plugins")] plugins, logging, cache, blacklist, connection_timeout, }) } /// Get the route at the given host and route indices. pub fn get_route(&self, host: usize, route: usize) -> &RouteConfig { if host == 0 { &self.default_host.routes[route] } else { &self.hosts[host - 1].routes[route] } } } /// Loads the configuration file. fn load_config_file(path: impl AsRef<str>) -> Result<(String, String), ()> { if let Ok(mut file) = File::open(path.as_ref()) { // The file can be opened let mut string = String::new(); if file.read_to_string(&mut string).is_ok() { // The file can be read Ok((path.as_ref().to_string(), string)) } else { Err(()) } } else { Err(()) } } /// Loads a file which is a list of values. fn load_list_file(path: Option<String>) -> Result<Vec<String>, &'static str> { if let Some(path) = path { // Try to open and read the file let mut file = File::open(path).map_err(|_| "List file could not be opened")?; let mut buf = String::new(); file.read_to_string(&mut buf) .map_err(|_| "List file could not be read")?; // Collect the lines of the file into a `Vec` let list: Vec<String> = buf.lines().map(|s| s.to_string()).collect(); Ok(list) } else { // Return an empty `Vec` if no file was supplied Ok(Vec::new()) } } /// Parses a node which contains the configuration for a host. fn parse_host(wild: &str, node: &ConfigNode) -> Result<HostConfig, &'static str> { let routes_map = node.get_routes(); let mut routes: Vec<RouteConfig> = Vec::with_capacity(routes_map.len()); for (wild, conf) in routes_map { routes.extend(parse_route(&wild, conf)?); } Ok(HostConfig { matches: wild.to_string(), routes, }) } /// Parses a route. fn parse_route( wild: &str, conf: HashMap<String, ConfigNode>, ) -> Result<Vec<RouteConfig>, &'static str> { let mut routes: Vec<RouteConfig> = Vec::new(); for wild in wild.split(',').map(|s| s.trim()) { let websocket_proxy = conf.get_owned("websocket"); if conf.contains_key("file") { // This is a regular file-serving route let file = conf.get_compulsory("file", "").unwrap(); routes.push(RouteConfig { route_type: RouteType::File, matches: wild.to_string(), path: Some(file), load_balancer: None, websocket_proxy, }); } else if conf.contains_key("directory") { // This is a regular directory-serving route let directory = conf.get_compulsory("directory", "").unwrap(); routes.push(RouteConfig { route_type: RouteType::Directory, matches: wild.to_string(), path: Some(directory), load_balancer: None, websocket_proxy, }); } else if conf.contains_key("proxy") { // This is a proxy route let targets: Vec<String> = conf .get_compulsory("proxy", "") .unwrap() .split(',') .map(|s| s.to_owned()) .collect(); let load_balancer_mode = conf.get_optional("load_balancer_mode", "round-robin".into()); let load_balancer_mode = match load_balancer_mode.as_str() { "round-robin" => LoadBalancerMode::RoundRobin, "random" => LoadBalancerMode::Random, _ => return Err( "Invalid load balancer mode, valid options are `round-robin` or `random`", ), }; let load_balancer = EqMutex::new(LoadBalancer { targets, mode: load_balancer_mode, lcg: Lcg::new(), index: 0, }); routes.push(RouteConfig { route_type: RouteType::Proxy, matches: wild.to_string(), path: None, load_balancer: Some(load_balancer), websocket_proxy, }); } else if conf.contains_key("redirect") { // This is a redirect route let target = conf.get_compulsory("redirect", "").unwrap(); routes.push(RouteConfig { route_type: RouteType::Redirect, matches: wild.to_string(), path: Some(target), load_balancer: None, websocket_proxy, }); } else if !conf.contains_key("websocket") { return Err("Invalid route configuration, every route must contain either the `file`, `directory`, `proxy` or `redirect` field, unless it defines a WebSocket proxy with the `websocket` field"); } } Ok(routes) }
33.307393
204
0.571437
728678873a1e17e49f4bf7f02de0645de1f74356
10,962
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service. #![allow(clippy::all)] use basilisk_runtime::{self, RuntimeApi}; use cumulus_client_consensus_aura::{build_aura_consensus, BuildAuraConsensusParams, SlotProportion}; use cumulus_client_consensus_common::ParachainConsensus; use cumulus_client_network::build_block_announce_validator; use cumulus_client_service::{ prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams, }; use cumulus_primitives_core::ParaId; use sc_client_api::ExecutorProvider; use sc_executor::native_executor_instance; pub use sc_executor::NativeExecutor; use sc_network::NetworkService; use sc_service::{Configuration, PartialComponents, Role, TFullBackend, TFullClient, TaskManager}; use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle}; use sp_consensus::SlotData; use sp_keystore::SyncCryptoStorePtr; use std::sync::Arc; use substrate_prometheus_endpoint::Registry; // Our native executor instance. native_executor_instance!( pub Executor, basilisk_runtime::api::dispatch, basilisk_runtime::native_version, frame_benchmarking::benchmarking::HostFunctions, ); type BlockNumber = u32; type Header = sp_runtime::generic::Header<BlockNumber, sp_runtime::traits::BlakeTwo256>; pub type Block = sp_runtime::generic::Block<Header, sp_runtime::OpaqueExtrinsic>; type Hash = sp_core::H256; pub fn new_partial( config: &Configuration, ) -> Result< PartialComponents< TFullClient<Block, RuntimeApi, Executor>, TFullBackend<Block>, (), sp_consensus::DefaultImportQueue<Block, TFullClient<Block, RuntimeApi, Executor>>, sc_transaction_pool::FullPool<Block, TFullClient<Block, RuntimeApi, Executor>>, (Option<Telemetry>, Option<TelemetryWorkerHandle>), >, sc_service::Error, > { let telemetry = config .telemetry_endpoints .clone() .filter(|x| !x.is_empty()) .map(|endpoints| -> Result<_, sc_telemetry::Error> { let worker = TelemetryWorker::new(16)?; let telemetry = worker.handle().new_telemetry(endpoints); Ok((worker, telemetry)) }) .transpose()?; let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::<Block, RuntimeApi, Executor>( &config, telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), )?; let client = Arc::new(client); let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle()); let telemetry = telemetry.map(|(worker, telemetry)| { task_manager.spawn_handle().spawn("telemetry", worker.run()); telemetry }); let transaction_pool = sc_transaction_pool::BasicPool::new_full( config.transaction_pool.clone(), config.role.is_authority().into(), config.prometheus_registry(), task_manager.spawn_essential_handle(), client.clone(), ); let import_queue = parachain_build_import_queue( client.clone(), config, telemetry.as_ref().map(|telemetry| telemetry.handle()), &task_manager, )?; Ok(PartialComponents { backend, client, import_queue, keystore_container, task_manager, transaction_pool, select_chain: (), other: (telemetry, telemetry_worker_handle), }) } /// Start a node with the given parachain `Configuration` and relay chain `Configuration`. /// /// This is the actual implementation that is abstract over the executor and the runtime api. async fn start_node_impl<BIC>( parachain_config: Configuration, polkadot_config: Configuration, para_id: ParaId, build_consensus: BIC, ) -> sc_service::error::Result<(TaskManager, Arc<TFullClient<Block, RuntimeApi, Executor>>)> where BIC: FnOnce( Arc<TFullClient<Block, RuntimeApi, Executor>>, Option<&Registry>, Option<TelemetryHandle>, &TaskManager, &polkadot_service::NewFull<polkadot_service::Client>, Arc<sc_transaction_pool::FullPool<Block, TFullClient<Block, RuntimeApi, Executor>>>, Arc<NetworkService<Block, Hash>>, SyncCryptoStorePtr, bool, ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>, { if matches!(parachain_config.role, Role::Light) { return Err("Light client not supported!".into()); } let parachain_config = prepare_node_config(parachain_config); let params = new_partial(&parachain_config)?; let (mut telemetry, telemetry_worker_handle) = params.other; let relay_chain_full_node = cumulus_client_service::build_polkadot_full_node(polkadot_config, telemetry_worker_handle).map_err( |e| match e { polkadot_service::Error::Sub(x) => x, s => format!("{}", s).into(), }, )?; let client = params.client.clone(); let backend = params.backend.clone(); let block_announce_validator = build_block_announce_validator( relay_chain_full_node.client.clone(), para_id, Box::new(relay_chain_full_node.network.clone()), relay_chain_full_node.backend.clone(), ); let force_authoring = parachain_config.force_authoring; let validator = parachain_config.role.is_authority(); let prometheus_registry = parachain_config.prometheus_registry().cloned(); let transaction_pool = params.transaction_pool.clone(); let mut task_manager = params.task_manager; let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue); let (network, system_rpc_tx, start_network) = sc_service::build_network(sc_service::BuildNetworkParams { config: &parachain_config, client: client.clone(), transaction_pool: transaction_pool.clone(), spawn_handle: task_manager.spawn_handle(), import_queue: import_queue.clone(), on_demand: None, block_announce_validator_builder: Some(Box::new(|_| block_announce_validator)), })?; let rpc_extensions_builder = { let client = client.clone(); let pool = transaction_pool.clone(); Box::new(move |deny_unsafe, _| { let deps = crate::rpc::FullDeps { client: client.clone(), pool: pool.clone(), deny_unsafe, }; crate::rpc::create_full(deps) }) }; sc_service::spawn_tasks(sc_service::SpawnTasksParams { on_demand: None, remote_blockchain: None, rpc_extensions_builder, client: client.clone(), transaction_pool: transaction_pool.clone(), task_manager: &mut task_manager, config: parachain_config, keystore: params.keystore_container.sync_keystore(), backend: backend.clone(), network: network.clone(), system_rpc_tx, telemetry: telemetry.as_mut(), })?; let announce_block = { let network = network.clone(); Arc::new(move |hash, data| network.announce_block(hash, data)) }; if validator { let parachain_consensus = build_consensus( client.clone(), prometheus_registry.as_ref(), telemetry.as_ref().map(|t| t.handle()), &task_manager, &relay_chain_full_node, transaction_pool, network, params.keystore_container.sync_keystore(), force_authoring, )?; let spawner = task_manager.spawn_handle(); let params = StartCollatorParams { para_id, block_status: client.clone(), announce_block, client: client.clone(), task_manager: &mut task_manager, relay_chain_full_node, spawner, parachain_consensus, import_queue, }; start_collator(params).await?; } else { let params = StartFullNodeParams { client: client.clone(), announce_block, task_manager: &mut task_manager, para_id, relay_chain_full_node, }; start_full_node(params)?; } start_network.start_network(); Ok((task_manager, client)) } /// Build the import queue for the parachain runtime. pub fn parachain_build_import_queue( client: Arc<TFullClient<Block, RuntimeApi, Executor>>, config: &Configuration, telemetry: Option<TelemetryHandle>, task_manager: &TaskManager, ) -> Result<sp_consensus::DefaultImportQueue<Block, TFullClient<Block, RuntimeApi, Executor>>, sc_service::Error> { let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; cumulus_client_consensus_aura::import_queue::<sp_consensus_aura::sr25519::AuthorityPair, _, _, _, _, _, _>( cumulus_client_consensus_aura::ImportQueueParams { block_import: client.clone(), client: client.clone(), create_inherent_data_providers: move |_, _| async move { let time = sp_timestamp::InherentDataProvider::from_system_time(); let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration( *time, slot_duration.slot_duration(), ); Ok((time, slot)) }, registry: config.prometheus_registry().clone(), can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()), spawner: &task_manager.spawn_essential_handle(), telemetry, }, ) .map_err(Into::into) } /// Start a normal parachain node. #[sc_tracing::logging::prefix_logs_with("Parachain")] pub async fn start_node( parachain_config: Configuration, polkadot_config: Configuration, para_id: ParaId, ) -> sc_service::error::Result<(TaskManager, Arc<TFullClient<Block, RuntimeApi, Executor>>)> { start_node_impl::<_>( parachain_config, polkadot_config, para_id, |client, prometheus_registry, telemetry, task_manager, relay_chain_node, transaction_pool, sync_oracle, keystore, force_authoring| { let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( task_manager.spawn_handle(), client.clone(), transaction_pool, prometheus_registry.clone(), telemetry.clone(), ); let relay_chain_backend = relay_chain_node.backend.clone(); let relay_chain_client = relay_chain_node.client.clone(); Ok(build_aura_consensus::< sp_consensus_aura::sr25519::AuthorityPair, _, _, _, _, _, _, _, _, _, >(BuildAuraConsensusParams { proposer_factory, create_inherent_data_providers: move |_, (relay_parent, validation_data)| { let parachain_inherent = cumulus_primitives_parachain_inherent::ParachainInherentData::create_at_with_client( relay_parent, &relay_chain_client, &*relay_chain_backend, &validation_data, para_id, ); async move { let time = sp_timestamp::InherentDataProvider::from_system_time(); let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration( *time, slot_duration.slot_duration(), ); let parachain_inherent = parachain_inherent.ok_or_else(|| { Box::<dyn std::error::Error + Send + Sync>::from("Failed to create parachain inherent") })?; Ok((time, slot, parachain_inherent)) } }, block_import: client.clone(), relay_chain_client: relay_chain_node.client.clone(), relay_chain_backend: relay_chain_node.backend.clone(), para_client: client.clone(), backoff_authoring_blocks: Option::<()>::None, sync_oracle, keystore, force_authoring, slot_duration, // We got around 500ms for proposing block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32), telemetry, })) }, ) .await }
30.281768
117
0.740011
718fb98c39966797a310b055afb439cbc808382a
624
// Copyright 2020-2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 mod primitives; mod types; pub use primitives::{ AeadAlg, AeadDecrypt, AeadEncrypt, BIP39Generate, BIP39Recover, Chain, ChainCode, Ed25519Sign, GenerateKey, Hash, HashType, Hkdf, Hmac, KeyType, MnemonicLanguage, Pbkdf2Hmac, PrimitiveProcedure, PublicKey, Sha2Hash, Slip10Derive, Slip10Generate, X25519DiffieHellman, }; pub use types::{ CollectedOutput, FatalProcedureError, InputData, OutputKey, PersistOutput, PersistSecret, Procedure, ProcedureError, ProcedureIo, ProcedureStep, }; pub(crate) use types::{Products, Runner};
36.705882
119
0.775641
1c6842b8b006a86934ef527f092997609517d66d
3,027
/* * Terra Contract Addresses * */ use serde_json::{json, Value}; use serde::Deserialize; use serde::Serialize; #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AssetWhitelist { pub contracts: Value, pub pairs_dex: Value, pub pairs: Value, pub tokens: Value, pub custom: Value, } pub fn contracts(list: &AssetWhitelist, protocol: &str, name: &str) -> Option<String> { let none_value = json!("None"); let contract_list = list.contracts.as_object().unwrap().get("mainnet").unwrap().as_object().unwrap(); for (key, value) in contract_list { let value_name = value.get("name").unwrap_or(&none_value).as_str().unwrap(); let value_protocol = value.get("protocol").unwrap_or(&none_value).as_str().unwrap(); if value_name == name && value_protocol.to_uppercase() == protocol.to_uppercase() { return Some(key.to_string()); } } None } pub fn pairs_dex(list: &AssetWhitelist, assets: [&str; 2], dex: &str) -> Option<String> { let none_value = json!("None"); let pairs_list = list.pairs_dex.as_object().unwrap().get("mainnet").unwrap().as_object().unwrap(); for (key, value) in pairs_list { let value_dex = value.get("dex").unwrap_or(&none_value).as_str().unwrap(); if value_dex.to_uppercase() == dex.to_uppercase() { let value_assets: Vec<&str> = value.get("assets").unwrap().as_array().unwrap().iter().map(|x| x.as_str().unwrap()).collect(); if value_assets.contains(&assets[0]) && value_assets.contains(&assets[1]) && value_assets.len() == 2 { return Some(key.to_string()); } } } None } pub fn tokens(list: &AssetWhitelist, protocol: &str, symbol: &str) -> Option<String> { let none_value = json!("None"); let tokens_list = list.tokens.as_object().unwrap().get("mainnet").unwrap().as_object().unwrap(); for (key, value) in tokens_list { let value_symbol = value.get("symbol").unwrap_or(&none_value).as_str().unwrap(); let value_protocol = value.get("protocol").unwrap_or(&none_value).as_str().unwrap(); if value_symbol == symbol && value_protocol.to_uppercase() == protocol.to_uppercase() { return Some(key.to_string()); } } None } // this is for contracts/tokens/pairs that are not whitelisted for whatever reason but needed for terra-ruts-bot pub fn custom(list: &AssetWhitelist, protocol: &str, symbol: &str) -> Option<String> { let none_value = json!("None"); let custom_list = list.custom.as_object().unwrap().get("mainnet").unwrap().as_object().unwrap(); for (key, value) in custom_list { let value_symbol = value.get("symbol").unwrap_or(&none_value).as_str().unwrap(); let value_protocol = value.get("protocol").unwrap_or(&none_value).as_str().unwrap(); if value_symbol == symbol && value_protocol.to_uppercase() == protocol.to_uppercase() { return Some(key.to_string()); } } None }
42.041667
137
0.642881
28fd0d3c2fb4d97c2b699c5cf201533d3ed7face
27,925
// 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. // Tracking of received packets and generating acks thereof. #![deny(clippy::pedantic)] use std::collections::VecDeque; use std::convert::TryInto; use std::ops::{Index, IndexMut}; use std::rc::Rc; use std::time::{Duration, Instant}; use neqo_common::{qdebug, qinfo, qtrace, qwarn}; use neqo_crypto::{Epoch, TLS_EPOCH_HANDSHAKE, TLS_EPOCH_INITIAL}; use crate::frame::{AckRange, Frame}; use crate::packet::{PacketNumber, PacketType}; use crate::recovery::RecoveryToken; use smallvec::{smallvec, SmallVec}; // TODO(mt) look at enabling EnumMap for this: https://stackoverflow.com/a/44905797/1375574 #[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Eq)] pub enum PNSpace { Initial, Handshake, ApplicationData, } #[allow(clippy::use_self)] // https://github.com/rust-lang/rust-clippy/issues/3410 impl PNSpace { pub fn iter() -> impl Iterator<Item = &'static PNSpace> { const SPACES: &[PNSpace] = &[ PNSpace::Initial, PNSpace::Handshake, PNSpace::ApplicationData, ]; SPACES.iter() } } impl From<Epoch> for PNSpace { fn from(epoch: Epoch) -> Self { match epoch { TLS_EPOCH_INITIAL => Self::Initial, TLS_EPOCH_HANDSHAKE => Self::Handshake, _ => Self::ApplicationData, } } } impl From<PacketType> for PNSpace { fn from(pt: PacketType) -> Self { match pt { PacketType::Initial => Self::Initial, PacketType::Handshake => Self::Handshake, PacketType::ZeroRtt | PacketType::Short => Self::ApplicationData, _ => panic!("Attempted to get space from wrong packet type"), } } } #[derive(Clone, Copy, Default)] pub struct PNSpaceSet { initial: bool, handshake: bool, application_data: bool, } impl Index<PNSpace> for PNSpaceSet { type Output = bool; fn index(&self, space: PNSpace) -> &Self::Output { match space { PNSpace::Initial => &self.initial, PNSpace::Handshake => &self.handshake, PNSpace::ApplicationData => &self.application_data, } } } impl IndexMut<PNSpace> for PNSpaceSet { fn index_mut(&mut self, space: PNSpace) -> &mut Self::Output { match space { PNSpace::Initial => &mut self.initial, PNSpace::Handshake => &mut self.handshake, PNSpace::ApplicationData => &mut self.application_data, } } } impl<T: AsRef<[PNSpace]>> From<T> for PNSpaceSet { fn from(spaces: T) -> Self { let mut v = Self::default(); for sp in spaces.as_ref() { v[*sp] = true; } v } } impl std::fmt::Debug for PNSpaceSet { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let mut first = true; f.write_str("(")?; for sp in PNSpace::iter() { if self[*sp] { if !first { f.write_str("+")?; first = false; } std::fmt::Display::fmt(sp, f)?; } } f.write_str(")") } } #[derive(Debug, Clone)] pub struct SentPacket { pub pt: PacketType, pub pn: u64, ack_eliciting: bool, pub time_sent: Instant, pub tokens: Rc<Vec<RecoveryToken>>, time_declared_lost: Option<Instant>, /// After a PTO, this is true when the packet has been released. pto: bool, pub size: usize, } impl SentPacket { pub fn new( pt: PacketType, pn: u64, time_sent: Instant, ack_eliciting: bool, tokens: Rc<Vec<RecoveryToken>>, size: usize, ) -> Self { Self { pt, pn, time_sent, ack_eliciting, tokens, time_declared_lost: None, pto: false, size, } } /// Returns `true` if the packet will elicit an ACK. pub fn ack_eliciting(&self) -> bool { self.ack_eliciting } /// Whether the packet has been declared lost. pub fn lost(&self) -> bool { self.time_declared_lost.is_some() } /// Whether accounting for the loss or acknowledgement in the /// congestion controller is pending. /// Returns `true` if the packet counts as being "in flight", /// and has not previously been declared lost. /// Note that this should count packets that contain only ACK and PADDING, /// but we don't send PADDING, so we don't track that. pub fn cc_outstanding(&self) -> bool { self.ack_eliciting() && !self.lost() } /// Declare the packet as lost. Returns `true` if this is the first time. pub fn declare_lost(&mut self, now: Instant) -> bool { if self.lost() { false } else { self.time_declared_lost = Some(now); true } } /// Ask whether this tracked packet has been declared lost for long enough /// that it can be expired and no longer tracked. pub fn expired(&self, now: Instant, expiration_period: Duration) -> bool { if let Some(loss_time) = self.time_declared_lost { (loss_time + expiration_period) <= now } else { false } } /// Whether the packet contents were cleared out after a PTO. pub fn pto_fired(&self) -> bool { self.pto } /// On PTO, we need to get the recovery tokens so that we can ensure that /// the frames we sent can be sent again in the PTO packet(s). Do that just once. pub fn pto(&mut self) -> bool { if self.pto || self.lost() { false } else { self.pto = true; true } } } impl std::fmt::Display for PNSpace { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str(match self { Self::Initial => "in", Self::Handshake => "hs", Self::ApplicationData => "ap", }) } } #[derive(Clone, Debug, Default)] pub struct PacketRange { largest: PacketNumber, smallest: PacketNumber, ack_needed: bool, } impl PacketRange { /// Make a single packet range. pub fn new(pn: u64) -> Self { Self { largest: pn, smallest: pn, ack_needed: true, } } /// Get the number of acknowleged packets in the range. pub fn len(&self) -> u64 { self.largest - self.smallest + 1 } /// Returns whether this needs to be sent. pub fn ack_needed(&self) -> bool { self.ack_needed } /// Return whether the given number is in the range. pub fn contains(&self, pn: u64) -> bool { (pn >= self.smallest) && (pn <= self.largest) } /// Maybe add a packet number to the range. Returns true if it was added. pub fn add(&mut self, pn: u64) -> bool { assert!(!self.contains(pn)); // Only insert if this is adjacent the current range. if (self.largest + 1) == pn { qtrace!([self], "Adding largest {}", pn); self.largest += 1; self.ack_needed = true; true } else if self.smallest == (pn + 1) { qtrace!([self], "Adding smallest {}", pn); self.smallest -= 1; self.ack_needed = true; true } else { false } } /// Maybe merge a lower-numbered range into this. pub fn merge_smaller(&mut self, other: &Self) { qinfo!([self], "Merging {}", other); // This only works if they are immediately adjacent. assert_eq!(self.smallest - 1, other.largest); self.smallest = other.smallest; self.ack_needed = self.ack_needed || other.ack_needed; } /// When a packet containing the range `other` is acknowledged, /// clear the `ack_needed` attribute on this. /// Requires that other is equal to this, or a larger range. pub fn acknowledged(&mut self, other: &Self) { if (other.smallest <= self.smallest) && (other.largest >= self.largest) { self.ack_needed = false; } } } impl ::std::fmt::Display for PacketRange { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}->{}", self.largest, self.smallest) } } /// The ACK delay we use. pub const ACK_DELAY: Duration = Duration::from_millis(20); // 20ms pub const MAX_UNACKED_PKTS: usize = 1; const MAX_TRACKED_RANGES: usize = 32; const MAX_ACKS_PER_FRAME: usize = 32; /// A structure that tracks what was included in an ACK. #[derive(Debug, Clone)] pub struct AckToken { space: PNSpace, ranges: Vec<PacketRange>, } /// A structure that tracks what packets have been received, /// and what needs acknowledgement for a packet number space. #[derive(Debug)] pub struct RecvdPackets { space: PNSpace, ranges: VecDeque<PacketRange>, /// The packet number of the lowest number packet that we are tracking. min_tracked: PacketNumber, /// The time we got the largest acknowledged. largest_pn_time: Option<Instant>, // The time that we should be sending an ACK. ack_time: Option<Instant>, pkts_since_last_ack: usize, } impl RecvdPackets { /// Make a new `RecvdPackets` for the indicated packet number space. pub fn new(space: PNSpace) -> Self { Self { space, ranges: VecDeque::new(), min_tracked: 0, largest_pn_time: None, ack_time: None, pkts_since_last_ack: 0, } } /// Get the time at which the next ACK should be sent. pub fn ack_time(&self) -> Option<Instant> { self.ack_time } /// Returns true if an ACK frame should be sent now. fn ack_now(&self, now: Instant) -> bool { match self.ack_time { Some(t) => t <= now, None => false, } } // A simple addition of a packet number to the tracked set. // This doesn't do a binary search on the assumption that // new packets will generally be added to the start of the list. fn add(&mut self, pn: u64) -> usize { for i in 0..self.ranges.len() { if self.ranges[i].add(pn) { // Maybe merge two ranges. let nxt = i + 1; if (nxt < self.ranges.len()) && (pn - 1 == self.ranges[nxt].largest) { let smaller = self.ranges.remove(nxt).unwrap(); self.ranges[i].merge_smaller(&smaller); } return i; } if self.ranges[i].largest < pn { self.ranges.insert(i, PacketRange::new(pn)); return i; } } self.ranges.push_back(PacketRange::new(pn)); self.ranges.len() - 1 } /// Add the packet to the tracked set. pub fn set_received(&mut self, now: Instant, pn: u64, ack_eliciting: bool) { let next_in_order_pn = self.ranges.front().map_or(0, |pr| pr.largest + 1); qdebug!([self], "next in order pn: {}", next_in_order_pn); let i = self.add(pn); // The new addition was the largest, so update the time we use for calculating ACK delay. if i == 0 && pn == self.ranges[0].largest { self.largest_pn_time = Some(now); } // Limit the number of ranges that are tracked to MAX_TRACKED_RANGES. if self.ranges.len() > MAX_TRACKED_RANGES { let oldest = self.ranges.pop_back().unwrap(); if oldest.ack_needed { qwarn!([self], "Dropping unacknowledged ACK range: {}", oldest); // TODO(mt) Record some statistics about this so we can tune MAX_TRACKED_RANGES. } else { qdebug!([self], "Drop ACK range: {}", oldest); } self.min_tracked = oldest.largest + 1; } if ack_eliciting { self.pkts_since_last_ack += 1; // Send ACK right away if out-of-order // On the first in-order ack-eliciting packet since sending an ACK, // set a delay. // Count packets until we exceed MAX_UNACKED_PKTS, then remove the // delay. if pn != next_in_order_pn { self.ack_time = Some(now); } else if self.space == PNSpace::ApplicationData { match &mut self.pkts_since_last_ack { 0 => unreachable!(), 1 => self.ack_time = Some(now + ACK_DELAY), x if *x > MAX_UNACKED_PKTS => self.ack_time = Some(now), _ => debug_assert!(self.ack_time.is_some()), } } else { self.ack_time = Some(now); } qdebug!([self], "Set ACK timer to {:?}", self.ack_time); } } /// Check if the packet is a duplicate. pub fn is_duplicate(&self, pn: PacketNumber) -> bool { if pn < self.min_tracked { return true; } // TODO(mt) consider a binary search or early exit. for range in &self.ranges { if range.contains(pn) { return true; } } false } /// Mark the given range as having been acknowledged. pub fn acknowledged(&mut self, acked: &[PacketRange]) { let mut range_iter = self.ranges.iter_mut(); let mut cur = range_iter.next().expect("should have at least one range"); for ack in acked { while cur.smallest > ack.largest { cur = match range_iter.next() { Some(c) => c, None => return, }; } cur.acknowledged(&ack); } } /// Generate an ACK frame for this packet number space. /// /// Unlike other frame generators this doesn't modify the underlying instance /// to track what has been sent. This only clears the delayed ACK timer. /// /// When sending ACKs, we want to always send the most recent ranges, /// even if they have been sent in other packets. /// /// We don't send ranges that have been acknowledged, but they still need /// to be tracked so that duplicates can be detected. fn get_frame(&mut self, now: Instant) -> Option<(Frame, Option<RecoveryToken>)> { // Check that we aren't delaying ACKs. if !self.ack_now(now) { return None; } // Limit the number of ACK ranges we send so that we'll always // have space for data in packets. let ranges: Vec<PacketRange> = self .ranges .iter() .filter(|r| r.ack_needed()) .take(MAX_ACKS_PER_FRAME) .cloned() .collect(); let mut iter = ranges.iter(); let first = match iter.next() { Some(v) => v, None => return None, // Nothing to send. }; let mut ack_ranges = Vec::new(); let mut last = first.smallest; for range in iter { ack_ranges.push(AckRange { // the difference must be at least 2 because 0-length gaps, // (difference 1) are illegal. gap: last - range.largest - 2, range: range.len() - 1, }); last = range.smallest; } // We've sent an ACK, reset the timer. self.ack_time = None; self.pkts_since_last_ack = 0; let ack_delay = now.duration_since(self.largest_pn_time.unwrap()); // We use the default exponent so // ack_delay is in multiples of 8 microseconds. if let Ok(delay) = (ack_delay.as_micros() / 8).try_into() { let ack = Frame::Ack { largest_acknowledged: first.largest, ack_delay: delay, first_ack_range: first.len() - 1, ack_ranges, }; let token = RecoveryToken::Ack(AckToken { space: self.space, ranges, }); Some((ack, Some(token))) } else { qwarn!( "ack_delay.as_micros() did not fit a u64 {:?}", ack_delay.as_micros() ); None } } } impl ::std::fmt::Display for RecvdPackets { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "Recvd-{}", self.space) } } #[derive(Debug)] pub struct AckTracker { /// This stores information about received packets in *reverse* order /// by spaces. Why reverse? Because we ultimately only want to keep /// `ApplicationData` and this allows us to drop other spaces easily. spaces: SmallVec<[RecvdPackets; 1]>, } impl AckTracker { pub fn drop_space(&mut self, space: PNSpace) { let sp = match space { PNSpace::Initial => self.spaces.pop(), PNSpace::Handshake => { let sp = self.spaces.pop(); self.spaces.shrink_to_fit(); sp } PNSpace::ApplicationData => panic!("discarding application space"), }; assert_eq!(sp.unwrap().space, space, "dropping spaces out of order"); } pub fn get_mut(&mut self, space: PNSpace) -> Option<&mut RecvdPackets> { self.spaces.get_mut(match space { PNSpace::ApplicationData => 0, PNSpace::Handshake => 1, PNSpace::Initial => 2, }) } /// Determine the earliest time that an ACK might be needed. pub fn ack_time(&self, now: Instant) -> Option<Instant> { if self.spaces.len() == 1 { self.spaces[0].ack_time() } else { // Ignore any time that is in the past relative to `now`. // That is something of a hack, but there are cases where we can't send ACK // frames for all spaces, which can mean that one space is stuck in the past. // That isn't a problem because we guarantee that earlier spaces will always // be able to send ACK frames. self.spaces .iter() .filter_map(|recvd| recvd.ack_time().filter(|t| *t > now)) .min() } } pub fn acked(&mut self, token: &AckToken) { if let Some(space) = self.get_mut(token.space) { space.acknowledged(&token.ranges); } } pub(crate) fn get_frame( &mut self, now: Instant, pn_space: PNSpace, ) -> Option<(Frame, Option<RecoveryToken>)> { self.get_mut(pn_space) .and_then(|space| space.get_frame(now)) } } impl Default for AckTracker { fn default() -> Self { Self { spaces: smallvec![ RecvdPackets::new(PNSpace::ApplicationData), RecvdPackets::new(PNSpace::Handshake), RecvdPackets::new(PNSpace::Initial), ], } } } #[cfg(test)] mod tests { use super::{ AckTracker, Duration, Instant, PNSpace, PNSpaceSet, RecoveryToken, RecvdPackets, ACK_DELAY, MAX_TRACKED_RANGES, MAX_UNACKED_PKTS, }; use lazy_static::lazy_static; use std::collections::HashSet; use std::convert::TryFrom; lazy_static! { static ref NOW: Instant = Instant::now(); } fn test_ack_range(pns: &[u64], nranges: usize) { let mut rp = RecvdPackets::new(PNSpace::Initial); // Any space will do. let mut packets = HashSet::new(); for pn in pns { rp.set_received(*NOW, *pn, true); packets.insert(*pn); } assert_eq!(rp.ranges.len(), nranges); // Check that all these packets will be detected as duplicates. for pn in pns { assert!(rp.is_duplicate(*pn)); } // Check that the ranges decrease monotonically and don't overlap. let mut iter = rp.ranges.iter(); let mut last = iter.next().expect("should have at least one"); for n in iter { assert!(n.largest + 1 < last.smallest); last = n; } // Check that the ranges include the right values. let mut in_ranges = HashSet::new(); for range in &rp.ranges { for included in range.smallest..=range.largest { in_ranges.insert(included); } } assert_eq!(packets, in_ranges); } #[test] fn pn0() { test_ack_range(&[0], 1); } #[test] fn pn1() { test_ack_range(&[1], 1); } #[test] fn two_ranges() { test_ack_range(&[0, 1, 2, 5, 6, 7], 2); } #[test] fn fill_in_range() { test_ack_range(&[0, 1, 2, 5, 6, 7, 3, 4], 1); } #[test] fn too_many_ranges() { let mut rp = RecvdPackets::new(PNSpace::Initial); // Any space will do. // This will add one too many disjoint ranges. for i in 0..=MAX_TRACKED_RANGES { rp.set_received(*NOW, (i * 2) as u64, true); } assert_eq!(rp.ranges.len(), MAX_TRACKED_RANGES); assert_eq!(rp.ranges.back().unwrap().largest, 2); // Even though the range was dropped, we still consider it a duplicate. assert!(rp.is_duplicate(0)); assert!(!rp.is_duplicate(1)); assert!(rp.is_duplicate(2)); } #[test] fn ack_delay() { // Only application data packets are delayed. let mut rp = RecvdPackets::new(PNSpace::ApplicationData); assert!(rp.ack_time().is_none()); assert!(!rp.ack_now(*NOW)); // Some packets won't cause an ACK to be needed. let max_unacked = u64::try_from(MAX_UNACKED_PKTS).unwrap(); for num in 0..max_unacked { rp.set_received(*NOW, num, true); assert_eq!(Some(*NOW + ACK_DELAY), rp.ack_time()); assert!(!rp.ack_now(*NOW)); assert!(rp.ack_now(*NOW + ACK_DELAY)); } // Exceeding MAX_UNACKED_PKTS will move the ACK time to now. rp.set_received(*NOW, max_unacked, true); assert_eq!(Some(*NOW), rp.ack_time()); assert!(rp.ack_now(*NOW)); } #[test] fn no_ack_delay() { for space in &[PNSpace::Initial, PNSpace::Handshake] { let mut rp = RecvdPackets::new(*space); assert!(rp.ack_time().is_none()); assert!(!rp.ack_now(*NOW)); // Any packet will be acknowledged straight away. rp.set_received(*NOW, 0, true); assert_eq!(Some(*NOW), rp.ack_time()); assert!(rp.ack_now(*NOW)); } } #[test] fn ooo_no_ack_delay() { for space in &[ PNSpace::Initial, PNSpace::Handshake, PNSpace::ApplicationData, ] { let mut rp = RecvdPackets::new(*space); assert!(rp.ack_time().is_none()); assert!(!rp.ack_now(*NOW)); // Any OoO packet will be acknowledged straight away. rp.set_received(*NOW, 3, true); assert_eq!(Some(*NOW), rp.ack_time()); assert!(rp.ack_now(*NOW)); } } #[test] fn aggregate_ack_time() { let mut tracker = AckTracker::default(); // This packet won't trigger an ACK. tracker .get_mut(PNSpace::Handshake) .unwrap() .set_received(*NOW, 0, false); assert_eq!(None, tracker.ack_time(*NOW)); // This should be delayed. tracker .get_mut(PNSpace::ApplicationData) .unwrap() .set_received(*NOW, 0, true); assert_eq!(Some(*NOW + ACK_DELAY), tracker.ack_time(*NOW)); // This should move the time forward. let later = *NOW + ACK_DELAY.checked_div(2).unwrap(); tracker .get_mut(PNSpace::Initial) .unwrap() .set_received(later, 0, true); assert_eq!(Some(later), tracker.ack_time(*NOW)); } #[test] #[should_panic(expected = "discarding application space")] fn drop_app() { let mut tracker = AckTracker::default(); tracker.drop_space(PNSpace::ApplicationData); } #[test] #[should_panic(expected = "dropping spaces out of order")] fn drop_out_of_order() { let mut tracker = AckTracker::default(); tracker.drop_space(PNSpace::Handshake); } #[test] fn drop_spaces() { let mut tracker = AckTracker::default(); tracker .get_mut(PNSpace::Initial) .unwrap() .set_received(*NOW, 0, true); // The reference time for `ack_time` has to be in the past or we filter out the timer. assert!(tracker.ack_time(*NOW - Duration::from_millis(1)).is_some()); let (_ack, token) = tracker.get_frame(*NOW, PNSpace::Initial).unwrap(); assert!(token.is_some()); // Mark another packet as received so we have cause to send another ACK in that space. tracker .get_mut(PNSpace::Initial) .unwrap() .set_received(*NOW, 1, true); assert!(tracker.ack_time(*NOW - Duration::from_millis(1)).is_some()); // Now drop that space. tracker.drop_space(PNSpace::Initial); assert!(tracker.get_mut(PNSpace::Initial).is_none()); assert!(tracker.ack_time(*NOW - Duration::from_millis(1)).is_none()); assert!(tracker.get_frame(*NOW, PNSpace::Initial).is_none()); if let RecoveryToken::Ack(tok) = token.as_ref().unwrap() { tracker.acked(tok); // Should be a noop. } else { panic!("not an ACK token"); } } #[test] fn ack_time_elapsed() { let mut tracker = AckTracker::default(); // While we have multiple PN spaces, we ignore ACK timers from the past. // Send out of order to cause the delayed ack timer to be set to `*NOW`. tracker .get_mut(PNSpace::ApplicationData) .unwrap() .set_received(*NOW, 3, true); assert!(tracker.ack_time(*NOW + Duration::from_millis(1)).is_none()); // When we are reduced to one space, that filter is off. tracker.drop_space(PNSpace::Initial); tracker.drop_space(PNSpace::Handshake); assert_eq!( tracker.ack_time(*NOW + Duration::from_millis(1)), Some(*NOW) ); } #[test] fn pnspaceset_default() { let set = PNSpaceSet::default(); assert!(!set[PNSpace::Initial]); assert!(!set[PNSpace::Handshake]); assert!(!set[PNSpace::ApplicationData]); } #[test] fn pnspaceset_from() { let set = PNSpaceSet::from(&[PNSpace::Initial]); assert!(set[PNSpace::Initial]); assert!(!set[PNSpace::Handshake]); assert!(!set[PNSpace::ApplicationData]); let set = PNSpaceSet::from(&[PNSpace::Handshake, PNSpace::Initial]); assert!(set[PNSpace::Initial]); assert!(set[PNSpace::Handshake]); assert!(!set[PNSpace::ApplicationData]); let set = PNSpaceSet::from(&[PNSpace::ApplicationData, PNSpace::ApplicationData]); assert!(!set[PNSpace::Initial]); assert!(!set[PNSpace::Handshake]); assert!(set[PNSpace::ApplicationData]); } #[test] fn pnspaceset_copy() { let set = PNSpaceSet::from(&[PNSpace::Handshake, PNSpace::ApplicationData]); let copy = set; assert!(!copy[PNSpace::Initial]); assert!(copy[PNSpace::Handshake]); assert!(copy[PNSpace::ApplicationData]); } }
31.805239
99
0.558496
9ccdb6a81b2eb0f6d353a119eec17b8347b4549e
5,716
use crate::errors::*; use crate::notifications::*; use crate::toml_utils::*; use crate::utils::utils; use std::cell::RefCell; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; pub const SUPPORTED_METADATA_VERSIONS: [&str; 2] = ["2", "12"]; pub const DEFAULT_METADATA_VERSION: &str = "12"; #[derive(Clone, Debug, PartialEq)] pub struct SettingsFile { path: PathBuf, cache: RefCell<Option<Settings>>, } impl SettingsFile { pub fn new(path: PathBuf) -> Self { Self { path, cache: RefCell::new(None), } } fn write_settings(&self) -> Result<()> { let s = self.cache.borrow().as_ref().unwrap().clone(); utils::write_file("settings", &self.path, &s.stringify())?; Ok(()) } fn read_settings(&self) -> Result<()> { let mut needs_save = false; { let mut b = self.cache.borrow_mut(); if b.is_none() { *b = Some(if utils::is_file(&self.path) { let content = utils::read_file("settings", &self.path)?; Settings::parse(&content)? } else { needs_save = true; Default::default() }); } } if needs_save { self.write_settings()?; } Ok(()) } pub fn with<T, F: FnOnce(&Settings) -> Result<T>>(&self, f: F) -> Result<T> { self.read_settings()?; // Settings can no longer be None so it's OK to unwrap f(self.cache.borrow().as_ref().unwrap()) } pub fn with_mut<T, F: FnOnce(&mut Settings) -> Result<T>>(&self, f: F) -> Result<T> { self.read_settings()?; // Settings can no longer be None so it's OK to unwrap let result = { f(self.cache.borrow_mut().as_mut().unwrap())? }; self.write_settings()?; Ok(result) } } #[derive(Clone, Debug, PartialEq)] pub struct Settings { pub version: String, pub default_host_triple: Option<String>, pub default_toolchain: Option<String>, pub overrides: BTreeMap<String, String>, } impl Default for Settings { fn default() -> Self { Self { version: DEFAULT_METADATA_VERSION.to_owned(), default_host_triple: None, default_toolchain: None, overrides: BTreeMap::new(), } } } impl Settings { fn path_to_key(path: &Path, notify_handler: &dyn Fn(Notification<'_>)) -> String { if path.exists() { utils::canonicalize_path(path, notify_handler) .display() .to_string() } else { path.display().to_string() } } pub fn remove_override( &mut self, path: &Path, notify_handler: &dyn Fn(Notification<'_>), ) -> bool { let key = Self::path_to_key(path, notify_handler); self.overrides.remove(&key).is_some() } pub fn add_override( &mut self, path: &Path, toolchain: String, notify_handler: &dyn Fn(Notification<'_>), ) { let key = Self::path_to_key(path, notify_handler); notify_handler(Notification::SetOverrideToolchain(path, &toolchain)); self.overrides.insert(key, toolchain); } pub fn dir_override( &self, dir: &Path, notify_handler: &dyn Fn(Notification<'_>), ) -> Option<String> { let key = Self::path_to_key(dir, notify_handler); self.overrides.get(&key).cloned() } pub fn parse(data: &str) -> Result<Self> { let value = toml::from_str(data).map_err(ErrorKind::ParsingSettings)?; Self::from_toml(value, "") } pub fn stringify(self) -> String { toml::Value::Table(self.into_toml()).to_string() } pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result<Self> { let version = get_string(&mut table, "version", path)?; if !SUPPORTED_METADATA_VERSIONS.contains(&&*version) { return Err(ErrorKind::UnknownMetadataVersion(version).into()); } Ok(Self { version, default_host_triple: get_opt_string(&mut table, "default_host_triple", path)?, default_toolchain: get_opt_string(&mut table, "default_toolchain", path)?, overrides: Self::table_to_overrides(&mut table, path)?, }) } pub fn into_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); result.insert("version".to_owned(), toml::Value::String(self.version)); if let Some(v) = self.default_host_triple { result.insert("default_host_triple".to_owned(), toml::Value::String(v)); } if let Some(v) = self.default_toolchain { result.insert("default_toolchain".to_owned(), toml::Value::String(v)); } let overrides = Self::overrides_to_table(self.overrides); result.insert("overrides".to_owned(), toml::Value::Table(overrides)); result } fn table_to_overrides( table: &mut toml::value::Table, path: &str, ) -> Result<BTreeMap<String, String>> { let mut result = BTreeMap::new(); let pkg_table = get_table(table, "overrides", path)?; for (k, v) in pkg_table { if let toml::Value::String(t) = v { result.insert(k, t); } } Ok(result) } fn overrides_to_table(overrides: BTreeMap<String, String>) -> toml::value::Table { let mut result = toml::value::Table::new(); for (k, v) in overrides { result.insert(k, toml::Value::String(v)); } result } }
30.566845
90
0.561057
752b1fa821f7f9cf59fcaa1610c3ef3d833028de
678
// Copyright 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. #![feature(rustc_attrs)] #![allow(dead_code)] fn main() { #![rustc_error] // rust-lang/rust#49855 let mut x = 33; let p = &x; x = 22; //~ ERROR cannot assign to `x` because it is borrowed [E0506] }
35.684211
73
0.70059
d9d2fc2fa4783fa8daa1e40760597fdba2eda335
2,215
use datamodel_connector::{connector_error::ConnectorError, Connector, ConnectorCapability}; use dml::model::Model; use dml::native_type_constructor::NativeTypeConstructor; use dml::native_type_instance::NativeTypeInstance; use dml::{field::Field, scalars::ScalarType}; pub struct SqliteDatamodelConnector { capabilities: Vec<ConnectorCapability>, constructors: Vec<NativeTypeConstructor>, } impl SqliteDatamodelConnector { pub fn new() -> SqliteDatamodelConnector { let capabilities = vec![ ConnectorCapability::RelationFieldsInArbitraryOrder, ConnectorCapability::UpdateableId, ]; let constructors: Vec<NativeTypeConstructor> = vec![]; SqliteDatamodelConnector { capabilities, constructors, } } } impl Connector for SqliteDatamodelConnector { fn name(&self) -> String { "sqlite".to_string() } fn capabilities(&self) -> &Vec<ConnectorCapability> { &self.capabilities } fn scalar_type_for_native_type(&self, _native_type: serde_json::Value) -> ScalarType { unreachable!("No native types on Sqlite"); } fn default_native_type_for_scalar_type(&self, _scalar_type: &ScalarType) -> serde_json::Value { serde_json::Value::Null } fn native_type_is_default_for_scalar_type( &self, _native_type: serde_json::Value, _scalar_type: &ScalarType, ) -> bool { false } fn validate_field(&self, _field: &Field) -> Result<(), ConnectorError> { Ok(()) } fn validate_model(&self, _model: &Model) -> Result<(), ConnectorError> { Ok(()) } fn available_native_type_constructors(&self) -> &[NativeTypeConstructor] { &self.constructors } fn parse_native_type(&self, _name: &str, _args: Vec<String>) -> Result<NativeTypeInstance, ConnectorError> { self.native_types_not_supported() } fn introspect_native_type(&self, _native_type: serde_json::Value) -> Result<NativeTypeInstance, ConnectorError> { self.native_types_not_supported() } } impl Default for SqliteDatamodelConnector { fn default() -> Self { Self::new() } }
28.397436
117
0.667269
64cf1422877af3bdd6dc6a1caf46412ba5e27f13
2,641
#![allow(clippy::module_inception)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::large_enum_variant)] #![allow(clippy::wrong_self_convention)] #![allow(clippy::should_implement_trait)] #![allow(clippy::blacklisted_name)] #![allow(clippy::vec_init_then_push)] #![allow(rustdoc::bare_urls)] #![warn(missing_docs)] //! <p>You can use the Amazon Redshift Data API to run queries on Amazon Redshift tables. You //! can run SQL statements, which are committed if the statement succeeds. </p> //! <p>For more information about the Amazon Redshift Data API, see //! <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/data-api.html">Using the Amazon Redshift Data API</a> in the //! <i>Amazon Redshift Cluster Management Guide</i>. </p> //! //! # Crate Organization //! //! The entry point for most customers will be [`Client`]. [`Client`] exposes one method for each API offered //! by the service. //! //! Some APIs require complex or nested arguments. These exist in [`model`]. //! //! Lastly, errors that can be returned by the service are contained within [`error`]. [`Error`] defines a meta //! error encompassing all possible errors that can be returned by the service. //! //! The other modules within this crate and not required for normal usage. //! //! # Examples // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use error_meta::Error; pub use config::Config; mod aws_endpoint; /// Client and fluent builders for calling the service. #[cfg(feature = "client")] pub mod client; /// Configuration for the service. pub mod config; /// Errors that can occur when calling the service. pub mod error; mod error_meta; /// Input structures for operations. pub mod input; mod json_deser; mod json_errors; mod json_ser; /// Data structures used by operation inputs/outputs. pub mod model; mod no_credentials; /// All operations that this crate can perform. pub mod operation; mod operation_deser; mod operation_ser; /// Output structures for operations. pub mod output; /// Crate version number. pub static PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub use aws_smithy_http::byte_stream::ByteStream; pub use aws_smithy_http::result::SdkError; pub use aws_smithy_types::Blob; pub use aws_smithy_types::DateTime; static API_METADATA: aws_http::user_agent::ApiMetadata = aws_http::user_agent::ApiMetadata::new("redshiftdata", PKG_VERSION); pub use aws_smithy_http::endpoint::Endpoint; pub use aws_smithy_types::retry::RetryConfig; pub use aws_types::app_name::AppName; pub use aws_types::region::Region; pub use aws_types::Credentials; #[cfg(feature = "client")] pub use client::Client;
36.178082
122
0.749337
38cd5059eefe7c981904494798f6c2bb785eeb13
14,260
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use std::i32; use std::net::{IpAddr, SocketAddr}; use std::str::FromStr; use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; use futures::{Future, Stream}; use grpcio::{ChannelBuilder, EnvBuilder, Environment, Server as GrpcServer, ServerBuilder}; use kvproto::tikvpb::*; use tokio_threadpool::{Builder as ThreadPoolBuilder, ThreadPool}; use tokio_timer::timer::Handle; use crate::coprocessor::Endpoint; use crate::raftstore::store::SnapManager; use crate::server::gc_worker::GCWorker; use crate::storage::lock_manager::LockMgr; use crate::storage::{Engine, Storage}; use tikv_util::security::SecurityManager; use tikv_util::timer::GLOBAL_TIMER_HANDLE; use tikv_util::worker::Worker; use tikv_util::Either; use super::load_statistics::*; use super::raft_client::RaftClient; use super::resolve::StoreAddrResolver; use super::service::*; use super::snap::{Runner as SnapHandler, Task as SnapTask}; use super::transport::{RaftStoreRouter, ServerTransport}; use super::{Config, Result}; const LOAD_STATISTICS_SLOTS: usize = 4; const LOAD_STATISTICS_INTERVAL: Duration = Duration::from_millis(100); pub const GRPC_THREAD_PREFIX: &str = "grpc-server"; pub const READPOOL_NORMAL_THREAD_PREFIX: &str = "store-read-norm"; pub const STATS_THREAD_PREFIX: &str = "transport-stats"; /// The TiKV server /// /// It hosts various internal components, including gRPC, the raftstore router /// and a snapshot worker. pub struct Server<T: RaftStoreRouter + 'static, S: StoreAddrResolver + 'static> { env: Arc<Environment>, /// A GrpcServer builder or a GrpcServer. /// /// If the listening port is configured, the server will be started lazily. builder_or_server: Option<Either<ServerBuilder, GrpcServer>>, local_addr: SocketAddr, // Transport. trans: ServerTransport<T, S>, raft_router: T, // For sending/receiving snapshots. snap_mgr: SnapManager, snap_worker: Worker<SnapTask>, // Currently load statistics is done in the thread. stats_pool: Option<ThreadPool>, grpc_thread_load: Arc<ThreadLoad>, readpool_normal_concurrency: usize, readpool_normal_thread_load: Arc<ThreadLoad>, timer: Handle, } impl<T: RaftStoreRouter, S: StoreAddrResolver + 'static> Server<T, S> { #[allow(clippy::too_many_arguments)] pub fn new<E: Engine, L: LockMgr>( cfg: &Arc<Config>, security_mgr: &Arc<SecurityManager>, storage: Storage<E, L>, cop: Endpoint<E>, raft_router: T, resolver: S, snap_mgr: SnapManager, gc_worker: GCWorker<E>, ) -> Result<Self> { // A helper thread (or pool) for transport layer. let stats_pool = ThreadPoolBuilder::new() .pool_size(cfg.stats_concurrency) .name_prefix(STATS_THREAD_PREFIX) .build(); let grpc_thread_load = Arc::new(ThreadLoad::with_threshold(cfg.heavy_load_threshold)); let readpool_normal_concurrency = storage.readpool_normal_concurrency(); let readpool_normal_thread_load = Arc::new(ThreadLoad::with_threshold(cfg.heavy_load_threshold)); let env = Arc::new( EnvBuilder::new() .cq_count(cfg.grpc_concurrency) .name_prefix(thd_name!(GRPC_THREAD_PREFIX)) .build(), ); let snap_worker = Worker::new("snap-handler"); let kv_service = KvService::new( storage, gc_worker, cop, raft_router.clone(), snap_worker.scheduler(), Arc::clone(&grpc_thread_load), Arc::clone(&readpool_normal_thread_load), cfg.enable_request_batch, if cfg.enable_request_batch && cfg.request_batch_enable_cross_command { Some(Duration::from(cfg.request_batch_wait_duration)) } else { None }, ); let addr = SocketAddr::from_str(&cfg.addr)?; let ip = format!("{}", addr.ip()); let channel_args = ChannelBuilder::new(Arc::clone(&env)) .stream_initial_window_size(cfg.grpc_stream_initial_window_size.0 as i32) .max_concurrent_stream(cfg.grpc_concurrent_stream) .max_receive_message_len(-1) .max_send_message_len(-1) .http2_max_ping_strikes(i32::MAX) // For pings without data from clients. .build_args(); let builder = { let mut sb = ServerBuilder::new(Arc::clone(&env)) .channel_args(channel_args) .register_service(create_tikv(kv_service)); sb = security_mgr.bind(sb, &ip, addr.port()); Either::Left(sb) }; let raft_client = Arc::new(RwLock::new(RaftClient::new( Arc::clone(&env), Arc::clone(cfg), Arc::clone(security_mgr), raft_router.clone(), Arc::clone(&grpc_thread_load), stats_pool.sender().clone(), ))); let trans = ServerTransport::new( raft_client, snap_worker.scheduler(), raft_router.clone(), resolver, ); let svr = Server { env: Arc::clone(&env), builder_or_server: Some(builder), local_addr: addr, trans, raft_router, snap_mgr, snap_worker, stats_pool: Some(stats_pool), grpc_thread_load, readpool_normal_concurrency, readpool_normal_thread_load, timer: GLOBAL_TIMER_HANDLE.clone(), }; Ok(svr) } pub fn transport(&self) -> ServerTransport<T, S> { self.trans.clone() } /// Register a gRPC service. /// Register after starting, it fails and returns the service. pub fn register_service(&mut self, svc: grpcio::Service) -> Option<grpcio::Service> { match self.builder_or_server.take() { Some(Either::Left(mut builder)) => { builder = builder.register_service(svc); self.builder_or_server = Some(Either::Left(builder)); None } Some(server) => { self.builder_or_server = Some(server); Some(svc) } None => Some(svc), } } /// Build gRPC server and bind to address. pub fn build_and_bind(&mut self) -> Result<SocketAddr> { let sb = self.builder_or_server.take().unwrap().left().unwrap(); let server = sb.build()?; let (ref host, port) = server.bind_addrs()[0]; let addr = SocketAddr::new(IpAddr::from_str(host)?, port as u16); self.local_addr = addr; self.builder_or_server = Some(Either::Right(server)); Ok(addr) } /// Starts the TiKV server. /// Notice: Make sure call `build_and_bind` first. pub fn start(&mut self, cfg: Arc<Config>, security_mgr: Arc<SecurityManager>) -> Result<()> { let snap_runner = SnapHandler::new( Arc::clone(&self.env), self.snap_mgr.clone(), self.raft_router.clone(), security_mgr, Arc::clone(&cfg), ); box_try!(self.snap_worker.start(snap_runner)); let mut grpc_server = self.builder_or_server.take().unwrap().right().unwrap(); info!("listening on addr"; "addr" => &self.local_addr); grpc_server.start(); self.builder_or_server = Some(Either::Right(grpc_server)); let mut grpc_load_stats = { let tl = Arc::clone(&self.grpc_thread_load); ThreadLoadStatistics::new(LOAD_STATISTICS_SLOTS, GRPC_THREAD_PREFIX, tl) }; let mut readpool_normal_load_stats = { let tl = Arc::clone(&self.readpool_normal_thread_load); let mut stats = ThreadLoadStatistics::new(LOAD_STATISTICS_SLOTS, READPOOL_NORMAL_THREAD_PREFIX, tl); stats.set_thread_target(self.readpool_normal_concurrency); stats }; self.stats_pool.as_ref().unwrap().spawn( self.timer .interval(Instant::now(), LOAD_STATISTICS_INTERVAL) .map_err(|_| ()) .for_each(move |i| { grpc_load_stats.record(i); readpool_normal_load_stats.record(i); Ok(()) }), ); info!("TiKV is ready to serve"); Ok(()) } /// Stops the TiKV server. pub fn stop(&mut self) -> Result<()> { self.snap_worker.stop(); if let Some(Either::Right(mut server)) = self.builder_or_server.take() { server.shutdown(); } if let Some(pool) = self.stats_pool.take() { let _ = pool.shutdown_now().wait(); } Ok(()) } // Return listening address, this may only be used for outer test // to get the real address because we may use "127.0.0.1:0" // in test to avoid port conflict. pub fn listening_addr(&self) -> SocketAddr { self.local_addr } } #[cfg(test)] mod tests { use std::sync::atomic::*; use std::sync::mpsc::*; use std::sync::*; use std::time::Duration; use super::*; use super::super::resolve::{Callback as ResolveCallback, StoreAddrResolver}; use super::super::transport::RaftStoreRouter; use super::super::{Config, Result}; use crate::config::CoprReadPoolConfig; use crate::coprocessor::{self, readpool_impl}; use crate::raftstore::store::transport::Transport; use crate::raftstore::store::*; use crate::raftstore::Result as RaftStoreResult; use crate::storage::TestStorageBuilder; use kvproto::raft_cmdpb::RaftCmdRequest; use kvproto::raft_serverpb::RaftMessage; use tikv_util::security::SecurityConfig; #[derive(Clone)] struct MockResolver { quick_fail: Arc<AtomicBool>, addr: Arc<Mutex<Option<String>>>, } impl StoreAddrResolver for MockResolver { fn resolve(&self, _: u64, cb: ResolveCallback) -> Result<()> { if self.quick_fail.load(Ordering::SeqCst) { return Err(box_err!("quick fail")); } let addr = self.addr.lock().unwrap(); cb(addr .as_ref() .map(|s| s.to_owned()) .ok_or(box_err!("not set"))); Ok(()) } } #[derive(Clone)] struct TestRaftStoreRouter { tx: Sender<usize>, significant_msg_sender: Sender<SignificantMsg>, } impl RaftStoreRouter for TestRaftStoreRouter { fn send_raft_msg(&self, _: RaftMessage) -> RaftStoreResult<()> { self.tx.send(1).unwrap(); Ok(()) } fn send_command(&self, _: RaftCmdRequest, _: Callback) -> RaftStoreResult<()> { self.tx.send(1).unwrap(); Ok(()) } fn significant_send(&self, _: u64, msg: SignificantMsg) -> RaftStoreResult<()> { self.significant_msg_sender.send(msg).unwrap(); Ok(()) } fn casual_send(&self, _: u64, _: CasualMessage) -> RaftStoreResult<()> { self.tx.send(1).unwrap(); Ok(()) } fn broadcast_unreachable(&self, _: u64) { let _ = self.tx.send(1); } } fn is_unreachable_to(msg: &SignificantMsg, region_id: u64, to_peer_id: u64) -> bool { *msg == SignificantMsg::Unreachable { region_id, to_peer_id, } } #[test] // if this failed, unset the environmental variables 'http_proxy' and 'https_proxy', and retry. fn test_peer_resolve() { let mut cfg = Config::default(); cfg.addr = "127.0.0.1:0".to_owned(); let storage = TestStorageBuilder::new().build().unwrap(); let mut gc_worker = GCWorker::new(storage.get_engine(), None, None, Default::default()); gc_worker.start().unwrap(); let (tx, rx) = mpsc::channel(); let (significant_msg_sender, significant_msg_receiver) = mpsc::channel(); let router = TestRaftStoreRouter { tx, significant_msg_sender, }; let quick_fail = Arc::new(AtomicBool::new(false)); let cfg = Arc::new(cfg); let security_mgr = Arc::new(SecurityManager::new(&SecurityConfig::default()).unwrap()); let cop_read_pool = readpool_impl::build_read_pool_for_test( &CoprReadPoolConfig::default_for_test(), storage.get_engine(), ); let cop = coprocessor::Endpoint::new(&cfg, cop_read_pool); let addr = Arc::new(Mutex::new(None)); let mut server = Server::new( &cfg, &security_mgr, storage, cop, router, MockResolver { quick_fail: Arc::clone(&quick_fail), addr: Arc::clone(&addr), }, SnapManager::new("", None), gc_worker, ) .unwrap(); server.build_and_bind().unwrap(); server.start(cfg, security_mgr).unwrap(); let mut trans = server.transport(); trans.report_unreachable(RaftMessage::default()); let mut resp = significant_msg_receiver.try_recv().unwrap(); assert!(is_unreachable_to(&resp, 0, 0), "{:?}", resp); let mut msg = RaftMessage::default(); msg.set_region_id(1); trans.send(msg.clone()).unwrap(); trans.flush(); resp = significant_msg_receiver.try_recv().unwrap(); assert!(is_unreachable_to(&resp, 1, 0), "{:?}", resp); *addr.lock().unwrap() = Some(format!("{}", server.listening_addr())); trans.send(msg.clone()).unwrap(); trans.flush(); assert!(rx.recv_timeout(Duration::from_secs(5)).is_ok()); msg.mut_to_peer().set_store_id(2); msg.set_region_id(2); quick_fail.store(true, Ordering::SeqCst); trans.send(msg.clone()).unwrap(); trans.flush(); resp = significant_msg_receiver.try_recv().unwrap(); assert!(is_unreachable_to(&resp, 2, 0), "{:?}", resp); server.stop().unwrap(); } }
34.527845
100
0.591304
f738fca40e3c34b769efa1f7b298b839d1b81e4a
5,602
//! Types and traits for working with asynchronous tasks. //! //! This module is similar to [`std::thread`], except it uses asynchronous tasks in place of //! threads. //! //! [`std::thread`]: https://doc.rust-lang.org/std/thread //! //! ## The task model //! //! An executing asynchronous Rust program consists of a collection of native OS threads, on top of //! which multiple stackless coroutines are multiplexed. We refer to these as "tasks". Tasks can //! be named, and provide some built-in support for synchronization. //! //! Communication between tasks can be done through channels, Rust's message-passing types, along //! with [other forms of tasks synchronization](../sync/index.html) and shared-memory data //! structures. In particular, types that are guaranteed to be threadsafe are easily shared between //! tasks using the atomically-reference-counted container, [`Arc`]. //! //! Fatal logic errors in Rust cause *thread panic*, during which a thread will unwind the stack, //! running destructors and freeing owned resources. If a panic occurs inside a task, there is no //! meaningful way of recovering, so the panic will propagate through any thread boundaries all the //! way to the root task. This is also known as a "panic = abort" model. //! //! ## Spawning a task //! //! A new task can be spawned using the [`task::spawn`][`spawn`] function: //! //! ```no_run //! use async_std::task; //! //! task::spawn(async { //! // some work here //! }); //! ``` //! //! In this example, the spawned task is "detached" from the current task. This means that it can //! outlive its parent (the task that spawned it), unless this parent is the root task. //! //! The root task can also wait on the completion of the child task; a call to [`spawn`] produces a //! [`JoinHandle`], which implements `Future` and can be `await`ed: //! //! ``` //! use async_std::task; //! //! # async_std::task::block_on(async { //! # //! let child = task::spawn(async { //! // some work here //! }); //! // some work here //! let res = child.await; //! # //! # }) //! ``` //! //! The `await` operator returns the final value produced by the child task. //! //! ## Configuring tasks //! //! A new task can be configured before it is spawned via the [`Builder`] type, //! which currently allows you to set the name for the child task: //! //! ``` //! # #![allow(unused_must_use)] //! use async_std::task; //! //! # async_std::task::block_on(async { //! # //! task::Builder::new().name("child1".to_string()).spawn(async { //! println!("Hello, world!"); //! }); //! # //! # }) //! ``` //! //! ## The `Task` type //! //! Tasks are represented via the [`Task`] type, which you can get in one of //! two ways: //! //! * By spawning a new task, e.g., using the [`task::spawn`][`spawn`] //! function, and calling [`task`][`JoinHandle::task`] on the [`JoinHandle`]. //! * By requesting the current task, using the [`task::current`] function. //! //! ## Task-local storage //! //! This module also provides an implementation of task-local storage for Rust //! programs. Task-local storage is a method of storing data into a global //! variable that each task in the program will have its own copy of. //! Tasks do not share this data, so accesses do not need to be synchronized. //! //! A task-local key owns the value it contains and will destroy the value when the //! task exits. It is created with the [`task_local!`] macro and can contain any //! value that is `'static` (no borrowed pointers). It provides an accessor function, //! [`with`], that yields a shared reference to the value to the specified //! closure. Task-local keys allow only shared access to values, as there would be no //! way to guarantee uniqueness if mutable borrows were allowed. //! //! ## Naming tasks //! //! Tasks are able to have associated names for identification purposes. By default, spawned //! tasks are unnamed. To specify a name for a task, build the task with [`Builder`] and pass //! the desired task name to [`Builder::name`]. To retrieve the task name from within the //! task, use [`Task::name`]. //! //! [`Arc`]: ../gsync/struct.Arc.html //! [`spawn`]: fn.spawn.html //! [`JoinHandle`]: struct.JoinHandle.html //! [`JoinHandle::task`]: struct.JoinHandle.html#method.task //! [`join`]: struct.JoinHandle.html#method.join //! [`panic!`]: https://doc.rust-lang.org/std/macro.panic.html //! [`Builder`]: struct.Builder.html //! [`Builder::name`]: struct.Builder.html#method.name //! [`task::current`]: fn.current.html //! [`Task`]: struct.Task.html //! [`Task::name`]: struct.Task.html#method.name //! [`task_local!`]: ../macro.task_local.html //! [`with`]: struct.LocalKey.html#method.with cfg_std! { #[doc(inline)] pub use std::task::{Context, Poll, Waker}; pub use ready::ready; pub use yield_now::yield_now; mod ready; mod yield_now; } cfg_default! { pub use block_on::block_on; pub use builder::Builder; pub use current::current; pub use task::Task; pub use task_id::TaskId; pub use join_handle::JoinHandle; pub use sleep::sleep; pub use spawn::spawn; pub use task_local::{AccessError, LocalKey}; use builder::Runnable; use task_local::LocalsMap; mod block_on; mod builder; mod current; mod executor; mod join_handle; mod sleep; mod spawn; mod spawn_blocking; mod task; mod task_id; mod task_local; #[cfg(any(feature = "unstable", test))] pub use spawn_blocking::spawn_blocking; #[cfg(not(any(feature = "unstable", test)))] pub(crate) use spawn_blocking::spawn_blocking; }
34.795031
99
0.665834
3354f99c8579917b77641d04db616217e6958ed4
1,768
// This file is part of simple-http-server. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/simple-http-server/master/COPYRIGHT. No part of simple-http-server, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2018 The developers of simple-http-server. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/simple-http-server/master/COPYRIGHT. /// Settings for creating a queue. #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] pub struct PosixMessageQueueCreateSettings { /// File-like permissions to use. pub permissions: mode_t, /// Optional create settings. /// /// If `None`, then Linux applies a default (see documentation of fields on `OptionalPosixMessageQueueCreateSettings`). pub optional_create_settings: Option<OptionalPosixMessageQueueCreateSettings>, } impl Default for PosixMessageQueueCreateSettings { #[inline(always)] fn default() -> Self { Self { permissions: S_IRUSR | S_IWUSR, optional_create_settings: None, } } } impl PosixMessageQueueCreateSettings { #[inline(always)] pub(crate) fn invoke_mq_open(&self, name_pointer: *const c_char, oflag: i32) -> c_int { let mode = self.permissions; match self.optional_create_settings { None => unsafe { mq_open(name_pointer, oflag, mode, null_mut::<mq_attr>()) }, Some(ref optional_create_settings) => { let mut attributes = mq_attr::for_create(optional_create_settings); unsafe { mq_open(name_pointer, oflag, mode, &mut attributes) } } } } }
35.36
409
0.754525
267c7d041fdcb11e7da2b6d5be3dcd0ae9d27436
100
pub mod graphics; pub mod interface; pub mod window; #[cfg(all(feature = "d3d11"))] pub mod d3d11;
14.285714
30
0.7
4a07acf020ae33b89c7c3902490fc3fcd5b27ee2
3,405
use std::io::Write; use nimiq_hash::{ argon2kdf, Argon2dHash, Argon2dHasher, Blake2bHash, Blake2bHasher, Blake2sHash, Blake2sHasher, Hasher, Sha256Hash, Sha256Hasher, Sha512Hash, Sha512Hasher, }; mod hmac; mod pbkdf2; #[test] fn it_can_compute_sha256() { // sha256('test') = '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' assert_eq!( Sha256Hasher::default().digest(b"test"), Sha256Hash::from("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08") ); let mut h = Sha256Hasher::default(); h.write(b"te").unwrap(); h.write(b"st").unwrap(); assert_eq!(h.finish(), Sha256Hash::from("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")); } #[test] fn it_can_compute_argon2d() { // argon2d('test') = '8c259fdcc2ad6799df728c11e895a3369e9dbae6a3166ebc3b353399fc565524' assert_eq!( Argon2dHasher::default().digest(b"test"), Argon2dHash::from("8c259fdcc2ad6799df728c11e895a3369e9dbae6a3166ebc3b353399fc565524") ); let mut h = Argon2dHasher::default(); h.write(b"te").unwrap(); h.write(b"st").unwrap(); assert_eq!( h.finish(), Argon2dHash::from("8c259fdcc2ad6799df728c11e895a3369e9dbae6a3166ebc3b353399fc565524") ); } #[test] fn it_can_compute_blake2b() { // blake2b('test') = '928b20366943e2afd11ebc0eae2e53a93bf177a4fcf35bcc64d503704e65e202' assert_eq!( Blake2bHasher::default().digest(b"test"), Blake2bHash::from("928b20366943e2afd11ebc0eae2e53a93bf177a4fcf35bcc64d503704e65e202") ); let mut h = Blake2bHasher::default(); h.write(b"te").unwrap(); h.write(b"st").unwrap(); assert_eq!( h.finish(), Blake2bHash::from("928b20366943e2afd11ebc0eae2e53a93bf177a4fcf35bcc64d503704e65e202") ); } #[test] fn it_can_compute_blake2s() { // blake2s('test') = 'f308fc02ce9172ad02a7d75800ecfc027109bc67987ea32aba9b8dcc7b10150e' assert_eq!( Blake2sHasher::default().digest(b"test"), Blake2sHash::from("f308fc02ce9172ad02a7d75800ecfc027109bc67987ea32aba9b8dcc7b10150e") ); let mut h = Blake2sHasher::default(); h.write(b"te").unwrap(); h.write(b"st").unwrap(); assert_eq!( h.finish(), Blake2sHash::from("f308fc02ce9172ad02a7d75800ecfc027109bc67987ea32aba9b8dcc7b10150e") ); } #[test] fn it_can_compute_sha512() { // sha512('test') = 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff' assert_eq!( Sha512Hasher::default().digest(b"test"), Sha512Hash::from("ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff") ); let mut h = Sha512Hasher::default(); h.write(b"te").unwrap(); h.write(b"st").unwrap(); assert_eq!( h.finish(), Sha512Hash::from("ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff") ); } #[test] fn it_can_compute_argon2_kdf() { let password = "test"; let salt = "nimiqrocks!"; let res = argon2kdf::compute_argon2_kdf(password.as_bytes(), salt.as_bytes(), 1, 32); assert_eq!( res.unwrap(), hex::decode("8c259fdcc2ad6799df728c11e895a3369e9dbae6a3166ebc3b353399fc565524").unwrap() ) }
33.058252
158
0.718649
f4b2caef8cc0d6508c9579acb36bf97f15214335
2,028
// This file is part of cpu-affinity. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/cpu-affinity/master/COPYRIGHT. No part of cpu-affinity, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2018 The developers of cpu-affinity. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/cpu-affinity/master/COPYRIGHT. use self::netbsd::*; impl LogicalCores { const _IsSettingProcessAffinitySupported: bool = true; const _IsSettingThreadAffinitySupported: bool = true; #[inline(always)] fn _set_process_affinity(&self, process_identifier: ProcessIdentifier) -> io::Result<()> { let cpu_set = self.as_cpuset_t()?; let result = match unsafe { sched_setaffinity_np(process_identifier, cpuset_size(cpu_set), cpu_set) } { 0 => Ok(()), -1 => Err(Self::last_os_error()), _ => unreachable!(), }; unsafe { cpuset_destroy(cpu_set) }; result } #[inline(always)] fn _set_thread_affinity(&self, thread_identifier: ThreadIdentifier) -> io::Result<()> { let cpu_set = self.as_cpuset_t()?; let result = unsafe { pthread_setaffinity_np(thread_identifier, cpuset_size(cpu_set), cpu_set) }; let result = if result == 0 { Ok(()) } else { Err(io::Error::from_raw_os_error(result)) }; unsafe { cpuset_destroy(cpu_set) }; result } #[inline(always)] fn as_cpuset_t(&self) -> io::Result<*mut cpuset_t> { let mut cpu_set = Self::empty_cpuset_t()?; for logical_core in self.0.iter() { unsafe { cpuset_set(*(logical_core as u32), cpu_set) }; } Ok(cpu_set) } #[inline(always)] fn empty_cpuset_t() -> io::Result<*mut cpuset_t> { let mut cpu_set = unsafe { cpuset_create() }; if cpu_set.is_null() { Err(Err(io::Error::from(io::ErrorKind::Other))) } else { Ok(cpu_set) } } }
28.971429
391
0.705621
7a98a9a6dd88d3de0f06b51564195ed8cc9a43d4
19,498
use anyhow::Result; use std::{fmt, future::Future, path::Path, pin::Pin}; use tokio::io::AsyncRead; mod demux; mod jlink; mod kflash; mod openocd; mod probe_rs; mod qemu; mod rp_pico; mod serial; mod slip; pub trait Target: Send + Sync { /// Get the target architecture. fn target_arch(&self) -> Arch; /// Get the additional Cargo features to enable when building /// `r3_port_*_test_driver`. fn cargo_features(&self) -> Vec<String>; /// The linker scripts used to link the test driver. fn linker_scripts(&self) -> LinkerScripts; /// Connect to the target. fn connect(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn DebugProbe>>>>>; } #[derive(Debug)] pub struct LinkerScripts { /// Linker scripts to specify with `-C link-arg=-T...` options. Note that /// linker scripts may refer to others by `INCLUDE` directives, in which /// case the referenced scripts shouldn't be specified here. pub inputs: Vec<String>, /// Temporary linker scripts to generate. pub generated_files: Vec<(String, String)>, } impl LinkerScripts { /// Create `LinkerScripts` to use the `link_ram_harvard.x` provided by /// `r3_port_arm`. The specified string is written to `memory.x`, which will /// be imported by `link_ram_harvard.x`. fn arm_harvard(memory_definition: String) -> Self { Self { inputs: vec!["link_ram_harvard.x".to_owned()], generated_files: vec![("memory.x".to_owned(), memory_definition)], } } /// Create `LinkerScripts` to use the `link.x` provided by `cortex-m-rt`. /// The specified string is written to `memory.x`, which will be imported by /// `link_ram_harvard.x`. fn arm_m_rt(memory_definition: String) -> Self { Self { inputs: vec!["link.x".to_owned()], generated_files: vec![("memory.x".to_owned(), memory_definition)], } } /// Create `LinkerScripts` to use the `link.x` provided by `riscv-rt`. /// The specified string is written to `memory.x`, which defines memory /// regions referenced by `link.x`. fn riscv_rt(memory_definition: String) -> Self { Self { inputs: vec!["memory.x".to_owned(), "link.x".to_owned()], generated_files: vec![("memory.x".to_owned(), memory_definition)], } } /// Create `LinkerScripts` to define some standard sections, which are to /// be included in the final image header and initialized by a section-aware /// loader. Symbol `start` is treated as the entry point. fn standard(base_address: u64) -> Self { let link = r#" ENTRY(start); SECTIONS { . = BASE_ADDRESS; .text : { *(.text .text.*); . = ALIGN(4); __etext = .; } .rodata __etext : ALIGN(4) { *(.rodata .rodata.*); . = ALIGN(4); } .data : ALIGN(4) { *(.data .data.*); . = ALIGN(4); } __sidata = LOADADDR(.data); .bss : ALIGN(4) { __sbss = .; *(.bss .bss.*); . = ALIGN(4); __ebss = .; } } "# .to_owned(); let link = link.replace("BASE_ADDRESS", &base_address.to_string()); Self { inputs: vec!["link.x".to_owned()], generated_files: vec![("link.x".to_owned(), link)], } } } pub trait DebugProbe: Send { /// Program the specified ELF image and run it from the beginning to /// capture its output. fn program_and_get_output( &mut self, exe: &Path, ) -> Pin<Box<dyn Future<Output = Result<DynAsyncRead<'_>>> + '_>>; } type DynAsyncRead<'a> = Pin<Box<dyn AsyncRead + 'a>>; pub static TARGETS: &[(&str, &dyn Target)] = &[ ("nucleo_f401re", &probe_rs::NucleoF401re), ("qemu_mps2_an385", &qemu::arm::QemuMps2An385), ("qemu_mps2_an505", &qemu::arm::QemuMps2An505), ("qemu_realview_pbx_a9", &qemu::arm::QemuRealviewPbxA9), ("gr_peach", &openocd::GrPeach), ("qemu_sifive_e_rv32", &qemu::riscv::QemuSiFiveE(Xlen::_32)), ("qemu_sifive_e_rv64", &qemu::riscv::QemuSiFiveE(Xlen::_64)), ("qemu_sifive_u_rv32", &qemu::riscv::QemuSiFiveU(Xlen::_32)), ("qemu_sifive_u_rv64", &qemu::riscv::QemuSiFiveU(Xlen::_64)), ( "qemu_sifive_u_s_rv32", &qemu::riscv::QemuSiFiveUModeS(Xlen::_32), ), ( "qemu_sifive_u_s_rv64", &qemu::riscv::QemuSiFiveUModeS(Xlen::_64), ), ("red_v", &jlink::RedV), ("maix", &kflash::Maix), ("rp_pico", &rp_pico::RaspberryPiPico), ]; struct OverrideTargetArch<T>(Arch, T); impl<T: Target> Target for OverrideTargetArch<T> { fn target_arch(&self) -> Arch { self.0 } fn cargo_features(&self) -> Vec<String> { self.1.cargo_features() } fn linker_scripts(&self) -> LinkerScripts { self.1.linker_scripts() } fn connect(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn DebugProbe>>>>> { self.1.connect() } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Arch { /// Armv7-A Armv7A, /// Arm M-Profile ArmM { /// Specifies the architecture version to use. version: ArmMVersion, /// The Floating-point extension. fpu: bool, /// The DSP extension. dsp: bool, }, Riscv { /// XLEN xlen: Xlen, /// Use the reduced register set e: bool, /// The "M" extension (multiplication and division) m: bool, /// The "A" extension (atomics) a: bool, /// The "C" extension (compressed instructions) c: bool, /// The "F" extension (single-precision floating point numbers) f: bool, /// The "D" extension (double-precision floating point numbers) d: bool, }, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ArmMVersion { Armv6M, Armv7M, Armv8MBaseline, Armv8MMainline, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Xlen { _32 = 32, _64 = 64, } /// A set of build options passed to `rustc` to build an application for some /// target specified by [`Arch`]. #[derive(Debug, Default)] pub struct BuildOpt { pub target_triple: &'static str, pub target_features: String, } impl Arch { const NAMED_ARCHS: &'static [(&'static str, Self)] = &[ ("cortex_a9", Self::CORTEX_A9), ("cortex_m0", Self::CORTEX_M0), ("cortex_m3", Self::CORTEX_M3), ("cortex_m4", Self::CORTEX_M4), ("cortex_m4f", Self::CORTEX_M4F), ("cortex_m23", Self::CORTEX_M23), ("cortex_m33", Self::CORTEX_M33), ( "rv32i", Self::Riscv { xlen: Xlen::_32, e: false, m: false, a: false, c: false, f: false, d: false, }, ), ( "rv64i", Self::Riscv { xlen: Xlen::_64, e: false, m: false, a: false, c: false, f: false, d: false, }, ), ( "rv32e", Self::Riscv { xlen: Xlen::_32, e: true, m: false, a: false, c: false, f: false, d: false, }, ), ]; const CORTEX_A9: Self = Self::Armv7A; const CORTEX_M0: Self = Self::ArmM { version: ArmMVersion::Armv6M, fpu: false, dsp: false, }; const CORTEX_M3: Self = Self::ArmM { version: ArmMVersion::Armv7M, fpu: false, dsp: false, }; const CORTEX_M4: Self = Self::ArmM { version: ArmMVersion::Armv7M, fpu: false, dsp: true, }; const CORTEX_M4F: Self = Self::ArmM { version: ArmMVersion::Armv7M, fpu: true, dsp: true, }; const CORTEX_M23: Self = Self::ArmM { version: ArmMVersion::Armv8MBaseline, fpu: false, dsp: false, }; const CORTEX_M33: Self = Self::ArmM { version: ArmMVersion::Armv8MMainline, fpu: false, dsp: false, }; const CORTEX_M33_FPU: Self = Self::ArmM { version: ArmMVersion::Armv8MMainline, fpu: true, dsp: false, }; const RV32IMAC: Self = Self::Riscv { xlen: Xlen::_32, e: false, m: true, a: true, c: true, f: false, d: false, }; const RV64IMAC: Self = Self::Riscv { xlen: Xlen::_64, e: false, m: true, a: true, c: true, f: false, d: false, }; const RV32GC: Self = Self::Riscv { xlen: Xlen::_32, e: false, m: true, a: true, c: true, f: true, d: true, }; const RV64GC: Self = Self::Riscv { xlen: Xlen::_64, e: false, m: true, a: true, c: true, f: true, d: true, }; pub fn build_opt(&self) -> Option<BuildOpt> { match self { // Arm A-Profile // ------------------------------------------------------------- Self::Armv7A => Some(BuildOpt::from_target_triple("armv7a-none-eabi")), // Arm M-Profile // ------------------------------------------------------------- Self::ArmM { version: ArmMVersion::Armv6M, fpu: false, dsp: false, } => Some(BuildOpt::from_target_triple("thumbv6m-none-eabi")), Self::ArmM { version: ArmMVersion::Armv6M, fpu: _, dsp: _, } => None, Self::ArmM { version: ArmMVersion::Armv7M, fpu: false, dsp: false, } => Some(BuildOpt::from_target_triple("thumbv7m-none-eabi")), Self::ArmM { version: ArmMVersion::Armv7M, fpu: false, dsp: true, } => Some(BuildOpt::from_target_triple("thumbv7em-none-eabi")), Self::ArmM { version: ArmMVersion::Armv7M, fpu: true, dsp: true, } => Some(BuildOpt::from_target_triple("thumbv7em-none-eabihf")), Self::ArmM { version: ArmMVersion::Armv7M, fpu: true, dsp: false, } => None, Self::ArmM { version: ArmMVersion::Armv8MBaseline, fpu: false, dsp: false, } => Some(BuildOpt::from_target_triple("thumbv8m.base-none-eabi")), Self::ArmM { version: ArmMVersion::Armv8MMainline, fpu: false, dsp: false, } => Some(BuildOpt::from_target_triple("thumbv8m.main-none-eabi")), Self::ArmM { version: ArmMVersion::Armv8MMainline, fpu: true, dsp: false, } => Some(BuildOpt::from_target_triple("thumbv8m.main-none-eabihf")), Self::ArmM { version: ArmMVersion::Armv8MBaseline | ArmMVersion::Armv8MMainline, fpu: _, dsp: _, } => None, // RISC-V // ------------------------------------------------------------- Self::Riscv { xlen: Xlen::_32, e: false, m: false, a: false, c: false, f: false, d: false, } => Some(BuildOpt::from_target_triple("riscv32i-unknown-none-elf")), Self::Riscv { xlen: Xlen::_32, e: false, m: true, a: false, c: true, f: false, d: false, } => Some(BuildOpt::from_target_triple("riscv32imc-unknown-none-elf")), Self::Riscv { xlen: Xlen::_32, e: false, m: true, a: true, c: true, f: false, d: false, } => Some(BuildOpt::from_target_triple("riscv32imac-unknown-none-elf")), Self::Riscv { xlen: Xlen::_64, e: false, m: true, a: true, c: true, f: false, d: false, } => Some(BuildOpt::from_target_triple("riscv64imac-unknown-none-elf")), Self::Riscv { xlen: Xlen::_64, e: false, m: true, a: true, c: true, f: true, d: true, } => Some(BuildOpt::from_target_triple("riscv64gc-unknown-none-elf")), Self::Riscv { xlen, e, m, a, c, f, d, } => Some( BuildOpt::from_target_triple(match xlen { Xlen::_32 => "riscv32imac-unknown-none-elf", Xlen::_64 => "riscv64imac-unknown-none-elf", }) .with_target_features(&[ if *e { Some("+e") } else { None }, if *m { None } else { Some("-m") }, if *a { None } else { Some("-a") }, if *c { None } else { Some("-c") }, if *f { Some("+f") } else { None }, if *d { Some("+d") } else { None }, ]), ), } } fn with_feature_by_name(self, name: &str, enable: bool) -> Option<Self> { macro features( Self::$variant:ident { // Allow these features to be modified $($feat:ident),*; // These fields are left untouched $($extra:ident),* } ) {{ $( let mut $feat = $feat; )* match name { $( stringify!($feat) => $feat = enable, )* _ => return None, } Some(Self::$variant { $($feat,)* $($extra,)* }) }} match self { Self::Armv7A => None, Self::ArmM { fpu, dsp, version } => features!(Self::ArmM { fpu, dsp; version }), Self::Riscv { e, m, a, c, f, d, xlen, } => features!(Self::Riscv { e, m, a, c, f, d; xlen }), } } } impl BuildOpt { fn from_target_triple(target_triple: &'static str) -> Self { Self { target_triple, ..Default::default() } } fn with_target_features(self, seq: &[Option<&'static str>]) -> Self { Self { target_features: crate::utils::CommaSeparatedNoSpace(seq.iter().filter_map(|x| *x)) .to_string(), ..self } } } impl fmt::Display for Arch { fn fmt(&self, fm: &mut fmt::Formatter) -> fmt::Result { match self { Self::Armv7A => write!(fm, "cortex_a9"), Self::ArmM { mut fpu, mut dsp, version, } => { match (version, fpu, dsp) { (ArmMVersion::Armv6M, _, _) => write!(fm, "cortex_m0")?, (ArmMVersion::Armv7M, true, true) => { write!(fm, "cortex_m4f")?; fpu = false; dsp = false; } (ArmMVersion::Armv7M, false, true) => { write!(fm, "cortex_m4")?; dsp = false; } (ArmMVersion::Armv7M, _, _) => write!(fm, "cortex_m3")?, (ArmMVersion::Armv8MBaseline, _, _) => write!(fm, "cortex_m23")?, (ArmMVersion::Armv8MMainline, _, _) => write!(fm, "cortex_m33")?, } if fpu { write!(fm, "+fpu")?; } if dsp { write!(fm, "+dsp")?; } Ok(()) } Self::Riscv { e, m, a, c, f, d, xlen, } => { if *e { write!(fm, "rv{}e", *xlen as u8)?; } else { write!(fm, "rv{}i", *xlen as u8)?; } if *m { write!(fm, "+m")?; } if *a { write!(fm, "+a")?; } if *c { write!(fm, "+c")?; } if *f { write!(fm, "+f")?; } if *d { write!(fm, "+d")?; } Ok(()) } } } } #[derive(thiserror::Error, Debug)] pub enum ArchParseError { #[error("Unknown base architecture: '{0}'")] UnknownBase(String), #[error("Unknown feature: '{0}'")] UnknownFeature(String), } impl std::str::FromStr for Arch { type Err = ArchParseError; /// Parse a target architecture string. /// /// A target architecture string should be specified in the following form: /// `base+feat1-feat2` /// /// - `base` chooses a named architecture from `NAMED_ARCHS`. /// - `+feat1` enables the feature `feat1`. /// - `-feat2` disables the feature `feat2`. /// fn from_str(s: &str) -> Result<Self, Self::Err> { let mut i = s.find(&['-', '+'][..]).unwrap_or(s.len()); let base = &s[0..i]; let mut arch = Self::NAMED_ARCHS .iter() .find(|x| x.0 == base) .ok_or_else(|| ArchParseError::UnknownBase(base.to_owned()))? .1; while i < s.len() { let add = match s.as_bytes()[i] { b'+' => true, b'-' => false, _ => unreachable!(), }; i += 1; // Find the next `-` or `+` let k = s[i..] .find(&['-', '+'][..]) .map(|k| k + i) .unwrap_or_else(|| s.len()); let feature = &s[i..k]; arch = arch .with_feature_by_name(feature, add) .ok_or_else(|| ArchParseError::UnknownFeature(feature.to_owned()))?; i = k; } Ok(arch) } } #[cfg(test)] mod tests { use super::*; #[test] fn arch_round_trip() { for (_, arch) in Arch::NAMED_ARCHS { let arch_str = arch.to_string(); let arch2: Arch = arch_str.parse().unwrap(); assert_eq!(*arch, arch2); } } }
28.381368
95
0.445994
28c46a12a885afd3f6c55100a71b2b8a60dfab95
2,141
#[doc = "Reader of register T1CNTR"] pub type R = crate::R<u32, super::T1CNTR>; #[doc = "Writer for register T1CNTR"] pub type W = crate::W<u32, super::T1CNTR>; #[doc = "Register T1CNTR `reset()`'s with value 0"] impl crate::ResetValue for super::T1CNTR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RESERVED16`"] pub type RESERVED16_R = crate::R<u16, u16>; #[doc = "Write proxy for field `RESERVED16`"] pub struct RESERVED16_W<'a> { w: &'a mut W, } impl<'a> RESERVED16_W<'a> { #[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 << 16)) | (((value as u32) & 0xffff) << 16); self.w } } #[doc = "Reader of field `VALUE`"] pub type VALUE_R = crate::R<u16, u16>; #[doc = "Write proxy for field `VALUE`"] pub struct VALUE_W<'a> { w: &'a mut W, } impl<'a> VALUE_W<'a> { #[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 16:31 - 31:16\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."] #[inline(always)] pub fn reserved16(&self) -> RESERVED16_R { RESERVED16_R::new(((self.bits >> 16) & 0xffff) as u16) } #[doc = "Bits 0:15 - 15:0\\] Timer 1 counter value."] #[inline(always)] pub fn value(&self) -> VALUE_R { VALUE_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 16:31 - 31:16\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."] #[inline(always)] pub fn reserved16(&mut self) -> RESERVED16_W { RESERVED16_W { w: self } } #[doc = "Bits 0:15 - 15:0\\] Timer 1 counter value."] #[inline(always)] pub fn value(&mut self) -> VALUE_W { VALUE_W { w: self } } }
31.028986
133
0.590845
7ac85f18553b04f908aab5a6963b24187cc2102b
373
pub mod models; pub mod schema; use diesel::prelude::*; use dotenv::dotenv; use std::env; pub fn establish_connection() -> SqliteConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); SqliteConnection::establish(&database_url) .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) }
24.866667
83
0.69437
f9054cdb1c553aa11d55fd02ceec66a0078f80d0
8,041
//! Module for items related to aggregating validation_receipts use futures::Stream; use futures::StreamExt; use futures::TryStreamExt; use holo_hash::AgentPubKey; use holo_hash::DhtOpHash; use holochain_keystore::AgentPubKeyExt; use holochain_keystore::MetaLairClient; use holochain_serialized_bytes::prelude::*; use holochain_sqlite::prelude::*; use holochain_sqlite::rusqlite::named_params; use holochain_sqlite::rusqlite::OptionalExtension; use holochain_sqlite::rusqlite::Transaction; use holochain_zome_types::signature::Signature; use holochain_zome_types::Timestamp; use holochain_zome_types::ValidationStatus; use mutations::StateMutationResult; use crate::mutations; use crate::prelude::from_blob; use crate::prelude::StateQueryResult; /// Validation receipt content - to be signed. #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, SerializedBytes, )] pub struct ValidationReceipt { /// the op this validation receipt is for. pub dht_op_hash: DhtOpHash, /// the result of this validation. pub validation_status: ValidationStatus, /// the remote validator which is signing this receipt. pub validators: Vec<AgentPubKey>, /// Time when the op was integrated pub when_integrated: Timestamp, } impl ValidationReceipt { /// Sign this validation receipt. pub async fn sign( self, keystore: &MetaLairClient, ) -> holochain_keystore::LairResult<Option<SignedValidationReceipt>> { if self.validators.is_empty() { return Ok(None); } let this = self.clone(); // Try to sign with all validators but silently fail on // any that cannot sign. // If all signatures fail then return an error. let futures = self .validators .iter() .map(|validator| { let this = this.clone(); let validator = validator.clone(); let keystore = keystore.clone(); async move { validator.sign(&keystore, this).await } }) .collect::<Vec<_>>(); let stream = futures::stream::iter(futures); let signatures = try_stream_of_results(stream).await?; if signatures.is_empty() { unreachable!("Signatures cannot be empty because the validators vec is not empty"); } Ok(Some(SignedValidationReceipt { receipt: self, validators_signatures: signatures, })) } } /// Try to collect a stream of futures that return results into a vec. async fn try_stream_of_results<T, U, E>(stream: U) -> Result<Vec<T>, E> where U: Stream, <U as Stream>::Item: futures::Future<Output = Result<T, E>>, { stream.buffer_unordered(10).map(|r| r).try_collect().await } /// A full, signed validation receipt. #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, SerializedBytes, )] pub struct SignedValidationReceipt { /// the content of the validation receipt. pub receipt: ValidationReceipt, /// the signature of the remote validator. pub validators_signatures: Vec<Signature>, } pub fn list_receipts( txn: &Transaction, op_hash: &DhtOpHash, ) -> StateQueryResult<Vec<SignedValidationReceipt>> { let mut stmt = txn.prepare( " SELECT blob FROM ValidationReceipt WHERE op_hash = :op_hash ", )?; let iter = stmt.query_and_then( named_params! { ":op_hash": op_hash }, |row| from_blob::<SignedValidationReceipt>(row.get("blob")?), )?; iter.collect() } pub fn count_valid(txn: &Transaction, op_hash: &DhtOpHash) -> DatabaseResult<usize> { let count: usize = txn .query_row( "SELECT COUNT(hash) FROM ValidationReceipt WHERE op_hash = :op_hash", named_params! { ":op_hash": op_hash }, |row| row.get(0), ) .optional()? .unwrap_or(0); Ok(count) } pub fn add_if_unique( txn: &mut Transaction, receipt: SignedValidationReceipt, ) -> StateMutationResult<()> { mutations::insert_validation_receipt(txn, receipt) } #[cfg(test)] mod tests { use super::*; use fixt::prelude::*; use holo_hash::HasHash; use holochain_types::dht_op::DhtOp; use holochain_types::dht_op::DhtOpHashed; use holochain_zome_types::fixt::*; async fn fake_vr( dht_op_hash: &DhtOpHash, keystore: &MetaLairClient, ) -> SignedValidationReceipt { let agent = keystore.new_sign_keypair_random().await.unwrap(); let receipt = ValidationReceipt { dht_op_hash: dht_op_hash.clone(), validation_status: ValidationStatus::Valid, validators: vec![agent], when_integrated: Timestamp::now(), }; receipt.sign(keystore).await.unwrap().unwrap() } #[tokio::test(flavor = "multi_thread")] async fn test_validation_receipts_db_populate_and_list() -> StateMutationResult<()> { observability::test_run().ok(); let test_db = crate::test_utils::test_authored_db(); let env = test_db.to_db(); let keystore = crate::test_utils::test_keystore(); let op = DhtOpHashed::from_content_sync(DhtOp::RegisterAgentActivity( fixt!(Signature), fixt!(Header), )); let test_op_hash = op.as_hash().clone(); env.conn() .unwrap() .with_commit_sync(|txn| mutations::insert_op(txn, &op)) .unwrap(); let vr1 = fake_vr(&test_op_hash, &keystore).await; let vr2 = fake_vr(&test_op_hash, &keystore).await; { env.conn().unwrap().with_commit_sync(|txn| { add_if_unique(txn, vr1.clone())?; add_if_unique(txn, vr1.clone())?; add_if_unique(txn, vr2.clone()) })?; env.conn() .unwrap() .with_commit_sync(|txn| add_if_unique(txn, vr1.clone()))?; } let mut g = env.conn().unwrap(); g.with_reader_test(|reader| { assert_eq!(2, count_valid(&reader, &test_op_hash).unwrap()); let mut list = list_receipts(&reader, &test_op_hash).unwrap(); list.sort_by(|a, b| { a.receipt.validators[0] .partial_cmp(&b.receipt.validators[0]) .unwrap() }); let mut expects = vec![vr1, vr2]; expects.sort_by(|a, b| { a.receipt.validators[0] .partial_cmp(&b.receipt.validators[0]) .unwrap() }); assert_eq!(expects, list); }); Ok(()) } #[tokio::test] async fn test_try_stream_of_results() { let iter: Vec<futures::future::Ready<Result<i32, String>>> = vec![]; let stream = futures::stream::iter(iter); assert_eq!(Ok(vec![]), try_stream_of_results(stream).await); let iter = vec![async move { Result::<_, String>::Ok(0) }]; let stream = futures::stream::iter(iter); assert_eq!(Ok(vec![0]), try_stream_of_results(stream).await); let iter = (0..10).map(|i| async move { Result::<_, String>::Ok(i) }); let stream = futures::stream::iter(iter); assert_eq!( Ok((0..10).collect::<Vec<_>>()), try_stream_of_results(stream).await ); let iter = vec![async move { Result::<i32, String>::Err("test".to_string()) }]; let stream = futures::stream::iter(iter); assert_eq!(Err("test".to_string()), try_stream_of_results(stream).await); let iter = (0..10).map(|_| async move { Result::<i32, String>::Err("test".to_string()) }); let stream = futures::stream::iter(iter); assert_eq!(Err("test".to_string()), try_stream_of_results(stream).await); } }
30.926923
98
0.602164
61aa822a993f8834a3108c69ad1a3bf7a62802e1
6,554
/* Copyright 2017 Takashi Ogura 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. */ //! `link` can be used to show the shape of the robot, or collision checking libraries. //! //! `link` module is optional for `k`. //! use na::{Isometry3, Matrix3, RealField, Vector3}; use nalgebra as na; #[derive(Debug, Clone)] pub enum Geometry<T: RealField> { Box { depth: T, width: T, height: T }, Cylinder { radius: T, length: T }, Capsule { radius: T, length: T }, Sphere { radius: T }, Mesh { filename: String, scale: Vector3<T> }, } #[derive(Debug, Default, Clone)] pub struct Color<T: RealField> { pub r: T, pub g: T, pub b: T, pub a: T, } #[derive(Debug, Clone)] pub struct Texture { pub filename: String, } impl Default for Texture { fn default() -> Texture { Texture { filename: "".to_string(), } } } #[derive(Debug, Default, Clone)] pub struct Material<T: RealField> { pub name: String, pub color: Color<T>, pub texture: Texture, } #[derive(Debug, Clone)] pub struct Inertial<T: RealField> { origin: Isometry3<T>, pub mass: T, pub inertia: Matrix3<T>, world_transform_cache: Option<Isometry3<T>>, } // TODO impl<T> Inertial<T> where T: RealField, { pub fn from_mass(mass: T) -> Self { Self { origin: Isometry3::identity(), mass, inertia: Matrix3::identity(), world_transform_cache: None, } } pub fn new(origin: Isometry3<T>, mass: T, inertia: Matrix3<T>) -> Self { Self { origin, mass, inertia, world_transform_cache: None, } } pub fn set_origin(&mut self, origin: Isometry3<T>) { self.origin = origin; self.world_transform_cache = None; } pub fn origin(&self) -> &Isometry3<T> { &self.origin } pub fn clear_world_transform(&mut self) { self.world_transform_cache = None } pub fn set_world_transform(&mut self, trans: Isometry3<T>) { self.world_transform_cache = Some(trans); } pub fn world_transform(&self) -> &Option<Isometry3<T>> { &self.world_transform_cache } } #[derive(Debug, Clone)] pub struct Visual<T: RealField> { pub name: String, origin: Isometry3<T>, pub geometry: Geometry<T>, pub material: Material<T>, world_transform_cache: Option<Isometry3<T>>, } impl<T> Visual<T> where T: RealField, { pub fn new( name: String, origin: Isometry3<T>, geometry: Geometry<T>, material: Material<T>, ) -> Self { Self { name, origin, geometry, material, world_transform_cache: None, } } pub fn set_origin(&mut self, origin: Isometry3<T>) { self.origin = origin; self.world_transform_cache = None; } pub fn origin(&self) -> &Isometry3<T> { &self.origin } pub fn clear_world_transform(&mut self) { self.world_transform_cache = None } pub fn set_world_transform(&mut self, trans: Isometry3<T>) { self.world_transform_cache = Some(trans); } pub fn world_transform(&self) -> &Option<Isometry3<T>> { &self.world_transform_cache } } #[derive(Debug, Clone)] pub struct Collision<T: RealField> { pub name: String, origin: Isometry3<T>, pub geometry: Geometry<T>, world_transform_cache: Option<Isometry3<T>>, } impl<T> Collision<T> where T: RealField, { pub fn new(name: String, origin: Isometry3<T>, geometry: Geometry<T>) -> Self { Self { name, origin, geometry, world_transform_cache: None, } } pub fn set_origin(&mut self, origin: Isometry3<T>) { self.origin = origin; self.world_transform_cache = None; } pub fn origin(&self) -> &Isometry3<T> { &self.origin } pub fn clear_world_transform(&mut self) { self.world_transform_cache = None } pub fn set_world_transform(&mut self, trans: Isometry3<T>) { self.world_transform_cache = Some(trans); } pub fn world_transform(&self) -> &Option<Isometry3<T>> { &self.world_transform_cache } } #[derive(Debug, Clone)] pub struct Link<T: RealField> { pub name: String, pub inertial: Inertial<T>, pub visuals: Vec<Visual<T>>, pub collisions: Vec<Collision<T>>, } impl<T> Default for Link<T> where T: RealField, { fn default() -> Self { Self { name: "".to_owned(), inertial: Inertial::new(Isometry3::identity(), T::zero(), Matrix3::identity()), visuals: Vec::new(), collisions: Vec::new(), } } } #[derive(Debug)] pub struct LinkBuilder<T> where T: RealField, { name: String, inertial: Inertial<T>, visuals: Vec<Visual<T>>, collisions: Vec<Collision<T>>, } impl<T> LinkBuilder<T> where T: RealField, { pub fn new() -> Self { Self { name: "".to_owned(), inertial: Inertial::new(Isometry3::identity(), T::zero(), Matrix3::identity()), visuals: Vec::new(), collisions: Vec::new(), } } pub fn name(mut self, name: &str) -> Self { self.name = name.to_owned(); self } pub fn inertial(mut self, inertial: Inertial<T>) -> Self { self.inertial = inertial; self } pub fn add_visual(mut self, visual: Visual<T>) -> Self { self.visuals.push(visual); self } pub fn add_collision(mut self, collision: Collision<T>) -> Self { self.collisions.push(collision); self } pub fn finalize(self) -> Link<T> { Link { name: self.name, inertial: self.inertial, visuals: self.visuals, collisions: self.collisions, } } } impl<T> Default for LinkBuilder<T> where T: RealField, { fn default() -> Self { Self::new() } }
24.364312
91
0.585597
6139eed0956c2f5bc762436c6974ad067ea8de52
12,693
use crate::prelude::*; use nu_engine::whole_stream_command; use std::error::Error; pub fn create_default_context(interactive: bool) -> Result<EvaluationContext, Box<dyn Error>> { let context = EvaluationContext::basic(); { use crate::commands::*; context.add_commands(vec![ // Fundamentals whole_stream_command(NuPlugin), whole_stream_command(Let), whole_stream_command(LetEnv), whole_stream_command(LoadEnv), whole_stream_command(Def), whole_stream_command(Source), whole_stream_command(Alias), whole_stream_command(Ignore), // System/file operations whole_stream_command(Exec), whole_stream_command(Pwd), whole_stream_command(Ls), whole_stream_command(Du), whole_stream_command(Cd), whole_stream_command(Remove), whole_stream_command(Open), whole_stream_command(Config), whole_stream_command(ConfigGet), whole_stream_command(ConfigSet), whole_stream_command(ConfigSetInto), whole_stream_command(ConfigClear), whole_stream_command(ConfigRemove), whole_stream_command(ConfigPath), whole_stream_command(Help), whole_stream_command(History), whole_stream_command(Save), whole_stream_command(Touch), whole_stream_command(Cpy), whole_stream_command(Date), whole_stream_command(DateListTimeZone), whole_stream_command(DateNow), whole_stream_command(DateToTable), whole_stream_command(DateToTimeZone), whole_stream_command(DateFormat), whole_stream_command(Cal), whole_stream_command(Mkdir), whole_stream_command(Mv), whole_stream_command(Kill), whole_stream_command(Version), whole_stream_command(Clear), whole_stream_command(Describe), whole_stream_command(Which), whole_stream_command(Debug), whole_stream_command(WithEnv), whole_stream_command(Do), whole_stream_command(Sleep), // Statistics whole_stream_command(Size), whole_stream_command(Length), whole_stream_command(Benchmark), // Metadata whole_stream_command(Tags), // Shells whole_stream_command(Next), whole_stream_command(Previous), whole_stream_command(Shells), whole_stream_command(Enter), whole_stream_command(Exit), // Viz whole_stream_command(Chart), // Viewers whole_stream_command(Autoview), whole_stream_command(Table), // Text manipulation whole_stream_command(Hash), whole_stream_command(HashBase64), whole_stream_command(HashMd5), whole_stream_command(Split), whole_stream_command(SplitColumn), whole_stream_command(SplitRow), whole_stream_command(SplitChars), whole_stream_command(Lines), whole_stream_command(Echo), whole_stream_command(Parse), whole_stream_command(Str), whole_stream_command(StrToDecimal), whole_stream_command(StrToInteger), whole_stream_command(StrDowncase), whole_stream_command(StrUpcase), whole_stream_command(StrCapitalize), whole_stream_command(StrFindReplace), whole_stream_command(StrSubstring), whole_stream_command(StrToDatetime), whole_stream_command(StrContains), whole_stream_command(StrIndexOf), whole_stream_command(StrTrim), whole_stream_command(StrTrimLeft), whole_stream_command(StrTrimRight), whole_stream_command(StrStartsWith), whole_stream_command(StrEndsWith), whole_stream_command(StrCollect), whole_stream_command(StrLength), whole_stream_command(StrLPad), whole_stream_command(StrReverse), whole_stream_command(StrRPad), whole_stream_command(StrCamelCase), whole_stream_command(StrPascalCase), whole_stream_command(StrKebabCase), whole_stream_command(StrSnakeCase), whole_stream_command(StrScreamingSnakeCase), whole_stream_command(BuildString), whole_stream_command(Ansi), whole_stream_command(AnsiStrip), whole_stream_command(AnsiGradient), whole_stream_command(Char), // Column manipulation whole_stream_command(DropColumn), whole_stream_command(Move), whole_stream_command(Reject), whole_stream_command(Select), whole_stream_command(Get), whole_stream_command(Update), whole_stream_command(Insert), whole_stream_command(Into), whole_stream_command(IntoBinary), whole_stream_command(IntoInt), whole_stream_command(IntoString), whole_stream_command(SplitBy), // Row manipulation whole_stream_command(All), whole_stream_command(Any), whole_stream_command(Reverse), whole_stream_command(Append), whole_stream_command(Prepend), whole_stream_command(SortBy), whole_stream_command(GroupBy), whole_stream_command(GroupByDate), whole_stream_command(First), whole_stream_command(Last), whole_stream_command(Every), whole_stream_command(Nth), whole_stream_command(Drop), whole_stream_command(Format), whole_stream_command(FileSize), whole_stream_command(Where), whole_stream_command(If), whole_stream_command(Compact), whole_stream_command(Default), whole_stream_command(Skip), whole_stream_command(SkipUntil), whole_stream_command(SkipWhile), whole_stream_command(Keep), whole_stream_command(KeepUntil), whole_stream_command(KeepWhile), whole_stream_command(Range), whole_stream_command(Rename), whole_stream_command(Uniq), whole_stream_command(Each), whole_stream_command(EachGroup), whole_stream_command(EachWindow), whole_stream_command(Empty), whole_stream_command(ForIn), // Table manipulation whole_stream_command(Flatten), whole_stream_command(Move), whole_stream_command(Merge), whole_stream_command(Shuffle), whole_stream_command(Wrap), whole_stream_command(Pivot), whole_stream_command(Headers), whole_stream_command(Reduce), whole_stream_command(Roll), whole_stream_command(RollColumn), whole_stream_command(RollUp), whole_stream_command(Rotate), whole_stream_command(RotateCounterClockwise), // Data processing whole_stream_command(Histogram), whole_stream_command(Autoenv), whole_stream_command(AutoenvTrust), whole_stream_command(AutoenvUnTrust), whole_stream_command(Math), whole_stream_command(MathAbs), whole_stream_command(MathAverage), whole_stream_command(MathEval), whole_stream_command(MathMedian), whole_stream_command(MathMinimum), whole_stream_command(MathMode), whole_stream_command(MathMaximum), whole_stream_command(MathStddev), whole_stream_command(MathSummation), whole_stream_command(MathVariance), whole_stream_command(MathProduct), whole_stream_command(MathRound), whole_stream_command(MathFloor), whole_stream_command(MathCeil), whole_stream_command(MathSqrt), // File format output whole_stream_command(To), whole_stream_command(ToCsv), whole_stream_command(ToHtml), whole_stream_command(ToJson), whole_stream_command(ToMarkdown), whole_stream_command(ToToml), whole_stream_command(ToTsv), whole_stream_command(ToUrl), whole_stream_command(ToYaml), whole_stream_command(ToXml), // File format input whole_stream_command(From), whole_stream_command(FromCsv), whole_stream_command(FromEml), whole_stream_command(FromTsv), whole_stream_command(FromSsv), whole_stream_command(FromIni), whole_stream_command(FromJson), whole_stream_command(FromOds), whole_stream_command(FromToml), whole_stream_command(FromUrl), whole_stream_command(FromXlsx), whole_stream_command(FromXml), whole_stream_command(FromYaml), whole_stream_command(FromYml), whole_stream_command(FromIcs), whole_stream_command(FromVcf), // "Private" commands (not intended to be accessed directly) whole_stream_command(RunExternalCommand { interactive }), // Random value generation whole_stream_command(Random), whole_stream_command(RandomBool), whole_stream_command(RandomDice), #[cfg(feature = "uuid_crate")] whole_stream_command(RandomUUID), whole_stream_command(RandomInteger), whole_stream_command(RandomDecimal), whole_stream_command(RandomChars), // Path whole_stream_command(PathBasename), whole_stream_command(PathCommand), whole_stream_command(PathDirname), whole_stream_command(PathExists), whole_stream_command(PathExpand), whole_stream_command(PathJoin), whole_stream_command(PathParse), whole_stream_command(PathRelativeTo), whole_stream_command(PathSplit), whole_stream_command(PathType), // Url whole_stream_command(UrlCommand), whole_stream_command(UrlScheme), whole_stream_command(UrlPath), whole_stream_command(UrlHost), whole_stream_command(UrlQuery), whole_stream_command(Seq), whole_stream_command(SeqDates), whole_stream_command(TermSize), ]); //Dataframe commands #[cfg(feature = "dataframe")] context.add_commands(vec![ whole_stream_command(DataFrame), whole_stream_command(DataFrameLoad), whole_stream_command(DataFrameList), whole_stream_command(DataFrameGroupBy), whole_stream_command(DataFrameAggregate), whole_stream_command(DataFrameShow), whole_stream_command(DataFrameSample), whole_stream_command(DataFrameJoin), whole_stream_command(DataFrameDrop), whole_stream_command(DataFrameSelect), whole_stream_command(DataFrameDTypes), whole_stream_command(DataFrameDummies), whole_stream_command(DataFrameHead), whole_stream_command(DataFrameTail), whole_stream_command(DataFrameSlice), whole_stream_command(DataFrameMelt), whole_stream_command(DataFramePivot), whole_stream_command(DataFrameWhere), whole_stream_command(DataFrameToDF), whole_stream_command(DataFrameToSeries), whole_stream_command(DataFrameToParquet), whole_stream_command(DataFrameToCsv), whole_stream_command(DataFrameSort), whole_stream_command(DataFrameGet), whole_stream_command(DataFrameDropDuplicates), whole_stream_command(DataFrameDropNulls), whole_stream_command(DataFrameColumn), whole_stream_command(DataFrameWithColumn), whole_stream_command(DataFrameFilter), whole_stream_command(DataFrameSeriesRename), ]); #[cfg(feature = "clipboard-cli")] { context.add_commands(vec![whole_stream_command(crate::commands::clip::Clip)]); } } Ok(context) }
41.753289
95
0.628614
6764d9530775078ae45c8937d6ab509984041c87
4,143
use crate::node_keys; use libra_wallet::{Mnemonic, key_factory::{ Seed, KeyFactory, ChildNumber }}; use libra_types::{waypoint::Waypoint}; use libra_types::{account_address::AccountAddress, transaction::authenticator::AuthenticationKey}; use libra_crypto::{ test_utils::KeyPair, ed25519::{Ed25519PrivateKey, Ed25519PublicKey} }; use anyhow::Error; use cli::{libra_client::LibraClient, AccountData, AccountStatus}; use reqwest::Url; use abscissa_core::{status_warn, status_ok}; use std::{io::{stdout, Write}, thread, time}; use libra_types::transaction::{Script, TransactionArgument, TransactionPayload}; use libra_types::{transaction::helpers::*}; use crate::{ config::MinerConfig }; use compiled_stdlib::transaction_scripts; use libra_json_rpc_types::views::{TransactionView, VMStatusView}; use libra_types::chain_id::ChainId; fn submit_noop() -> Result<String, Error> { let path = PathBuf::from("/root/saved_logs/0/node.yaml"); let config = NodeConfig::load(&path) .unwrap_or_else(|_| panic!("Failed to load NodeConfig from file: {:?}", &home)); match &config.test { Some(_conf) => { // println!("Swarm Keys : {:?}", conf); }, None =>{ println!("test config does not set."); } } // This mnemonic is hard coded into the swarm configs. see configs/config_builder let alice_mnemonic = "talent sunset lizard pill fame nuclear spy noodle basket okay critic grow sleep legend hurry pitch blanket clerk impose rough degree sock insane purse".to_string(); let private_key = node_keys::key_scheme_new(alice_mnemonic); let keypair = KeyPair::from(private_key.child_0_owner.get_private_key()); let auth_key = AuthenticationKey::ed25519(&private_key.child_0_owner.get_public()); let address = auth_key.derived_address(); // config_path.push("../saved_logs/0/node.config.toml"); // let config = NodeConfig::load(&config_path) // .unwrap_or_else(|_| panic!("Failed to load NodeConfig from file: {:?}", config_path)); // match &config.test { // Some( conf) => { // // println!("Swarm Keys : {:?}", conf); // }, // None =>{ // // println!("test config does not set."); // } // } // // Create a client object // let mut client = LibraClient::new( // Url::parse(format!("http://localhost:{}", config.rpc.address.port()).as_str()).unwrap(), // config.base.waypoint.waypoint_from_config().unwrap().clone() // ).unwrap(); // let mut private_key = config.test.unwrap().operator_keypair.unwrap(); // let auth_key = AuthenticationKey::ed25519(&private_key.public_key()); // let address = auth_key.derived_address(); let account_state = client.get_account_state(address.clone(), true).unwrap(); let mut sequence_number = 0u64; if account_state.0.is_some() { sequence_number = account_state.0.unwrap().sequence_number; } // Doing a no-op transaction here which will print // [debug] 000000000000000011e110 in the logs if successful. let hello_world= 100u64; let script = transaction_builder::encode_demo_e2e_script(hello_world); let keypair = KeyPair::from(private_key.take_private().clone().unwrap()); let chain_id = ChainId::new(1); let txn = create_user_txn( &keypair, TransactionPayload::Script(script), address, sequence_number, 700_000, 0, "GAS".parse()?, 5_000_000, chain_id )?; // get account_data struct let mut sender_account_data = AccountData { address, authentication_key: Some(auth_key.to_vec()), key_pair: Some(keypair), sequence_number, status: AccountStatus::Persisted, }; // Submit the transaction with libra_client match client.submit_transaction( Some(&mut sender_account_data), txn ){ Ok(_) => { ol_wait_for_tx(address, sequence_number, &mut client); Ok("Tx submitted".to_string()) } Err(err) => Err(err) } }
32.622047
190
0.646633
7680767edbb977998317f7a070dbdfe3541f8f8c
11,973
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. */ // ----------------------------------------------- // This file is generated, Please do not edit it manually. // Run the following in the root of the repo to regenerate: // // cargo make generate-api // ----------------------------------------------- //! X-Pack APIs //! //! Provide general information about the installed X-Pack features and their usage. # ! [ allow ( unused_imports ) ]use crate::{ client::Elasticsearch, error::Error, http::{ headers::{HeaderMap, HeaderName, HeaderValue, ACCEPT, CONTENT_TYPE}, request::{Body, JsonBody, NdBody, PARTS_ENCODED}, response::Response, transport::Transport, Method, }, params::*, }; use percent_encoding::percent_encode; use serde::Serialize; use std::{borrow::Cow, time::Duration}; #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Xpack Info API"] pub enum XpackInfoParts { #[doc = "No parts"] None, } impl XpackInfoParts { #[doc = "Builds a relative URL path to the Xpack Info API"] pub fn url(self) -> Cow<'static, str> { match self { XpackInfoParts::None => "/_xpack".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Xpack Info API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/info-api.html)\n\nRetrieves information about the installed X-Pack features."] pub struct XpackInfo<'a, 'b> { transport: &'a Transport, parts: XpackInfoParts, accept_enterprise: Option<bool>, categories: Option<&'b [&'b str]>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> XpackInfo<'a, 'b> { #[doc = "Creates a new instance of [XpackInfo]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); XpackInfo { transport, parts: XpackInfoParts::None, headers, accept_enterprise: None, categories: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "If this param is used it must be set to true"] pub fn accept_enterprise(mut self, accept_enterprise: bool) -> Self { self.accept_enterprise = Some(accept_enterprise); self } #[doc = "Comma-separated list of info categories. Can be any of: build, license, features"] pub fn categories(mut self, categories: &'b [&'b str]) -> Self { self.categories = Some(categories); self } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Xpack Info API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { accept_enterprise: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] categories: Option<&'b [&'b str]>, error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { accept_enterprise: self.accept_enterprise, categories: self.categories, error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Xpack Usage API"] pub enum XpackUsageParts { #[doc = "No parts"] None, } impl XpackUsageParts { #[doc = "Builds a relative URL path to the Xpack Usage API"] pub fn url(self) -> Cow<'static, str> { match self { XpackUsageParts::None => "/_xpack/usage".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Xpack Usage API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/usage-api.html)\n\nRetrieves usage information about the installed X-Pack features."] pub struct XpackUsage<'a, 'b> { transport: &'a Transport, parts: XpackUsageParts, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, master_timeout: Option<&'b str>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> XpackUsage<'a, 'b> { #[doc = "Creates a new instance of [XpackUsage]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); XpackUsage { transport, parts: XpackUsageParts::None, headers, error_trace: None, filter_path: None, human: None, master_timeout: None, pretty: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Specify timeout for watch write operation"] pub fn master_timeout(mut self, master_timeout: &'b str) -> Self { self.master_timeout = Some(master_timeout); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Xpack Usage API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, master_timeout: Option<&'b str>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, master_timeout: self.master_timeout, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[doc = "Namespace client for X-Pack APIs"] pub struct Xpack<'a> { transport: &'a Transport, } impl<'a> Xpack<'a> { #[doc = "Creates a new instance of [Xpack]"] pub fn new(transport: &'a Transport) -> Self { Self { transport } } pub fn transport(&self) -> &Transport { self.transport } #[doc = "[Xpack Info API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/info-api.html)\n\nRetrieves information about the installed X-Pack features."] pub fn info<'b>(&'a self) -> XpackInfo<'a, 'b> { XpackInfo::new(self.transport()) } #[doc = "[Xpack Usage API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/usage-api.html)\n\nRetrieves usage information about the installed X-Pack features."] pub fn usage<'b>(&'a self) -> XpackUsage<'a, 'b> { XpackUsage::new(self.transport()) } } impl Elasticsearch { #[doc = "Creates a namespace client for X-Pack APIs"] pub fn xpack(&self) -> Xpack { Xpack::new(self.transport()) } }
36.84
188
0.59417
1a3bbc5ecc49ed3bce7c9f370efa8a65059f5860
13,655
use crate::hir::map::definitions::*; use crate::hir::def_id::{CRATE_DEF_INDEX, DefIndex, DefIndexAddressSpace}; use crate::session::CrateDisambiguator; use syntax::ast::*; use syntax::ext::hygiene::Mark; use syntax::visit; use syntax::symbol::keywords; use syntax::symbol::Symbol; use syntax::parse::token::{self, Token}; use syntax_pos::Span; use crate::hir::map::{ITEM_LIKE_SPACE, REGULAR_SPACE}; /// Creates `DefId`s for nodes in the AST. pub struct DefCollector<'a> { definitions: &'a mut Definitions, parent_def: Option<DefIndex>, expansion: Mark, pub visit_macro_invoc: Option<&'a mut dyn FnMut(MacroInvocationData)>, } pub struct MacroInvocationData { pub mark: Mark, pub def_index: DefIndex, } impl<'a> DefCollector<'a> { pub fn new(definitions: &'a mut Definitions, expansion: Mark) -> Self { DefCollector { definitions, expansion, parent_def: None, visit_macro_invoc: None, } } pub fn collect_root(&mut self, crate_name: &str, crate_disambiguator: CrateDisambiguator) { let root = self.definitions.create_root_def(crate_name, crate_disambiguator); assert_eq!(root, CRATE_DEF_INDEX); self.parent_def = Some(root); } fn create_def(&mut self, node_id: NodeId, data: DefPathData, address_space: DefIndexAddressSpace, span: Span) -> DefIndex { let parent_def = self.parent_def.unwrap(); debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def); self.definitions .create_def_with_parent(parent_def, node_id, data, address_space, self.expansion, span) } pub fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) { let parent = self.parent_def; self.parent_def = Some(parent_def); f(self); self.parent_def = parent; } fn visit_async_fn( &mut self, id: NodeId, name: Name, span: Span, header: &FnHeader, generics: &'a Generics, decl: &'a FnDecl, body: &'a Block, ) { let (closure_id, return_impl_trait_id) = match header.asyncness.node { IsAsync::Async { closure_id, return_impl_trait_id, } => (closure_id, return_impl_trait_id), _ => unreachable!(), }; // For async functions, we need to create their inner defs inside of a // closure to match their desugared representation. let fn_def_data = DefPathData::ValueNs(name.as_interned_str()); let fn_def = self.create_def(id, fn_def_data, ITEM_LIKE_SPACE, span); return self.with_parent(fn_def, |this| { this.create_def(return_impl_trait_id, DefPathData::ImplTrait, REGULAR_SPACE, span); visit::walk_generics(this, generics); visit::walk_fn_decl(this, decl); let closure_def = this.create_def(closure_id, DefPathData::ClosureExpr, REGULAR_SPACE, span); this.with_parent(closure_def, |this| { visit::walk_block(this, body); }) }) } fn visit_macro_invoc(&mut self, id: NodeId) { if let Some(ref mut visit) = self.visit_macro_invoc { visit(MacroInvocationData { mark: id.placeholder_to_mark(), def_index: self.parent_def.unwrap(), }) } } } impl<'a> visit::Visitor<'a> for DefCollector<'a> { fn visit_item(&mut self, i: &'a Item) { debug!("visit_item: {:?}", i); // Pick the def data. This need not be unique, but the more // information we encapsulate into, the better let def_data = match i.node { ItemKind::Impl(..) => DefPathData::Impl, ItemKind::Trait(..) => DefPathData::Trait(i.ident.as_interned_str()), ItemKind::TraitAlias(..) => DefPathData::TraitAlias(i.ident.as_interned_str()), ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) | ItemKind::Existential(..) | ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) | ItemKind::Ty(..) => DefPathData::TypeNs(i.ident.as_interned_str()), ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => { return visit::walk_item(self, i); } ItemKind::Fn( ref decl, ref header, ref generics, ref body, ) if header.asyncness.node.is_async() => { return self.visit_async_fn( i.id, i.ident.name, i.span, header, generics, decl, body, ) } ItemKind::Mod(..) => DefPathData::Module(i.ident.as_interned_str()), ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) => DefPathData::ValueNs(i.ident.as_interned_str()), ItemKind::MacroDef(..) => DefPathData::MacroDef(i.ident.as_interned_str()), ItemKind::Mac(..) => return self.visit_macro_invoc(i.id), ItemKind::GlobalAsm(..) => DefPathData::Misc, ItemKind::Use(..) => { return visit::walk_item(self, i); } }; let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE, i.span); self.with_parent(def, |this| { match i.node { ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => { // If this is a unit or tuple-like struct, register the constructor. if let Some(ctor_hir_id) = struct_def.ctor_id() { this.create_def(ctor_hir_id, DefPathData::Ctor, REGULAR_SPACE, i.span); } } _ => {} } visit::walk_item(this, i); }); } fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) { self.create_def(id, DefPathData::Misc, ITEM_LIKE_SPACE, use_tree.span); visit::walk_use_tree(self, use_tree, id); } fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) { if let ForeignItemKind::Macro(_) = foreign_item.node { return self.visit_macro_invoc(foreign_item.id); } let def = self.create_def(foreign_item.id, DefPathData::ValueNs(foreign_item.ident.as_interned_str()), REGULAR_SPACE, foreign_item.span); self.with_parent(def, |this| { visit::walk_foreign_item(this, foreign_item); }); } fn visit_variant(&mut self, v: &'a Variant, g: &'a Generics, item_id: NodeId) { let def = self.create_def(v.node.id, DefPathData::EnumVariant(v.node.ident.as_interned_str()), REGULAR_SPACE, v.span); self.with_parent(def, |this| { if let Some(ctor_hir_id) = v.node.data.ctor_id() { this.create_def(ctor_hir_id, DefPathData::Ctor, REGULAR_SPACE, v.span); } visit::walk_variant(this, v, g, item_id) }); } fn visit_variant_data(&mut self, data: &'a VariantData, _: Ident, _: &'a Generics, _: NodeId, _: Span) { for (index, field) in data.fields().iter().enumerate() { let name = field.ident.map(|ident| ident.name) .unwrap_or_else(|| Symbol::intern(&index.to_string())); let def = self.create_def(field.id, DefPathData::Field(name.as_interned_str()), REGULAR_SPACE, field.span); self.with_parent(def, |this| this.visit_struct_field(field)); } } fn visit_generic_param(&mut self, param: &'a GenericParam) { let name = param.ident.as_interned_str(); let def_path_data = match param.kind { GenericParamKind::Lifetime { .. } => DefPathData::LifetimeParam(name), GenericParamKind::Type { .. } => DefPathData::TypeParam(name), GenericParamKind::Const { .. } => DefPathData::ConstParam(name), }; self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span); visit::walk_generic_param(self, param); } fn visit_trait_item(&mut self, ti: &'a TraitItem) { let def_data = match ti.node { TraitItemKind::Method(..) | TraitItemKind::Const(..) => DefPathData::ValueNs(ti.ident.as_interned_str()), TraitItemKind::Type(..) => { DefPathData::AssocTypeInTrait(ti.ident.as_interned_str()) }, TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id), }; let def = self.create_def(ti.id, def_data, ITEM_LIKE_SPACE, ti.span); self.with_parent(def, |this| visit::walk_trait_item(this, ti)); } fn visit_impl_item(&mut self, ii: &'a ImplItem) { let def_data = match ii.node { ImplItemKind::Method(MethodSig { ref header, ref decl, }, ref body) if header.asyncness.node.is_async() => { return self.visit_async_fn( ii.id, ii.ident.name, ii.span, header, &ii.generics, decl, body, ) } ImplItemKind::Method(..) | ImplItemKind::Const(..) => DefPathData::ValueNs(ii.ident.as_interned_str()), ImplItemKind::Type(..) => DefPathData::AssocTypeInImpl(ii.ident.as_interned_str()), ImplItemKind::Existential(..) => { DefPathData::AssocExistentialInImpl(ii.ident.as_interned_str()) }, ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id), }; let def = self.create_def(ii.id, def_data, ITEM_LIKE_SPACE, ii.span); self.with_parent(def, |this| visit::walk_impl_item(this, ii)); } fn visit_pat(&mut self, pat: &'a Pat) { match pat.node { PatKind::Mac(..) => return self.visit_macro_invoc(pat.id), _ => visit::walk_pat(self, pat), } } fn visit_anon_const(&mut self, constant: &'a AnonConst) { let def = self.create_def(constant.id, DefPathData::AnonConst, REGULAR_SPACE, constant.value.span); self.with_parent(def, |this| visit::walk_anon_const(this, constant)); } fn visit_expr(&mut self, expr: &'a Expr) { let parent_def = self.parent_def; match expr.node { ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id), ExprKind::Closure(_, asyncness, ..) => { let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, REGULAR_SPACE, expr.span); self.parent_def = Some(closure_def); // Async closures desugar to closures inside of closures, so // we must create two defs. if let IsAsync::Async { closure_id, .. } = asyncness { let async_def = self.create_def(closure_id, DefPathData::ClosureExpr, REGULAR_SPACE, expr.span); self.parent_def = Some(async_def); } } ExprKind::Async(_, async_id, _) => { let async_def = self.create_def(async_id, DefPathData::ClosureExpr, REGULAR_SPACE, expr.span); self.parent_def = Some(async_def); } _ => {} }; visit::walk_expr(self, expr); self.parent_def = parent_def; } fn visit_ty(&mut self, ty: &'a Ty) { match ty.node { TyKind::Mac(..) => return self.visit_macro_invoc(ty.id), TyKind::ImplTrait(node_id, _) => { self.create_def(node_id, DefPathData::ImplTrait, REGULAR_SPACE, ty.span); } _ => {} } visit::walk_ty(self, ty); } fn visit_stmt(&mut self, stmt: &'a Stmt) { match stmt.node { StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id), _ => visit::walk_stmt(self, stmt), } } fn visit_token(&mut self, t: Token) { if let Token::Interpolated(nt) = t { if let token::NtExpr(ref expr) = *nt { if let ExprKind::Mac(..) = expr.node { self.visit_macro_invoc(expr.id); } } } } }
38.792614
99
0.51483
1645abf754d140fafb7dfde729aecd2a4f58be63
1,542
use super::{Registers, RawOp}; pub fn addr(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a] + regs[raw.b]; } pub fn addi(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a] + raw.b; } pub fn mulr(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a] * regs[raw.b]; } pub fn muli(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a] * raw.b; } pub fn banr(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a] & regs[raw.b]; } pub fn bani(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a] & raw.b; } pub fn borr(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a] | regs[raw.b]; } pub fn bori(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a] | raw.b; } pub fn setr(raw: RawOp, regs: &mut Registers) { regs[raw.c] = regs[raw.a]; } pub fn seti(raw: RawOp, regs: &mut Registers) { regs[raw.c] = raw.a; } pub fn gtir(raw: RawOp, regs: &mut Registers) { regs[raw.c] = (raw.a > regs[raw.b]) as u32; } pub fn gtri(raw: RawOp, regs: &mut Registers) { regs[raw.c] = (regs[raw.a] > raw.b) as u32; } pub fn gtrr(raw: RawOp, regs: &mut Registers) { regs[raw.c] = (regs[raw.a] > regs[raw.b]) as u32; } pub fn eqir(raw: RawOp, regs: &mut Registers) { regs[raw.c] = (raw.a == regs[raw.b]) as u32; } pub fn eqri(raw: RawOp, regs: &mut Registers) { regs[raw.c] = (regs[raw.a] == raw.b) as u32; } pub fn eqrr(raw: RawOp, regs: &mut Registers) { regs[raw.c] = (regs[raw.a] == regs[raw.b]) as u32; }
23.363636
54
0.59144
fe85e5a222dad8d22ef015df28510156d75239ed
15,817
// Generated from definition io.k8s.api.admissionregistration.v1.RuleWithOperations /// RuleWithOperations is a tuple of Operations and Resources. It is recommended to make sure that all the tuple expansions are valid. #[derive(Clone, Debug, Default, PartialEq)] pub struct RuleWithOperations { /// APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required. pub api_groups: Option<Vec<String>>, /// APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required. pub api_versions: Option<Vec<String>>, /// Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required. pub operations: Option<Vec<String>>, /// Resources is a list of resources this rule applies to. /// /// For example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources. /// /// If wildcard is present, the validation rule will ensure resources do not overlap with each other. /// /// Depending on the enclosing object, subresources might not be allowed. Required. pub resources: Option<Vec<String>>, /// scope specifies the scope of this rule. Valid values are "Cluster", "Namespaced", and "*" "Cluster" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. "Namespaced" means that only namespaced resources will match this rule. "*" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is "*". pub scope: Option<String>, } impl<'de> crate::serde::Deserialize<'de> for RuleWithOperations { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_api_groups, Key_api_versions, Key_operations, Key_resources, Key_scope, 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 { "apiGroups" => Field::Key_api_groups, "apiVersions" => Field::Key_api_versions, "operations" => Field::Key_operations, "resources" => Field::Key_resources, "scope" => Field::Key_scope, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct Visitor; impl<'de> crate::serde::de::Visitor<'de> for Visitor { type Value = RuleWithOperations; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("RuleWithOperations") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: crate::serde::de::MapAccess<'de> { let mut value_api_groups: Option<Vec<String>> = None; let mut value_api_versions: Option<Vec<String>> = None; let mut value_operations: Option<Vec<String>> = None; let mut value_resources: Option<Vec<String>> = None; let mut value_scope: Option<String> = None; while let Some(key) = crate::serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_api_groups => value_api_groups = crate::serde::de::MapAccess::next_value(&mut map)?, Field::Key_api_versions => value_api_versions = crate::serde::de::MapAccess::next_value(&mut map)?, Field::Key_operations => value_operations = crate::serde::de::MapAccess::next_value(&mut map)?, Field::Key_resources => value_resources = crate::serde::de::MapAccess::next_value(&mut map)?, Field::Key_scope => value_scope = crate::serde::de::MapAccess::next_value(&mut map)?, Field::Other => { let _: crate::serde::de::IgnoredAny = crate::serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(RuleWithOperations { api_groups: value_api_groups, api_versions: value_api_versions, operations: value_operations, resources: value_resources, scope: value_scope, }) } } deserializer.deserialize_struct( "RuleWithOperations", &[ "apiGroups", "apiVersions", "operations", "resources", "scope", ], Visitor, ) } } impl crate::serde::Serialize for RuleWithOperations { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: crate::serde::Serializer { let mut state = serializer.serialize_struct( "RuleWithOperations", self.api_groups.as_ref().map_or(0, |_| 1) + self.api_versions.as_ref().map_or(0, |_| 1) + self.operations.as_ref().map_or(0, |_| 1) + self.resources.as_ref().map_or(0, |_| 1) + self.scope.as_ref().map_or(0, |_| 1), )?; if let Some(value) = &self.api_groups { crate::serde::ser::SerializeStruct::serialize_field(&mut state, "apiGroups", value)?; } if let Some(value) = &self.api_versions { crate::serde::ser::SerializeStruct::serialize_field(&mut state, "apiVersions", value)?; } if let Some(value) = &self.operations { crate::serde::ser::SerializeStruct::serialize_field(&mut state, "operations", value)?; } if let Some(value) = &self.resources { crate::serde::ser::SerializeStruct::serialize_field(&mut state, "resources", value)?; } if let Some(value) = &self.scope { crate::serde::ser::SerializeStruct::serialize_field(&mut state, "scope", value)?; } crate::serde::ser::SerializeStruct::end(state) } } #[cfg(feature = "schemars")] impl crate::schemars::JsonSchema for RuleWithOperations { fn schema_name() -> String { "io.k8s.api.admissionregistration.v1.RuleWithOperations".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("RuleWithOperations is a tuple of Operations and Resources. It is recommended to make sure that all the tuple expansions are valid.".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: [ ( "apiGroups".to_owned(), crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { metadata: Some(Box::new(crate::schemars::schema::Metadata { description: Some("APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.".to_owned()), ..Default::default() })), instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Array))), array: Some(Box::new(crate::schemars::schema::ArrayValidation { items: Some(crate::schemars::schema::SingleOrVec::Single(Box::new( crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))), ..Default::default() }) ))), ..Default::default() })), ..Default::default() }), ), ( "apiVersions".to_owned(), crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { metadata: Some(Box::new(crate::schemars::schema::Metadata { description: Some("APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required.".to_owned()), ..Default::default() })), instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Array))), array: Some(Box::new(crate::schemars::schema::ArrayValidation { items: Some(crate::schemars::schema::SingleOrVec::Single(Box::new( crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))), ..Default::default() }) ))), ..Default::default() })), ..Default::default() }), ), ( "operations".to_owned(), crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { metadata: Some(Box::new(crate::schemars::schema::Metadata { description: Some("Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required.".to_owned()), ..Default::default() })), instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Array))), array: Some(Box::new(crate::schemars::schema::ArrayValidation { items: Some(crate::schemars::schema::SingleOrVec::Single(Box::new( crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))), ..Default::default() }) ))), ..Default::default() })), ..Default::default() }), ), ( "resources".to_owned(), crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { metadata: Some(Box::new(crate::schemars::schema::Metadata { description: Some("Resources is a list of resources this rule applies to.\n\nFor example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources.\n\nIf wildcard is present, the validation rule will ensure resources do not overlap with each other.\n\nDepending on the enclosing object, subresources might not be allowed. Required.".to_owned()), ..Default::default() })), instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Array))), array: Some(Box::new(crate::schemars::schema::ArrayValidation { items: Some(crate::schemars::schema::SingleOrVec::Single(Box::new( crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))), ..Default::default() }) ))), ..Default::default() })), ..Default::default() }), ), ( "scope".to_owned(), crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject { metadata: Some(Box::new(crate::schemars::schema::Metadata { description: Some("scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\".".to_owned()), ..Default::default() })), instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))), ..Default::default() }), ), ].into(), ..Default::default() })), ..Default::default() }) } }
60.834615
562
0.530695
fb084afe960de8d478130f801a6dfea4e50049de
1,491
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn target() -> Target { Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(), options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string(), env: "newlib".to_string(), vendor: "espressif".to_string(), linker_flavor: LinkerFlavor::Gcc, linker: Some("riscv32-esp-elf-gcc".to_string()), cpu: "generic-rv32".to_string(), // While the RiscV32IMC architecture does not natively support atomics, ESP-IDF does support // the __atomic* and __sync* GCC builtins, so setting `max_atomic_width` to `Some(32)` // and `atomic_cas` to `true` will cause the compiler to emit libcalls to these builtins. // // Support for atomics is necessary for the Rust STD library, which is supported by the ESP-IDF framework. max_atomic_width: Some(32), atomic_cas: true, features: "+m,+c".to_string(), executables: true, panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, eh_frame_header: false, ..Default::default() }, } }
39.236842
118
0.589537
337ec8dbb96135c50e8e71b4cadab88761263352
2,041
#[doc = "Writer for register TASKS_STARTEPIN[%s]"] pub type W = crate::W<u32, super::TASKS_STARTEPIN>; #[doc = "Register TASKS_STARTEPIN[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::TASKS_STARTEPIN { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Captures the EPIN\\[n\\].PTR and EPIN\\[n\\].MAXCNT registers values, and enables endpoint IN n to respond to traffic from host\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TASKS_STARTEPIN_AW { #[doc = "1: Trigger task"] TRIGGER, } impl From<TASKS_STARTEPIN_AW> for bool { #[inline(always)] fn from(variant: TASKS_STARTEPIN_AW) -> Self { match variant { TASKS_STARTEPIN_AW::TRIGGER => true, } } } #[doc = "Write proxy for field `TASKS_STARTEPIN`"] pub struct TASKS_STARTEPIN_W<'a> { w: &'a mut W, } impl<'a> TASKS_STARTEPIN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TASKS_STARTEPIN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Trigger task"] #[inline(always)] pub fn trigger(self) -> &'a mut W { self.variant(TASKS_STARTEPIN_AW::TRIGGER) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl W { #[doc = "Bit 0 - Captures the EPIN\\[n\\].PTR and EPIN\\[n\\].MAXCNT registers values, and enables endpoint IN n to respond to traffic from host"] #[inline(always)] pub fn tasks_startepin(&mut self) -> TASKS_STARTEPIN_W { TASKS_STARTEPIN_W { w: self } } }
30.924242
159
0.594317
69e156a4f4020c50d49d4bd4934d2b009bffedf4
4,052
/* * Ory Kratos API * * Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the administative API port you should use something like Nginx, Ory Oathkeeper, or any other technology capable of authorizing incoming requests. * * The version of the OpenAPI document: v0.10.1 * Contact: [email protected] * Generated by: https://openapi-generator.tech */ /// Identity : An identity can be a real human, a service, an IoT device - everything that can be described as an \"actor\" in a system. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Identity { /// CreatedAt is a helper struct field for gobuffalo.pop. #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, /// Credentials represents all credentials that can be used for authenticating this identity. #[serde(rename = "credentials", skip_serializing_if = "Option::is_none")] pub credentials: Option<::std::collections::HashMap<String, crate::models::IdentityCredentials>>, #[serde(rename = "id")] pub id: String, /// NullJSONRawMessage represents a json.RawMessage that works well with JSON, SQL, and Swagger and is NULLable- #[serde(rename = "metadata_admin", skip_serializing_if = "Option::is_none")] pub metadata_admin: Option<serde_json::Value>, /// NullJSONRawMessage represents a json.RawMessage that works well with JSON, SQL, and Swagger and is NULLable- #[serde(rename = "metadata_public", skip_serializing_if = "Option::is_none")] pub metadata_public: Option<serde_json::Value>, /// RecoveryAddresses contains all the addresses that can be used to recover an identity. #[serde(rename = "recovery_addresses", skip_serializing_if = "Option::is_none")] pub recovery_addresses: Option<Vec<crate::models::RecoveryAddress>>, /// SchemaID is the ID of the JSON Schema to be used for validating the identity's traits. #[serde(rename = "schema_id")] pub schema_id: String, /// SchemaURL is the URL of the endpoint where the identity's traits schema can be fetched from. format: url #[serde(rename = "schema_url")] pub schema_url: String, #[serde(rename = "state", skip_serializing_if = "Option::is_none")] pub state: Option<crate::models::IdentityState>, #[serde(rename = "state_changed_at", skip_serializing_if = "Option::is_none")] pub state_changed_at: Option<String>, /// Traits represent an identity's traits. The identity is able to create, modify, and delete traits in a self-service manner. The input will always be validated against the JSON Schema defined in `schema_url`. #[serde(rename = "traits")] pub traits: Option<serde_json::Value>, /// UpdatedAt is a helper struct field for gobuffalo.pop. #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] pub updated_at: Option<String>, /// VerifiableAddresses contains all the addresses that can be verified by the user. #[serde(rename = "verifiable_addresses", skip_serializing_if = "Option::is_none")] pub verifiable_addresses: Option<Vec<crate::models::VerifiableIdentityAddress>>, } impl Identity { /// An identity can be a real human, a service, an IoT device - everything that can be described as an \"actor\" in a system. pub fn new(id: String, schema_id: String, schema_url: String, traits: Option<serde_json::Value>) -> Identity { Identity { created_at: None, credentials: None, id, metadata_admin: None, metadata_public: None, recovery_addresses: None, schema_id, schema_url, state: None, state_changed_at: None, traits, updated_at: None, verifiable_addresses: None, } } }
52.623377
431
0.702863
e2c4c2f744c9b67a56e184b4efe2ceabf719667d
1,633
//! Model evaluation metrics for ARIMA forecasting models. use crate::model::arima_fitting_metrics::ArimaFittingMetrics; use crate::model::arima_order::ArimaOrder; use crate::model::arima_single_model_forecasting_metrics::ArimaSingleModelForecastingMetrics; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ArimaForecastingMetrics { /// Id to differentiate different time series for the large-scale case. pub time_series_id: Option<Vec<String>>, /// Seasonal periods. Repeated because multiple periods are supported for one time series. pub seasonal_periods: Option<Vec<SeasonalPeriods>>, /// Whether Arima model fitted with drift or not. It is always false when d is not 1. pub has_drift: Option<Vec<bool>>, /// Non-seasonal order. pub non_seasonal_order: Option<Vec<ArimaOrder>>, /// Repeated as there can be many metric sets (one for each model) in auto-arima and the large-scale case. pub arima_single_model_forecasting_metrics: Option<Vec<ArimaSingleModelForecastingMetrics>>, /// Arima model fitting metrics. pub arima_fitting_metrics: Option<Vec<ArimaFittingMetrics>>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SeasonalPeriods { /// SeasonalPeriodTypeUnspecified, /// No seasonality NoSeasonality, /// Daily period, 24 hours. Daily, /// Weekly period, 7 days. Weekly, /// Monthly period, 30 days or irregular. Monthly, /// Quarterly period, 90 days or irregular. Quarterly, /// Yearly period, 365 days or irregular. Yearly, }
39.829268
110
0.733007
9b98939c97d4eb289f6dc70645202a8c0b3e00b4
13,032
use legion::prelude::*; #[derive(Clone, Copy, Debug, PartialEq)] struct Pos(f32, f32, f32); #[derive(Clone, Copy, Debug, PartialEq)] struct Rot(f32, f32, f32); #[derive(Clone, Copy, Debug, PartialEq)] struct Scale(f32, f32, f32); #[derive(Clone, Copy, Debug, PartialEq)] struct Vel(f32, f32, f32); #[derive(Clone, Copy, Debug, PartialEq)] struct Accel(f32, f32, f32); #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] struct Model(u32); #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] struct Static; #[test] fn insert() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (1usize, 2f32, 3u16); let components = vec![(4f32, 5u64, 6u16), (4f32, 5u64, 6u16)]; let entities = world.insert(shared, components); assert_eq!(2, entities.len()); } #[test] fn get_component() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Static, Model(5)); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let mut entities: Vec<Entity> = Vec::new(); for e in world.insert(shared, components.clone()) { entities.push(*e); } for (i, e) in entities.iter().enumerate() { match world.get_component(*e) { Some(x) => assert_eq!(components.get(i).map(|(x, _)| x), Some(&x as &Pos)), None => assert_eq!(components.get(i).map(|(x, _)| x), None), } match world.get_component(*e) { Some(x) => assert_eq!(components.get(i).map(|(_, x)| x), Some(&x as &Rot)), None => assert_eq!(components.get(i).map(|(_, x)| x), None), } } } #[test] fn get_component_wrong_type() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let entity = *world.insert((), vec![(0f64,)]).get(0).unwrap(); assert!(world.get_component::<i32>(entity).is_none()); } #[test] fn get_shared() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Static, Model(5)); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let mut entities: Vec<Entity> = Vec::new(); for e in world.insert(shared, components) { entities.push(*e); } for e in entities.iter() { assert_eq!(Some(&Static), world.get_tag(*e)); assert_eq!(Some(&Model(5)), world.get_tag(*e)); } } #[test] fn get_shared_wrong_type() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let entity = *world.insert((Static,), vec![(0f64,)]).get(0).unwrap(); assert!(world.get_tag::<Model>(entity).is_none()); } #[test] fn delete() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Static, Model(5)); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let mut entities: Vec<Entity> = Vec::new(); for e in world.insert(shared, components) { entities.push(*e); } for e in entities.iter() { assert_eq!(true, world.is_alive(*e)); } for e in entities.iter() { world.delete(*e); assert_eq!(false, world.is_alive(*e)); } } #[test] fn delete_last() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Static, Model(5)); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let mut entities: Vec<Entity> = Vec::new(); for e in world.insert(shared, components.clone()) { entities.push(*e); } let last = *entities.last().unwrap(); world.delete(last); assert_eq!(false, world.is_alive(last)); for (i, e) in entities.iter().take(entities.len() - 1).enumerate() { assert_eq!(true, world.is_alive(*e)); match world.get_component(*e) { Some(x) => assert_eq!(components.get(i).map(|(x, _)| x), Some(&x as &Pos)), None => assert_eq!(components.get(i).map(|(x, _)| x), None), } match world.get_component(*e) { Some(x) => assert_eq!(components.get(i).map(|(_, x)| x), Some(&x as &Rot)), None => assert_eq!(components.get(i).map(|(_, x)| x), None), } } } #[test] fn delete_first() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Static, Model(5)); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let mut entities: Vec<Entity> = Vec::new(); for e in world.insert(shared, components.clone()) { entities.push(*e); } let first = *entities.first().unwrap(); world.delete(first); assert_eq!(false, world.is_alive(first)); for (i, e) in entities.iter().skip(1).enumerate() { assert_eq!(true, world.is_alive(*e)); match world.get_component(*e) { Some(x) => assert_eq!(components.get(i + 1).map(|(x, _)| x), Some(&x as &Pos)), None => assert_eq!(components.get(i + 1).map(|(x, _)| x), None), } match world.get_component(*e) { Some(x) => assert_eq!(components.get(i + 1).map(|(_, x)| x), Some(&x as &Rot)), None => assert_eq!(components.get(i + 1).map(|(_, x)| x), None), } } } #[test] fn merge() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world_1 = universe.create_world(); let mut world_2 = universe.create_world(); let shared = (Static, Model(5)); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let mut world_1_entities: Vec<Entity> = Vec::new(); for e in world_1.insert(shared, components.clone()) { world_1_entities.push(*e); } let mut world_2_entities: Vec<Entity> = Vec::new(); for e in world_2.insert(shared, components.clone()) { world_2_entities.push(*e); } world_1.merge(world_2); for (i, e) in world_2_entities.iter().enumerate() { assert!(world_1.is_alive(*e)); let (pos, rot) = components.get(i).unwrap(); assert_eq!(pos, &world_1.get_component(*e).unwrap() as &Pos); assert_eq!(rot, &world_1.get_component(*e).unwrap() as &Rot); } } #[test] fn mutate_add_component() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Static, Model(5)); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let entities = world.insert(shared, components).to_vec(); let query_without_scale = <(Read<Pos>, Read<Rot>)>::query(); let query_with_scale = <(Read<Pos>, Read<Rot>, Read<Scale>)>::query(); assert_eq!(3, query_without_scale.iter(&world).count()); assert_eq!(0, query_with_scale.iter(&world).count()); world .add_component(*entities.get(1).unwrap(), Scale(0.5, 0.5, 0.5)) .unwrap(); assert_eq!(3, query_without_scale.iter(&world).count()); assert_eq!(1, query_with_scale.iter(&world).count()); } #[test] fn mutate_remove_component() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Static, Model(5)); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let entities = world.insert(shared, components).to_vec(); let query_without_rot = Read::<Pos>::query().filter(!component::<Rot>()); let query_with_rot = <(Read<Pos>, Read<Rot>)>::query(); assert_eq!(0, query_without_rot.iter(&world).count()); assert_eq!(3, query_with_rot.iter(&world).count()); world .remove_component::<Rot>(*entities.get(1).unwrap()) .unwrap(); assert_eq!(1, query_without_rot.iter(&world).count()); assert_eq!(2, query_with_rot.iter(&world).count()); } #[test] fn mutate_add_tag() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Model(5),); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let entities = world.insert(shared, components).to_vec(); let query_without_static = <(Read<Pos>, Read<Rot>)>::query(); let query_with_static = <(Read<Pos>, Read<Rot>, Tagged<Static>)>::query(); assert_eq!(3, query_without_static.iter(&world).count()); assert_eq!(0, query_with_static.iter(&world).count()); world.add_tag(*entities.get(1).unwrap(), Static).unwrap(); assert_eq!(3, query_without_static.iter(&world).count()); assert_eq!(1, query_with_static.iter(&world).count()); } #[test] fn mutate_remove_tag() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Model(5), Static); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let entities = world.insert(shared, components).to_vec(); let query_without_static = <(Read<Pos>, Read<Rot>)>::query().filter(!tag::<Static>()); let query_with_static = <(Read<Pos>, Read<Rot>, Tagged<Static>)>::query(); assert_eq!(0, query_without_static.iter(&world).count()); assert_eq!(3, query_with_static.iter(&world).count()); world .remove_tag::<Static>(*entities.get(1).unwrap()) .unwrap(); assert_eq!(1, query_without_static.iter(&world).count()); assert_eq!(2, query_with_static.iter(&world).count()); } #[test] fn mutate_change_tag_minimum_test() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Model(5),); let components = vec![(Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3))]; let entities = world.insert(shared, components).to_vec(); tracing::trace!("STARTING CHANGE"); world.add_tag(entities[0], Model(3)).unwrap(); tracing::trace!("CHANGED\n"); assert_eq!(*world.get_tag::<Model>(entities[0]).unwrap(), Model(3)); } #[test] #[allow(clippy::suspicious_map)] fn mutate_change_tag() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); let mut world = universe.create_world(); let shared = (Model(5),); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let entities = world.insert(shared, components).to_vec(); let query_model_3 = <(Read<Pos>, Read<Rot>)>::query().filter(tag_value(&Model(3))); let query_model_5 = <(Read<Pos>, Read<Rot>)>::query().filter(tag_value(&Model(5))); assert_eq!(3, query_model_5.iter(&world).count()); assert_eq!(0, query_model_3.iter(&world).count()); tracing::trace!("STARTING CHANGE"); world.add_tag(*entities.get(1).unwrap(), Model(3)).unwrap(); tracing::trace!("CHANGED\n"); assert_eq!( 1, query_model_3 .iter_entities_mut(&mut world) .map(|e| { tracing::trace!("iter: {:?}", e); e }) .count() ); assert_eq!( *world.get_tag::<Model>(*entities.get(1).unwrap()).unwrap(), Model(3) ); assert_eq!(2, query_model_5.iter(&world).count()); } // This test repeatedly creates a world with new entities and drops it, reproducing // https://github.com/TomGillen/legion/issues/92 #[test] fn lots_of_deletes() { let _ = tracing_subscriber::fmt::try_init(); let universe = Universe::new(); for _ in 0..10000 { let shared = (Model(5),); let components = vec![ (Pos(1., 2., 3.), Rot(0.1, 0.2, 0.3)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), (Pos(4., 5., 6.), Rot(0.4, 0.5, 0.6)), ]; let mut world = universe.create_world(); world.insert(shared, components).to_vec(); } }
29.219731
91
0.570826
891e9f88656a1158b5f21df7227b3ca17180aa8f
126
#![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { let _ = lofty::FileType::from_buffer(data); });
18
47
0.65873
e924ef703f0ca765ae9692abbb75915811497ac2
71,623
#![feature(async_await)] #![deny(warnings)] extern crate bytes; extern crate hyper; #[macro_use] extern crate matches; extern crate net2; extern crate pretty_env_logger; extern crate tokio; extern crate tokio_io; extern crate tokio_tcp; extern crate tokio_timer; use std::io::{Read, Write}; use std::net::{SocketAddr, TcpListener}; use std::pin::Pin; use std::task::{Context, Poll}; use std::thread; use std::time::Duration; use hyper::{Body, Client, Method, Request, StatusCode}; use futures_core::{Future, Stream, TryFuture}; use futures_channel::oneshot; use futures_util::future::{self, FutureExt}; use futures_util::try_future::{self, TryFutureExt}; use futures_util::try_stream::TryStreamExt; use tokio::runtime::current_thread::Runtime; use tokio_tcp::TcpStream; fn s(buf: &[u8]) -> &str { ::std::str::from_utf8(buf).expect("from_utf8") } fn tcp_connect(addr: &SocketAddr) -> impl Future<Output = std::io::Result<TcpStream>> { TcpStream::connect(addr) } macro_rules! test { ( name: $name:ident, server: expected: $server_expected:expr, reply: $server_reply:expr, client: request: {$( $c_req_prop:ident: $c_req_val: tt, )*}, response: status: $client_status:ident, headers: { $($response_header_name:expr => $response_header_val:expr,)* }, body: $response_body:expr, ) => ( test! { name: $name, server: expected: $server_expected, reply: $server_reply, client: set_host: true, request: {$( $c_req_prop: $c_req_val, )*}, response: status: $client_status, headers: { $($response_header_name => $response_header_val,)* }, body: $response_body, } ); ( name: $name:ident, server: expected: $server_expected:expr, reply: $server_reply:expr, client: set_host: $set_host:expr, request: {$( $c_req_prop:ident: $c_req_val:tt, )*}, response: status: $client_status:ident, headers: { $($response_header_name:expr => $response_header_val:expr,)* }, body: $response_body:expr, ) => ( test! { name: $name, server: expected: $server_expected, reply: $server_reply, client: set_host: $set_host, title_case_headers: false, request: {$( $c_req_prop: $c_req_val, )*}, response: status: $client_status, headers: { $($response_header_name => $response_header_val,)* }, body: $response_body, } ); ( name: $name:ident, server: expected: $server_expected:expr, reply: $server_reply:expr, client: set_host: $set_host:expr, title_case_headers: $title_case_headers:expr, request: {$( $c_req_prop:ident: $c_req_val:tt, )*}, response: status: $client_status:ident, headers: { $($response_header_name:expr => $response_header_val:expr,)* }, body: $response_body:expr, ) => ( #[test] fn $name() { let _ = pretty_env_logger::try_init(); let mut rt = Runtime::new().expect("runtime new"); let res = test! { INNER; name: $name, runtime: &mut rt, server: expected: $server_expected, reply: $server_reply, client: set_host: $set_host, title_case_headers: $title_case_headers, request: {$( $c_req_prop: $c_req_val, )*}, }.expect("test"); assert_eq!(res.status(), StatusCode::$client_status); $( assert_eq!( res .headers() .get($response_header_name) .expect(concat!("response header '", stringify!($response_header_name), "'")), $response_header_val, "response header '{}'", stringify!($response_header_name), ); )* let body = rt.block_on(res.into_body().try_concat()) .expect("body concat wait"); let expected_res_body = Option::<&[u8]>::from($response_body) .unwrap_or_default(); assert_eq!(body.as_ref(), expected_res_body); } ); ( name: $name:ident, server: expected: $server_expected:expr, reply: $server_reply:expr, client: request: {$( $c_req_prop:ident: $c_req_val:tt, )*}, error: $err:expr, ) => ( #[test] fn $name() { let _ = pretty_env_logger::try_init(); let mut rt = Runtime::new().expect("runtime new"); let err: ::hyper::Error = test! { INNER; name: $name, runtime: &mut rt, server: expected: $server_expected, reply: $server_reply, client: set_host: true, title_case_headers: false, request: {$( $c_req_prop: $c_req_val, )*}, }.unwrap_err(); fn infer_closure<F: FnOnce(&::hyper::Error) -> bool>(f: F) -> F { f } let closure = infer_closure($err); if !closure(&err) { panic!("expected error, unexpected variant: {:?}", err); } } ); ( INNER; name: $name:ident, runtime: $runtime:expr, server: expected: $server_expected:expr, reply: $server_reply:expr, client: set_host: $set_host:expr, title_case_headers: $title_case_headers:expr, request: {$( $c_req_prop:ident: $c_req_val:tt, )*}, ) => ({ let server = TcpListener::bind("127.0.0.1:0").expect("bind"); let addr = server.local_addr().expect("local_addr"); let rt = $runtime; let connector = ::hyper::client::HttpConnector::new(1); let client = Client::builder() .set_host($set_host) .http1_title_case_headers($title_case_headers) .build(connector); #[allow(unused_assignments, unused_mut)] let mut body = Body::empty(); let mut req_builder = Request::builder(); $( test!(@client_request; req_builder, body, addr, $c_req_prop: $c_req_val); )* let req = req_builder .body(body) .expect("request builder"); let res = client.request(req); let (tx, rx) = oneshot::channel(); let thread = thread::Builder::new() .name(format!("tcp-server<{}>", stringify!($name))); thread.spawn(move || { let mut inc = server.accept().expect("accept").0; inc.set_read_timeout(Some(Duration::from_secs(5))).expect("set_read_timeout"); inc.set_write_timeout(Some(Duration::from_secs(5))).expect("set_write_timeout"); let expected = format!($server_expected, addr=addr); let mut buf = [0; 4096]; let mut n = 0; while n < buf.len() && n < expected.len() { n += match inc.read(&mut buf[n..]) { Ok(n) => n, Err(e) => panic!("failed to read request, partially read = {:?}, error: {}", s(&buf[..n]), e), }; } assert_eq!(s(&buf[..n]), expected); inc.write_all($server_reply.as_ref()).expect("write_all"); let _ = tx.send(Ok::<_, hyper::Error>(())); }).expect("thread spawn"); let rx = rx.expect("thread panicked"); rt.block_on(try_future::try_join(res, rx).map_ok(|r| r.0)).map(move |mut resp| { // Always check that HttpConnector has set the "extra" info... let extra = resp .extensions_mut() .remove::<::hyper::client::connect::HttpInfo>() .expect("HttpConnector should set HttpInfo"); assert_eq!(extra.remote_addr(), addr, "HttpInfo should have server addr"); resp }) }); ( @client_request; $req_builder:ident, $body:ident, $addr:ident, $c_req_prop:ident: $c_req_val:tt ) => ({ __client_req_prop!($req_builder, $body, $addr, $c_req_prop: $c_req_val) }); } macro_rules! __client_req_prop { ($req_builder:ident, $body:ident, $addr:ident, headers: $map:tt) => ({ __client_req_header!($req_builder, $map) }); ($req_builder:ident, $body:ident, $addr:ident, method: $method:ident) => ({ $req_builder.method(Method::$method); }); ($req_builder:ident, $body:ident, $addr:ident, version: $version:ident) => ({ $req_builder.version(hyper::Version::$version); }); ($req_builder:ident, $body:ident, $addr:ident, url: $url:expr) => ({ $req_builder.uri(format!($url, addr=$addr)); }); ($req_builder:ident, $body:ident, $addr:ident, body: $body_e:expr) => ({ $body = $body_e.into(); }); } macro_rules! __client_req_header { ($req_builder:ident, { $($name:expr => $val:expr,)* }) => { $( $req_builder.header($name, $val); )* } } static REPLY_OK: &'static str = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; test! { name: client_get, server: expected: "GET / HTTP/1.1\r\nhost: {addr}\r\n\r\n", reply: REPLY_OK, client: request: { method: GET, url: "http://{addr}/", }, response: status: OK, headers: { "Content-Length" => "0", }, body: None, } test! { name: client_get_query, server: expected: "GET /foo?key=val HTTP/1.1\r\nhost: {addr}\r\n\r\n", reply: REPLY_OK, client: request: { method: GET, url: "http://{addr}/foo?key=val#dont_send_me", }, response: status: OK, headers: { "Content-Length" => "0", }, body: None, } test! { name: client_get_implicitly_empty, server: expected: "GET / HTTP/1.1\r\nhost: {addr}\r\n\r\n", reply: REPLY_OK, client: request: { method: GET, url: "http://{addr}/", body: "", // not Body::empty }, response: status: OK, headers: { "Content-Length" => "0", }, body: None, } test! { name: client_post_sized, server: expected: "\ POST /length HTTP/1.1\r\n\ content-length: 7\r\n\ host: {addr}\r\n\ \r\n\ foo bar\ ", reply: REPLY_OK, client: request: { method: POST, url: "http://{addr}/length", headers: { "Content-Length" => "7", }, body: "foo bar", }, response: status: OK, headers: {}, body: None, } test! { name: client_post_chunked, server: expected: "\ POST /chunks HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\ host: {addr}\r\n\ \r\n\ B\r\n\ foo bar baz\r\n\ 0\r\n\r\n\ ", reply: REPLY_OK, client: request: { method: POST, url: "http://{addr}/chunks", headers: { "Transfer-Encoding" => "chunked", }, body: "foo bar baz", }, response: status: OK, headers: {}, body: None, } test! { name: client_post_empty, server: expected: "\ POST /empty HTTP/1.1\r\n\ content-length: 0\r\n\ host: {addr}\r\n\ \r\n\ ", reply: REPLY_OK, client: request: { method: POST, url: "http://{addr}/empty", headers: { "Content-Length" => "0", }, }, response: status: OK, headers: {}, body: None, } test! { name: client_head_ignores_body, server: expected: "\ HEAD /head HTTP/1.1\r\n\ host: {addr}\r\n\ \r\n\ ", reply: "\ HTTP/1.1 200 OK\r\n\ content-Length: 11\r\n\ \r\n\ Hello World\ ", client: request: { method: HEAD, url: "http://{addr}/head", }, response: status: OK, headers: {}, body: None, } test! { name: client_pipeline_responses_extra, server: expected: "\ GET /pipe HTTP/1.1\r\n\ host: {addr}\r\n\ \r\n\ ", reply: "\ HTTP/1.1 200 OK\r\n\ Content-Length: 0\r\n\ \r\n\ HTTP/1.1 200 OK\r\n\ Content-Length: 0\r\n\ \r\n\ ", client: request: { method: GET, url: "http://{addr}/pipe", }, response: status: OK, headers: {}, body: None, } test! { name: client_requires_absolute_uri, server: expected: "won't get here {addr}", reply: "won't reply", client: request: { method: GET, url: "/relative-{addr}", }, error: |err| err.to_string() == "client requires absolute-form URIs", } test! { name: client_error_unexpected_eof, server: expected: "\ GET /err HTTP/1.1\r\n\ host: {addr}\r\n\ \r\n\ ", reply: "\ HTTP/1.1 200 OK\r\n\ ", // unexpected eof before double CRLF client: request: { method: GET, url: "http://{addr}/err", }, error: |err| err.is_incomplete_message(), } test! { name: client_error_parse_version, server: expected: "\ GET /err HTTP/1.1\r\n\ host: {addr}\r\n\ \r\n\ ", reply: "\ HEAT/1.1 200 OK\r\n\ \r\n\ ", client: request: { method: GET, url: "http://{addr}/err", }, // should get a Parse(Version) error error: |err| err.is_parse(), } test! { name: client_100_continue, server: expected: "\ POST /continue HTTP/1.1\r\n\ content-length: 7\r\n\ host: {addr}\r\n\ \r\n\ foo bar\ ", reply: "\ HTTP/1.1 100 Continue\r\n\ \r\n\ HTTP/1.1 200 OK\r\n\ Content-Length: 0\r\n\ \r\n\ ", client: request: { method: POST, url: "http://{addr}/continue", headers: { "Content-Length" => "7", }, body: "foo bar", }, response: status: OK, headers: {}, body: None, } test! { name: client_connect_method, server: expected: "\ CONNECT {addr} HTTP/1.1\r\n\ host: {addr}\r\n\ \r\n\ ", reply: "\ HTTP/1.1 200 OK\r\n\ \r\n\ ", client: request: { method: CONNECT, url: "{addr}", }, response: status: OK, headers: {}, body: None, } test! { name: client_connect_method_with_absolute_uri, server: expected: "\ CONNECT {addr} HTTP/1.1\r\n\ host: {addr}\r\n\ \r\n\ ", reply: "\ HTTP/1.1 200 OK\r\n\ \r\n\ ", client: request: { method: CONNECT, url: "http://{addr}", }, response: status: OK, headers: {}, body: None, } test! { name: client_set_host_false, server: // {addr} is here because format! requires it to exist in the string expected: "\ GET /no-host/{addr} HTTP/1.1\r\n\ \r\n\ ", reply: "\ HTTP/1.1 200 OK\r\n\ Content-Length: 0\r\n\ \r\n\ ", client: set_host: false, request: { method: GET, url: "http://{addr}/no-host/{addr}", }, response: status: OK, headers: {}, body: None, } test! { name: client_set_http1_title_case_headers, server: expected: "\ GET / HTTP/1.1\r\n\ X-Test-Header: test\r\n\ Host: {addr}\r\n\ \r\n\ ", reply: "\ HTTP/1.1 200 OK\r\n\ Content-Length: 0\r\n\ \r\n\ ", client: set_host: true, title_case_headers: true, request: { method: GET, url: "http://{addr}/", headers: { "X-Test-Header" => "test", }, }, response: status: OK, headers: {}, body: None, } test! { name: client_h1_rejects_http2, server: expected: "won't get here {addr}", reply: "won't reply", client: request: { method: GET, url: "http://{addr}/", version: HTTP_2, }, error: |err| err.to_string() == "request has unsupported HTTP version", } test! { name: client_always_rejects_http09, server: expected: "won't get here {addr}", reply: "won't reply", client: request: { method: GET, url: "http://{addr}/", version: HTTP_09, }, error: |err| err.to_string() == "request has unsupported HTTP version", } mod dispatch_impl { use super::*; use std::io::{self, Read, Write}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; use std::time::{Duration, Instant}; use futures_core::{self, Future}; use futures_channel::{mpsc, oneshot}; use futures_util::future::FutureExt; use futures_util::stream::StreamExt; use futures_util::try_future::TryFutureExt; use futures_util::try_stream::TryStreamExt; use tokio::runtime::current_thread::Runtime; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_tcp::TcpStream; use tokio_timer::Delay; use hyper::client::connect::{Connect, Connected, Destination, HttpConnector}; use hyper::Client; use hyper; #[test] fn drop_body_before_eof_closes_connection() { // https://github.com/hyperium/hyper/issues/1353 let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (closes_tx, closes) = mpsc::channel(10); let client = Client::builder() .build(DebugConnector::with_http_and_closes(HttpConnector::new(1), closes_tx)); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); let body = vec![b'x'; 1024 * 128]; write!(sock, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len()).expect("write head"); let _ = sock.write_all(&body); let _ = tx1.send(()); }); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req).map_ok(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); Delay::new(Instant::now() + Duration::from_secs(1)) }); let rx = rx1.expect("thread panicked"); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); rt.block_on(closes.into_future()).0.expect("closes"); } #[test] fn dropped_client_closes_connection() { // https://github.com/hyperium/hyper/issues/1353 let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); let body =[b'x'; 64]; write!(sock, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len()).expect("write head"); let _ = sock.write_all(&body); let _ = tx1.send(()); }); let res = { let client = Client::builder() .build(DebugConnector::with_http_and_closes(HttpConnector::new(1), closes_tx)); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); client.request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }).map_ok(|_| { Delay::new(Instant::now() + Duration::from_secs(1)) }) }; // client is dropped let rx = rx1.expect("thread panicked"); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); rt.block_on(closes.into_future()).0.expect("closes"); } #[test] fn drop_client_closes_idle_connections() { use futures_util::future; let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (closes_tx, mut closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); let (_client_drop_tx, client_drop_rx) = oneshot::channel::<()>(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); let body = [b'x'; 64]; write!(sock, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len()).expect("write head"); let _ = sock.write_all(&body); let _ = tx1.send(()); // prevent this thread from closing until end of test, so the connection // stays open and idle until Client is dropped Runtime::new().unwrap().block_on(client_drop_rx.into_future()) }); let client = Client::builder() .build(DebugConnector::with_http_and_closes(HttpConnector::new(1), closes_tx)); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }); let rx = rx1.expect("thread panicked"); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); // not closed yet, just idle { rt.block_on(future::poll_fn(|ctx| { assert!(Pin::new(&mut closes).poll_next(ctx).is_pending()); Poll::Ready(Ok::<_, ()>(())) })).unwrap(); } drop(client); let t = Delay::new(Instant::now() + Duration::from_millis(100)) .map(|_| panic!("time out")); let close = closes .into_future() .map(|(opt, _)| opt.expect("closes")); let _ = rt.block_on(future::select(t, close)); } #[test] fn drop_response_future_closes_in_progress_connection() { let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); let (_client_drop_tx, client_drop_rx) = std::sync::mpsc::channel::<()>(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); // we never write a response head // simulates a slow server operation let _ = tx1.send(()); // prevent this thread from closing until end of test, so the connection // stays open and idle until Client is dropped let _ = client_drop_rx.recv(); }); let res = { let client = Client::builder() .build(DebugConnector::with_http_and_closes(HttpConnector::new(1), closes_tx)); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); client.request(req) }; rt.block_on(future::select(res, rx1)); // res now dropped let t = Delay::new(Instant::now() + Duration::from_millis(100)) .map(|_| panic!("time out")); let close = closes .into_future() .map(|(opt, _)| opt.expect("closes")); let _ = rt.block_on(future::select(t, close)); } #[test] fn drop_response_body_closes_in_progress_connection() { let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); let (_client_drop_tx, client_drop_rx) = std::sync::mpsc::channel::<()>(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); write!(sock, "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n").expect("write head"); let _ = tx1.send(()); // prevent this thread from closing until end of test, so the connection // stays open and idle until Client is dropped let _ = client_drop_rx.recv(); }); let res = { let client = Client::builder() .build(DebugConnector::with_http_and_closes(HttpConnector::new(1), closes_tx)); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); // notably, havent read body yet client.request(req) }; let rx = rx1.expect("thread panicked"); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); let t = Delay::new(Instant::now() + Duration::from_millis(100)) .map(|_| panic!("time out")); let close = closes .into_future() .map(|(opt, _)| opt.expect("closes")); let _ = rt.block_on(future::select(t, close)); } #[test] fn no_keep_alive_closes_connection() { // https://github.com/hyperium/hyper/issues/1383 let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); let (_tx2, rx2) = std::sync::mpsc::channel::<()>(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); let _ = tx1.send(()); // prevent this thread from closing until end of test, so the connection // stays open and idle until Client is dropped let _ = rx2.recv(); }); let client = Client::builder() .keep_alive(false) .build(DebugConnector::with_http_and_closes(HttpConnector::new(1), closes_tx)); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }); let rx = rx1.expect("thread panicked"); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); let t = Delay::new(Instant::now() + Duration::from_millis(100)) .map(|_| panic!("time out")); let close = closes .into_future() .map(|(opt, _)| opt.expect("closes")); let _ = rt.block_on(future::select(t, close)); } #[test] fn socket_disconnect_closes_idle_conn() { // notably when keep-alive is enabled let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); let _ = tx1.send(()); }); let client = Client::builder() .build(DebugConnector::with_http_and_closes(HttpConnector::new(1), closes_tx)); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }); let rx = rx1.expect("thread panicked"); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); let t = Delay::new(Instant::now() + Duration::from_millis(100)) .map(|_| panic!("time out")); let close = closes .into_future() .map(|(opt, _)| opt.expect("closes")); let _ = rt.block_on(future::select(t, close)); } #[test] fn connect_call_is_lazy() { // We especially don't want connects() triggered if there's // idle connections that the Checkout would have found let _ = pretty_env_logger::try_init(); let _rt = Runtime::new().unwrap(); let connector = DebugConnector::new(); let connects = connector.connects.clone(); let client = Client::builder() .build(connector); assert_eq!(connects.load(Ordering::Relaxed), 0); let req = Request::builder() .uri("http://hyper.local/a") .body(Body::empty()) .unwrap(); let _fut = client.request(req); // internal Connect::connect should have been lazy, and not // triggered an actual connect yet. assert_eq!(connects.load(Ordering::Relaxed), 0); } #[test] fn client_keep_alive_0() { let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let connector = DebugConnector::new(); let connects = connector.connects.clone(); let client = Client::builder() .build(connector); let (tx1, rx1) = oneshot::channel(); let (tx2, rx2) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; //drop(server); sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 1"); let _ = tx1.send(()); let n2 = sock.read(&mut buf).expect("read 2"); assert_ne!(n2, 0); let second_get = "GET /b HTTP/1.1\r\n"; assert_eq!(s(&buf[..second_get.len()]), second_get); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 2"); let _ = tx2.send(()); }); assert_eq!(connects.load(Ordering::SeqCst), 0); let rx = rx1.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); assert_eq!(connects.load(Ordering::SeqCst), 1); // sleep real quick to let the threadpool put connection in ready // state and back into client pool thread::sleep(Duration::from_millis(50)); let rx = rx2.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/b", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); assert_eq!(connects.load(Ordering::SeqCst), 1, "second request should still only have 1 connect"); drop(client); } #[test] fn client_keep_alive_extra_body() { let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let connector = DebugConnector::new(); let connects = connector.connects.clone(); let client = Client::builder() .build(connector); let (tx1, rx1) = oneshot::channel(); let (tx2, rx2) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello").expect("write 1"); // the body "hello", while ignored because its a HEAD request, should mean the connection // cannot be put back in the pool let _ = tx1.send(()); let mut sock2 = server.accept().unwrap().0; let n2 = sock2.read(&mut buf).expect("read 2"); assert_ne!(n2, 0); let second_get = "GET /b HTTP/1.1\r\n"; assert_eq!(s(&buf[..second_get.len()]), second_get); sock2.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 2"); let _ = tx2.send(()); }); assert_eq!(connects.load(Ordering::Relaxed), 0); let rx = rx1.expect("thread panicked"); let req = Request::builder() .method("HEAD") .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); assert_eq!(connects.load(Ordering::Relaxed), 1); let rx = rx2.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/b", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); assert_eq!(connects.load(Ordering::Relaxed), 2); } #[test] fn client_keep_alive_when_response_before_request_body_ends() { use tokio_timer::Delay; let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let connector = DebugConnector::new(); let connects = connector.connects.clone(); let client = Client::builder() .build(connector); let (tx1, rx1) = oneshot::channel(); let (tx2, rx2) = oneshot::channel(); let (tx3, rx3) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 1"); // after writing the response, THEN stream the body let _ = tx1.send(()); sock.read(&mut buf).expect("read 2"); let _ = tx2.send(()); let n2 = sock.read(&mut buf).expect("read 3"); assert_ne!(n2, 0); let second_get = "GET /b HTTP/1.1\r\n"; assert_eq!(s(&buf[..second_get.len()]), second_get); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 2"); let _ = tx3.send(()); }); assert_eq!(connects.load(Ordering::Relaxed), 0); let delayed_body = rx1 .then(|_| Delay::new(Instant::now() + Duration::from_millis(200))) .map(|_| Ok::<_, ()>("hello a")) .map_err(|_| -> hyper::Error { panic!("rx1") }) .into_stream(); let rx = rx2.expect("thread panicked"); let req = Request::builder() .method("POST") .uri(&*format!("http://{}/a", addr)) .body(Body::wrap_stream(delayed_body)) .unwrap(); let client2 = client.clone(); // req 1 let fut = future::join(client.request(req), rx) .then(|_| Delay::new(Instant::now() + Duration::from_millis(200))) // req 2 .then(move |()| { let rx = rx3.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/b", addr)) .body(Body::empty()) .unwrap(); future::join(client2.request(req), rx) .map(|r| r.0) }); rt.block_on(fut).unwrap(); assert_eq!(connects.load(Ordering::Relaxed), 1); } #[test] fn connect_proxy_sends_absolute_uri() { let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let connector = DebugConnector::new() .proxy(); let client = Client::builder() .build(connector); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; //drop(server); sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; let n = sock.read(&mut buf).expect("read 1"); let expected = format!("GET http://{addr}/foo/bar HTTP/1.1\r\nhost: {addr}\r\n\r\n", addr=addr); assert_eq!(s(&buf[..n]), expected); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 1"); let _ = tx1.send(()); }); let rx = rx1.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/foo/bar", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); } #[test] fn connect_proxy_http_connect_sends_authority_form() { let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let connector = DebugConnector::new() .proxy(); let client = Client::builder() .build(connector); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; //drop(server); sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; let n = sock.read(&mut buf).expect("read 1"); let expected = format!("CONNECT {addr} HTTP/1.1\r\nhost: {addr}\r\n\r\n", addr=addr); assert_eq!(s(&buf[..n]), expected); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 1"); let _ = tx1.send(()); }); let rx = rx1.expect("thread panicked"); let req = Request::builder() .method("CONNECT") .uri(&*format!("http://{}/useless/path", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); } #[test] fn client_upgrade() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let connector = DebugConnector::new(); let client = Client::builder() .build(connector); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"\ HTTP/1.1 101 Switching Protocols\r\n\ Upgrade: foobar\r\n\ \r\n\ foobar=ready\ ").unwrap(); let _ = tx1.send(()); let n = sock.read(&mut buf).expect("read 2"); assert_eq!(&buf[..n], b"foo=bar"); sock.write_all(b"bar=foo").expect("write 2"); }); let rx = rx1.expect("thread panicked"); let req = Request::builder() .method("GET") .uri(&*format!("http://{}/up", addr)) .body(Body::empty()) .unwrap(); let res = client.request(req); let res = rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); assert_eq!(res.status(), 101); let upgraded = rt.block_on(res .into_body() .on_upgrade()) .expect("on_upgrade"); let parts = upgraded.downcast::<DebugStream>().unwrap(); assert_eq!(s(&parts.read_buf), "foobar=ready"); let mut io = parts.io; rt.block_on(io.write_all(b"foo=bar")).unwrap(); let mut vec = vec![]; rt.block_on(io.read_to_end(&mut vec)).unwrap(); assert_eq!(vec, b"bar=foo"); } /*#[test] fn alpn_h2() { use hyper::Response; use hyper::server::conn::Http; use hyper::service::service_fn; let _ = pretty_env_logger::try_init(); let mut rt = Runtime::new().unwrap(); let listener = TkTcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); let addr = listener.local_addr().unwrap(); let mut connector = DebugConnector::new(); connector.alpn_h2 = true; let connects = connector.connects.clone(); let client = Client::builder() .build::<_, ::hyper::Body>(connector); let srv = listener.incoming() .try_next() .map_err(|_| unreachable!()) .and_then(|item| { let socket = item.unwrap(); Http::new() .http2_only(true) .serve_connection(socket, service_fn(|req| async move { assert_eq!(req.headers().get("host"), None); Ok(Response::new(Body::empty())) })) }) .map_err(|e| panic!("server error: {}", e)); rt.block_on(srv).unwrap(); assert_eq!(connects.load(Ordering::SeqCst), 0); let url = format!("http://{}/a", addr).parse::<::hyper::Uri>().unwrap(); let res1 = client.get(url.clone()); let res2 = client.get(url.clone()); let res3 = client.get(url.clone()); rt.block_on(try_future::try_join3(res1, res2, res3)).unwrap(); // Since the client doesn't know it can ALPN at first, it will have // started 3 connections. But, the server above will only handle 1, // so the unwrapped responses futures show it still worked. assert_eq!(connects.load(Ordering::SeqCst), 3); let res4 = client.get(url.clone()); rt.block_on(res4).unwrap(); assert_eq!(connects.load(Ordering::SeqCst), 3, "after ALPN, no more connects"); drop(client); }*/ struct DebugConnector { http: HttpConnector, closes: mpsc::Sender<()>, connects: Arc<AtomicUsize>, is_proxy: bool, alpn_h2: bool, } impl DebugConnector { fn new() -> DebugConnector { let http = HttpConnector::new(1); let (tx, _) = mpsc::channel(10); DebugConnector::with_http_and_closes(http, tx) } fn with_http_and_closes(http: HttpConnector, closes: mpsc::Sender<()>) -> DebugConnector { DebugConnector { http: http, closes: closes, connects: Arc::new(AtomicUsize::new(0)), is_proxy: false, alpn_h2: false, } } fn proxy(mut self) -> Self { self.is_proxy = true; self } } impl Connect for DebugConnector { type Transport = DebugStream; type Error = io::Error; type Future = Pin<Box<dyn Future< Output = Result<(DebugStream, Connected), io::Error> > + Send>>; fn connect(&self, dst: Destination) -> Self::Future { self.connects.fetch_add(1, Ordering::SeqCst); let closes = self.closes.clone(); let is_proxy = self.is_proxy; let is_alpn_h2 = self.alpn_h2; Box::pin(self.http.connect(dst).map_ok(move |(s, mut c)| { if is_alpn_h2 { c = c.negotiated_h2(); } (DebugStream(s, closes), c.proxy(is_proxy)) })) } } struct DebugStream(TcpStream, mpsc::Sender<()>); impl Drop for DebugStream { fn drop(&mut self) { let _ = self.1.try_send(()); } } impl AsyncWrite for DebugStream { fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { Pin::new(&mut self.0).poll_shutdown(cx) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { Pin::new(&mut self.0).poll_flush(cx) } fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { Pin::new(&mut self.0).poll_write(cx, buf) } } impl AsyncRead for DebugStream { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<Result<usize, io::Error>> { Pin::new(&mut self.0).poll_read(cx, buf) } } } mod conn { use std::io::{self, Read, Write}; use std::net::TcpListener; use std::pin::Pin; use std::task::{Context, Poll}; use std::thread; use std::time::{Duration, Instant}; use futures_channel::oneshot; use futures_util::future::{self, poll_fn, FutureExt}; use futures_util::try_future::TryFutureExt; use futures_util::try_stream::TryStreamExt; use tokio::runtime::current_thread::Runtime; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_tcp::TcpStream; use tokio_timer::Delay; use hyper::{self, Request, Body, Method}; use hyper::client::conn; use super::{s, tcp_connect, FutureHyperExt}; #[test] fn get() { let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; let n = sock.read(&mut buf).expect("read 1"); // Notably: // - Just a path, since just a path was set // - No host, since no host was set let expected = "GET /a HTTP/1.1\r\n\r\n"; assert_eq!(s(&buf[..n]), expected); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); let _ = tx1.send(()); }); let tcp = rt.block_on(tcp_connect(&addr)).unwrap(); let (mut client, conn) = rt.block_on(conn::handshake(tcp)).unwrap(); rt.spawn(conn.map_err(|e| panic!("conn error: {}", e)).map(|_| ())); let req = Request::builder() .uri("/a") .body(Default::default()) .unwrap(); let res = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }); let rx = rx1.expect("thread panicked"); let rx = rx.then(|_| Delay::new(Instant::now() + Duration::from_millis(200))); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); } #[test] fn incoming_content_length() { use hyper::body::Payload; let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; let n = sock.read(&mut buf).expect("read 1"); let expected = "GET / HTTP/1.1\r\n\r\n"; assert_eq!(s(&buf[..n]), expected); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello").unwrap(); let _ = tx1.send(()); }); let tcp = rt.block_on(tcp_connect(&addr)).unwrap(); let (mut client, conn) = rt.block_on(conn::handshake(tcp)).unwrap(); rt.spawn(conn.map_err(|e| panic!("conn error: {}", e)).map(|_| ())); let req = Request::builder() .uri("/") .body(Default::default()) .unwrap(); let res = client.send_request(req).and_then(move |mut res| { assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.body().content_length(), Some(5)); assert!(!res.body().is_end_stream()); poll_fn(move |ctx| Pin::new(res.body_mut()).poll_data(ctx)).map(Option::unwrap) }); let rx = rx1.expect("thread panicked"); let rx = rx.then(|_| Delay::new(Instant::now() + Duration::from_millis(200))); let chunk = rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); assert_eq!(chunk.len(), 5); } #[test] fn aborted_body_isnt_completed() { let _ = ::pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (tx, rx) = oneshot::channel(); let server = thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let expected = "POST / HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n5\r\nhello\r\n"; let mut buf = vec![0; expected.len()]; sock.read_exact(&mut buf).expect("read 1"); assert_eq!(s(&buf), expected); let _ = tx.send(()); assert_eq!(sock.read(&mut buf).expect("read 2"), 0); }); let tcp = rt.block_on(tcp_connect(&addr)).unwrap(); let (mut client, conn) = rt.block_on(conn::handshake(tcp)).unwrap(); rt.spawn(conn.map_err(|e| panic!("conn error: {}", e)).map(|_| ())); let (mut sender, body) = Body::channel(); let sender = thread::spawn(move || { sender.send_data("hello".into()).ok().unwrap(); Runtime::new().unwrap().block_on(rx).unwrap(); sender.abort(); }); let req = Request::builder() .method(Method::POST) .uri("/") .body(body) .unwrap(); let res = client.send_request(req); rt.block_on(res).unwrap_err(); server.join().expect("server thread panicked"); sender.join().expect("sender thread panicked"); } #[test] fn uri_absolute_form() { let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; let n = sock.read(&mut buf).expect("read 1"); // Notably: // - Still no Host header, since it wasn't set let expected = "GET http://hyper.local/a HTTP/1.1\r\n\r\n"; assert_eq!(s(&buf[..n]), expected); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); let _ = tx1.send(()); }); let tcp = rt.block_on(tcp_connect(&addr)).unwrap(); let (mut client, conn) = rt.block_on(conn::handshake(tcp)).unwrap(); rt.spawn(conn.map_err(|e| panic!("conn error: {}", e)).map(|_| ())); let req = Request::builder() .uri("http://hyper.local/a") .body(Default::default()) .unwrap(); let res = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }); let rx = rx1.expect("thread panicked"); let rx = rx.then(|_| Delay::new(Instant::now() + Duration::from_millis(200))); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); } #[test] fn http1_conn_coerces_http2_request() { let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; let n = sock.read(&mut buf).expect("read 1"); // Not HTTP/2, nor panicked let expected = "GET /a HTTP/1.1\r\n\r\n"; assert_eq!(s(&buf[..n]), expected); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); let _ = tx1.send(()); }); let tcp = rt.block_on(tcp_connect(&addr)).unwrap(); let (mut client, conn) = rt.block_on(conn::handshake(tcp)).unwrap(); rt.spawn(conn.map_err(|e| panic!("conn error: {}", e)).map(|_| ())); let req = Request::builder() .uri("/a") .version(hyper::Version::HTTP_2) .body(Default::default()) .unwrap(); let res = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }); let rx = rx1.expect("thread panicked"); let rx = rx.then(|_| Delay::new(Instant::now() + Duration::from_millis(200))); rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); } #[test] fn pipeline() { let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); let _ = tx1.send(Ok::<_, ()>(())); }); let tcp = rt.block_on(tcp_connect(&addr)).unwrap(); let (mut client, conn) = rt.block_on(conn::handshake(tcp)).unwrap(); rt.spawn(conn.map_err(|e| panic!("conn error: {}", e)).map(|_| ())); let req = Request::builder() .uri("/a") .body(Default::default()) .unwrap(); let res1 = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }); // pipelined request will hit NotReady, and thus should return an Error::Cancel let req = Request::builder() .uri("/b") .body(Default::default()) .unwrap(); let res2 = client .send_request(req) .map(|result| { let err = result.expect_err("res2"); assert!(err.is_canceled(), "err not canceled, {:?}", err); Ok::<_, ()>(()) }); let rx = rx1.expect("thread panicked"); let rx = rx.then(|_| Delay::new(Instant::now() + Duration::from_millis(200))); rt.block_on(future::join3(res1, res2, rx).map(|r| r.0)).unwrap(); } #[test] fn upgrade() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let _ = ::pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"\ HTTP/1.1 101 Switching Protocols\r\n\ Upgrade: foobar\r\n\ \r\n\ foobar=ready\ ").unwrap(); let _ = tx1.send(()); let n = sock.read(&mut buf).expect("read 2"); assert_eq!(&buf[..n], b"foo=bar"); sock.write_all(b"bar=foo").expect("write 2"); }); let tcp = rt.block_on(tcp_connect(&addr)).unwrap(); let io = DebugStream { tcp: tcp, shutdown_called: false, }; let (mut client, mut conn) = rt.block_on(conn::handshake(io)).unwrap(); { let until_upgrade = poll_fn(|ctx| { conn.poll_without_shutdown(ctx) }); let req = Request::builder() .uri("/a") .body(Default::default()) .unwrap(); let res = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::SWITCHING_PROTOCOLS); assert_eq!(res.headers()["Upgrade"], "foobar"); res.into_body().try_concat() }); let rx = rx1.expect("thread panicked"); let rx = rx.then(|_| Delay::new(Instant::now() + Duration::from_millis(200))); rt.block_on(future::join3(until_upgrade, res, rx).map(|r| r.0)).unwrap(); // should not be ready now rt.block_on(poll_fn(|ctx| { assert!(client.poll_ready(ctx).is_pending()); Poll::Ready(Ok::<_, ()>(())) })).unwrap(); } let parts = conn.into_parts(); let mut io = parts.io; let buf = parts.read_buf; assert_eq!(buf, b"foobar=ready"[..]); assert!(!io.shutdown_called, "upgrade shouldn't shutdown AsyncWrite"); rt.block_on(poll_fn(|ctx| { let ready = client.poll_ready(ctx); assert_matches!(ready, Poll::Ready(Err(_))); ready })).unwrap_err(); let mut vec = vec![]; rt.block_on(io.write_all(b"foo=bar")).unwrap(); rt.block_on(io.read_to_end(&mut vec)).unwrap(); assert_eq!(vec, b"bar=foo"); } #[test] fn connect_method() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let _ = ::pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut rt = Runtime::new().unwrap(); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { let mut sock = server.accept().unwrap().0; sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"\ HTTP/1.1 200 OK\r\n\ \r\n\ foobar=ready\ ").unwrap(); let _ = tx1.send(Ok::<_, ()>(())); let n = sock.read(&mut buf).expect("read 2"); assert_eq!(&buf[..n], b"foo=bar", "sock read 2 bytes"); sock.write_all(b"bar=foo").expect("write 2"); }); let tcp = rt.block_on(tcp_connect(&addr)).unwrap(); let io = DebugStream { tcp: tcp, shutdown_called: false, }; let (mut client, mut conn) = rt.block_on(conn::handshake(io)).unwrap(); { let until_tunneled = poll_fn(|ctx| { conn.poll_without_shutdown(ctx) }); let req = Request::builder() .method("CONNECT") .uri(addr.to_string()) .body(Default::default()) .unwrap(); let res = client .send_request(req) .and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().try_concat() }) .map_ok(|body| { assert_eq!(body.as_ref(), b""); }); let rx = rx1.expect("thread panicked"); let rx = rx.then(|_| Delay::new(Instant::now() + Duration::from_millis(200))); rt.block_on(future::join3(until_tunneled, res, rx).map(|r| r.0)).unwrap(); // should not be ready now rt.block_on(poll_fn(|ctx| { assert!(client.poll_ready(ctx).is_pending()); Poll::Ready(Ok::<_, ()>(())) })).unwrap(); } let parts = conn.into_parts(); let mut io = parts.io; let buf = parts.read_buf; assert_eq!(buf, b"foobar=ready"[..]); assert!(!io.shutdown_called, "tunnel shouldn't shutdown AsyncWrite"); rt.block_on(poll_fn(|ctx| { let ready = client.poll_ready(ctx); assert_matches!(ready, Poll::Ready(Err(_))); ready })).unwrap_err(); let mut vec = vec![]; rt.block_on(io.write_all(b"foo=bar")).unwrap(); rt.block_on(io.read_to_end(&mut vec)).unwrap(); assert_eq!(vec, b"bar=foo"); } // DISABLED // #[test] /*fn http2_detect_conn_eof() { use futures_util::future; use hyper::{Response, Server}; use hyper::service::service_fn; use tokio::timer::Delay; let _ = pretty_env_logger::try_init(); let mut rt = Runtime::new().unwrap(); let server = Server::bind(&([127, 0, 0, 1], 0).into()) .http2_only(true) .serve(|| service_fn(|_req| { Ok(Response::new(Body::empty())) })); let addr = server.local_addr(); let (shdn_tx, shdn_rx) = oneshot::channel(); rt.spawn(server.with_graceful_shutdown(shdn_rx).map_err(|e| panic!("server error: {:?}", e))); let io = rt.block_on(tcp_connect(&addr)).expect("tcp connect"); let (mut client, conn) = rt.block_on( conn::Builder::new().http2_only(true).handshake::<_, Body>(io) ).expect("http handshake"); rt.spawn(conn.map_err(|e| panic!("client conn error: {:?}", e))); // Sanity check that client is ready rt.block_on(future::poll_fn(|ctx| client.poll_ready(ctx))).expect("client poll ready sanity"); let req = Request::builder() .uri(format!("http://{}/", addr)) .body(Body::empty()) .expect("request builder"); rt.block_on(client.send_request(req)).expect("req1 send"); // Sanity check that client is STILL ready rt.block_on(future::poll_fn(|ctx| client.poll_ready(ctx))).expect("client poll ready after"); // Trigger the server shutdown... let _ = shdn_tx.send(()); // Allow time for graceful shutdown roundtrips... rt.block_on(Delay::new(::std::time::Instant::now() + Duration::from_millis(100)).map_err(|e| panic!("delay error: {:?}", e))).expect("delay"); // After graceful shutdown roundtrips, the client should be closed... rt.block_on(future::poll_fn(|ctx| client.poll_ready(ctx))).expect_err("client should be closed"); }*/ struct DebugStream { tcp: TcpStream, shutdown_called: bool, } /*impl Write for DebugStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.tcp.write(buf) } fn flush(&mut self) -> io::Result<()> { self.tcp.flush() } }*/ impl AsyncWrite for DebugStream { fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { self.shutdown_called = true; Pin::new(&mut self.tcp).poll_shutdown(cx) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { Pin::new(&mut self.tcp).poll_flush(cx) } fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { Pin::new(&mut self.tcp).poll_write(cx, buf) } } impl AsyncRead for DebugStream { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<Result<usize, io::Error>> { Pin::new(&mut self.tcp).poll_read(cx, buf) } } } trait FutureHyperExt: TryFuture { fn expect(self, msg: &'static str) -> Pin<Box<dyn Future<Output=Self::Ok>>>; } impl<F> FutureHyperExt for F where F: TryFuture + 'static, F::Error: ::std::fmt::Debug, { fn expect(self, msg: &'static str) -> Pin<Box<dyn Future<Output=Self::Ok>>> { Box::pin(self .inspect_err(move |e| panic!("expect: {}; error={:?}", msg, e)) .map(Result::unwrap)) } }
32.437953
150
0.509669
bbd97ab2a53ab360b65cf20b5a9a0b52e1693dcc
5,499
use std::{fmt, iter::Sum}; use num::Zero; use casper_types::U512; use crate::shared::motes::Motes; #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub struct Gas(U512); impl Gas { pub fn new(value: U512) -> Self { Gas(value) } pub fn value(&self) -> U512 { self.0 } pub fn from_motes(motes: Motes, conv_rate: u64) -> Option<Self> { motes .value() .checked_div(U512::from(conv_rate)) .map(Self::new) } pub fn checked_add(&self, rhs: Self) -> Option<Self> { self.0.checked_add(rhs.value()).map(Self::new) } } impl fmt::Display for Gas { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.0) } } impl std::ops::Add for Gas { type Output = Gas; fn add(self, rhs: Self) -> Self::Output { let val = self.value() + rhs.value(); Gas::new(val) } } impl std::ops::Sub for Gas { type Output = Gas; fn sub(self, rhs: Self) -> Self::Output { let val = self.value() - rhs.value(); Gas::new(val) } } impl std::ops::Div for Gas { type Output = Gas; fn div(self, rhs: Self) -> Self::Output { let val = self.value() / rhs.value(); Gas::new(val) } } impl std::ops::Mul for Gas { type Output = Gas; fn mul(self, rhs: Self) -> Self::Output { let val = self.value() * rhs.value(); Gas::new(val) } } impl std::ops::AddAssign for Gas { fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0 } } impl Zero for Gas { fn zero() -> Self { Gas::new(U512::zero()) } fn is_zero(&self) -> bool { self.0.is_zero() } } impl Sum for Gas { fn sum<I: Iterator<Item = Self>>(iter: I) -> Self { iter.fold(Gas::zero(), std::ops::Add::add) } } impl From<u32> for Gas { fn from(gas: u32) -> Self { let gas_u512: U512 = gas.into(); Gas::new(gas_u512) } } #[cfg(test)] mod tests { use casper_types::U512; use crate::shared::{gas::Gas, motes::Motes}; #[test] fn should_be_able_to_get_instance_of_gas() { let initial_value = 1; let gas = Gas::new(U512::from(initial_value)); assert_eq!( initial_value, gas.value().as_u64(), "should have equal value" ) } #[test] fn should_be_able_to_compare_two_instances_of_gas() { let left_gas = Gas::new(U512::from(1)); let right_gas = Gas::new(U512::from(1)); assert_eq!(left_gas, right_gas, "should be equal"); let right_gas = Gas::new(U512::from(2)); assert_ne!(left_gas, right_gas, "should not be equal") } #[test] fn should_be_able_to_add_two_instances_of_gas() { let left_gas = Gas::new(U512::from(1)); let right_gas = Gas::new(U512::from(1)); let expected_gas = Gas::new(U512::from(2)); assert_eq!((left_gas + right_gas), expected_gas, "should be equal") } #[test] fn should_be_able_to_subtract_two_instances_of_gas() { let left_gas = Gas::new(U512::from(1)); let right_gas = Gas::new(U512::from(1)); let expected_gas = Gas::new(U512::from(0)); assert_eq!((left_gas - right_gas), expected_gas, "should be equal") } #[test] fn should_be_able_to_multiply_two_instances_of_gas() { let left_gas = Gas::new(U512::from(100)); let right_gas = Gas::new(U512::from(10)); let expected_gas = Gas::new(U512::from(1000)); assert_eq!((left_gas * right_gas), expected_gas, "should be equal") } #[test] fn should_be_able_to_divide_two_instances_of_gas() { let left_gas = Gas::new(U512::from(1000)); let right_gas = Gas::new(U512::from(100)); let expected_gas = Gas::new(U512::from(10)); assert_eq!((left_gas / right_gas), expected_gas, "should be equal") } #[test] fn should_be_able_to_convert_from_mote() { let mote = Motes::new(U512::from(100)); let gas = Gas::from_motes(mote, 10).expect("should have gas"); let expected_gas = Gas::new(U512::from(10)); assert_eq!(gas, expected_gas, "should be equal") } #[test] fn should_be_able_to_default() { let gas = Gas::default(); let expected_gas = Gas::new(U512::from(0)); assert_eq!(gas, expected_gas, "should be equal") } #[test] fn should_be_able_to_compare_relative_value() { let left_gas = Gas::new(U512::from(100)); let right_gas = Gas::new(U512::from(10)); assert!(left_gas > right_gas, "should be gt"); let right_gas = Gas::new(U512::from(100)); assert!(left_gas >= right_gas, "should be gte"); assert!(left_gas <= right_gas, "should be lte"); let left_gas = Gas::new(U512::from(10)); assert!(left_gas < right_gas, "should be lt"); } #[test] fn should_default() { let left_gas = Gas::new(U512::from(0)); let right_gas = Gas::default(); assert_eq!(left_gas, right_gas, "should be equal"); let u512 = U512::zero(); assert_eq!(left_gas.value(), u512, "should be equal"); } #[test] fn should_support_checked_div_from_motes() { let motes = Motes::new(U512::zero()); let conv_rate = 0; let maybe = Gas::from_motes(motes, conv_rate); assert!(maybe.is_none(), "should be none due to divide by zero"); } }
26.694175
75
0.571013
879f37427f82d0b82d3d0b4f11bb54a67ec9ad5d
106
//! Map alias. use std::collections::BTreeMap; /// Map alias type. pub type Map<T, S> = BTreeMap<T, S>;
15.142857
36
0.632075
22cd2228df4f3ff31330e7b7ddb94ca6fe5568f0
1,046
use graphql_client::Response; use seed::prelude::fetch; use serde::{Deserialize, Serialize}; use super::ErrorPayload; use crate::operations::authentication; pub struct AttemptLoginPayload { pub username: String, pub password: String, } pub struct LoginSuccessPayload { pub username: String, pub token: String, } pub struct RegisterPayload { pub username: String, pub password: String, } #[derive(Deserialize, Serialize)] pub struct AuthenticationRequestBody { pub password: String, pub username: String, } #[derive(Deserialize, Serialize)] pub struct AuthenticationResponseBody { pub token: String, } pub enum AuthMsg { AttemptLogin(AttemptLoginPayload), AttemptLoginFetched(String, fetch::Result<AuthenticationResponseBody>), LoginFailed(ErrorPayload), LoginSuccess(LoginSuccessPayload), Logout, Register(RegisterPayload), RegistrationFetched(fetch::Result<Response<authentication::register::ResponseData>>), RegistrationFailed(ErrorPayload), RegistrationSuccess, }
23.244444
89
0.748566
ed982accc0b25979dfee1d592f1519fd1e23ee92
601
//! Re-exports for low-level, efficient APIs. //! //! In order for high-performance processing of large documents, //! We must use parsers that lazily read and write items to and from //! documents. The writers accept both by-value and by-reference //! iterators, allowing you to easily chain lazy readers and writers //! to convert between export formats. //! //! The memory footprint of these lazy low-level functions is minimal, //! typically < 16 KB required for internal buffers, and < 1 KB for each //! individual item. #[cfg(feature = "fastq")] pub use super::fastq::*; pub use super::re::*;
35.352941
72
0.72213
904534112acbb70d1ac8991a6b0500d199ad2ba0
60
mod user; mod post; pub use post::Post; pub use user::User;
12
19
0.7
285db7aada879d1b38258b4324bc183d12c39d76
1,381
#[doc = "Reader of register SCMPR0"] pub type R = crate::R<u32, super::SCMPR0>; #[doc = "Writer for register SCMPR0"] pub type W = crate::W<u32, super::SCMPR0>; #[doc = "Register SCMPR0 `reset()`'s with value 0"] impl crate::ResetValue for super::SCMPR0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `VALUE`"] pub type VALUE_R = crate::R<u32, u32>; #[doc = "Write proxy for field `VALUE`"] pub struct VALUE_W<'a> { w: &'a mut W, } impl<'a> VALUE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - Compare this value to the value in the COUNTER register according to the match criterion, as selected in the COMPARE_A_EN bit in the REG_CTIMER_STCGF register."] #[inline(always)] pub fn value(&self) -> VALUE_R { VALUE_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - Compare this value to the value in the COUNTER register according to the match criterion, as selected in the COMPARE_A_EN bit in the REG_CTIMER_STCGF register."] #[inline(always)] pub fn value(&mut self) -> VALUE_W { VALUE_W { w: self } } }
33.682927
186
0.625634
099cdc5ca51d40c7b8d47f6d021d8ed8c4141f6f
448
use std::collections::HashMap; impl Solution { pub fn longest_palindrome(s: String) -> i32 { let mut map = HashMap::new(); for c in s.chars() { *map.entry(c).or_insert(0) += 1; } let mut has_odd = 0; let mut ans = 0; for v in map.values() { if *v % 2 != 0 { has_odd = 1; } ans += v / 2 * 2; } ans + has_odd } }
22.4
49
0.419643
29eea394d4584f99ac8a86a2657689588192d31a
15,757
#![allow(dead_code)] use crate::reference_tables; use crate::structs::*; use crate::transformation::TransformationMatrix; use doc_cfg::doc_cfg; #[cfg(feature = "rayon")] use rayon::prelude::*; use std::cmp::Ordering; use std::fmt; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, Clone, PartialEq, Eq)] /// A Conformer containing multiple atoms, analogous to `atom_group` in cctbx pub struct Conformer { /// The name of this Conformer name: String, /// The alternative location of this Conformer, None is blank alternative_location: Option<String>, /// The list of atoms making up this Conformer atoms: Vec<Atom>, /// The modification, if present modification: Option<(String, String)>, } impl Conformer { /// Create a new Conformer /// /// ## Arguments /// * `name` - the name /// * `alt_loc` - the alternative location identifier, if not blank /// * `atom` - if available it can already add an atom /// /// ## Fails /// It fails and returns `None` if any of the characters making up the name are invalid. #[must_use] pub fn new( name: impl AsRef<str>, alt_loc: Option<&str>, atom: Option<Atom>, ) -> Option<Conformer> { prepare_identifier(name).map(|n| { let mut res = Conformer { name: n, alternative_location: None, atoms: Vec::new(), modification: None, }; if let Some(al) = alt_loc { res.alternative_location = prepare_identifier(al); } if let Some(a) = atom { res.atoms.push(a); } res }) } /// Get the name of the Conformer pub fn name(&self) -> &str { &self.name } /// Set the name of the Conformer. /// /// ## Fails /// It fails if any of the characters of the new name are invalid. pub fn set_name(&mut self, new_name: impl AsRef<str>) -> bool { prepare_identifier(new_name) .map(|n| self.name = n) .is_some() } /// Get the alternative location of the Conformer, if present. pub fn alternative_location(&self) -> Option<&str> { self.alternative_location.as_deref() } /// Set the alternative location of the Conformer. /// /// ## Fails /// It fails if any of the characters of the new alternative location are invalid. pub fn set_alternative_location(&mut self, new_loc: &str) -> bool { if let Some(l) = prepare_identifier(new_loc) { self.alternative_location = Some(l); true } else { false } } /// Set the alternative location of the Conformer to `None`. pub fn remove_alternative_location(&mut self) { self.alternative_location = None; } /// Returns the uniquely identifying construct for this Conformer. /// It consists of the name and alternative location. pub fn id(&self) -> (&str, Option<&str>) { (&self.name, self.alternative_location()) } /// Get the modification of this Conformer e.g., chemical or post-translational. These is saved in the MODRES records in the PDB file. pub const fn modification(&self) -> Option<&(String, String)> { self.modification.as_ref() } /// Set the modification of this Conformer e.g., chemical or post-translational. These will be saved in the MODRES records in the PDB file. /// # Errors /// It fails if the conformer name or comment has invalid characters. pub fn set_modification(&mut self, new_modification: (String, String)) -> Result<(), String> { if !valid_identifier(&new_modification.0) { Err(format!( "New modification has invalid characters for standard conformer name, conformer: {:?}, standard name \"{}\"", self.id(), new_modification.0 )) } else if !valid_text(&new_modification.1) { Err(format!( "New modification has invalid characters in the comment, conformer: {:?}, comment \"{}\"", self.id(), new_modification.1 )) } else { self.modification = Some(new_modification); Ok(()) } } /// The number of atoms making up this Conformer pub fn atom_count(&self) -> usize { self.atoms.len() } /// Get a specific atom from the list of atoms making up this Conformer. /// /// ## Arguments /// * `index` - the index of the atom /// /// ## Fails /// It returns `None` if the index is out of bounds. pub fn atom(&self, index: usize) -> Option<&Atom> { self.atoms.get(index) } /// Get a specific atom as a mutable reference from list of atoms making up this Conformer. /// /// ## Arguments /// * `index` - the index of the atom /// /// ## Fails /// It returns `None` if the index is out of bounds. pub fn atom_mut(&mut self, index: usize) -> Option<&mut Atom> { self.atoms.get_mut(index) } /// Get a reference to the specified atom which is unique within a single conformer. /// The algorithm is based on binary search so it is faster than an exhaustive search, but the /// underlying vector is assumed to be sorted. This assumption can be enforced /// by using `conformer.sort()`. pub fn binary_find_atom(&self, serial_number: usize) -> Option<&Atom> { if let Ok(i) = self .atoms .binary_search_by(|a| a.serial_number().cmp(&serial_number)) { unsafe { Some(self.atoms.get_unchecked(i)) } } else { None } } /// Get a mutable reference to the specified atom which is unique within a single conformer. /// The algorithm is based on binary search so it is faster than an exhaustive search, but the /// underlying vector is assumed to be sorted. This assumption can be enforced /// by using `conformer.sort()`. pub fn binary_find_atom_mut(&mut self, serial_number: usize) -> Option<&mut Atom> { if let Ok(i) = self .atoms .binary_search_by(|a| a.serial_number().cmp(&serial_number)) { unsafe { Some(self.atoms.get_unchecked_mut(i)) } } else { None } } /// Find all atoms matching the given information pub fn find(&self, search: Search) -> impl DoubleEndedIterator<Item = &Atom> + '_ { self.atoms() .filter(move |a| search.add_atom_info(a).complete().unwrap_or(true)) } /// Find all atoms matching the given information pub fn find_mut(&mut self, search: Search) -> impl DoubleEndedIterator<Item = &mut Atom> + '_ { self.atoms_mut() .filter(move |a| search.add_atom_info(a).complete().unwrap_or(true)) } /// Get an iterator of references to Atoms making up this Conformer. /// Double ended so iterating from the end is just as fast as from the start. pub fn atoms(&self) -> impl DoubleEndedIterator<Item = &Atom> + '_ { self.atoms.iter() } /// Get a parallel iterator of references to Atoms making up this Conformer. #[doc_cfg(feature = "rayon")] pub fn par_atoms(&self) -> impl ParallelIterator<Item = &Atom> + '_ { self.atoms.par_iter() } /// Get an iterator of mutable references to Atoms making up this Conformer. /// Double ended so iterating from the end is just as fast as from the start. pub fn atoms_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Atom> + '_ { self.atoms.iter_mut() } /// Get a parallel iterator of mutable references to Atoms making up this Conformer. #[doc_cfg(feature = "rayon")] pub fn par_atoms_mut(&mut self) -> impl ParallelIterator<Item = &mut Atom> + '_ { self.atoms.par_iter_mut() } /// Add a new atom to the list of atoms making up this Conformer. /// ## Arguments /// * `new_atom` - the new Atom to add pub fn add_atom(&mut self, new_atom: Atom) { self.atoms.push(new_atom); } /// Returns whether this Conformer is an amino acid. pub fn is_amino_acid(&self) -> bool { reference_tables::get_amino_acid_number(self.name()).is_some() } /// Remove all Atoms matching the given predicate. As this is done in place this is the fastest way to remove Atoms from this Conformer. pub fn remove_atoms_by<F>(&mut self, predicate: F) where F: Fn(&Atom) -> bool, { self.atoms.retain(|atom| !predicate(atom)); } /// Remove the Atom specified. /// /// ## Arguments /// * `index` - the index of the atom to remove /// /// ## Panics /// Panics if the index is out of bounds. pub fn remove_atom(&mut self, index: usize) { self.atoms.remove(index); } /// Remove the specified Atom. Returns `true` if a matching Atom was found and removed. /// Removes the first matching Atom from the list. /// /// ## Arguments /// * `serial_number` - the serial number of the Atom to remove /// /// ## Panics /// Panics if the index is out of bounds. pub fn remove_atom_by_serial_number(&mut self, serial_number: usize) -> bool { let index = self .atoms() .position(|a| a.serial_number() == serial_number); if let Some(i) = index { self.remove_atom(i); true } else { false } } /// Remove the specified Atom. Returns `true` if a matching Atom was found and removed. /// Removes the first matching Atom from the list. Matching is done in parallel. /// /// ## Arguments /// * `serial_number` - the serial number of the Atom to remove /// /// ## Panics /// Panics if the index is out of bounds. #[doc_cfg(feature = "rayon")] pub fn par_remove_atom_by_serial_number(&mut self, serial_number: usize) -> bool { let index = self .atoms .par_iter() .position_first(|a| a.serial_number() == serial_number); if let Some(i) = index { self.remove_atom(i); true } else { false } } /// Remove the specified Atom. Returns `true` if a matching Atom was found and removed. /// Removes the first matching Atom from the list. /// /// ## Arguments /// * `name` - the name of the Atom to remove /// /// ## Panics /// Panics if the index is out of bounds. pub fn remove_atom_by_name(&mut self, name: impl AsRef<str>) -> bool { let name = name.as_ref(); let index = self.atoms().position(|a| a.name() == name); if let Some(i) = index { self.remove_atom(i); true } else { false } } /// Remove the specified Atom. Returns `true` if a matching Atom was found and removed. /// Removes the first matching Atom from the list. Matching is done in parallel. /// /// ## Arguments /// * `name` - the name of the Atom to remove /// /// ## Panics /// Panics if the index is out of bounds. #[doc_cfg(feature = "rayon")] pub fn par_remove_atom_by_name(&mut self, name: impl AsRef<str>) -> bool { let name = name.as_ref(); let index = self.atoms.par_iter().position_first(|a| a.name() == name); if let Some(i) = index { self.remove_atom(i); true } else { false } } /// Apply a transformation to the position of all atoms making up this Conformer, the new position is immediately set. pub fn apply_transformation(&mut self, transformation: &TransformationMatrix) { for atom in self.atoms_mut() { atom.apply_transformation(transformation); } } /// Apply a transformation to the position of all atoms making up this Conformer, the new position is immediately set. /// This is done in parallel. #[doc_cfg(feature = "rayon")] pub fn par_apply_transformation(&mut self, transformation: &TransformationMatrix) { self.par_atoms_mut() .for_each(|a| a.apply_transformation(transformation)); } /// Join this Conformer with another Conformer, this moves all atoms from the other Conformer /// to this Conformer. All other (meta) data of this Conformer will stay the same. pub fn join(&mut self, other: Conformer) { self.atoms.extend(other.atoms); } /// Extend the Atoms on this Conformer by the given iterator over Atoms. pub fn extend<T: IntoIterator<Item = Atom>>(&mut self, iter: T) { self.atoms.extend(iter); } /// Sort the Atoms of this Conformer. pub fn sort(&mut self) { self.atoms.sort(); } /// Sort the Atoms of this Conformer in parallel. #[doc_cfg(feature = "rayon")] pub fn par_sort(&mut self) { self.atoms.par_sort(); } } impl fmt::Display for Conformer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "CONFORMER ID:{:?}, Atoms:{}", self.id(), self.atoms.len(), ) } } impl PartialOrd for Conformer { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.id().cmp(&other.id())) } } impl Ord for Conformer { fn cmp(&self, other: &Self) -> Ordering { self.id().cmp(&other.id()) } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; #[test] fn test_text_validation() { let mut a = Conformer::new("A", None, None).unwrap(); assert_eq!(Conformer::new("R̊", None, None), None); assert!(!a.set_name("Oͦ")); assert_eq!(a.name(), "A"); a.set_name("atom"); assert_eq!(a.name(), "ATOM"); assert!(a.set_alternative_location("A")); assert!(!a.set_alternative_location("Aͦ")); assert_eq!(a.alternative_location(), Some("A")); assert!(a .set_modification(("ALA".to_string(), "Alanine".to_string())) .is_ok()); assert!(a .set_modification(("ALAͦ".to_string(), "Alanine".to_string())) .is_err()); assert!(a .set_modification(("ALA".to_string(), "Aͦlanine".to_string())) .is_err()); } #[test] fn ordering_and_equality() { let a = Conformer::new("A", None, None).unwrap(); let b = Conformer::new("A", None, None).unwrap(); let c = Conformer::new("B", None, None).unwrap(); assert_eq!(a, b); assert_ne!(a, c); assert!(a < c); assert!(b < c); } #[test] fn test_empty() { let a = Conformer::new("A", None, None).unwrap(); assert_eq!(a.modification(), None); assert_eq!(a.atom_count(), 0); } #[test] fn test_atom() { let mut a = Conformer::new("A", None, None).unwrap(); let mut atom1 = Atom::new(false, 12, "CB", 1.0, 1.0, 1.0, 1.0, 1.0, "C", 0).unwrap(); let atom2 = Atom::new(false, 13, "CB", 1.0, 1.0, 1.0, 1.0, 1.0, "C", 0).unwrap(); a.add_atom(atom1.clone()); a.add_atom(atom2.clone()); a.add_atom(atom2); assert_eq!(a.atom(0), Some(&atom1)); assert_eq!(a.atom_mut(0), Some(&mut atom1)); a.remove_atom(0); assert!(a.remove_atom_by_name("CB")); assert!(a.remove_atom_by_serial_number(13)); assert_eq!(a.atom_count(), 0); } #[test] fn check_display() { let a = Conformer::new("A", None, None).unwrap(); format!("{:?}", a); format!("{}", a); } }
33.740899
143
0.583169
2ff186f0719a4cddfb3d3741bd00f10c850e5f72
28,702
pub type c_char = u8; pub type wchar_t = u32; pub type stat64 = ::stat; s! { pub struct stat { pub st_dev: ::dev_t, pub st_ino: ::c_ulonglong, pub st_mode: ::c_uint, pub st_nlink: ::c_uint, pub st_uid: ::c_uint, pub st_gid: ::c_uint, pub st_rdev: ::c_ulonglong, __st_rdev_padding: ::c_ulong, pub st_size: ::c_longlong, pub st_blksize: ::blksize_t, __st_blksize_padding: ::c_int, pub st_blocks: ::blkcnt_t, pub st_atime: ::time_t, pub st_atime_nsec: ::c_long, pub st_mtime: ::time_t, pub st_mtime_nsec: ::c_long, pub st_ctime: ::time_t, pub st_ctime_nsec: ::c_long, __unused: [::c_int;2], } pub struct stack_t { pub ss_sp: *mut ::c_void, pub ss_flags: ::c_int, pub ss_size: ::size_t } pub struct ipc_perm { pub __ipc_perm_key: ::key_t, pub uid: ::uid_t, pub gid: ::gid_t, pub cuid: ::uid_t, pub cgid: ::gid_t, pub mode: ::mode_t, pub __seq: ::c_ushort, } pub struct shmid_ds { pub shm_perm: ::ipc_perm, pub shm_segsz: ::size_t, pub shm_atime: ::time_t, __unused1: ::c_int, pub shm_dtime: ::time_t, __unused2: ::c_int, pub shm_ctime: ::time_t, __unused3: ::c_int, pub shm_cpid: ::pid_t, pub shm_lpid: ::pid_t, pub shm_nattch: ::c_ulong, __pad1: ::c_ulong, __pad2: ::c_ulong, } pub struct msqid_ds { pub msg_perm: ::ipc_perm, pub msg_stime: ::time_t, __unused1: ::c_int, pub msg_rtime: ::time_t, __unused2: ::c_int, pub msg_ctime: ::time_t, __unused3: ::c_int, __msg_cbytes: ::c_ulong, pub msg_qnum: ::msgqnum_t, pub msg_qbytes: ::msglen_t, pub msg_lspid: ::pid_t, pub msg_lrpid: ::pid_t, __pad1: ::c_ulong, __pad2: ::c_ulong, } pub struct statfs { pub f_type: ::c_ulong, pub f_bsize: ::c_ulong, pub f_blocks: ::fsblkcnt_t, pub f_bfree: ::fsblkcnt_t, pub f_bavail: ::fsblkcnt_t, pub f_files: ::fsfilcnt_t, pub f_ffree: ::fsfilcnt_t, pub f_fsid: ::fsid_t, pub f_namelen: ::c_ulong, pub f_frsize: ::c_ulong, pub f_flags: ::c_ulong, pub f_spare: [::c_ulong; 4], } pub struct siginfo_t { pub si_signo: ::c_int, pub si_errno: ::c_int, pub si_code: ::c_int, pub _pad: [::c_int; 29], _align: [usize; 0], } pub struct statfs64 { pub f_type: ::c_ulong, pub f_bsize: ::c_ulong, pub f_blocks: ::fsblkcnt_t, pub f_bfree: ::fsblkcnt_t, pub f_bavail: ::fsblkcnt_t, pub f_files: ::fsfilcnt_t, pub f_ffree: ::fsfilcnt_t, pub f_fsid: ::fsid_t, pub f_namelen: ::c_ulong, pub f_frsize: ::c_ulong, pub f_flags: ::c_ulong, pub f_spare: [::c_ulong; 4], } pub struct statvfs64 { pub f_bsize: ::c_ulong, pub f_frsize: ::c_ulong, pub f_blocks: u64, pub f_bfree: u64, pub f_bavail: u64, pub f_files: u64, pub f_ffree: u64, pub f_favail: u64, pub f_fsid: ::c_ulong, __f_unused: ::c_int, pub f_flag: ::c_ulong, pub f_namemax: ::c_ulong, __f_spare: [::c_int; 6], } pub struct termios2 { pub c_iflag: ::tcflag_t, pub c_oflag: ::tcflag_t, pub c_cflag: ::tcflag_t, pub c_lflag: ::tcflag_t, pub c_line: ::cc_t, pub c_cc: [::cc_t; 19], pub c_ispeed: ::speed_t, pub c_ospeed: ::speed_t, } } pub const AF_FILE: ::c_int = 1; pub const AF_KCM: ::c_int = 41; pub const AF_MAX: ::c_int = 43; pub const AF_QIPCRTR: ::c_int = 42; pub const EADDRINUSE: ::c_int = 98; pub const EADDRNOTAVAIL: ::c_int = 99; pub const EAFNOSUPPORT: ::c_int = 97; pub const EALREADY: ::c_int = 114; pub const EBADE: ::c_int = 52; pub const EBADMSG: ::c_int = 74; pub const EBADR: ::c_int = 53; pub const EBADRQC: ::c_int = 56; pub const EBADSLT: ::c_int = 57; pub const ECANCELED: ::c_int = 125; pub const ECHRNG: ::c_int = 44; pub const ECONNABORTED: ::c_int = 103; pub const ECONNREFUSED: ::c_int = 111; pub const ECONNRESET: ::c_int = 104; pub const EDEADLK: ::c_int = 35; pub const EDEADLOCK: ::c_int = 35; pub const EDESTADDRREQ: ::c_int = 89; pub const EDQUOT: ::c_int = 122; pub const EHOSTDOWN: ::c_int = 112; pub const EHOSTUNREACH: ::c_int = 113; pub const EHWPOISON: ::c_int = 133; pub const EIDRM: ::c_int = 43; pub const EILSEQ: ::c_int = 84; pub const EINPROGRESS: ::c_int = 115; pub const EISCONN: ::c_int = 106; pub const EISNAM: ::c_int = 120; pub const EKEYEXPIRED: ::c_int = 127; pub const EKEYREJECTED: ::c_int = 129; pub const EKEYREVOKED: ::c_int = 128; pub const EL2HLT: ::c_int = 51; pub const EL2NSYNC: ::c_int = 45; pub const EL3HLT: ::c_int = 46; pub const EL3RST: ::c_int = 47; pub const ELIBACC: ::c_int = 79; pub const ELIBBAD: ::c_int = 80; pub const ELIBEXEC: ::c_int = 83; pub const ELIBMAX: ::c_int = 82; pub const ELIBSCN: ::c_int = 81; pub const ELNRNG: ::c_int = 48; pub const ELOOP: ::c_int = 40; pub const EMEDIUMTYPE: ::c_int = 124; pub const EMSGSIZE: ::c_int = 90; pub const EMULTIHOP: ::c_int = 72; pub const ENAMETOOLONG: ::c_int = 36; pub const ENAVAIL: ::c_int = 119; pub const ENETDOWN: ::c_int = 100; pub const ENETRESET: ::c_int = 102; pub const ENETUNREACH: ::c_int = 101; pub const ENOANO: ::c_int = 55; pub const ENOBUFS: ::c_int = 105; pub const ENOCSI: ::c_int = 50; pub const ENOKEY: ::c_int = 126; pub const ENOLCK: ::c_int = 37; pub const ENOMEDIUM: ::c_int = 123; pub const ENOMSG: ::c_int = 42; pub const ENOPROTOOPT: ::c_int = 92; pub const ENOSYS: ::c_int = 38; pub const ENOTCONN: ::c_int = 107; pub const ENOTEMPTY: ::c_int = 39; pub const ENOTNAM: ::c_int = 118; pub const ENOTRECOVERABLE: ::c_int = 131; pub const ENOTSOCK: ::c_int = 88; pub const ENOTSUP: ::c_int = 95; pub const ENOTUNIQ: ::c_int = 76; pub const EOPNOTSUPP: ::c_int = 95; pub const EOVERFLOW: ::c_int = 75; pub const EOWNERDEAD: ::c_int = 130; pub const EPFNOSUPPORT: ::c_int = 96; pub const EREMCHG: ::c_int = 78; pub const ERESTART: ::c_int = 85; pub const ERFKILL: ::c_int = 132; pub const ESHUTDOWN: ::c_int = 108; pub const ESOCKTNOSUPPORT: ::c_int = 94; pub const ESTALE: ::c_int = 116; pub const ESTRPIPE: ::c_int = 86; pub const ETOOMANYREFS: ::c_int = 109; pub const EUCLEAN: ::c_int = 117; pub const EUNATCH: ::c_int = 49; pub const EUSERS: ::c_int = 87; pub const EXFULL: ::c_int = 54; pub const EXTPROC: ::c_int = 65536; pub const F_EXLCK: ::c_int = 4; pub const F_GETLK: ::c_int = 12; pub const F_GETOWN: ::c_int = 9; pub const F_GETOWNER_UIDS: ::c_int = 17; pub const F_GETOWN_EX: ::c_int = 16; pub const F_GETSIG: ::c_int = 11; pub const FIOASYNC: ::c_int = 21586; pub const FIOCLEX: ::c_int = 21585; pub const FIONBIO: ::c_int = 21537; pub const FIONCLEX: ::c_int = 21584; pub const FIONREAD: ::c_int = 21531; pub const FIOQSIZE: ::c_int = 21600; pub const F_LINUX_SPECIFIC_BASE: ::c_int = 1024; pub const FLUSHO: ::c_int = 4096; pub const F_OFD_GETLK: ::c_int = 36; pub const F_OFD_SETLK: ::c_int = 37; pub const F_OFD_SETLKW: ::c_int = 38; pub const F_OWNER_PGRP: ::c_int = 2; pub const F_OWNER_PID: ::c_int = 1; pub const F_OWNER_TID: ::c_int = 0; pub const F_SETLK: ::c_int = 13; pub const F_SETLKW: ::c_int = 14; pub const F_SETOWN: ::c_int = 8; pub const F_SETOWN_EX: ::c_int = 15; pub const F_SETSIG: ::c_int = 10; pub const F_SHLCK: ::c_int = 8; pub const IEXTEN: ::c_int = 32768; pub const MAP_ANON: ::c_int = 32; pub const MAP_DENYWRITE: ::c_int = 2048; pub const MAP_EXECUTABLE: ::c_int = 4096; pub const MAP_GROWSDOWN: ::c_int = 256; pub const MAP_HUGE_MASK: ::c_int = 63; pub const MAP_HUGE_SHIFT: ::c_int = 26; pub const MAP_HUGETLB: ::c_int = 262144; pub const MAP_LOCKED: ::c_int = 8192; pub const MAP_NONBLOCK: ::c_int = 65536; pub const MAP_NORESERVE: ::c_int = 16384; pub const MAP_POPULATE: ::c_int = 32768; pub const MAP_STACK: ::c_int = 131072; pub const MAP_UNINITIALIZED: ::c_int = 0; pub const O_APPEND: ::c_int = 1024; pub const O_ASYNC: ::c_int = 8192; pub const O_CREAT: ::c_int = 64; pub const O_DIRECT: ::c_int = 16384; pub const O_DIRECTORY: ::c_int = 65536; pub const O_DSYNC: ::c_int = 4096; pub const O_EXCL: ::c_int = 128; pub const O_LARGEFILE: ::c_int = 32768; pub const O_NOCTTY: ::c_int = 256; pub const O_NOFOLLOW: ::c_int = 131072; pub const O_NONBLOCK: ::c_int = 2048; pub const O_SYNC: ::c_int = 1052672; pub const PF_FILE: ::c_int = 1; pub const PF_KCM: ::c_int = 41; pub const PF_MAX: ::c_int = 43; pub const PF_QIPCRTR: ::c_int = 42; pub const RLIMIT_AS: ::c_int = 9; pub const RLIMIT_MEMLOCK: ::c_int = 8; pub const RLIMIT_NOFILE: ::c_int = 7; pub const RLIMIT_NPROC: ::c_int = 6; pub const RLIMIT_RSS: ::c_int = 5; #[deprecated( since = "0.2.64", note = "Not stable across OS versions" )] pub const RLIM_NLIMITS: ::c_int = 16; pub const SA_ONSTACK: ::c_int = 0x08000000; pub const SA_SIGINFO: ::c_int = 0x00000004; pub const SA_NOCLDWAIT: ::c_int = 0x00000002; pub const SIGBUS: ::c_int = 7; pub const SIGCHLD: ::c_int = 17; pub const SIGCONT: ::c_int = 18; pub const SIGIO: ::c_int = 29; pub const SIGPOLL: ::c_int = 29; pub const SIGPROF: ::c_int = 27; pub const SIGPWR: ::c_int = 30; pub const SIGSTKFLT: ::c_int = 16; pub const SIGSTOP: ::c_int = 19; pub const SIGSYS: ::c_int = 31; pub const SIGTSTP: ::c_int = 20; pub const SIGTTIN: ::c_int = 21; pub const SIGTTOU: ::c_int = 22; pub const SIGURG: ::c_int = 23; pub const SIGUSR1: ::c_int = 10; pub const SIGUSR2: ::c_int = 12; pub const SIGVTALRM: ::c_int = 26; pub const SIGWINCH: ::c_int = 28; pub const SIGXCPU: ::c_int = 24; pub const SIGXFSZ: ::c_int = 25; pub const SIG_SETMASK: ::c_int = 2; // FIXME check these pub const SIG_BLOCK: ::c_int = 0x000000; pub const SIG_UNBLOCK: ::c_int = 0x01; pub const SO_ACCEPTCONN: ::c_int = 30; pub const SO_ATTACH_BPF: ::c_int = 50; pub const SO_ATTACH_FILTER: ::c_int = 26; pub const SO_ATTACH_REUSEPORT_CBPF: ::c_int = 51; pub const SO_ATTACH_REUSEPORT_EBPF: ::c_int = 52; pub const SO_BPF_EXTENSIONS: ::c_int = 48; pub const SO_BROADCAST: ::c_int = 6; pub const SO_BSDCOMPAT: ::c_int = 14; pub const SOCK_DGRAM: ::c_int = 2; pub const SOCK_NONBLOCK: ::c_int = 2048; pub const SOCK_SEQPACKET: ::c_int = 5; pub const SOCK_STREAM: ::c_int = 1; pub const SO_CNX_ADVICE: ::c_int = 53; pub const SO_DETACH_BPF: ::c_int = 27; pub const SO_DETACH_FILTER: ::c_int = 27; pub const SO_DOMAIN: ::c_int = 39; pub const SO_DONTROUTE: ::c_int = 5; pub const SO_ERROR: ::c_int = 4; pub const SO_GET_FILTER: ::c_int = 26; pub const SO_INCOMING_CPU: ::c_int = 49; pub const SO_KEEPALIVE: ::c_int = 9; pub const SOL_CAIF: ::c_int = 278; pub const SO_LINGER: ::c_int = 13; pub const SOL_IUCV: ::c_int = 277; pub const SOL_KCM: ::c_int = 281; pub const SOL_NFC: ::c_int = 280; pub const SO_LOCK_FILTER: ::c_int = 44; pub const SOL_PNPIPE: ::c_int = 275; pub const SOL_PPPOL2TP: ::c_int = 273; pub const SOL_RDS: ::c_int = 276; pub const SOL_RXRPC: ::c_int = 272; pub const SOL_SOCKET: ::c_int = 1; pub const SO_MAX_PACING_RATE: ::c_int = 47; pub const SO_NO_CHECK: ::c_int = 11; pub const SO_NOFCS: ::c_int = 43; pub const SO_OOBINLINE: ::c_int = 10; pub const SO_PASSCRED: ::c_int = 16; pub const SO_PASSSEC: ::c_int = 34; pub const SO_PEERCRED: ::c_int = 17; pub const SO_PEERNAME: ::c_int = 28; pub const SO_PEERSEC: ::c_int = 31; pub const SO_PRIORITY: ::c_int = 12; pub const SO_PROTOCOL: ::c_int = 38; pub const SO_RCVBUF: ::c_int = 8; pub const SO_RCVBUFFORCE: ::c_int = 33; pub const SO_RCVLOWAT: ::c_int = 18; pub const SO_RCVTIMEO: ::c_int = 20; pub const SO_REUSEADDR: ::c_int = 2; pub const SO_REUSEPORT: ::c_int = 15; pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; pub const SO_SNDBUF: ::c_int = 7; pub const SO_SNDBUFFORCE: ::c_int = 32; pub const SO_SNDLOWAT: ::c_int = 19; pub const SO_SNDTIMEO: ::c_int = 21; pub const SO_TYPE: ::c_int = 3; pub const SO_WIFI_STATUS: ::c_int = 41; pub const SYS3264_fadvise64: ::c_int = 223; pub const SYS3264_fcntl: ::c_int = 25; pub const SYS3264_fstatat: ::c_int = 79; pub const SYS3264_fstat: ::c_int = 80; pub const SYS3264_fstatfs: ::c_int = 44; pub const SYS3264_ftruncate: ::c_int = 46; pub const SYS3264_lseek: ::c_int = 62; pub const SYS3264_lstat: ::c_int = 1039; pub const SYS3264_mmap: ::c_int = 222; pub const SYS3264_sendfile: ::c_int = 71; pub const SYS3264_stat: ::c_int = 1038; pub const SYS3264_statfs: ::c_int = 43; pub const SYS3264_truncate: ::c_int = 45; pub const SYS_accept4: ::c_int = 242; pub const SYS_accept: ::c_int = 202; pub const SYS_access: ::c_int = 1033; pub const SYS_acct: ::c_int = 89; pub const SYS_add_key: ::c_int = 217; pub const SYS_adjtimex: ::c_int = 171; pub const SYS_alarm: ::c_int = 1059; pub const SYS_arch_specific_syscall: ::c_int = 244; pub const SYS_bdflush: ::c_int = 1075; pub const SYS_bind: ::c_int = 200; pub const SYS_bpf: ::c_int = 280; pub const SYS_brk: ::c_int = 214; pub const SYS_capget: ::c_int = 90; pub const SYS_capset: ::c_int = 91; pub const SYS_chdir: ::c_int = 49; pub const SYS_chmod: ::c_int = 1028; pub const SYS_chown: ::c_int = 1029; pub const SYS_chroot: ::c_int = 51; pub const SYS_clock_adjtime: ::c_int = 266; pub const SYS_clock_getres: ::c_int = 114; pub const SYS_clock_gettime: ::c_int = 113; pub const SYS_clock_nanosleep: ::c_int = 115; pub const SYS_clock_settime: ::c_int = 112; pub const SYS_clone: ::c_int = 220; pub const SYS_close: ::c_int = 57; pub const SYS_connect: ::c_int = 203; pub const SYS_copy_file_range: ::c_int = -1; // FIXME pub const SYS_creat: ::c_int = 1064; pub const SYS_delete_module: ::c_int = 106; pub const SYS_dup2: ::c_int = 1041; pub const SYS_dup3: ::c_int = 24; pub const SYS_dup: ::c_int = 23; pub const SYS_epoll_create1: ::c_int = 20; pub const SYS_epoll_create: ::c_int = 1042; pub const SYS_epoll_ctl: ::c_int = 21; pub const SYS_epoll_pwait: ::c_int = 22; pub const SYS_epoll_wait: ::c_int = 1069; pub const SYS_eventfd2: ::c_int = 19; pub const SYS_eventfd: ::c_int = 1044; pub const SYS_execveat: ::c_int = 281; pub const SYS_execve: ::c_int = 221; pub const SYS_exit: ::c_int = 93; pub const SYS_exit_group: ::c_int = 94; pub const SYS_faccessat: ::c_int = 48; pub const SYS_fadvise64_64: ::c_int = 223; pub const SYS_fallocate: ::c_int = 47; pub const SYS_fanotify_init: ::c_int = 262; pub const SYS_fanotify_mark: ::c_int = 263; pub const SYS_fchdir: ::c_int = 50; pub const SYS_fchmodat: ::c_int = 53; pub const SYS_fchmod: ::c_int = 52; pub const SYS_fchownat: ::c_int = 54; pub const SYS_fchown: ::c_int = 55; pub const SYS_fcntl64: ::c_int = 25; pub const SYS_fcntl: ::c_int = 25; pub const SYS_fdatasync: ::c_int = 83; pub const SYS_fgetxattr: ::c_int = 10; pub const SYS_finit_module: ::c_int = 273; pub const SYS_flistxattr: ::c_int = 13; pub const SYS_flock: ::c_int = 32; pub const SYS_fork: ::c_int = 1079; pub const SYS_fremovexattr: ::c_int = 16; pub const SYS_fsetxattr: ::c_int = 7; pub const SYS_fstat64: ::c_int = 80; pub const SYS_fstatat64: ::c_int = 79; pub const SYS_fstatfs64: ::c_int = 44; pub const SYS_fstatfs: ::c_int = 44; pub const SYS_fsync: ::c_int = 82; pub const SYS_ftruncate64: ::c_int = 46; pub const SYS_ftruncate: ::c_int = 46; pub const SYS_futex: ::c_int = 98; pub const SYS_futimesat: ::c_int = 1066; pub const SYS_getcpu: ::c_int = 168; pub const SYS_getcwd: ::c_int = 17; pub const SYS_getdents64: ::c_int = 61; pub const SYS_getdents: ::c_int = 1065; pub const SYS_getegid: ::c_int = 177; pub const SYS_geteuid: ::c_int = 175; pub const SYS_getgid: ::c_int = 176; pub const SYS_getgroups: ::c_int = 158; pub const SYS_getitimer: ::c_int = 102; pub const SYS_get_mempolicy: ::c_int = 236; pub const SYS_getpeername: ::c_int = 205; pub const SYS_getpgid: ::c_int = 155; pub const SYS_getpgrp: ::c_int = 1060; pub const SYS_getpid: ::c_int = 172; pub const SYS_getppid: ::c_int = 173; pub const SYS_getpriority: ::c_int = 141; pub const SYS_getrandom: ::c_int = 278; pub const SYS_getresgid: ::c_int = 150; pub const SYS_getresuid: ::c_int = 148; pub const SYS_getrlimit: ::c_int = 163; pub const SYS_get_robust_list: ::c_int = 100; pub const SYS_getrusage: ::c_int = 165; pub const SYS_getsid: ::c_int = 156; pub const SYS_getsockname: ::c_int = 204; pub const SYS_getsockopt: ::c_int = 209; pub const SYS_gettid: ::c_int = 178; pub const SYS_gettimeofday: ::c_int = 169; pub const SYS_getuid: ::c_int = 174; pub const SYS_getxattr: ::c_int = 8; pub const SYS_init_module: ::c_int = 105; pub const SYS_inotify_add_watch: ::c_int = 27; pub const SYS_inotify_init1: ::c_int = 26; pub const SYS_inotify_init: ::c_int = 1043; pub const SYS_inotify_rm_watch: ::c_int = 28; pub const SYS_io_cancel: ::c_int = 3; pub const SYS_ioctl: ::c_int = 29; pub const SYS_io_destroy: ::c_int = 1; pub const SYS_io_getevents: ::c_int = 4; pub const SYS_ioprio_get: ::c_int = 31; pub const SYS_ioprio_set: ::c_int = 30; pub const SYS_io_setup: ::c_int = 0; pub const SYS_io_submit: ::c_int = 2; pub const SYS_kcmp: ::c_int = 272; pub const SYS_kexec_load: ::c_int = 104; pub const SYS_keyctl: ::c_int = 219; pub const SYS_kill: ::c_int = 129; pub const SYS_lchown: ::c_int = 1032; pub const SYS_lgetxattr: ::c_int = 9; pub const SYS_linkat: ::c_int = 37; pub const SYS_link: ::c_int = 1025; pub const SYS_listen: ::c_int = 201; pub const SYS_listxattr: ::c_int = 11; pub const SYS_llistxattr: ::c_int = 12; pub const SYS__llseek: ::c_int = 62; pub const SYS_lookup_dcookie: ::c_int = 18; pub const SYS_lremovexattr: ::c_int = 15; pub const SYS_lseek: ::c_int = 62; pub const SYS_lsetxattr: ::c_int = 6; pub const SYS_lstat64: ::c_int = 1039; pub const SYS_lstat: ::c_int = 1039; pub const SYS_madvise: ::c_int = 233; pub const SYS_mbind: ::c_int = 235; pub const SYS_memfd_create: ::c_int = 279; pub const SYS_migrate_pages: ::c_int = 238; pub const SYS_mincore: ::c_int = 232; pub const SYS_mkdirat: ::c_int = 34; pub const SYS_mkdir: ::c_int = 1030; pub const SYS_mknodat: ::c_int = 33; pub const SYS_mknod: ::c_int = 1027; pub const SYS_mlockall: ::c_int = 230; pub const SYS_mlock: ::c_int = 228; pub const SYS_mmap2: ::c_int = 222; pub const SYS_mount: ::c_int = 40; pub const SYS_move_pages: ::c_int = 239; pub const SYS_mprotect: ::c_int = 226; pub const SYS_mq_getsetattr: ::c_int = 185; pub const SYS_mq_notify: ::c_int = 184; pub const SYS_mq_open: ::c_int = 180; pub const SYS_mq_timedreceive: ::c_int = 183; pub const SYS_mq_timedsend: ::c_int = 182; pub const SYS_mq_unlink: ::c_int = 181; pub const SYS_mremap: ::c_int = 216; pub const SYS_msgctl: ::c_int = 187; pub const SYS_msgget: ::c_int = 186; pub const SYS_msgrcv: ::c_int = 188; pub const SYS_msgsnd: ::c_int = 189; pub const SYS_msync: ::c_int = 227; pub const SYS_munlockall: ::c_int = 231; pub const SYS_munlock: ::c_int = 229; pub const SYS_munmap: ::c_int = 215; pub const SYS_name_to_handle_at: ::c_int = 264; pub const SYS_nanosleep: ::c_int = 101; pub const SYS_newfstatat: ::c_int = 79; pub const SYS_nfsservctl: ::c_int = 42; pub const SYS_oldwait4: ::c_int = 1072; pub const SYS_openat: ::c_int = 56; pub const SYS_open_by_handle_at: ::c_int = 265; pub const SYS_open: ::c_int = 1024; pub const SYS_pause: ::c_int = 1061; pub const SYS_perf_event_open: ::c_int = 241; pub const SYS_personality: ::c_int = 92; pub const SYS_pipe2: ::c_int = 59; pub const SYS_pipe: ::c_int = 1040; pub const SYS_pivot_root: ::c_int = 41; pub const SYS_poll: ::c_int = 1068; pub const SYS_ppoll: ::c_int = 73; pub const SYS_prctl: ::c_int = 167; pub const SYS_pread64: ::c_int = 67; pub const SYS_preadv: ::c_int = 69; pub const SYS_prlimit64: ::c_int = 261; pub const SYS_process_vm_readv: ::c_int = 270; pub const SYS_process_vm_writev: ::c_int = 271; pub const SYS_pselect6: ::c_int = 72; pub const SYS_ptrace: ::c_int = 117; pub const SYS_pwrite64: ::c_int = 68; pub const SYS_pwritev: ::c_int = 70; pub const SYS_quotactl: ::c_int = 60; pub const SYS_readahead: ::c_int = 213; pub const SYS_read: ::c_int = 63; pub const SYS_readlinkat: ::c_int = 78; pub const SYS_readlink: ::c_int = 1035; pub const SYS_readv: ::c_int = 65; pub const SYS_reboot: ::c_int = 142; pub const SYS_recv: ::c_int = 1073; pub const SYS_recvfrom: ::c_int = 207; pub const SYS_recvmmsg: ::c_int = 243; pub const SYS_recvmsg: ::c_int = 212; pub const SYS_remap_file_pages: ::c_int = 234; pub const SYS_removexattr: ::c_int = 14; pub const SYS_renameat2: ::c_int = 276; pub const SYS_renameat: ::c_int = 38; pub const SYS_rename: ::c_int = 1034; pub const SYS_request_key: ::c_int = 218; pub const SYS_restart_syscall: ::c_int = 128; pub const SYS_rmdir: ::c_int = 1031; pub const SYS_rt_sigaction: ::c_int = 134; pub const SYS_rt_sigpending: ::c_int = 136; pub const SYS_rt_sigprocmask: ::c_int = 135; pub const SYS_rt_sigqueueinfo: ::c_int = 138; pub const SYS_rt_sigreturn: ::c_int = 139; pub const SYS_rt_sigsuspend: ::c_int = 133; pub const SYS_rt_sigtimedwait: ::c_int = 137; pub const SYS_rt_tgsigqueueinfo: ::c_int = 240; pub const SYS_sched_getaffinity: ::c_int = 123; pub const SYS_sched_getattr: ::c_int = 275; pub const SYS_sched_getparam: ::c_int = 121; pub const SYS_sched_get_priority_max: ::c_int = 125; pub const SYS_sched_get_priority_min: ::c_int = 126; pub const SYS_sched_getscheduler: ::c_int = 120; pub const SYS_sched_rr_get_interval: ::c_int = 127; pub const SYS_sched_setaffinity: ::c_int = 122; pub const SYS_sched_setattr: ::c_int = 274; pub const SYS_sched_setparam: ::c_int = 118; pub const SYS_sched_setscheduler: ::c_int = 119; pub const SYS_sched_yield: ::c_int = 124; pub const SYS_seccomp: ::c_int = 277; pub const SYS_select: ::c_int = 1067; pub const SYS_semctl: ::c_int = 191; pub const SYS_semget: ::c_int = 190; pub const SYS_semop: ::c_int = 193; pub const SYS_semtimedop: ::c_int = 192; pub const SYS_send: ::c_int = 1074; pub const SYS_sendfile64: ::c_int = 71; pub const SYS_sendfile: ::c_int = 71; pub const SYS_sendmmsg: ::c_int = 269; pub const SYS_sendmsg: ::c_int = 211; pub const SYS_sendto: ::c_int = 206; pub const SYS_setdomainname: ::c_int = 162; pub const SYS_setfsgid: ::c_int = 152; pub const SYS_setfsuid: ::c_int = 151; pub const SYS_setgid: ::c_int = 144; pub const SYS_setgroups: ::c_int = 159; pub const SYS_sethostname: ::c_int = 161; pub const SYS_setitimer: ::c_int = 103; pub const SYS_set_mempolicy: ::c_int = 237; pub const SYS_setns: ::c_int = 268; pub const SYS_setpgid: ::c_int = 154; pub const SYS_setpriority: ::c_int = 140; pub const SYS_setregid: ::c_int = 143; pub const SYS_setresgid: ::c_int = 149; pub const SYS_setresuid: ::c_int = 147; pub const SYS_setreuid: ::c_int = 145; pub const SYS_setrlimit: ::c_int = 164; pub const SYS_set_robust_list: ::c_int = 99; pub const SYS_setsid: ::c_int = 157; pub const SYS_setsockopt: ::c_int = 208; pub const SYS_set_tid_address: ::c_int = 96; pub const SYS_settimeofday: ::c_int = 170; pub const SYS_setuid: ::c_int = 146; pub const SYS_setxattr: ::c_int = 5; pub const SYS_shmat: ::c_int = 196; pub const SYS_shmctl: ::c_int = 195; pub const SYS_shmdt: ::c_int = 197; pub const SYS_shmget: ::c_int = 194; pub const SYS_shutdown: ::c_int = 210; pub const SYS_sigaltstack: ::c_int = 132; pub const SYS_signalfd4: ::c_int = 74; pub const SYS_signalfd: ::c_int = 1045; pub const SYS_socket: ::c_int = 198; pub const SYS_socketpair: ::c_int = 199; pub const SYS_splice: ::c_int = 76; pub const SYS_stat64: ::c_int = 1038; pub const SYS_stat: ::c_int = 1038; pub const SYS_statfs64: ::c_int = 43; pub const SYS_swapoff: ::c_int = 225; pub const SYS_swapon: ::c_int = 224; pub const SYS_symlinkat: ::c_int = 36; pub const SYS_symlink: ::c_int = 1036; pub const SYS_sync: ::c_int = 81; pub const SYS_sync_file_range2: ::c_int = 84; pub const SYS_sync_file_range: ::c_int = 84; pub const SYS_syncfs: ::c_int = 267; pub const SYS_syscalls: ::c_int = 1080; pub const SYS__sysctl: ::c_int = 1078; pub const SYS_sysinfo: ::c_int = 179; pub const SYS_syslog: ::c_int = 116; pub const SYS_tee: ::c_int = 77; pub const SYS_tgkill: ::c_int = 131; pub const SYS_time: ::c_int = 1062; pub const SYS_timer_create: ::c_int = 107; pub const SYS_timer_delete: ::c_int = 111; pub const SYS_timerfd_create: ::c_int = 85; pub const SYS_timerfd_gettime: ::c_int = 87; pub const SYS_timerfd_settime: ::c_int = 86; pub const SYS_timer_getoverrun: ::c_int = 109; pub const SYS_timer_gettime: ::c_int = 108; pub const SYS_timer_settime: ::c_int = 110; pub const SYS_times: ::c_int = 153; pub const SYS_tkill: ::c_int = 130; pub const SYS_truncate64: ::c_int = 45; pub const SYS_truncate: ::c_int = 45; pub const SYS_umask: ::c_int = 166; pub const SYS_umount2: ::c_int = 39; pub const SYS_umount: ::c_int = 1076; pub const SYS_uname: ::c_int = 160; pub const SYS_unlinkat: ::c_int = 35; pub const SYS_unlink: ::c_int = 1026; pub const SYS_unshare: ::c_int = 97; pub const SYS_uselib: ::c_int = 1077; pub const SYS_ustat: ::c_int = 1070; pub const SYS_utime: ::c_int = 1063; pub const SYS_utimensat: ::c_int = 88; pub const SYS_utimes: ::c_int = 1037; pub const SYS_vfork: ::c_int = 1071; pub const SYS_vhangup: ::c_int = 58; pub const SYS_vmsplice: ::c_int = 75; pub const SYS_wait4: ::c_int = 260; pub const SYS_waitid: ::c_int = 95; pub const SYS_write: ::c_int = 64; pub const SYS_writev: ::c_int = 66; pub const TCFLSH: ::c_int = 21515; pub const TCGETA: ::c_int = 21509; pub const TCGETS: ::c_int = 21505; pub const TCGETX: ::c_int = 21554; pub const TCSBRK: ::c_int = 21513; pub const TCSBRKP: ::c_int = 21541; pub const TCSETA: ::c_int = 21510; pub const TCSETAF: ::c_int = 21512; pub const TCSETAW: ::c_int = 21511; pub const TCSETS: ::c_int = 21506; pub const TCSETSF: ::c_int = 21508; pub const TCSETSW: ::c_int = 21507; pub const TCSETX: ::c_int = 21555; pub const TCSETXF: ::c_int = 21556; pub const TCSETXW: ::c_int = 21557; pub const TCXONC: ::c_int = 21514; pub const TIOCCBRK: ::c_int = 21544; pub const TIOCCONS: ::c_int = 21533; pub const TIOCEXCL: ::c_int = 21516; pub const TIOCGETD: ::c_int = 21540; pub const TIOCGICOUNT: ::c_int = 21597; pub const TIOCGLCKTRMIOS: ::c_int = 21590; pub const TIOCGPGRP: ::c_int = 21519; pub const TIOCGRS485: ::c_int = 21550; pub const TIOCGSERIAL: ::c_int = 21534; pub const TIOCGSID: ::c_int = 21545; pub const TIOCGSOFTCAR: ::c_int = 21529; pub const TIOCGWINSZ: ::c_int = 21523; pub const TIOCLINUX: ::c_int = 21532; pub const TIOCMBIC: ::c_int = 21527; pub const TIOCMBIS: ::c_int = 21526; pub const TIOCM_CAR: ::c_int = 64; pub const TIOCM_CD: ::c_int = 64; pub const TIOCM_CTS: ::c_int = 32; pub const TIOCM_DSR: ::c_int = 256; pub const TIOCM_DTR: ::c_int = 2; pub const TIOCMGET: ::c_int = 21525; pub const TIOCMIWAIT: ::c_int = 21596; pub const TIOCM_LE: ::c_int = 1; pub const TIOCM_LOOP: ::c_int = 32768; pub const TIOCM_OUT1: ::c_int = 8192; pub const TIOCM_OUT2: ::c_int = 16384; pub const TIOCM_RI: ::c_int = 128; pub const TIOCM_RNG: ::c_int = 128; pub const TIOCM_RTS: ::c_int = 4; pub const TIOCMSET: ::c_int = 21528; pub const TIOCM_SR: ::c_int = 16; pub const TIOCM_ST: ::c_int = 8; pub const TIOCNOTTY: ::c_int = 21538; pub const TIOCNXCL: ::c_int = 21517; pub const TIOCOUTQ: ::c_int = 21521; pub const TIOCPKT: ::c_int = 21536; pub const TIOCPKT_DATA: ::c_int = 0; pub const TIOCPKT_DOSTOP: ::c_int = 32; pub const TIOCPKT_FLUSHREAD: ::c_int = 1; pub const TIOCPKT_FLUSHWRITE: ::c_int = 2; pub const TIOCPKT_IOCTL: ::c_int = 64; pub const TIOCPKT_NOSTOP: ::c_int = 16; pub const TIOCPKT_START: ::c_int = 8; pub const TIOCPKT_STOP: ::c_int = 4; pub const TIOCSBRK: ::c_int = 21543; pub const TIOCSCTTY: ::c_int = 21518; pub const TIOCSERCONFIG: ::c_int = 21587; pub const TIOCSERGETLSR: ::c_int = 21593; pub const TIOCSERGETMULTI: ::c_int = 21594; pub const TIOCSERGSTRUCT: ::c_int = 21592; pub const TIOCSERGWILD: ::c_int = 21588; pub const TIOCSERSETMULTI: ::c_int = 21595; pub const TIOCSERSWILD: ::c_int = 21589; pub const TIOCSER_TEMT: ::c_int = 1; pub const TIOCSETD: ::c_int = 21539; pub const TIOCSLCKTRMIOS: ::c_int = 21591; pub const TIOCSPGRP: ::c_int = 21520; pub const TIOCSRS485: ::c_int = 21551; pub const TIOCSSERIAL: ::c_int = 21535; pub const TIOCSSOFTCAR: ::c_int = 21530; pub const TIOCSTI: ::c_int = 21522; pub const TIOCSWINSZ: ::c_int = 21524; pub const TIOCVHANGUP: ::c_int = 21559; pub const TOSTOP: ::c_int = 256; pub const VEOF: ::c_int = 4; pub const VEOL2: ::c_int = 16; pub const VEOL: ::c_int = 11; pub const VMIN: ::c_int = 6;
35.8775
57
0.686956
9b54af1692d85913e701eb01c8a4b16980c7bdd6
3,004
//! Identifies each shard by an integer identifier. use crate::{AttestationData, ChainSpec, CommitteeIndex, EthSpec, Slot}; use safe_arith::{ArithError, SafeArith}; use serde_derive::{Deserialize, Serialize}; use std::ops::{Deref, DerefMut}; const MAX_SUBNET_ID: usize = 64; lazy_static! { static ref SUBNET_ID_TO_STRING: Vec<String> = { let mut v = Vec::with_capacity(MAX_SUBNET_ID); for i in 0..MAX_SUBNET_ID { v.push(i.to_string()); } v }; } #[cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct SubnetId(#[serde(with = "serde_utils::quoted_u64")] u64); pub fn subnet_id_to_string(i: u64) -> &'static str { if i < MAX_SUBNET_ID as u64 { &SUBNET_ID_TO_STRING .get(i as usize) .expect("index below MAX_SUBNET_ID") } else { "subnet id out of range" } } impl SubnetId { pub fn new(id: u64) -> Self { id.into() } /// Compute the subnet for an attestation with `attestation_data` where each slot in the /// attestation epoch contains `committee_count_per_slot` committees. pub fn compute_subnet_for_attestation_data<T: EthSpec>( attestation_data: &AttestationData, committee_count_per_slot: u64, spec: &ChainSpec, ) -> Result<SubnetId, ArithError> { Self::compute_subnet::<T>( attestation_data.slot, attestation_data.index, committee_count_per_slot, spec, ) } /// Compute the subnet for an attestation with `attestation.data.slot == slot` and /// `attestation.data.index == committee_index` where each slot in the attestation epoch /// contains `committee_count_at_slot` committees. pub fn compute_subnet<T: EthSpec>( slot: Slot, committee_index: CommitteeIndex, committee_count_at_slot: u64, spec: &ChainSpec, ) -> Result<SubnetId, ArithError> { let slots_since_epoch_start: u64 = slot.as_u64().safe_rem(T::slots_per_epoch())?; let committees_since_epoch_start = committee_count_at_slot.safe_mul(slots_since_epoch_start)?; Ok(committees_since_epoch_start .safe_add(committee_index)? .safe_rem(spec.attestation_subnet_count)? .into()) } } impl Deref for SubnetId { type Target = u64; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for SubnetId { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<u64> for SubnetId { fn from(x: u64) -> Self { Self(x) } } impl Into<u64> for SubnetId { fn into(self) -> u64 { self.0 } } impl Into<u64> for &SubnetId { fn into(self) -> u64 { self.0 } } impl AsRef<str> for SubnetId { fn as_ref(&self) -> &str { subnet_id_to_string(self.0) } }
26.584071
92
0.626165
560844332a128d4718362b8a7debb61deb7436a0
663
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(dead_code)] mod inner { pub trait Trait { fn f(&self) { f(); } } impl Trait for int {} fn f() {} } pub fn foo() { let a = &1 as &inner::Trait; a.f(); }
24.555556
68
0.656109
2f78db2c9053c023f42692f0b0628a526d22b93d
119
mod admin_key_guard; mod authorization_token_guard; pub use admin_key_guard::*; pub use authorization_token_guard::*;
19.833333
37
0.823529
64e7ac19ea7a05873f3ebd85eaa1a36acc786c20
3,067
// This file is part of Substrate. // Copyright (C) 2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. //! Autogenerated weights for pallet_session //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev //! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 // Executed Command: // target/release/substrate // benchmark // --chain=dev // --steps=50 // --repeat=20 // --pallet=pallet_session // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/session/src/weights.rs // --template=./.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_session. pub trait WeightInfo { fn set_keys() -> Weight; fn purge_keys() -> Weight; } /// Weights for pallet_session using the Substrate node and recommended hardware. pub struct SubstrateWeight<T>(PhantomData<T>); impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> { // Storage: Staking Ledger (r:1 w:0) // Storage: Session NextKeys (r:1 w:1) // Storage: Session KeyOwner (r:4 w:4) fn set_keys() -> Weight { (64_427_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Session NextKeys (r:1 w:1) // Storage: Session KeyOwner (r:0 w:4) fn purge_keys() -> Weight { (42_497_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } } // For backwards compatibility and tests impl WeightInfo for () { // Storage: Staking Ledger (r:1 w:0) // Storage: Session NextKeys (r:1 w:1) // Storage: Session KeyOwner (r:4 w:4) fn set_keys() -> Weight { (64_427_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Session NextKeys (r:1 w:1) // Storage: Session KeyOwner (r:0 w:4) fn purge_keys() -> Weight { (42_497_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } }
33.336957
86
0.703293
e8da01126f321f1c4259035493aecc35f81fe880
40,302
//! Implementation of the SAM4L ADCIFE. //! //! This is an implementation of the SAM4L analog to digital converter. It is //! bare-bones because it provides little flexibility on how samples are taken. //! Currently, all samples: //! //! - are 12 bits //! - use the ground pad as the negative reference //! - use a VCC/2 positive reference //! - use a gain of 0.5x //! - are left justified //! //! Samples can either be collected individually or continuously at a specified //! frequency. //! //! - Author: Philip Levis <[email protected]>, Branden Ghena <[email protected]> //! - Updated: May 1, 2017 use crate::dma; use crate::pm::{self, Clock, PBAClock}; use crate::scif; use core::cell::Cell; use core::{cmp, mem, slice}; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::common::math; use kernel::common::registers::{register_bitfields, ReadOnly, ReadWrite, WriteOnly}; use kernel::common::StaticRef; use kernel::hil; use kernel::ReturnCode; /// Representation of an ADC channel on the SAM4L. pub struct AdcChannel { chan_num: u32, internal: u32, } /// SAM4L ADC channels. #[derive(Copy, Clone, Debug)] #[repr(u8)] enum Channel { AD0 = 0x00, AD1 = 0x01, AD2 = 0x02, AD3 = 0x03, AD4 = 0x04, AD5 = 0x05, AD6 = 0x06, AD7 = 0x07, AD8 = 0x08, AD9 = 0x09, AD10 = 0x0A, AD11 = 0x0B, AD12 = 0x0C, AD13 = 0x0D, AD14 = 0x0E, Bandgap = 0x0F, ScaledVCC = 0x12, DAC = 0x13, Vsingle = 0x16, ReferenceGround = 0x17, } /// Initialization of an ADC channel. impl AdcChannel { /// Create a new ADC channel. /// /// - `channel`: Channel enum representing the channel number and whether it /// is internal const fn new(channel: Channel) -> AdcChannel { AdcChannel { chan_num: ((channel as u8) & 0x0F) as u32, internal: (((channel as u8) >> 4) & 0x01) as u32, } } } /// Statically allocated ADC channels. Used in board configurations to specify /// which channels are used on the platform. pub static mut CHANNEL_AD0: AdcChannel = AdcChannel::new(Channel::AD0); pub static mut CHANNEL_AD1: AdcChannel = AdcChannel::new(Channel::AD1); pub static mut CHANNEL_AD2: AdcChannel = AdcChannel::new(Channel::AD2); pub static mut CHANNEL_AD3: AdcChannel = AdcChannel::new(Channel::AD3); pub static mut CHANNEL_AD4: AdcChannel = AdcChannel::new(Channel::AD4); pub static mut CHANNEL_AD5: AdcChannel = AdcChannel::new(Channel::AD5); pub static mut CHANNEL_AD6: AdcChannel = AdcChannel::new(Channel::AD6); pub static mut CHANNEL_AD7: AdcChannel = AdcChannel::new(Channel::AD7); pub static mut CHANNEL_AD8: AdcChannel = AdcChannel::new(Channel::AD8); pub static mut CHANNEL_AD9: AdcChannel = AdcChannel::new(Channel::AD9); pub static mut CHANNEL_AD10: AdcChannel = AdcChannel::new(Channel::AD10); pub static mut CHANNEL_AD11: AdcChannel = AdcChannel::new(Channel::AD11); pub static mut CHANNEL_AD12: AdcChannel = AdcChannel::new(Channel::AD12); pub static mut CHANNEL_AD13: AdcChannel = AdcChannel::new(Channel::AD13); pub static mut CHANNEL_AD14: AdcChannel = AdcChannel::new(Channel::AD14); pub static mut CHANNEL_BANDGAP: AdcChannel = AdcChannel::new(Channel::Bandgap); pub static mut CHANNEL_SCALED_VCC: AdcChannel = AdcChannel::new(Channel::ScaledVCC); pub static mut CHANNEL_DAC: AdcChannel = AdcChannel::new(Channel::DAC); pub static mut CHANNEL_VSINGLE: AdcChannel = AdcChannel::new(Channel::Vsingle); pub static mut CHANNEL_REFERENCE_GROUND: AdcChannel = AdcChannel::new(Channel::ReferenceGround); /// Create a trait of both client types to allow a single client reference to /// act as both pub trait EverythingClient: hil::adc::Client + hil::adc::HighSpeedClient {} impl<C: hil::adc::Client + hil::adc::HighSpeedClient> EverythingClient for C {} /// ADC driver code for the SAM4L. pub struct Adc { registers: StaticRef<AdcRegisters>, // state tracking for the ADC enabled: Cell<bool>, adc_clk_freq: Cell<u32>, active: Cell<bool>, continuous: Cell<bool>, dma_running: Cell<bool>, cpu_clock: Cell<bool>, // timer fire counting for slow sampling rates timer_repeats: Cell<u8>, timer_counts: Cell<u8>, // DMA peripheral, buffers, and length rx_dma: OptionalCell<&'static dma::DMAChannel>, rx_dma_peripheral: dma::DMAPeripheral, rx_length: Cell<usize>, next_dma_buffer: TakeCell<'static, [u16]>, next_dma_length: Cell<usize>, stopped_buffer: TakeCell<'static, [u16]>, // ADC client to send sample complete notifications to client: OptionalCell<&'static dyn EverythingClient>, } /// Memory mapped registers for the ADC. #[repr(C)] pub struct AdcRegisters { // From page 1005 of SAM4L manual cr: WriteOnly<u32, Control::Register>, cfg: ReadWrite<u32, Configuration::Register>, sr: ReadOnly<u32, Status::Register>, scr: WriteOnly<u32, Interrupt::Register>, _reserved0: u32, seqcfg: ReadWrite<u32, SequencerConfig::Register>, cdma: WriteOnly<u32>, tim: ReadWrite<u32, TimingConfiguration::Register>, itimer: ReadWrite<u32, InternalTimer::Register>, wcfg: ReadWrite<u32, WindowMonitorConfiguration::Register>, wth: ReadWrite<u32, WindowMonitorThresholdConfiguration::Register>, lcv: ReadOnly<u32, SequencerLastConvertedValue::Register>, ier: WriteOnly<u32, Interrupt::Register>, idr: WriteOnly<u32, Interrupt::Register>, imr: ReadOnly<u32, Interrupt::Register>, calib: ReadWrite<u32>, } register_bitfields![u32, Control [ /// Bandgap buffer request disable BGREQDIS 11, /// Bandgap buffer request enable BGREQEN 10, /// ADCIFE disable DIS 9, /// ADCIFE enable EN 8, /// Reference buffer disable REFBUFDIS 5, /// Reference buffer enable REFBUFEN 4, /// Sequence trigger STRIG 3, /// Internal timer start bit TSTART 2, /// Internal timer stop bit TSTOP 1, /// Software reset SWRST 0 ], Configuration [ /// Prescaler Rate Selection PRESCAL OFFSET(8) NUMBITS(3) [ DIV4 = 0, DIV8 = 1, DIV16 = 2, DIV32 = 3, DIV64 = 4, DIV128 = 5, DIV256 = 6, DIV512 = 7 ], /// Clock Selection for sequencer/ADC cell CLKSEL OFFSET(6) NUMBITS(1) [ GenericClock = 0, ApbClock = 1 ], /// ADC current reduction SPEED OFFSET(4) NUMBITS(2) [ ksps300 = 0, ksps225 = 1, ksps150 = 2, ksps75 = 3 ], /// ADC Reference selection REFSEL OFFSET(1) NUMBITS(3) [ Internal1V = 0, VccX0p625 = 1, ExternalRef1 = 2, ExternalRef2 = 3, VccX0p5 = 4 ] ], Status [ /// Bandgap buffer request Status BGREQ 30, /// Reference Buffer Status REFBUF 28, /// Conversion busy CBUSY 27, /// Sequencer busy SBUSY 26, /// Timer busy TBUSY 25, /// Enable Status EN 24, /// Timer time out TTO 5, /// Sequencer missed trigger event SMTRG 3, /// Window monitor WM 2, /// Sequencer last converted value overrun LOVR 1, /// Sequencer end of conversion SEOC 0 ], Interrupt [ /// Timer time out TTO 5, /// Sequencer missed trigger event SMTRG 3, /// Window monitor WM 2, /// Sequencer last converted value overrun LOVR 1, /// Sequencer end of conversion SEOC 0 ], SequencerConfig [ /// Zoom shift/unipolar reference source selection ZOOMRANGE OFFSET(28) NUMBITS(3) [], /// MUX selection on Negative ADC input channel MUXNEG OFFSET(20) NUMBITS(3) [], /// MUS selection of Positive ADC input channel MUXPOS OFFSET(16) NUMBITS(4) [], /// Internal Voltage Sources Selection INTERNAL OFFSET(14) NUMBITS(2) [], /// Resolution RES OFFSET(12) NUMBITS(1) [ Bits12 = 0, Bits8 = 1 ], /// Trigger selection TRGSEL OFFSET(8) NUMBITS(3) [ Software = 0, InternalAdcTimer = 1, InternalTriggerSource = 2, ContinuousMode = 3, ExternalTriggerPinRising = 4, ExternalTriggerPinFalling = 5, ExternalTriggerPinBoth = 6 ], /// Gain Compensation GCOMP OFFSET(7) NUMBITS(1) [ Disable = 0, Enable = 1 ], /// Gain factor GAIN OFFSET(4) NUMBITS(3) [ Gain1x = 0, Gain2x = 1, Gain4x = 2, Gain8x = 3, Gain16x = 4, Gain32x = 5, Gain64x = 6, Gain0p5x = 7 ], /// Bipolar Mode BIPOLAR OFFSET(2) NUMBITS(1) [ Disable = 0, Enable = 1 ], /// Half Word Left Adjust HWLA OFFSET(0) NUMBITS(1) [ Disable = 0, Enable = 1 ] ], TimingConfiguration [ /// Enable Startup ENSTUP OFFSET(8) NUMBITS(1) [ Disable = 0, Enable = 1 ], /// Startup time STARTUP OFFSET(0) NUMBITS(5) [] ], InternalTimer [ /// Internal Timer Max Counter ITMC OFFSET(0) NUMBITS(16) [] ], WindowMonitorConfiguration [ /// Window Monitor Mode WM OFFSET(12) NUMBITS(3) [] ], WindowMonitorThresholdConfiguration [ /// High Threshold HT OFFSET(16) NUMBITS(12) [], /// Low Threshold LT OFFSET(0) NUMBITS(12) [] ], SequencerLastConvertedValue [ /// Last converted negative channel LCNC OFFSET(20) NUMBITS(3) [], /// Last converted positive channel LCPC OFFSET(16) NUMBITS(4) [], /// Last converted value LCV OFFSET(0) NUMBITS(16) [] ] ]; // Page 59 of SAM4L data sheet const BASE_ADDRESS: StaticRef<AdcRegisters> = unsafe { StaticRef::new(0x40038000 as *const AdcRegisters) }; /// Statically allocated ADC driver. Used in board configurations to connect to /// various capsules. pub static mut ADC0: Adc = Adc::new(BASE_ADDRESS, dma::DMAPeripheral::ADCIFE_RX); /// Functions for initializing the ADC. impl Adc { /// Create a new ADC driver. /// /// - `base_address`: pointer to the ADC's memory mapped I/O registers /// - `rx_dma_peripheral`: type used for DMA transactions const fn new( base_address: StaticRef<AdcRegisters>, rx_dma_peripheral: dma::DMAPeripheral, ) -> Adc { Adc { // pointer to memory mapped I/O registers registers: base_address, // status of the ADC peripheral enabled: Cell::new(false), adc_clk_freq: Cell::new(0), active: Cell::new(false), continuous: Cell::new(false), dma_running: Cell::new(false), cpu_clock: Cell::new(false), // timer repeating state for slow sampling rates timer_repeats: Cell::new(0), timer_counts: Cell::new(0), // DMA status and stuff rx_dma: OptionalCell::empty(), rx_dma_peripheral: rx_dma_peripheral, rx_length: Cell::new(0), next_dma_buffer: TakeCell::empty(), next_dma_length: Cell::new(0), stopped_buffer: TakeCell::empty(), // higher layer to send responses to client: OptionalCell::empty(), } } /// Sets the client for this driver. /// /// - `client`: reference to capsule which handles responses pub fn set_client<C: EverythingClient>(&self, client: &'static C) { self.client.set(client); } /// Sets the DMA channel for this driver. /// /// - `rx_dma`: reference to the DMA channel the ADC should use pub fn set_dma(&self, rx_dma: &'static dma::DMAChannel) { self.rx_dma.set(rx_dma); } /// Interrupt handler for the ADC. pub fn handle_interrupt(&mut self) { let status = self.registers.sr.is_set(Status::SEOC); if self.enabled.get() && self.active.get() { if status { // sample complete interrupt // should we deal with this sample now, or wait for the next // one? if self.timer_counts.get() >= self.timer_repeats.get() { // we actually care about this sample // single sample complete. Send value to client let val = self.registers.lcv.read(SequencerLastConvertedValue::LCV) as u16; self.client.map(|client| { client.sample_ready(val); }); // clean up state if self.continuous.get() { // continuous sampling, reset counts and keep going self.timer_counts.set(0); } else { // single sampling, disable interrupt and set inactive self.active.set(false); self.registers.idr.write(Interrupt::SEOC::SET); } } else { // increment count and wait for next sample self.timer_counts.set(self.timer_counts.get() + 1); } // clear status self.registers.scr.write(Interrupt::SEOC::SET); } } else { // we are inactive, why did we get an interrupt? // disable all interrupts, clear status, and just ignore it self.registers.idr.write( Interrupt::TTO::SET + Interrupt::SMTRG::SET + Interrupt::WM::SET + Interrupt::LOVR::SET + Interrupt::SEOC::SET, ); self.clear_status(); } } /// Clear all status bits using the status clear register. fn clear_status(&self) { self.registers.scr.write( Interrupt::TTO::SET + Interrupt::SMTRG::SET + Interrupt::WM::SET + Interrupt::LOVR::SET + Interrupt::SEOC::SET, ); } // Configures the ADC with the slowest clock that can provide continuous sampling at // the desired frequency and enables the ADC. Subsequent calls with the same frequency // value have no effect. Using the slowest clock also ensures efficient discrete // sampling. fn config_and_enable(&self, frequency: u32) -> ReturnCode { if self.active.get() { // disallow reconfiguration during sampling ReturnCode::EBUSY } else if frequency == self.adc_clk_freq.get() { // already configured to work on this frequency ReturnCode::SUCCESS } else { // disabling the ADC before switching clocks is necessary to avoid // leaving it in undefined state self.registers.cr.write(Control::DIS::SET); // wait until status is disabled let mut timeout = 10000; while self.registers.sr.is_set(Status::EN) { timeout -= 1; if timeout == 0 { // ADC never disabled return ReturnCode::FAIL; } } self.enabled.set(true); // configure the ADC max speed and reference select let mut cfg_val = Configuration::SPEED::ksps300 + Configuration::REFSEL::VccX0p5; // First, enable the clocks // Both the ADCIFE clock and GCLK10 are needed, // but the GCLK10 source depends on the requested sampling frequency // turn on ADCIFE bus clock. Already set to the same frequency // as the CPU clock pm::enable_clock(Clock::PBA(PBAClock::ADCIFE)); // Now, determine the prescalar. // The maximum sampling frequency with the RC clocks is 1/32th of their clock // frequency. This is because of the minimum PRESCAL by a factor of 4 and the // 7+1 cycles needed for conversion in continuous mode. Hence, 4*(7+1)=32. if frequency <= 113600 / 32 { // RC oscillator self.cpu_clock.set(false); let max_freq: u32; if frequency <= 32000 / 32 { // frequency of the RC32K is 32KHz. scif::generic_clock_enable( scif::GenericClock::GCLK10, scif::ClockSource::RC32K, ); max_freq = 32000 / 32; } else { // frequency of the RCSYS is 115KHz. scif::generic_clock_enable( scif::GenericClock::GCLK10, scif::ClockSource::RCSYS, ); max_freq = 113600 / 32; } let divisor = (frequency + max_freq - 1) / frequency; // ceiling of division let divisor_pow2 = math::closest_power_of_two(divisor); let clock_divisor = cmp::min(math::log_base_two(divisor_pow2), 7); self.adc_clk_freq.set(max_freq / (1 << (clock_divisor))); cfg_val += Configuration::PRESCAL.val(clock_divisor); } else { // CPU clock self.cpu_clock.set(true); scif::generic_clock_enable(scif::GenericClock::GCLK10, scif::ClockSource::CLK_CPU); // determine clock divider // we need the ADC_CLK to be a maximum of 1.5 MHz in frequency, // so we need to find the PRESCAL value that will make this // happen. // Formula: f(ADC_CLK) = f(CLK_CPU)/2^(N+2) <= 1.5 MHz // and we solve for N // becomes: N <= ceil(log_2(f(CLK_CPU)/1500000)) - 2 let cpu_frequency = pm::get_system_frequency(); let divisor = (cpu_frequency + (1500000 - 1)) / 1500000; // ceiling of division let divisor_pow2 = math::closest_power_of_two(divisor); let clock_divisor = cmp::min( math::log_base_two(divisor_pow2).checked_sub(2).unwrap_or(0), 7, ); self.adc_clk_freq .set(cpu_frequency / (1 << (clock_divisor + 2))); cfg_val += Configuration::PRESCAL.val(clock_divisor); } if self.cpu_clock.get() { cfg_val += Configuration::CLKSEL::ApbClock } else { cfg_val += Configuration::CLKSEL::GenericClock } self.registers.cfg.write(cfg_val); // set startup to wait 24 cycles self.registers.tim.write( TimingConfiguration::ENSTUP::Enable + TimingConfiguration::STARTUP.val(0x17), ); // software reset (does not clear registers) self.registers.cr.write(Control::SWRST::SET); // enable ADC self.registers.cr.write(Control::EN::SET); // wait until status is enabled let mut timeout = 10000; while !self.registers.sr.is_set(Status::EN) { timeout -= 1; if timeout == 0 { // ADC never enabled return ReturnCode::FAIL; } } // enable Bandgap buffer and Reference buffer. I don't actually // know what these do, but you need to turn them on self.registers .cr .write(Control::BGREQEN::SET + Control::REFBUFEN::SET); // wait until buffers are enabled timeout = 100000; while !self .registers .sr .matches_all(Status::BGREQ::SET + Status::REFBUF::SET + Status::EN::SET) { timeout -= 1; if timeout == 0 { // ADC buffers never enabled return ReturnCode::FAIL; } } ReturnCode::SUCCESS } } /// Disables the ADC so that the chip can return to deep sleep fn disable(&self) { // disable ADC self.registers.cr.write(Control::DIS::SET); // wait until status is disabled let mut timeout = 10000; while self.registers.sr.is_set(Status::EN) { timeout -= 1; if timeout == 0 { // ADC never disabled return; } } // disable bandgap and reference buffers self.registers .cr .write(Control::BGREQDIS::SET + Control::REFBUFDIS::SET); self.enabled.set(false); scif::generic_clock_disable(scif::GenericClock::GCLK10); pm::disable_clock(Clock::PBA(PBAClock::ADCIFE)); } } /// Implements an ADC capable reading ADC samples on any channel. impl hil::adc::Adc for Adc { type Channel = AdcChannel; /// Capture a single analog sample, calling the client when complete. /// Returns an error if the ADC is already sampling. /// /// - `channel`: the ADC channel to sample fn sample(&self, channel: &Self::Channel) -> ReturnCode { // always configure to 1KHz to get the slowest clock with single sampling let res = self.config_and_enable(1000); if res != ReturnCode::SUCCESS { res } else if !self.enabled.get() { ReturnCode::EOFF } else if self.active.get() { // only one operation at a time ReturnCode::EBUSY } else { self.active.set(true); self.continuous.set(false); self.timer_repeats.set(0); self.timer_counts.set(0); let cfg = SequencerConfig::MUXNEG.val(0x7) + // ground pad SequencerConfig::MUXPOS.val(channel.chan_num) + SequencerConfig::INTERNAL.val(0x2 | channel.internal) + SequencerConfig::RES::Bits12 + SequencerConfig::TRGSEL::Software + SequencerConfig::GCOMP::Disable + SequencerConfig::GAIN::Gain0p5x + SequencerConfig::BIPOLAR::Disable + SequencerConfig::HWLA::Enable; self.registers.seqcfg.write(cfg); // clear any current status self.clear_status(); // enable end of conversion interrupt self.registers.ier.write(Interrupt::SEOC::SET); // initiate conversion self.registers.cr.write(Control::STRIG::SET); ReturnCode::SUCCESS } } /// Request repeated analog samples on a particular channel, calling after /// each sample. In order to not unacceptably slow down the system /// collecting samples, this interface is limited to one sample every 100 /// microseconds (10000 samples per second). To sample faster, use the /// sample_highspeed function. /// /// - `channel`: the ADC channel to sample /// - `frequency`: the number of samples per second to collect fn sample_continuous(&self, channel: &Self::Channel, frequency: u32) -> ReturnCode { let res = self.config_and_enable(frequency); if res != ReturnCode::SUCCESS { res } else if !self.enabled.get() { ReturnCode::EOFF } else if self.active.get() { // only one sample at a time ReturnCode::EBUSY } else if frequency == 0 || frequency > 10000 { // limit sampling frequencies to a valid range ReturnCode::EINVAL } else { self.active.set(true); self.continuous.set(true); // adc sequencer configuration let mut cfg = SequencerConfig::MUXNEG.val(0x7) + // ground pad SequencerConfig::MUXPOS.val(channel.chan_num) + SequencerConfig::INTERNAL.val(0x2 | channel.internal) + SequencerConfig::RES::Bits12 + SequencerConfig::GCOMP::Disable + SequencerConfig::GAIN::Gain0p5x + SequencerConfig::BIPOLAR::Disable + SequencerConfig::HWLA::Enable; // set trigger based on how good our clock is if self.cpu_clock.get() { cfg += SequencerConfig::TRGSEL::InternalAdcTimer; } else { cfg += SequencerConfig::TRGSEL::ContinuousMode; } self.registers.seqcfg.write(cfg); // stop timer if running self.registers.cr.write(Control::TSTOP::SET); if self.cpu_clock.get() { // This logic only applies for sampling off the CPU // setup timer for low-frequency samples. Based on the ADC clock, // the minimum timer frequency is: // 1500000 / (0xFFFF + 1) = 22.888 Hz. // So for any frequency less than 23 Hz, we will keep our own // counter in addition and only actually perform a callback every N // timer fires. This is important to enable low-jitter sampling in // the 1-22 Hz range. let timer_frequency; if frequency < 23 { // set a number of timer repeats before the callback is // performed. 60 here is an arbitrary number which limits the // actual itimer frequency to between 42 and 60 in the desired // range of 1-22 Hz, which seems slow enough to keep the system // from getting bogged down with interrupts let counts = 60 / frequency; self.timer_repeats.set(counts as u8); self.timer_counts.set(0); timer_frequency = frequency * counts; } else { // we can sample at this frequency directly with the timer self.timer_repeats.set(0); self.timer_counts.set(0); timer_frequency = frequency; } // set timer, limit to bounds // f(timer) = f(adc) / (counter + 1) let mut counter = (self.adc_clk_freq.get() / timer_frequency) - 1; counter = cmp::max(cmp::min(counter, 0xFFFF), 0); self.registers .itimer .write(InternalTimer::ITMC.val(counter)); } else { // we can sample at this frequency directly with the timer self.timer_repeats.set(0); self.timer_counts.set(0); } // clear any current status self.clear_status(); // enable end of conversion interrupt self.registers.ier.write(Interrupt::SEOC::SET); // start timer self.registers.cr.write(Control::TSTART::SET); ReturnCode::SUCCESS } } /// Stop continuously sampling the ADC. /// This is expected to be called to stop continuous sampling operations, /// but can be called to abort any currently running operation. The buffer, /// if any, will be returned via the `samples_ready` callback. fn stop_sampling(&self) -> ReturnCode { if !self.enabled.get() { ReturnCode::EOFF } else if !self.active.get() { // cannot cancel sampling that isn't running ReturnCode::EINVAL } else { // clean up state self.active.set(false); self.continuous.set(false); self.dma_running.set(false); // stop internal timer self.registers.cr.write(Control::TSTOP::SET); // disable sample interrupts self.registers.idr.write(Interrupt::SEOC::SET); // reset the ADC peripheral self.registers.cr.write(Control::SWRST::SET); // disable the ADC self.disable(); // stop DMA transfer if going. This should safely return a None if // the DMA was not being used let dma_buffer = self.rx_dma.map_or(None, |rx_dma| { let dma_buf = rx_dma.abort_transfer(); rx_dma.disable(); dma_buf }); self.rx_length.set(0); // store the buffer if it exists dma_buffer.map(|dma_buf| { // change buffer back into a [u16] // the buffer was originally a [u16] so this should be okay let buf_ptr = unsafe { mem::transmute::<*mut u8, *mut u16>(dma_buf.as_mut_ptr()) }; let buf = unsafe { slice::from_raw_parts_mut(buf_ptr, dma_buf.len() / 2) }; // we'll place it here so we can return it to the higher level // later in a `retrieve_buffers` call self.stopped_buffer.replace(buf); }); ReturnCode::SUCCESS } } /// Resolution of the reading. fn get_resolution_bits(&self) -> usize { 12 } /// Voltage reference is VCC/2, we assume VCC is 3.3 V, and we use a gain /// of 0.5. fn get_voltage_reference_mv(&self) -> Option<usize> { Some(3300) } } /// Implements an ADC capable of continuous sampling impl hil::adc::AdcHighSpeed for Adc { /// Capture buffered samples from the ADC continuously at a given /// frequency, calling the client whenever a buffer fills up. The client is /// then expected to either stop sampling or provide an additional buffer /// to sample into. Note that due to hardware constraints the maximum /// frequency range of the ADC is from 187 kHz to 23 Hz (although its /// precision is limited at higher frequencies due to aliasing). /// /// - `channel`: the ADC channel to sample /// - `frequency`: frequency to sample at /// - `buffer1`: first buffer to fill with samples /// - `length1`: number of samples to collect (up to buffer length) /// - `buffer2`: second buffer to fill once the first is full /// - `length2`: number of samples to collect (up to buffer length) fn sample_highspeed( &self, channel: &Self::Channel, frequency: u32, buffer1: &'static mut [u16], length1: usize, buffer2: &'static mut [u16], length2: usize, ) -> ( ReturnCode, Option<&'static mut [u16]>, Option<&'static mut [u16]>, ) { let res = self.config_and_enable(frequency); if res != ReturnCode::SUCCESS { (res, Some(buffer1), Some(buffer2)) } else if !self.enabled.get() { (ReturnCode::EOFF, Some(buffer1), Some(buffer2)) } else if self.active.get() { // only one sample at a time (ReturnCode::EBUSY, Some(buffer1), Some(buffer2)) } else if frequency <= (self.adc_clk_freq.get() / (0xFFFF + 1)) || frequency > 250000 { // can't sample faster than the max sampling frequency or slower // than the timer can be set to (ReturnCode::EINVAL, Some(buffer1), Some(buffer2)) } else if length1 == 0 { // at least need a valid length for the for the first buffer full of // samples. Otherwise, what are we doing here? (ReturnCode::EINVAL, Some(buffer1), Some(buffer2)) } else { self.active.set(true); self.continuous.set(true); // store the second buffer for later use self.next_dma_buffer.replace(buffer2); self.next_dma_length.set(length2); // adc sequencer configuration let mut cfg = SequencerConfig::MUXNEG.val(0x7) + // ground pad SequencerConfig::MUXPOS.val(channel.chan_num) + SequencerConfig::INTERNAL.val(0x2 | channel.internal) + SequencerConfig::RES::Bits12 + SequencerConfig::GCOMP::Disable + SequencerConfig::GAIN::Gain0p5x + SequencerConfig::BIPOLAR::Disable + SequencerConfig::HWLA::Enable; // set trigger based on how good our clock is if self.cpu_clock.get() { cfg += SequencerConfig::TRGSEL::InternalAdcTimer; } else { cfg += SequencerConfig::TRGSEL::ContinuousMode; } self.registers.seqcfg.write(cfg); // stop timer if running self.registers.cr.write(Control::TSTOP::SET); if self.cpu_clock.get() { // set timer, limit to bounds // f(timer) = f(adc) / (counter + 1) let mut counter = (self.adc_clk_freq.get() / frequency) - 1; counter = cmp::max(cmp::min(counter, 0xFFFF), 0); self.registers .itimer .write(InternalTimer::ITMC.val(counter)); } // clear any current status self.clear_status(); // receive up to the buffer's length samples let dma_len = cmp::min(buffer1.len(), length1); // change buffer into a [u8] // this is unsafe but acceptable for the following reasons // * the buffer is aligned based on 16-bit boundary, so the 8-bit // alignment is fine // * the DMA is doing checking based on our expected data width to // make sure we don't go past dma_buf.len()/width // * we will transmute the array back to a [u16] after the DMA // transfer is complete let dma_buf_ptr = unsafe { mem::transmute::<*mut u16, *mut u8>(buffer1.as_mut_ptr()) }; let dma_buf = unsafe { slice::from_raw_parts_mut(dma_buf_ptr, buffer1.len() * 2) }; // set up the DMA self.rx_dma.map(move |dma| { self.dma_running.set(true); dma.enable(); self.rx_length.set(dma_len); dma.do_transfer(self.rx_dma_peripheral, dma_buf, dma_len); }); // start timer self.registers.cr.write(Control::TSTART::SET); (ReturnCode::SUCCESS, None, None) } } /// Provide a new buffer to send on-going buffered continuous samples to. /// This is expected to be called after the `samples_ready` callback. /// /// - `buf`: buffer to fill with samples /// - `length`: number of samples to collect (up to buffer length) fn provide_buffer( &self, buf: &'static mut [u16], length: usize, ) -> (ReturnCode, Option<&'static mut [u16]>) { if !self.enabled.get() { (ReturnCode::EOFF, Some(buf)) } else if !self.active.get() { // cannot continue sampling that isn't running (ReturnCode::EINVAL, Some(buf)) } else if !self.continuous.get() { // cannot continue a single sample operation (ReturnCode::EINVAL, Some(buf)) } else if self.next_dma_buffer.is_some() { // we've already got a second buffer, we don't need a third yet (ReturnCode::EBUSY, Some(buf)) } else { // store the buffer for later use self.next_dma_buffer.replace(buf); self.next_dma_length.set(length); (ReturnCode::SUCCESS, None) } } /// Reclaim buffers after the ADC is stopped. /// This is expected to be called after `stop_sampling`. fn retrieve_buffers( &self, ) -> ( ReturnCode, Option<&'static mut [u16]>, Option<&'static mut [u16]>, ) { if self.active.get() { // cannot return buffers while running (ReturnCode::EINVAL, None, None) } else { // we're not running, so give back whatever we've got ( ReturnCode::SUCCESS, self.next_dma_buffer.take(), self.stopped_buffer.take(), ) } } } /// Implements a client of a DMA. impl dma::DMAClient for Adc { /// Handler for DMA transfer completion. /// /// - `pid`: the DMA peripheral that is complete fn transfer_done(&self, pid: dma::DMAPeripheral) { // check if this was an RX transfer if pid == self.rx_dma_peripheral { // RX transfer was completed // get buffer filled with samples from DMA let dma_buffer = self.rx_dma.map_or(None, |rx_dma| { self.dma_running.set(false); let dma_buf = rx_dma.abort_transfer(); rx_dma.disable(); dma_buf }); // get length of received buffer let length = self.rx_length.get(); // start a new transfer with the next buffer // we need to do this quickly in order to keep from missing samples. // At 175000 Hz, we only have 5.8 us (~274 cycles) to do so self.next_dma_buffer.take().map(|buf| { // first determine the buffer's length in samples let dma_len = cmp::min(buf.len(), self.next_dma_length.get()); // only continue with a nonzero length. If we were given a // zero-length buffer or length field, assume that the user knew // what was going on, and just don't use the buffer if dma_len > 0 { // change buffer into a [u8] // this is unsafe but acceptable for the following reasons // * the buffer is aligned based on 16-bit boundary, so the // 8-bit alignment is fine // * the DMA is doing checking based on our expected data // width to make sure we don't go past // dma_buf.len()/width // * we will transmute the array back to a [u16] after the // DMA transfer is complete let dma_buf_ptr = unsafe { mem::transmute::<*mut u16, *mut u8>(buf.as_mut_ptr()) }; let dma_buf = unsafe { slice::from_raw_parts_mut(dma_buf_ptr, buf.len() * 2) }; // set up the DMA self.rx_dma.map(move |dma| { self.dma_running.set(true); dma.enable(); self.rx_length.set(dma_len); dma.do_transfer(self.rx_dma_peripheral, dma_buf, dma_len); }); } else { // if length was zero, just keep the buffer in the takecell // so we can return it when `stop_sampling` is called self.next_dma_buffer.replace(buf); } }); // alert client self.client.map(|client| { dma_buffer.map(|dma_buf| { // change buffer back into a [u16] // the buffer was originally a [u16] so this should be okay let buf_ptr = unsafe { mem::transmute::<*mut u8, *mut u16>(dma_buf.as_mut_ptr()) }; let buf = unsafe { slice::from_raw_parts_mut(buf_ptr, dma_buf.len() / 2) }; // pass the buffer up to the next layer. It will then either // send down another buffer to continue sampling, or stop // sampling client.samples_ready(buf, length); }); }); } } }
37.042279
99
0.551983
efcce4e52fd3c4967a770c5bec430d21e3fbc69e
6,047
use super::rocket; use rocket::http::ContentType; use rocket::http::Status; use rocket::local::blocking::Client; use serde_json::Value; #[test] fn test_create() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/create").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!( response.into_string(), Some("Created clingo Solver.".into()) ); let response = client.get("/register_dl_theory").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!( response.into_string(), Some("Difference logic theory registered.".into()) ); let response = client.post("/add").body("a.").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.into_string(), Some("Added data to Solver.".into())); let response = client .post("/ground") .header(ContentType::JSON) .body("{\"base\":[]}") .dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.into_string(), Some("Grounding.".into())); let response = client.get("/solve").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.into_string(), Some("Solving.".into())); let mut response = client.get("/model").dispatch(); assert_eq!(response.status(), Status::Ok); let mut body_string = response.into_string(); while body_string == Some("\"Running\"".into()) { response = client.get("/model").dispatch(); body_string = response.into_string(); } // assert_eq!(response.status(), Status::Ok); let data = body_string.unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!( data["Model"], Value::Array(vec![Value::Number(97.into()), Value::Number(10.into())]) ); let response = client.get("/resume").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.into_string(), Some("Search is resumed.".into())); let response = client.get("/close").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.into_string(), Some("Solve handle closed.".into())); let response = client.get("/statistics").dispatch(); assert_eq!(response.status(), Status::Ok); // assert_eq!( // response.body_string(), // Some("InternalError: Solver::solve failed! No control object.".into()) // ); } #[test] fn test_register_dl_theory() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/register_dl_theory").dispatch(); assert_eq!(response.status(), Status::Ok); let data = response.into_string().unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!(data["type"], "InternalError"); assert_eq!( &data["msg"], "Solver::register_dl_theory failed! No control object." ); } #[test] fn test_add() { let client = Client::tracked(rocket()).unwrap(); let response = client.post("/add").body("body.").dispatch(); assert_eq!(response.status(), Status::Ok); let data = response.into_string().unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!(data["type"], "InternalError"); assert_eq!(&data["msg"], "Solver::add failed! No control object."); } #[test] fn test_ground() { let client = Client::tracked(rocket()).unwrap(); let response = client .post("/ground") .header(ContentType::JSON) .body("{\"base\":[]}") .dispatch(); assert_eq!(response.status(), Status::Ok); let data = response.into_string().unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!(data["type"], "InternalError"); assert_eq!(&data["msg"], "Solver::ground failed! No control object."); } #[test] fn test_solve() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/solve").dispatch(); assert_eq!(response.status(), Status::Ok); let data = response.into_string().unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!(data["type"], "InternalError"); assert_eq!(&data["msg"], "Solver::solve failed! No control object."); } #[test] fn test_model() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/model").dispatch(); assert_eq!(response.status(), Status::Ok); let data = response.into_string().unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!(data["type"], "InternalError"); assert_eq!( data["msg"], Value::String("Solver::model failed! No SolveHandle.".to_string()) ); } #[test] fn test_resume() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/resume").dispatch(); assert_eq!(response.status(), Status::Ok); let data = response.into_string().unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!(data["type"], "InternalError"); assert_eq!( data["msg"], Value::String("Solver::resume failed! No SolveHandle.".to_string()) ); } #[test] fn test_close() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/close").dispatch(); assert_eq!(response.status(), Status::Ok); let data = response.into_string().unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!(data["type"], "InternalError"); assert_eq!( data["msg"], Value::String("Solver::close failed! Solver is not running.".to_string()) ); } #[test] fn test_statistics() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/statistics").dispatch(); assert_eq!(response.status(), Status::Ok); let data = response.into_string().unwrap(); let data: Value = serde_json::from_str(&data).unwrap(); assert_eq!(data["type"], "InternalError"); assert_eq!( &data["msg"], "Solver::statistics failed! No control object." ); }
37.09816
81
0.626261
8ff1cb5d2ba3c6c700379eb58ef006bc1e1e7d02
256
use crate::error::DatabaseError; use crate::mysql::protocol::ErrPacket; pub struct MySqlError(pub(super) ErrPacket); impl DatabaseError for MySqlError { fn message(&self) -> &str { &*self.0.error_message } } impl_fmt_error!(MySqlError);
19.692308
44
0.703125
6188d0643b64357d92f3b7e8845f5119a7e78a35
1,040
use crate::sound::wav; use std::io; use std::fmt; pub struct SoundBank { pub wave100: Box<[u8; 25600]>, pub samples: Vec<wav::WavSample> } impl fmt::Display for SoundBank { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "WAVE100: {:2X?}...", &self.wave100[..8])?; for sample in self.samples.iter() { writeln!(f, "{}", sample)?; } Ok(()) } } impl SoundBank { pub fn load_from<R: io::Read>(mut f: R) -> io::Result<SoundBank> { let mut wave100 = Box::new([0u8; 25600]); f.read_exact(wave100.as_mut())?; let mut samples = Vec::with_capacity(16); loop { match wav::WavSample::read_from(&mut f) { Ok(sample) => samples.push(sample), Err(_) => return Ok(SoundBank { wave100, samples }) } } } pub fn get_wave(&self, index: usize) -> &[u8] { &self.wave100[index*256..(index+1)*256] } }
23.636364
71
0.496154
5040aa4c7bd2ff03aa2233a16d6236c21f8c397e
1,242
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct OSFingerprint { pub id: String, pub os_name: String, pub version: String, pub icmp_echo_code: u8, pub icmp_ip_ttl: u8, pub icmp_echo_ip_df: bool, pub icmp_unreach_ip_df: bool, pub icmp_unreach_ip_len: String, pub icmp_unreach_data_ip_id_byte_order: String, pub tcp_ip_ttl: u8, pub tcp_ip_df: bool, pub tcp_window_size: Vec<u16>, pub tcp_option_order: Vec<String>, pub tcp_rst_text_payload: bool, pub tcp_ecn_support: bool, } impl OSFingerprint { pub fn new() -> OSFingerprint { OSFingerprint { id: String::new(), os_name: String::new(), version: String::new(), icmp_echo_code: 0, icmp_ip_ttl: 0, icmp_echo_ip_df: false, icmp_unreach_ip_df: false, icmp_unreach_ip_len: String::from("EQ"), icmp_unreach_data_ip_id_byte_order: String::from("EQ"), tcp_ip_ttl: 0, tcp_ip_df: false, tcp_window_size: vec![], tcp_option_order: vec![], tcp_rst_text_payload: false, tcp_ecn_support: false, } } }
28.883721
67
0.609501
67c3ff25d3cf3c219b93e6441dbdbe7bbd698275
4,098
mod annotation; pub use annotation::annotate; mod bbh_factory; pub use bbh_factory::*; mod bitmap; pub use bitmap::*; mod blend_mode; pub use blend_mode::*; mod blender; pub use blender::*; mod blur_types; pub use blur_types::*; pub mod canvas; pub use canvas::{AutoCanvasRestore, Canvas, OwnedCanvas}; mod clip_op; pub use clip_op::*; mod color; pub use color::*; pub mod color_filter; pub use color_filter::{color_filters, ColorFilter}; mod color_space; pub use color_space::*; pub mod contour_measure; pub use contour_measure::{ContourMeasure, ContourMeasureIter}; mod coverage_mode; pub use coverage_mode::*; mod cubic_map; pub use cubic_map::*; mod data; pub use data::*; mod data_table; pub use data_table::*; mod deferred_display_list; pub use deferred_display_list::*; mod deferred_display_list_recorder; pub use deferred_display_list_recorder::*; pub mod document; pub use document::Document; pub mod drawable; pub use drawable::Drawable; mod encoded_image_format; pub use encoded_image_format::*; // unsupported, because it's used in experimental APIs only. // mod executor; mod flattenable; pub use flattenable::*; pub mod font; pub use font::Font; pub mod font_arguments; pub use font_arguments::FontArguments; // unsupported, because it's not used in publicly exposed APIs: // mod font_lcd_config; pub mod font_metrics; pub use font_metrics::FontMetrics; mod font_mgr; pub use font_mgr::*; pub mod font_parameters; pub mod font_style; pub use font_style::FontStyle; mod font_types; pub use font_types::*; pub mod graphics; pub mod image; pub use image::Image; mod image_encoder; pub use image_encoder::*; pub mod image_filter; pub use image_filter::ImageFilter; mod image_generator; pub use image_generator::*; mod image_info; pub use image_info::*; mod m44; pub use m44::*; mod mask_filter; pub use mask_filter::*; pub mod matrix; pub use matrix::Matrix; mod milestone; pub use milestone::*; pub mod paint; pub use paint::Paint; // We keep these around for the time being. pub use paint::Cap as PaintCap; pub use paint::Join as PaintJoin; pub use paint::Style as PaintStyle; pub mod path; pub use path::Path; mod path_builder; pub use path_builder::PathBuilder; pub mod path_effect; pub use path_effect::PathEffect; pub mod path_measure; pub use path_measure::PathMeasure; pub mod path_types; pub use path_types::*; mod picture; pub use picture::*; pub mod picture_recorder; pub use picture_recorder::PictureRecorder; mod pixel_ref; pub use pixel_ref::*; mod pixmap; pub use pixmap::*; mod point; pub use point::*; mod point3; pub use point3::*; mod promise_image_texture; pub use promise_image_texture::*; mod raster_handle_allocator; pub use raster_handle_allocator::*; mod rect; pub use rect::*; pub mod region; pub use region::Region; pub mod rrect; pub use rrect::RRect; mod rsxform; pub use rsxform::*; pub mod sampling_options; #[allow(deprecated)] pub use sampling_options::{ CubicResampler, FilterMode, FilterOptions, MipmapMode, SamplingMode, SamplingOptions, }; mod scalar_; pub use scalar_::*; pub mod shader; pub use shader::{shaders, Shader}; mod size; pub use size::*; pub mod stroke_rec; pub use stroke_rec::StrokeRec; pub mod surface; pub use surface::Surface; mod surface_characterization; pub use surface_characterization::*; mod surface_props; pub use surface_props::*; mod swizzle; pub use swizzle::*; mod text_blob; pub use text_blob::*; mod tile_mode; pub use self::tile_mode::*; mod time; pub use time::*; mod trace_memory_dump; pub use trace_memory_dump::*; pub mod typeface; pub use typeface::Typeface; mod types; pub use types::*; mod un_pre_multiply; pub use un_pre_multiply::*; pub mod vertices; pub use vertices::Vertices; pub mod yuva_info; pub use yuva_info::YUVAInfo; pub mod yuva_pixmaps; pub use yuva_pixmaps::{yuva_pixmap_info, YUVAPixmapInfo, YUVAPixmaps}; // // Skia specific traits used for overloading functions. // pub trait Contains<T> { fn contains(&self, other: T) -> bool; } pub trait QuickReject<T> { fn quick_reject(&self, other: &T) -> bool; }
16.326693
89
0.74939
8f420f34a8a5a5629b79e41faa1c989e7ca019da
33,973
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod operations { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationListResult, list::Error> { let client = &operation_config.client; let uri_str = &format!("{}/providers/Microsoft.ContainerService/operations", &operation_config.base_path,); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: OperationListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; list::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } } pub mod managed_clusters { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<ManagedClusterListResult, list::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/providers/Microsoft.ContainerService/managedClusters", &operation_config.base_path, subscription_id ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ManagedClusterListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; list::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn list_by_resource_group( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, ) -> std::result::Result<ManagedClusterListResult, list_by_resource_group::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters", &operation_config.base_path, subscription_id, resource_group_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_by_resource_group::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list_by_resource_group::BuildRequestError)?; let rsp = client.execute(req).await.context(list_by_resource_group::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?; let rsp_value: ManagedClusterListResult = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?; list_by_resource_group::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod list_by_resource_group { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn get_upgrade_profile( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, ) -> std::result::Result<ManagedClusterUpgradeProfile, get_upgrade_profile::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}/upgradeProfiles/default", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get_upgrade_profile::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get_upgrade_profile::BuildRequestError)?; let rsp = client.execute(req).await.context(get_upgrade_profile::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get_upgrade_profile::ResponseBytesError)?; let rsp_value: ManagedClusterUpgradeProfile = serde_json::from_slice(&body).context(get_upgrade_profile::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get_upgrade_profile::ResponseBytesError)?; get_upgrade_profile::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod get_upgrade_profile { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn get_access_profile( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, role_name: &str, ) -> std::result::Result<ManagedClusterAccessProfile, get_access_profile::Error> { let client = &operation_config.client; let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}/accessProfiles/{}/listCredential" , & operation_config . base_path , subscription_id , resource_group_name , resource_name , role_name) ; let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get_access_profile::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(get_access_profile::BuildRequestError)?; let rsp = client.execute(req).await.context(get_access_profile::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get_access_profile::ResponseBytesError)?; let rsp_value: ManagedClusterAccessProfile = serde_json::from_slice(&body).context(get_access_profile::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get_access_profile::ResponseBytesError)?; get_access_profile::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod get_access_profile { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn list_cluster_admin_credentials( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, ) -> std::result::Result<CredentialResults, list_cluster_admin_credentials::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}/listClusterAdminCredential", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_cluster_admin_credentials::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(list_cluster_admin_credentials::BuildRequestError)?; let rsp = client .execute(req) .await .context(list_cluster_admin_credentials::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_cluster_admin_credentials::ResponseBytesError)?; let rsp_value: CredentialResults = serde_json::from_slice(&body).context(list_cluster_admin_credentials::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_cluster_admin_credentials::ResponseBytesError)?; list_cluster_admin_credentials::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod list_cluster_admin_credentials { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn list_cluster_user_credentials( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, ) -> std::result::Result<CredentialResults, list_cluster_user_credentials::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}/listClusterUserCredential", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_cluster_user_credentials::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(list_cluster_user_credentials::BuildRequestError)?; let rsp = client .execute(req) .await .context(list_cluster_user_credentials::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_cluster_user_credentials::ResponseBytesError)?; let rsp_value: CredentialResults = serde_json::from_slice(&body).context(list_cluster_user_credentials::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_cluster_user_credentials::ResponseBytesError)?; list_cluster_user_credentials::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod list_cluster_user_credentials { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, ) -> std::result::Result<ManagedCluster, get::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get::BuildRequestError)?; let rsp = client.execute(req).await.context(get::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: ManagedCluster = serde_json::from_slice(&body).context(get::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; get::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod get { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, parameters: &ManagedCluster, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.put(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(create_or_update::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(parameters); let req = req_builder.build().context(create_or_update::BuildRequestError)?; let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?; let rsp_value: ManagedCluster = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?; Ok(create_or_update::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?; let rsp_value: ManagedCluster = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?; create_or_update::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod create_or_update { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(ManagedCluster), Created201(ManagedCluster), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn update_tags( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, parameters: &TagsObject, ) -> std::result::Result<ManagedCluster, update_tags::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.patch(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(update_tags::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(parameters); let req = req_builder.build().context(update_tags::BuildRequestError)?; let rsp = client.execute(req).await.context(update_tags::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(update_tags::ResponseBytesError)?; let rsp_value: ManagedCluster = serde_json::from_slice(&body).context(update_tags::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(update_tags::ResponseBytesError)?; update_tags::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod update_tags { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, ) -> std::result::Result<delete::Response, delete::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.delete(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(delete::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(delete::BuildRequestError)?; let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { StatusCode::ACCEPTED => Ok(delete::Response::Accepted202), StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; delete::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod delete { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Accepted202, NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn reset_service_principal_profile( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, parameters: &ManagedClusterServicePrincipalProfile, ) -> std::result::Result<reset_service_principal_profile::Response, reset_service_principal_profile::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}/resetServicePrincipalProfile", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(reset_service_principal_profile::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(parameters); let req = req_builder.build().context(reset_service_principal_profile::BuildRequestError)?; let rsp = client .execute(req) .await .context(reset_service_principal_profile::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(reset_service_principal_profile::Response::Ok200), StatusCode::ACCEPTED => Ok(reset_service_principal_profile::Response::Accepted202), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(reset_service_principal_profile::ResponseBytesError)?; reset_service_principal_profile::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod reset_service_principal_profile { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, Accepted202, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } pub async fn reset_aad_profile( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, parameters: &ManagedClusterAadProfile, ) -> std::result::Result<reset_aad_profile::Response, reset_aad_profile::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerService/managedClusters/{}/resetAADProfile", &operation_config.base_path, subscription_id, resource_group_name, resource_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(reset_aad_profile::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(parameters); let req = req_builder.build().context(reset_aad_profile::BuildRequestError)?; let rsp = client.execute(req).await.context(reset_aad_profile::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(reset_aad_profile::Response::Ok200), StatusCode::ACCEPTED => Ok(reset_aad_profile::Response::Accepted202), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(reset_aad_profile::ResponseBytesError)?; reset_aad_profile::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod reset_aad_profile { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, Accepted202, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } }
49.740849
266
0.62479
50046917924735f70894e88874f61189867e3a51
4,235
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::vote_data::VoteData; use failure::prelude::*; use libra_crypto::{hash::CryptoHash, HashValue}; use libra_types::{ block_info::BlockInfo, crypto_proxies::{LedgerInfoWithSignatures, ValidatorVerifier}, ledger_info::LedgerInfo, }; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fmt::{Display, Formatter}; #[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, } } pub fn vote_data(&self) -> &VoteData { &self.vote_data } pub fn certified_block(&self) -> &BlockInfo { self.vote_data().proposed() } pub fn parent_block(&self) -> &BlockInfo { self.vote_data().parent() } pub fn ledger_info(&self) -> &LedgerInfoWithSignatures { &self.signed_ledger_info } pub fn commit_info(&self) -> &BlockInfo { self.ledger_info().ledger_info().commit_info() } /// If the QC commits reconfiguration and starts a new epoch pub fn ends_epoch(&self) -> bool { self.signed_ledger_info .ledger_info() .next_validator_set() .is_some() } /// QuorumCert for the genesis block deterministically generated from end-epoch LedgerInfo: /// - the ID of the block is determined by the generated genesis block. /// - the accumulator root hash of the LedgerInfo is set to the last executed state of previous /// epoch. /// - the map of signatures is empty because genesis block is implicitly agreed. pub fn certificate_for_genesis_from_ledger_info( ledger_info: &LedgerInfo, genesis_id: HashValue, ) -> QuorumCert { let ancestor = BlockInfo::new( ledger_info.epoch() + 1, 0, genesis_id, ledger_info.transaction_accumulator_hash(), ledger_info.version(), ledger_info.timestamp_usecs(), None, ); let vote_data = VoteData::new(ancestor.clone(), ancestor.clone()); let li = LedgerInfo::new(ancestor, vote_data.hash()); QuorumCert::new( vote_data, LedgerInfoWithSignatures::new(li, BTreeMap::new()), ) } 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's QC is implicitly agreed upon, it doesn't have real signatures. // If someone sends us a QC on a fake genesis, it'll fail to insert into BlockStore // because of the round constraint. if self.certified_block().round() == 0 { ensure!( self.parent_block() == self.certified_block(), "Genesis QC has inconsistent parent block with certified block" ); ensure!( self.certified_block() == self.ledger_info().ledger_info().commit_info(), "Genesis QC has inconsistent commit block with certified block" ); ensure!( self.ledger_info().signatures().is_empty(), "Genesis QC should not carry signatures" ); return Ok(()); } self.ledger_info() .verify(validator) .with_context(|e| format!("Fail to verify QuorumCert: {:?}", e))?; Ok(()) } }
33.346457
99
0.606612
d958dfc681b00fe0703c2770dbf5ef78807a3033
751
//! HIR datatypes. See the [rustc guide] for more info. //! //! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html #![feature(crate_visibility_modifier)] #![feature(const_fn)] // For the unsizing cast on `&[]` #![feature(in_band_lifetimes)] #![feature(specialization)] #![recursion_limit = "256"] #[macro_use] extern crate rustc_data_structures; pub mod def; pub use rustc_span::def_id; mod hir; pub mod hir_id; pub mod intravisit; pub mod itemlikevisit; pub mod lang_items; pub mod pat_util; pub mod print; mod stable_hash_impls; mod target; pub mod weak_lang_items; pub use hir::*; pub use hir_id::*; pub use lang_items::{LangItem, LanguageItems}; pub use stable_hash_impls::HashStableContext; pub use target::{MethodKind, Target};
23.46875
67
0.744341
f8b0865f26321c7b68e8ed9f9ae0e1147b4641f9
2,017
use crossbeam_channel as cc; use serde::Serialize; #[derive(Serialize, Debug, PartialEq)] pub enum Severity { WARNING, ERROR, } impl Severity { pub fn as_str(&self) -> &str { match self { Severity::WARNING => "WARNING", Severity::ERROR => "ERROR", } } } pub type IndexingResults<T> = std::result::Result<IndexingProgress<T>, Notification>; #[derive(Debug)] pub enum IndexingProgress<T> { GotItem { item: T, }, /// Progress indicates how many ticks of the total amount have been processed /// the first number indicates the actual amount, the second the presumed total Progress { ticks: (u64, u64), }, Stopped, Finished, } pub struct Notification { pub severity: Severity, pub content: String, pub line: Option<usize>, } pub struct ProgressReporter<T> { update_channel: cc::Sender<std::result::Result<IndexingProgress<T>, Notification>>, processed_bytes: u64, progress_percentage: u64, total: u64, } impl<T> ProgressReporter<T> { pub fn new( total: u64, update_channel: cc::Sender<std::result::Result<IndexingProgress<T>, Notification>>, ) -> ProgressReporter<T> { ProgressReporter { update_channel, processed_bytes: 0, progress_percentage: 0, total, } } pub fn make_progress(&mut self, consumed: usize) { self.processed_bytes += consumed as u64; let new_progress_percentage: u64 = (self.processed_bytes as f64 / self.total as f64 * 100.0).round() as u64; if new_progress_percentage != self.progress_percentage { self.progress_percentage = new_progress_percentage; match self.update_channel.send(Ok(IndexingProgress::Progress { ticks: (self.processed_bytes, self.total), })) { Ok(()) => (), Err(e) => warn!("could not send: {}", e), } } } }
27.630137
91
0.599405
0a863c01845ee9f785eaf6c6c30aedcc597568fa
23,273
use crate::avm1::activation::Activation; use crate::avm1::error::Error; use crate::avm1::function::{Executable, FunctionObject}; use crate::avm1::object::shared_object::SharedObject; use crate::avm1::property::Attribute; use crate::avm1::{AvmString, Object, TObject, Value}; use crate::avm_warn; use crate::display_object::TDisplayObject; use flash_lso::types::Value as AmfValue; use flash_lso::types::{AMFVersion, Element, Lso}; use gc_arena::MutationContext; use json::JsonValue; pub fn delete_all<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.deleteAll() not implemented"); Ok(Value::Undefined) } pub fn get_disk_usage<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.getDiskUsage() not implemented"); Ok(Value::Undefined) } /// Serialize a Value to an AmfValue fn serialize_value<'gc>( activation: &mut Activation<'_, 'gc, '_>, elem: Value<'gc>, ) -> Option<AmfValue> { match elem { Value::Undefined => Some(AmfValue::Undefined), Value::Null => Some(AmfValue::Null), Value::Bool(b) => Some(AmfValue::Bool(b)), Value::Number(f) => Some(AmfValue::Number(f)), Value::String(s) => Some(AmfValue::String(s.to_string())), Value::Object(o) => { // Don't attempt to serialize functions let function = activation.context.avm1.prototypes.function; let array = activation.context.avm1.prototypes.array; let xml = activation.context.avm1.prototypes.xml_node; let date = activation.context.avm1.prototypes.date; if !o .is_instance_of(activation, o, function) .unwrap_or_default() { if o.is_instance_of(activation, o, array).unwrap_or_default() { let mut values = Vec::new(); let len = o.length(); recursive_serialize(activation, o, &mut values); Some(AmfValue::ECMAArray(vec![], values, len as u32)) } else if o.is_instance_of(activation, o, xml).unwrap_or_default() { o.as_xml_node().and_then(|xml_node| { xml_node .into_string(&mut |_| true) .map(|xml_string| AmfValue::XML(xml_string, true)) .ok() }) } else if o.is_instance_of(activation, o, date).unwrap_or_default() { o.as_date_object() .and_then(|date_obj| { date_obj .date_time() .map(|date_time| date_time.timestamp_millis()) }) .map(|millis| AmfValue::Date(millis as f64, None)) } else { let mut object_body = Vec::new(); recursive_serialize(activation, o, &mut object_body); Some(AmfValue::Object(object_body, None)) } } else { None } } } } /// Serialize an Object and any children to a JSON object fn recursive_serialize<'gc>( activation: &mut Activation<'_, 'gc, '_>, obj: Object<'gc>, elements: &mut Vec<Element>, ) { // Reversed to match flash player ordering for element_name in obj.get_keys(activation).iter().rev() { if let Ok(elem) = obj.get(element_name, activation) { if let Some(v) = serialize_value(activation, elem) { elements.push(Element::new(element_name, v)); } } } } /// Deserialize a AmfValue to a Value fn deserialize_value<'gc>(activation: &mut Activation<'_, 'gc, '_>, val: &AmfValue) -> Value<'gc> { match val { AmfValue::Null => Value::Null, AmfValue::Undefined => Value::Undefined, AmfValue::Number(f) => Value::Number(*f), AmfValue::String(s) => Value::String(AvmString::new(activation.context.gc_context, s)), AmfValue::Bool(b) => Value::Bool(*b), AmfValue::ECMAArray(_, associative, len) => { let array_constructor = activation.context.avm1.prototypes.array_constructor; if let Ok(Value::Object(obj)) = array_constructor.construct(activation, &[Value::Number(*len as f64)]) { for entry in associative { let value = deserialize_value(activation, entry.value()); if let Ok(i) = entry.name().parse::<usize>() { obj.set_array_element(i, value, activation.context.gc_context); } else { obj.define_value( activation.context.gc_context, &entry.name, value, Attribute::empty(), ); } } obj.into() } else { Value::Undefined } } AmfValue::Object(elements, _) => { // Deserialize Object let obj_proto = activation.context.avm1.prototypes.object; if let Ok(obj) = obj_proto.create_bare_object(activation, obj_proto) { for entry in elements { let value = deserialize_value(activation, entry.value()); obj.define_value( activation.context.gc_context, &entry.name, value, Attribute::empty(), ); } obj.into() } else { Value::Undefined } } AmfValue::Date(time, _) => { let date_proto = activation.context.avm1.prototypes.date_constructor; if let Ok(Value::Object(obj)) = date_proto.construct(activation, &[Value::Number(*time)]) { Value::Object(obj) } else { Value::Undefined } } AmfValue::XML(content, _) => { let xml_proto = activation.context.avm1.prototypes.xml_constructor; if let Ok(Value::Object(obj)) = xml_proto.construct( activation, &[Value::String(AvmString::new( activation.context.gc_context, content, ))], ) { Value::Object(obj) } else { Value::Undefined } } _ => Value::Undefined, } } /// Deserializes a Lso into an object containing the properties stored fn deserialize_lso<'gc>( activation: &mut Activation<'_, 'gc, '_>, lso: &Lso, ) -> Result<Object<'gc>, Error<'gc>> { let obj_proto = activation.context.avm1.prototypes.object; let obj = obj_proto.create_bare_object(activation, obj_proto)?; for child in &lso.body { obj.define_value( activation.context.gc_context, &child.name, deserialize_value(activation, child.value()), Attribute::empty(), ); } Ok(obj) } /// Deserialize a Json shared object element into a Value fn recursive_deserialize_json<'gc>( json_value: JsonValue, activation: &mut Activation<'_, 'gc, '_>, ) -> Value<'gc> { match json_value { JsonValue::Null => Value::Null, JsonValue::Short(s) => { Value::String(AvmString::new(activation.context.gc_context, s.to_string())) } JsonValue::String(s) => Value::String(AvmString::new(activation.context.gc_context, s)), JsonValue::Number(f) => Value::Number(f.into()), JsonValue::Boolean(b) => Value::Bool(b), JsonValue::Object(o) => { if o.get("__proto__").and_then(JsonValue::as_str) == Some("Array") { deserialize_array_json(o, activation) } else { deserialize_object_json(o, activation) } } JsonValue::Array(_) => Value::Undefined, } } /// Deserialize an Object and any children from a JSON object fn deserialize_object_json<'gc>( json_obj: json::object::Object, activation: &mut Activation<'_, 'gc, '_>, ) -> Value<'gc> { // Deserialize Object let obj_proto = activation.context.avm1.prototypes.object; if let Ok(obj) = obj_proto.create_bare_object(activation, obj_proto) { for entry in json_obj.iter() { let value = recursive_deserialize_json(entry.1.clone(), activation); obj.define_value( activation.context.gc_context, entry.0, value, Attribute::empty(), ); } obj.into() } else { Value::Undefined } } /// Deserialize an Array and any children from a JSON object fn deserialize_array_json<'gc>( mut json_obj: json::object::Object, activation: &mut Activation<'_, 'gc, '_>, ) -> Value<'gc> { let array_constructor = activation.context.avm1.prototypes.array_constructor; let len = json_obj .get("length") .and_then(JsonValue::as_i32) .unwrap_or_default(); if let Ok(Value::Object(obj)) = array_constructor.construct(activation, &[len.into()]) { // Remove length and proto meta-properties. json_obj.remove("length"); json_obj.remove("__proto__"); for entry in json_obj.iter() { let value = recursive_deserialize_json(entry.1.clone(), activation); if let Ok(i) = entry.0.parse::<usize>() { obj.set_array_element(i, value, activation.context.gc_context); } else { obj.define_value( activation.context.gc_context, entry.0, value, Attribute::empty(), ); } } obj.into() } else { Value::Undefined } } pub fn get_local<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let name = args .get(0) .unwrap_or(&Value::Undefined) .coerce_to_string(activation)? .to_string(); const INVALID_CHARS: &str = "~%&\\;:\"',<>?# "; if name.contains(|c| INVALID_CHARS.contains(c)) { log::error!("SharedObject::get_local: Invalid character in name"); return Ok(Value::Null); } let movie = if let Some(movie) = activation.base_clip().movie() { movie } else { log::error!("SharedObject::get_local: Movie was None"); return Ok(Value::Null); }; let mut movie_url = if let Some(url) = movie.url() { if let Ok(url) = url::Url::parse(url) { url } else { log::error!("SharedObject::get_local: Unable to parse movie URL"); return Ok(Value::Null); } } else { // No URL (loading local data). Use a dummy URL to allow SharedObjects to work. url::Url::parse("file://localhost").unwrap() }; movie_url.set_query(None); movie_url.set_fragment(None); let secure = args .get(2) .unwrap_or(&Value::Undefined) .as_bool(activation.swf_version()); // Secure parameter disallows using the shared object from non-HTTPS. if secure && movie_url.scheme() != "https" { log::warn!( "SharedObject.get_local: Tried to load a secure shared object from non-HTTPS origin" ); return Ok(Value::Null); } // Shared objects are sandboxed per-domain. // By default, they are keyed based on the SWF URL, but the `localHost` parameter can modify this path. let mut movie_path = movie_url.path(); // Remove leading/trailing slashes. movie_path = movie_path.strip_prefix('/').unwrap_or(movie_path); movie_path = movie_path.strip_suffix('/').unwrap_or(movie_path); let movie_host = if movie_url.scheme() == "file" { // Remove drive letter on Windows (TODO: move this logic into DiskStorageBackend?) if let [_, b':', b'/', ..] = movie_path.as_bytes() { movie_path = &movie_path[3..]; } "localhost" } else { movie_url.host_str().unwrap_or_default() }; let local_path = if let Some(Value::String(local_path)) = args.get(1) { // Empty local path always fails. if local_path.is_empty() { return Ok(Value::Null); } // Remove leading/trailing slashes. let mut local_path = local_path.as_str().strip_prefix('/').unwrap_or(local_path); local_path = local_path.strip_suffix('/').unwrap_or(local_path); // Verify that local_path is a prefix of the SWF path. if movie_path.starts_with(&local_path) && (local_path.is_empty() || movie_path.len() == local_path.len() || movie_path[local_path.len()..].starts_with('/')) { local_path } else { log::warn!("SharedObject.get_local: localPath parameter does not match SWF path"); return Ok(Value::Null); } } else { movie_path }; // Final SO path: foo.com/folder/game.swf/SOName // SOName may be a path containing slashes. In this case, prefix with # to mimic Flash Player behavior. let prefix = if name.contains('/') { "#" } else { "" }; let full_name = format!("{}/{}/{}{}", movie_host, local_path, prefix, name); // Avoid any paths with `..` to prevent SWFs from crawling the file system on desktop. // Flash will generally fail to save shared objects with a path component starting with `.`, // so let's disallow them altogether. if full_name.split('/').any(|s| s.starts_with('.')) { log::error!("SharedObject.get_local: Invalid path with .. segments"); return Ok(Value::Null); } // Check if this is referencing an existing shared object if let Some(so) = activation.context.shared_objects.get(&full_name) { return Ok(Value::Object(*so)); } // Data property only should exist when created with getLocal/Remote let constructor = activation.context.avm1.prototypes.shared_object_constructor; let this = constructor .construct(activation, &[])? .coerce_to_object(activation); // Set the internal name let obj_so = this.as_shared_object().unwrap(); obj_so.set_name(activation.context.gc_context, full_name.clone()); let mut data = Value::Undefined; // Load the data object from storage if it existed prior if let Some(saved) = activation.context.storage.get(&full_name) { // Attempt to load it as an Lso if let Ok(lso) = flash_lso::read::Reader::default().parse(&saved) { data = deserialize_lso(activation, &lso)?.into(); } else { // Attempt to load legacy Json if let Ok(saved_string) = String::from_utf8(saved) { if let Ok(json_data) = json::parse(&saved_string) { data = recursive_deserialize_json(json_data, activation); } } } } if data == Value::Undefined { // No data; create a fresh data object. let prototype = activation.context.avm1.prototypes.object; data = prototype.create_bare_object(activation, prototype)?.into(); } this.define_value( activation.context.gc_context, "data", data, Attribute::DONT_DELETE, ); activation.context.shared_objects.insert(full_name, this); Ok(this.into()) } pub fn get_remote<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.getRemote() not implemented"); Ok(Value::Undefined) } pub fn get_max_size<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.getMaxSize() not implemented"); Ok(Value::Undefined) } pub fn add_listener<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.addListener() not implemented"); Ok(Value::Undefined) } pub fn remove_listener<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.removeListener() not implemented"); Ok(Value::Undefined) } pub fn create_shared_object_object<'gc>( gc_context: MutationContext<'gc, '_>, shared_object_proto: Object<'gc>, fn_proto: Option<Object<'gc>>, ) -> Object<'gc> { let shared_obj = FunctionObject::constructor( gc_context, Executable::Native(constructor), constructor_to_fn!(constructor), fn_proto, shared_object_proto, ); let mut object = shared_obj.as_script_object().unwrap(); object.force_set_function( "deleteAll", delete_all, gc_context, Attribute::empty(), fn_proto, ); object.force_set_function( "getDiskUsage", get_disk_usage, gc_context, Attribute::empty(), fn_proto, ); object.force_set_function( "getLocal", get_local, gc_context, Attribute::empty(), fn_proto, ); object.force_set_function( "getRemote", get_remote, gc_context, Attribute::empty(), fn_proto, ); object.force_set_function( "getMaxSize", get_max_size, gc_context, Attribute::empty(), fn_proto, ); object.force_set_function( "addListener", add_listener, gc_context, Attribute::empty(), fn_proto, ); object.force_set_function( "removeListener", remove_listener, gc_context, Attribute::empty(), fn_proto, ); shared_obj } pub fn clear<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let data = this.get("data", activation)?.coerce_to_object(activation); for k in &data.get_keys(activation) { data.delete(activation, k); } let so = this.as_shared_object().unwrap(); let name = so.get_name(); activation.context.storage.remove_key(&name); Ok(Value::Undefined) } pub fn close<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.close() not implemented"); Ok(Value::Undefined) } pub fn connect<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.connect() not implemented"); Ok(Value::Undefined) } pub fn flush<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let data = this.get("data", activation)?.coerce_to_object(activation); let this_obj = this.as_shared_object().unwrap(); let name = this_obj.get_name(); let mut elements = Vec::new(); recursive_serialize(activation, data, &mut elements); let mut lso = Lso::new( elements, &name .split('/') .last() .map(|e| e.to_string()) .unwrap_or_else(|| "<unknown>".to_string()), AMFVersion::AMF0, ); let bytes = flash_lso::write::write_to_bytes(&mut lso).unwrap_or_default(); Ok(activation.context.storage.put(&name, &bytes).into()) } pub fn get_size<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.getSize() not implemented"); Ok(Value::Undefined) } pub fn send<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.send() not implemented"); Ok(Value::Undefined) } pub fn set_fps<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.setFps() not implemented"); Ok(Value::Undefined) } pub fn on_status<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.onStatus() not implemented"); Ok(Value::Undefined) } pub fn on_sync<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { avm_warn!(activation, "SharedObject.onSync() not implemented"); Ok(Value::Undefined) } pub fn create_proto<'gc>( gc_context: MutationContext<'gc, '_>, proto: Object<'gc>, fn_proto: Object<'gc>, ) -> Object<'gc> { let shared_obj = SharedObject::empty_shared_obj(gc_context, Some(proto)); let mut object = shared_obj.as_script_object().unwrap(); object.force_set_function( "clear", clear, gc_context, Attribute::empty(), Some(fn_proto), ); object.force_set_function( "close", close, gc_context, Attribute::empty(), Some(fn_proto), ); object.force_set_function( "connect", connect, gc_context, Attribute::empty(), Some(fn_proto), ); object.force_set_function( "flush", flush, gc_context, Attribute::empty(), Some(fn_proto), ); object.force_set_function( "getSize", get_size, gc_context, Attribute::empty(), Some(fn_proto), ); object.force_set_function("send", send, gc_context, Attribute::empty(), Some(fn_proto)); object.force_set_function( "setFps", set_fps, gc_context, Attribute::empty(), Some(fn_proto), ); object.force_set_function( "onStatus", on_status, gc_context, Attribute::empty(), Some(fn_proto), ); object.force_set_function( "onSync", on_sync, gc_context, Attribute::empty(), Some(fn_proto), ); shared_obj.into() } pub fn constructor<'gc>( _activation: &mut Activation<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { Ok(this.into()) }
31.238926
107
0.566837
1e6993199427d911f8e90344c062e7ae94308073
1,335
// enum IpAddrKind { // V4(String), // V6(String) // } enum IpAddrKind { V4(u8, u8, u8, u8), V6(String), } struct IpAddr { kind: IpAddrKind, address: String, } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } impl Message { fn call(&self) { } } struct QuitMessage; struct MoveMesage { x: i32, y: i32, } struct WriteMessage(String); struct ChangeColorMessage(i32, i32, i32); fn main() { // println!("Hello, world!"); // let four = IpAddrKind::V4; // let six = IpAddrKind::V6; // route(four); // route(six) // let home = IpAddr { // kind: IpAddrKind::V4, // address: String::from("127.0.0.1"), // }; // let loopback = IpAddr { // kind: IpAddrKind::V6, // address: String::from("::1"), // }; // let home = IpAddrKind::V4(String::from("127.0.0.1")); let home = IpAddrKind::V4(127, 0, 0, 1); let loopback = IpAddrKind::V6(String::from("::1")); let m = Message::Write(String::from("hello")); m.call(); let some_number = Some(5); let some_string = Some("hello"); let absent_number: Option<i32> = None; let x: i8 = 5; let y: Option<i8> = Some(8); println!("{}", x + y); } // fn route(ip_kind: IpAddrKind) { // }
16.898734
60
0.53633
eb2a3b787ad72ac6a9c354fd6d2d6d71bcaad763
2,387
use std::ops::Deref; use std::rc::Rc; #[derive(Debug)] pub enum List { Cons(i32, Box<List>), Nil } #[derive(Debug)] pub enum List2 { Cons(i32, Rc<List2>), Nil } #[derive(Debug)] pub struct MyBox<T>(T); impl<T> MyBox<T> { pub fn new(x: T) -> MyBox<T> { MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } pub trait Messenger { fn send(&self, msg: &str); } pub struct LimitTracker<'a , T: 'a + Messenger> { messenger: &'a T, value: usize, max: usize, } impl<'a, T> LimitTracker<'a, T> where T: Messenger { pub fn new(messenger: &T, max: usize) -> LimitTracker<T>{ LimitTracker { messenger, value: 0, max, } } pub fn set_value(&mut self, value: usize) { self.value = value; let percent_of_max = self.value as f64 / self.max as f64; if percent_of_max > 0.75 && percent_of_max < 0.9 { self.messenger.send("Warning: you have used up over 75% of of your quota!"); } else if percent_of_max >= 0.9 && percent_of_max < 1.0 { self.messenger.send("Urgent Warning: you have used up over 90% of of your quota!"); } else if percent_of_max >= 1.0 { self.messenger.send("Error: you are over your quota!"); } } } #[cfg(test)] mod tests { use super::*; use std::cell::RefCell; #[derive(Debug)] struct MockMessenger { sent_messenges: RefCell<Vec<String>>, } impl MockMessenger { fn new() -> Self { MockMessenger{ sent_messenges: RefCell::new(vec![]) } } } impl Messenger for MockMessenger { fn send(&self, msg: &str){ self.sent_messenges.borrow_mut().push(String::from(msg)); // folowwing 2 line will panic as it break the borrow rules // let first_borrow = self.sent_messenges.borrow_mut(); // let second_borrow = self.sent_messenges.borrow_mut(); } } #[test] fn it_sends_an_over_75_percent_warning_message() { let mock_messenger = MockMessenger::new(); let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); limit_tracker.set_value(80); assert_eq!(mock_messenger.sent_messenges.borrow().len(), 1); } }
22.308411
95
0.56305
f5b15f807fedef2041b0bcfb31cc706cd9d56746
753
extern crate oro_semver; #[test] fn test_regressions() { use oro_semver::ReqParseError; use oro_semver::VersionReq; let versions = vec![ (".*", VersionReq::any()), ("0.1.0.", VersionReq::parse("0.1.0").unwrap()), ("0.3.1.3", VersionReq::parse("0.3.13").unwrap()), ("0.2*", VersionReq::parse("0.2.*").unwrap()), // TODO: this actually parses as '*' now, not sure if that's OK // ("*.0", VersionReq::any()), ]; for (version, requirement) in versions.into_iter() { let parsed = VersionReq::parse(version); let error = parsed.err().unwrap(); assert_eq!( ReqParseError::DeprecatedVersionRequirement(requirement), error ); } }
27.888889
71
0.553785
768cab3b6a9bb1955da90af3c54c423ed7c25b95
12,903
use crate::app::App; use crate::colors::ColorScheme; use crate::game::{ChooseSomething, State, Transition}; use aabb_quadtree::QuadTree; use abstutil::{prettyprint_usize, Parallelism}; use geom::{Circle, Distance, PolyLine, Polygon, Pt2D, Ring}; use kml::ExtraShapes; use map_model::BuildingID; use std::collections::{BTreeMap, HashMap, HashSet}; use widgetry::{ hotkey, lctrl, Btn, Choice, Color, Drawable, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, Text, TextExt, VerticalAlignment, Widget, }; pub struct ViewKML { panel: Panel, objects: Vec<Object>, draw: Drawable, selected: Option<usize>, quadtree: QuadTree<usize>, draw_query: Drawable, } struct Object { polygon: Polygon, color: Color, attribs: BTreeMap<String, String>, osm_bldg: Option<BuildingID>, } const RADIUS: Distance = Distance::const_meters(5.0); const THICKNESS: Distance = Distance::const_meters(2.0); impl ViewKML { pub fn new(ctx: &mut EventCtx, app: &App, path: Option<String>) -> Box<dyn State> { ctx.loading_screen("load kml", |ctx, mut timer| { let raw_shapes = if let Some(ref path) = path { if path.ends_with(".kml") { let shapes = kml::load(&path, &app.primary.map.get_gps_bounds(), true, &mut timer) .unwrap(); // Assuming this is some huge file, conveniently convert the extract to .bin. // The new file will show up as untracked in git, so it'll be obvious this // happened. abstutil::write_binary(path.replace(".kml", ".bin"), &shapes); shapes } else { abstutil::read_binary::<ExtraShapes>(path.to_string(), &mut timer) } } else { ExtraShapes { shapes: Vec::new() } }; let bounds = app.primary.map.get_gps_bounds(); let boundary = app.primary.map.get_boundary_polygon(); let dataset_name = path .as_ref() .map(|p| abstutil::basename(p)) .unwrap_or("no file".to_string()); let bldg_lookup: HashMap<String, BuildingID> = app .primary .map .all_buildings() .iter() .map(|b| (b.orig_id.inner().to_string(), b.id)) .collect(); let cs = &app.cs; let objects: Vec<Object> = timer .parallelize( "convert shapes", Parallelism::Fastest, raw_shapes.shapes.into_iter().enumerate().collect(), |(idx, shape)| { let pts = bounds.convert(&shape.points); if pts.iter().any(|pt| boundary.contains_pt(*pt)) { Some(make_object( cs, &bldg_lookup, shape.attributes, pts, &dataset_name, idx, )) } else { None } }, ) .into_iter() .flatten() .collect(); let mut batch = GeomBatch::new(); let mut quadtree = QuadTree::default(app.primary.map.get_bounds().as_bbox()); timer.start_iter("render shapes", objects.len()); for (idx, obj) in objects.iter().enumerate() { timer.next(); quadtree.insert_with_box(idx, obj.polygon.get_bounds().as_bbox()); batch.push(obj.color, obj.polygon.clone()); } let mut choices = vec![Choice::string("None")]; if dataset_name == "parcels" { choices.push(Choice::string("parcels without buildings")); choices.push(Choice::string( "parcels without buildings and trips or parking", )); choices.push(Choice::string("parcels with multiple buildings")); choices.push(Choice::string("parcels with >1 households")); choices.push(Choice::string("parcels with parking")); } Box::new(ViewKML { draw: ctx.upload(batch), panel: Panel::new(Widget::col(vec![ Widget::row(vec![ Line("KML viewer").small_heading().draw(ctx), Btn::text_fg("X") .build(ctx, "close", hotkey(Key::Escape)) .align_right(), ]), format!( "{}: {} objects", dataset_name, prettyprint_usize(objects.len()) ) .draw_text(ctx), Btn::text_fg("load KML file").build_def(ctx, lctrl(Key::L)), Widget::row(vec![ "Query:".draw_text(ctx), Widget::dropdown(ctx, "query", "None".to_string(), choices), ]), Widget::row(vec![ "Key=value filter:".draw_text(ctx), Widget::text_entry(ctx, String::new(), false).named("filter"), ]), "Query matches 0 objects".draw_text(ctx).named("matches"), ])) .aligned(HorizontalAlignment::Center, VerticalAlignment::Top) .build(ctx), objects, quadtree, selected: None, draw_query: ctx.upload(GeomBatch::new()), }) }) } } impl State for ViewKML { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition { ctx.canvas_movement(); if ctx.redo_mouseover() { self.selected = None; if let Some(pt) = ctx.canvas.get_cursor_in_map_space() { for &(idx, _, _) in &self.quadtree.query( Circle::new(pt, Distance::meters(3.0)) .get_bounds() .as_bbox(), ) { if self.objects[*idx].polygon.contains_pt(pt) { self.selected = Some(*idx); break; } } } } match self.panel.event(ctx) { Outcome::Clicked(x) => match x.as_ref() { "close" => { return Transition::Pop; } "load KML file" => { return Transition::Push(ChooseSomething::new( ctx, "Load file", Choice::strings( abstutil::list_dir(std::path::Path::new(&abstutil::path(format!( "input/{}/", app.primary.map.get_city_name() )))) .into_iter() .filter(|x| { (x.ends_with(".bin") || x.ends_with(".kml")) && !x.ends_with("popdat.bin") }) .collect(), ), Box::new(|path, ctx, app| { Transition::Replace(ViewKML::new(ctx, app, Some(path))) }), )); } _ => unreachable!(), }, Outcome::Changed => { let mut query: String = self.panel.dropdown_value("query"); let filter = self.panel.text_box("filter"); if query == "None" && !filter.is_empty() { query = filter; } let (batch, cnt) = make_query(app, &self.objects, &query); self.draw_query = ctx.upload(batch); self.panel.replace( ctx, "matches", format!("Query matches {} objects", cnt) .draw_text(ctx) .named("matches"), ); } _ => {} } Transition::Keep } fn draw(&self, g: &mut GfxCtx, app: &App) { g.redraw(&self.draw); g.redraw(&self.draw_query); self.panel.draw(g); if let Some(idx) = self.selected { let obj = &self.objects[idx]; g.draw_polygon(Color::BLUE, obj.polygon.clone()); let mut txt = Text::new(); for (k, v) in &obj.attribs { txt.add(Line(format!("{} = {}", k, v))); } g.draw_mouse_tooltip(txt); if let Some(b) = obj.osm_bldg { g.draw_polygon(Color::GREEN, app.primary.map.get_b(b).polygon.clone()); } } } } fn make_object( cs: &ColorScheme, bldg_lookup: &HashMap<String, BuildingID>, attribs: BTreeMap<String, String>, pts: Vec<Pt2D>, dataset_name: &str, obj_idx: usize, ) -> Object { let mut color = Color::RED.alpha(0.8); let polygon = if pts.len() == 1 { Circle::new(pts[0], RADIUS).to_polygon() } else if let Ok(ring) = Ring::new(pts.clone()) { if attribs.get("spatial_type") == Some(&"Polygon".to_string()) { color = cs.rotating_color_plot(obj_idx).alpha(0.8); ring.to_polygon() } else { ring.to_outline(THICKNESS) } } else { let backup = pts[0]; match PolyLine::new(pts) { Ok(pl) => pl.make_polygons(THICKNESS), Err(err) => { println!( "Object with attribs {:?} has messed up geometry: {}", attribs, err ); Circle::new(backup, RADIUS).to_polygon() } } }; let mut osm_bldg = None; if dataset_name == "parcels" { if let Some(bldg) = attribs.get("osm_bldg") { if let Some(id) = bldg_lookup.get(bldg) { osm_bldg = Some(*id); } } } Object { polygon, color, attribs, osm_bldg, } } fn make_query(app: &App, objects: &Vec<Object>, query: &str) -> (GeomBatch, usize) { let mut batch = GeomBatch::new(); let mut cnt = 0; let color = Color::BLUE.alpha(0.8); match query { "None" => {} "parcels without buildings" => { for obj in objects { if obj.osm_bldg.is_none() { cnt += 1; batch.push(color, obj.polygon.clone()); } } } "parcels without buildings and trips or parking" => { for obj in objects { if obj.osm_bldg.is_none() && (obj.attribs.contains_key("households") || obj.attribs.contains_key("parking")) { cnt += 1; batch.push(color, obj.polygon.clone()); } } } "parcels with multiple buildings" => { let mut seen = HashSet::new(); for obj in objects { if let Some(b) = obj.osm_bldg { if seen.contains(&b) { cnt += 1; batch.push(color, app.primary.map.get_b(b).polygon.clone()); } else { seen.insert(b); } } } } "parcels with >1 households" => { for obj in objects { if let Some(hh) = obj.attribs.get("households") { if hh != "1" { cnt += 1; batch.push(color, obj.polygon.clone()); } } } } "parcels with parking" => { for obj in objects { if obj.attribs.contains_key("parking") { cnt += 1; batch.push(color, obj.polygon.clone()); } } } x => { for obj in objects { for (k, v) in &obj.attribs { if format!("{}={}", k, v).contains(x) { batch.push(color, obj.polygon.clone()); break; } } } } } (batch, cnt) }
35.841667
98
0.43145
22b153237883e2c4961a95cade9f0ae4e7fcc117
5,681
use std::sync::Arc; use std::sync::Mutex; use std::path::PathBuf; use async_trait::async_trait; use tantivy::Index; use tantivy::space_usage::SearcherSpaceUsage; use tantivy::IndexWriter; use tantivy::merge_policy::*; use tantivy::{Document}; use serde::{Deserialize, Serialize}; use crate::Result; /// Defines the interface for obtaining a handle from a catalog to an index #[async_trait::async_trait] pub trait IndexServer { // TODO fn find_shard(index_name str, shard_id u64) -> Server /// The current catalog's raft_id fn raft_id(&self) -> u64; } #[async_trait] pub trait IndexHandle { fn get_name(&self) -> String ; fn get_index(&self) -> Index ; fn get_writer(&self) -> Arc<Mutex<IndexWriter>>; fn get_space(&self) -> SearcherSpaceUsage; async fn search_index(&self, search: Query) -> Result<SearchResults> ; async fn add_document(&self, doc: Document) -> Result<()> ; } /// The request body of a search POST #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Search { /// Field to sort results by #[serde(default)] pub sort_by: Option<String>, #[serde(default)] pub query: String, #[serde(default)] pub limit: u64, } pub struct CanisterSettings { pub base_path: PathBuf, pub server_id: u64, pub index_settings: IndexSettings, } pub struct IndexSettings { pub index_name: String, pub writer_memory: usize, pub merge_policy: String, } impl IndexSettings{ pub fn get_merge_policy(&self) -> Box<dyn MergePolicy> { match self.merge_policy.as_ref() { // TODO convert these to an ENUM and make them Serde types, like SchemaField "merge_log" => { let mp = LogMergePolicy::default(); //mp.set_level_log_size(self.merge_policy.level_log_size); //mp.set_min_layer_size(self.merge_policy.min_layer_size); //mp.set_min_merge_size(self.merge_policy.min_merge_size); Box::new(mp) } "merge_no_merge" => Box::new(NoMergePolicy::default()), _ => { let mp = LogMergePolicy::default(); Box::new(mp) } } } } impl Clone for IndexSettings { fn clone(&self) -> Self { Self { index_name: self.index_name.clone(), writer_memory: self.writer_memory, merge_policy: self.merge_policy.clone(), } } } pub struct Query {} pub struct SearchResults {} /* /// Documents are really just a list of couple `(field, value)`. /// In this list, one field may appear more than once. #[derive(serde::Serialize, serde::Deserialize)] pub struct Document { field_values: Vec<FieldValue>, } */ ////////////////////////////////////////////////////////// // Schema data Types // #[derive(Debug, Deserialize)] #[serde(tag = "type")] #[serde(rename_all(serialize = "lowercase", deserialize = "lowercase"))] pub enum SchemaField { Text { column_name: String, stored: bool, indexed: bool, indexed_lang_stem: String, indexed_tokenized: bool, indexed_tokenized_with_freqs_positions: bool, indexed_tokenized_with_freqs: bool }, Keyword { column_name: String, stored: bool }, UInt64 { column_name: String, stored: bool, indexed: bool, doc_values: bool }, Int64 { column_name: String, stored: bool, indexed: bool, doc_values: bool }, Float64 { column_name: String, stored: bool, indexed: bool, doc_values: bool }, Date { column_name: String, stored: bool, indexed: bool, doc_values: bool }, Facet { column_name: String }, Bytes { column_name: String }, } // #[cfg(test)] // mod tests { // #[test] // use crate::info_retrieval::types::SchemaField; // // fn schema_serialize_deserialize() { // let data_a = r#" // [ // { // "type": "text", // "column_name": "a_foo", // "stored": true, // "indexed": true, // "indexed_lang_stem": "en", // "indexed_tokenized": true, // "indexed_tokenized_with_freqs_positions": true, // "indexed_tokenized_with_freqs": true // }, // { // "type": "keyword", // "column_name": "b_foo", // "stored": true // }, // { // "type": "uint64", // "column_name": "c_foo", // "stored": true, // "doc_values": true, // "indexed": true // }, // { // "type": "int64", // "column_name": "d_foo", // "stored": true, // "doc_values": true, // "indexed": true // }, // { // "type": "float64", // "column_name": "e_foo", // "stored": true, // "doc_values": true, // "indexed": true // }, // { // "type": "date", // "column_name": "f_foo", // "stored": true, // "doc_values": true, // "indexed": true // }, // { // "type": "facet", // "column_name": "g_foo" // }, // { // "type": "bytes", // "column_name": "h_foo" // } // ] "#; // let schema_fields: Vec<SchemaField> = serde_json::from_str(data_a)?; // assert_eq!(2 + 2, 4); // } // } // //
29.9
88
0.525436
9015724a8b3025dc137be6755706620f935c34c1
2,763
use header::{Header, HeaderFormat}; use std::fmt; use header::parsing::from_one_raw_str; /// The `Host` header. /// /// HTTP/1.1 requires that all requests include a `Host` header, and so hyper /// client requests add one automatically. /// /// Currently is just a String, but it should probably become a better type, /// like url::Host or something. #[derive(Clone, PartialEq, Debug)] pub struct Host { /// The hostname, such a example.domain. pub hostname: String, /// An optional port number. pub port: Option<u16> } impl Header for Host { fn header_name() -> &'static str { "Host" } fn parse_header(raw: &[Vec<u8>]) -> Option<Host> { from_one_raw_str(raw).and_then(|mut s: String| { // FIXME: use rust-url to parse this // https://github.com/servo/rust-url/issues/42 let idx = { let slice = &s[..]; let mut chars = slice.chars(); chars.next(); if chars.next().unwrap() == '[' { match slice.rfind(']') { Some(idx) => { if slice.len() > idx + 2 { Some(idx + 1) } else { None } } None => return None // this is a bad ipv6 address... } } else { slice.rfind(':') } }; let port = match idx { Some(idx) => s[idx + 1..].parse().ok(), None => None }; match idx { Some(idx) => s.truncate(idx), None => () } Some(Host { hostname: s, port: port }) }) } } impl HeaderFormat for Host { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.port { None | Some(80) | Some(443) => write!(fmt, "{}", self.hostname), Some(port) => write!(fmt, "{}:{}", self.hostname, port) } } } #[cfg(test)] mod tests { use super::Host; use header::Header; #[test] fn test_host() { let host = Header::parse_header([b"foo.com".to_vec()].as_ref()); assert_eq!(host, Some(Host { hostname: "foo.com".to_string(), port: None })); let host = Header::parse_header([b"foo.com:8080".to_vec()].as_ref()); assert_eq!(host, Some(Host { hostname: "foo.com".to_string(), port: Some(8080) })); } } bench_header!(bench, Host, { vec![b"foo.com:3000".to_vec()] });
27.356436
77
0.452407
c1c5f87129defeb5ea4aaf486aeae8875b045772
7,478
use ffi::{ self, BIO_clear_retry_flags, BIO_new, BIO_set_retry_read, BIO_set_retry_write, BIO, BIO_CTRL_FLUSH, }; use libc::{c_char, c_int, c_long, c_void, strlen}; use std::any::Any; use std::io; use std::io::prelude::*; use std::mem; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::ptr; use std::slice; use cvt_p; use error::ErrorStack; pub struct StreamState<S> { pub stream: S, pub error: Option<io::Error>, pub panic: Option<Box<Any + Send>>, } /// Safe wrapper for BIO_METHOD pub struct BioMethod(BIO_METHOD); impl BioMethod { fn new<S: Read + Write>() -> BioMethod { BioMethod(BIO_METHOD::new::<S>()) } } unsafe impl Sync for BioMethod {} unsafe impl Send for BioMethod {} pub fn new<S: Read + Write>(stream: S) -> Result<(*mut BIO, BioMethod), ErrorStack> { let method = BioMethod::new::<S>(); let state = Box::new(StreamState { stream: stream, error: None, panic: None, }); unsafe { let bio = cvt_p(BIO_new(method.0.get()))?; BIO_set_data(bio, Box::into_raw(state) as *mut _); BIO_set_init(bio, 1); return Ok((bio, method)); } } pub unsafe fn take_error<S>(bio: *mut BIO) -> Option<io::Error> { let state = state::<S>(bio); state.error.take() } pub unsafe fn take_panic<S>(bio: *mut BIO) -> Option<Box<Any + Send>> { let state = state::<S>(bio); state.panic.take() } pub unsafe fn get_ref<'a, S: 'a>(bio: *mut BIO) -> &'a S { let state: &'a StreamState<S> = mem::transmute(BIO_get_data(bio)); &state.stream } pub unsafe fn get_mut<'a, S: 'a>(bio: *mut BIO) -> &'a mut S { &mut state(bio).stream } unsafe fn state<'a, S: 'a>(bio: *mut BIO) -> &'a mut StreamState<S> { &mut *(BIO_get_data(bio) as *mut _) } unsafe extern "C" fn bwrite<S: Write>(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int { BIO_clear_retry_flags(bio); let state = state::<S>(bio); let buf = slice::from_raw_parts(buf as *const _, len as usize); match catch_unwind(AssertUnwindSafe(|| state.stream.write(buf))) { Ok(Ok(len)) => len as c_int, Ok(Err(err)) => { if retriable_error(&err) { BIO_set_retry_write(bio); } state.error = Some(err); -1 } Err(err) => { state.panic = Some(err); -1 } } } unsafe extern "C" fn bread<S: Read>(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int { BIO_clear_retry_flags(bio); let state = state::<S>(bio); let buf = slice::from_raw_parts_mut(buf as *mut _, len as usize); match catch_unwind(AssertUnwindSafe(|| state.stream.read(buf))) { Ok(Ok(len)) => len as c_int, Ok(Err(err)) => { if retriable_error(&err) { BIO_set_retry_read(bio); } state.error = Some(err); -1 } Err(err) => { state.panic = Some(err); -1 } } } fn retriable_error(err: &io::Error) -> bool { match err.kind() { io::ErrorKind::WouldBlock | io::ErrorKind::NotConnected => true, _ => false, } } unsafe extern "C" fn bputs<S: Write>(bio: *mut BIO, s: *const c_char) -> c_int { bwrite::<S>(bio, s, strlen(s) as c_int) } unsafe extern "C" fn ctrl<S: Write>( bio: *mut BIO, cmd: c_int, _num: c_long, _ptr: *mut c_void, ) -> c_long { if cmd == BIO_CTRL_FLUSH { let state = state::<S>(bio); match catch_unwind(AssertUnwindSafe(|| state.stream.flush())) { Ok(Ok(())) => 1, Ok(Err(err)) => { state.error = Some(err); 0 } Err(err) => { state.panic = Some(err); 0 } } } else { 0 } } unsafe extern "C" fn create(bio: *mut BIO) -> c_int { BIO_set_init(bio, 0); BIO_set_num(bio, 0); BIO_set_data(bio, ptr::null_mut()); BIO_set_flags(bio, 0); 1 } unsafe extern "C" fn destroy<S>(bio: *mut BIO) -> c_int { if bio.is_null() { return 0; } let data = BIO_get_data(bio); assert!(!data.is_null()); Box::<StreamState<S>>::from_raw(data as *mut _); BIO_set_data(bio, ptr::null_mut()); BIO_set_init(bio, 0); 1 } cfg_if! { if #[cfg(any(ossl110, libressl273))] { use ffi::{BIO_get_data, BIO_set_data, BIO_set_flags, BIO_set_init}; #[allow(bad_style)] unsafe fn BIO_set_num(_bio: *mut ffi::BIO, _num: c_int) {} #[allow(bad_style)] struct BIO_METHOD(*mut ffi::BIO_METHOD); impl BIO_METHOD { fn new<S: Read + Write>() -> BIO_METHOD { unsafe { let ptr = ffi::BIO_meth_new(ffi::BIO_TYPE_NONE, b"rust\0".as_ptr() as *const _); assert!(!ptr.is_null()); let ret = BIO_METHOD(ptr); assert!(ffi::BIO_meth_set_write(ptr, bwrite::<S>) != 0); assert!(ffi::BIO_meth_set_read(ptr, bread::<S>) != 0); assert!(ffi::BIO_meth_set_puts(ptr, bputs::<S>) != 0); assert!(ffi::BIO_meth_set_ctrl(ptr, ctrl::<S>) != 0); assert!(ffi::BIO_meth_set_create(ptr, create) != 0); assert!(ffi::BIO_meth_set_destroy(ptr, destroy::<S>) != 0); return ret; } } fn get(&self) -> *mut ffi::BIO_METHOD { self.0 } } impl Drop for BIO_METHOD { fn drop(&mut self) { unsafe { ffi::BIO_meth_free(self.0); } } } } else { #[allow(bad_style)] struct BIO_METHOD(*mut ffi::BIO_METHOD); impl BIO_METHOD { fn new<S: Read + Write>() -> BIO_METHOD { let ptr = Box::new(ffi::BIO_METHOD { type_: ffi::BIO_TYPE_NONE, name: b"rust\0".as_ptr() as *const _, bwrite: Some(bwrite::<S>), bread: Some(bread::<S>), bputs: Some(bputs::<S>), bgets: None, ctrl: Some(ctrl::<S>), create: Some(create), destroy: Some(destroy::<S>), callback_ctrl: None, }); BIO_METHOD(Box::into_raw(ptr)) } fn get(&self) -> *mut ffi::BIO_METHOD { self.0 } } impl Drop for BIO_METHOD { fn drop(&mut self) { unsafe { Box::<ffi::BIO_METHOD>::from_raw(self.0); } } } #[allow(bad_style)] unsafe fn BIO_set_init(bio: *mut ffi::BIO, init: c_int) { (*bio).init = init; } #[allow(bad_style)] unsafe fn BIO_set_flags(bio: *mut ffi::BIO, flags: c_int) { (*bio).flags = flags; } #[allow(bad_style)] unsafe fn BIO_get_data(bio: *mut ffi::BIO) -> *mut c_void { (*bio).ptr } #[allow(bad_style)] unsafe fn BIO_set_data(bio: *mut ffi::BIO, data: *mut c_void) { (*bio).ptr = data; } #[allow(bad_style)] unsafe fn BIO_set_num(bio: *mut ffi::BIO, num: c_int) { (*bio).num = num; } } }
27.094203
100
0.503343