hexsha
stringlengths
40
40
size
int64
4
1.05M
content
stringlengths
4
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
0931f132c0214b8a784e931d39145b74ae4cfc1b
2,338
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::{io, str}; #[deriving(Clone)] pub struct ExternalHtml{ pub in_header: String, pub before_content: String, pub after_content: String } impl ExternalHtml { pub fn load(in_header: &[String], before_content: &[String], after_content: &[String]) -> Option<ExternalHtml> { match (load_external_files(in_header), load_external_files(before_content), load_external_files(after_content)) { (Some(ih), Some(bc), Some(ac)) => Some(ExternalHtml { in_header: ih, before_content: bc, after_content: ac }), _ => None } } } pub fn load_string(input: &Path) -> io::IoResult<Option<String>> { let mut f = try!(io::File::open(input)); let d = try!(f.read_to_end()); Ok(str::from_utf8(d.as_slice()).map(|s| s.to_string())) } macro_rules! load_or_return { ($input: expr, $cant_read: expr, $not_utf8: expr) => { { let input = Path::new($input); match ::externalfiles::load_string(&input) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: {}", input.display(), e); return $cant_read; } Ok(None) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: not UTF-8", input.display()); return $not_utf8; } Ok(Some(s)) => s } } } } pub fn load_external_files(names: &[String]) -> Option<String> { let mut out = String::new(); for name in names.iter() { out.push_str(load_or_return!(name.as_slice(), None, None).as_slice()); out.push_char('\n'); } Some(out) }
32.929577
90
0.545766
e8929cd5c0237b91eff421c617c40c3683e5d363
6,918
//! Dynamic library facilities. //! //! A simple wrapper over the platform's dynamic library facilities use std::ffi::CString; use std::path::Path; pub struct DynamicLibrary { handle: *mut u8, } impl Drop for DynamicLibrary { fn drop(&mut self) { unsafe { dl::close(self.handle) } } } impl DynamicLibrary { /// Lazily open a dynamic library. pub fn open(filename: &Path) -> Result<DynamicLibrary, String> { let maybe_library = dl::open(filename.as_os_str()); // The dynamic library must not be constructed if there is // an error opening the library so the destructor does not // run. match maybe_library { Err(err) => Err(err), Ok(handle) => Ok(DynamicLibrary { handle }), } } /// Accesses the value at the symbol of the dynamic library. pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented let raw_string = CString::new(symbol).unwrap(); let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr()); // The value must not be constructed if there is an error so // the destructor does not run. match maybe_symbol_value { Err(err) => Err(err), Ok(symbol_value) => Ok(symbol_value as *mut T), } } } #[cfg(test)] mod tests; #[cfg(unix)] mod dl { use std::ffi::{CString, OsStr}; use std::os::unix::prelude::*; // As of the 2017 revision of the POSIX standard (IEEE 1003.1-2017), it is // implementation-defined whether `dlerror` is thread-safe (in which case it returns the most // recent error in the calling thread) or not thread-safe (in which case it returns the most // recent error in *any* thread). // // There's no easy way to tell what strategy is used by a given POSIX implementation, so we // lock around all calls that can modify `dlerror` in this module lest we accidentally read an // error from a different thread. This is bulletproof when we are the *only* code using the // dynamic library APIs at a given point in time. However, it's still possible for us to race // with other code (see #74469) on platforms where `dlerror` is not thread-safe. mod error { use std::ffi::CStr; use std::lazy::SyncLazy; use std::sync::{Mutex, MutexGuard}; pub fn lock() -> MutexGuard<'static, Guard> { static LOCK: SyncLazy<Mutex<Guard>> = SyncLazy::new(|| Mutex::new(Guard)); LOCK.lock().unwrap() } #[non_exhaustive] pub struct Guard; impl Guard { pub fn get(&mut self) -> Result<(), String> { let msg = unsafe { libc::dlerror() }; if msg.is_null() { Ok(()) } else { let msg = unsafe { CStr::from_ptr(msg as *const _) }; Err(msg.to_string_lossy().into_owned()) } } pub fn clear(&mut self) { let _ = unsafe { libc::dlerror() }; } } } pub(super) fn open(filename: &OsStr) -> Result<*mut u8, String> { let s = CString::new(filename.as_bytes()).unwrap(); let mut dlerror = error::lock(); let ret = unsafe { libc::dlopen(s.as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL) }; if !ret.is_null() { return Ok(ret.cast()); } // A null return from `dlopen` indicates that an error has definitely occurred, so if // nothing is in `dlerror`, we are racing with another thread that has stolen our error // message. See the explanation on the `dl::error` module for more information. dlerror.get().and_then(|()| Err("Unknown error".to_string())) } pub(super) unsafe fn symbol( handle: *mut u8, symbol: *const libc::c_char, ) -> Result<*mut u8, String> { let mut dlerror = error::lock(); // Unlike `dlopen`, it's possible for `dlsym` to return null without overwriting `dlerror`. // Because of this, we clear `dlerror` before calling `dlsym` to avoid picking up a stale // error message by accident. dlerror.clear(); let ret = libc::dlsym(handle as *mut libc::c_void, symbol); if !ret.is_null() { return Ok(ret.cast()); } // If `dlsym` returns null but there is nothing in `dlerror` it means one of two things: // - We tried to load a symbol mapped to address 0. This is not technically an error but is // unlikely to occur in practice and equally unlikely to be handled correctly by calling // code. Therefore we treat it as an error anyway. // - An error has occurred, but we are racing with another thread that has stolen our error // message. See the explanation on the `dl::error` module for more information. dlerror.get().and_then(|()| Err("Tried to load symbol mapped to address 0".to_string())) } pub(super) unsafe fn close(handle: *mut u8) { libc::dlclose(handle as *mut libc::c_void); } } #[cfg(windows)] mod dl { use std::ffi::OsStr; use std::io; use std::os::windows::prelude::*; use std::ptr; use winapi::shared::minwindef::HMODULE; use winapi::um::errhandlingapi::SetThreadErrorMode; use winapi::um::libloaderapi::{FreeLibrary, GetProcAddress, LoadLibraryW}; use winapi::um::winbase::SEM_FAILCRITICALERRORS; pub(super) fn open(filename: &OsStr) -> Result<*mut u8, String> { // disable "dll load failed" error dialog. let prev_error_mode = unsafe { let new_error_mode = SEM_FAILCRITICALERRORS; let mut prev_error_mode = 0; let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode); if result == 0 { return Err(io::Error::last_os_error().to_string()); } prev_error_mode }; let filename_str: Vec<_> = filename.encode_wide().chain(Some(0)).collect(); let result = unsafe { LoadLibraryW(filename_str.as_ptr()) } as *mut u8; let result = ptr_result(result); unsafe { SetThreadErrorMode(prev_error_mode, ptr::null_mut()); } result } pub(super) unsafe fn symbol( handle: *mut u8, symbol: *const libc::c_char, ) -> Result<*mut u8, String> { let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8; ptr_result(ptr) } pub(super) unsafe fn close(handle: *mut u8) { FreeLibrary(handle as HMODULE); } fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> { if ptr.is_null() { Err(io::Error::last_os_error().to_string()) } else { Ok(ptr) } } }
35.476923
99
0.596993
1eb65634190f84f5194458d9207100e8b616f16b
6,098
use crate::resources::billing::discounts::Discount; use crate::resources::billing::subscriptions::Subscription; use crate::resources::common::address::Address; use crate::resources::common::currency::Currency; use crate::resources::common::object::Object; use crate::resources::common::path::UrlPath; use crate::resources::core::customer_taxid::{CustomerTaxID, CustomerTaxIDParam}; use crate::resources::paymentmethods::source::{PaymentSource, PaymentSourceParam, Source}; use crate::util::{Deleted, Expandable, List, RangeQuery}; use crate::Client; use std::collections::HashMap; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct CustomerShipping { pub address: Address, pub name: String, pub phone: String, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Customer { pub id: String, pub object: Object, pub account_balance: i64, pub address: Option<Address>, pub created: i64, pub currency: Option<Currency>, pub default_source: Option<Expandable<Source>>, pub delinquent: bool, pub description: Option<String>, pub discount: Option<Expandable<Discount>>, pub email: Option<String>, pub invoice_prefix: Option<String>, pub invoice_settings: InvoiceSettings, pub livemode: bool, pub metadata: HashMap<String, String>, pub name: Option<String>, pub phone: Option<String>, pub preferred_locales: Option<Vec<String>>, pub shipping: Option<CustomerShipping>, pub sources: Option<List<PaymentSource>>, pub subscriptions: Option<List<Subscription>>, pub tax_exempt: Option<TaxExempt>, pub tax_ids: Option<List<CustomerTaxID>>, pub tax_info: Option<TaxInfo>, //Deprecated pub tax_info_verification: Option<TaxInfoVerification>, //Deprecated } //TODO: Move to invoice? #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct InvoiceSettings { pub custom_fields: Option<CustomFields>, pub default_payment_method: Option<String>, pub footer: Option<String>, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct CustomFields { pub name: String, pub value: String, } #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(rename_all = "lowercase")] pub enum TaxExempt { None, Exempt, Reversed, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct TaxInfo { pub tax_id: String, #[serde(rename = "type")] pub tax_type: String, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct TaxInfoVerification { pub verified_name: Option<String>, pub status: TaxStatus, } #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(rename_all = "lowercase")] pub enum TaxStatus { Unverified, Pending, Verified, } #[derive(Default, Debug, Serialize, PartialEq)] pub struct CustomerParam<'a> { #[serde(skip_serializing_if = "Option::is_none")] pub account_balance: Option<i64>, #[serde(skip_serializing_if = "Option::is_none")] pub address: Option<Address>, #[serde(skip_serializing_if = "Option::is_none")] pub coupon: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub default_source: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub phone: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub preferred_locales: Option<Vec<&'a str>>, #[serde(skip_serializing_if = "Option::is_none")] pub invoice_prefix: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub invoice_settings: Option<InvoiceSettings>, #[serde(skip_serializing_if = "Option::is_none")] pub metadata: Option<HashMap<String, String>>, #[serde(skip_serializing_if = "Option::is_none")] pub shipping: Option<CustomerShipping>, #[serde(skip_serializing_if = "Option::is_none")] pub source: Option<PaymentSourceParam<'a>>, #[serde(skip_serializing_if = "Option::is_none")] pub tax_info: Option<TaxInfo>, //Deprecated #[serde(skip_serializing_if = "Option::is_none")] pub tax_exempt: Option<TaxExempt>, #[serde(skip_serializing_if = "Option::is_none")] pub tax_id_data: Option<Vec<CustomerTaxIDParam<'a>>>, #[serde(skip_serializing_if = "Option::is_none")] pub expand: Option<Vec<&'a str>>, } #[derive(Default, Serialize, Debug, PartialEq)] pub struct CustomerListParams<'a> { #[serde(skip_serializing_if = "Option::is_none")] pub created: Option<RangeQuery>, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub ending_before: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, #[serde(skip_serializing_if = "Option::is_none")] pub starting_after: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub expand: Option<Vec<&'a str>>, } impl Customer { pub fn create<B: serde::Serialize>(client: &Client, param: B) -> crate::Result<Self> { client.post(UrlPath::Customers, vec![], param) } pub fn retrieve(client: &Client, id: &str) -> crate::Result<Self> { client.get(UrlPath::Customers, vec![id], serde_json::Map::new()) } pub fn update<B: serde::Serialize>(client: &Client, id: &str, param: B) -> crate::Result<Self> { client.post(UrlPath::Customers, vec![id], param) } pub fn delete(client: &Client, id: &str) -> crate::Result<Deleted> { client.delete(UrlPath::Customers, vec![id], serde_json::Map::new()) } pub fn list<B: serde::Serialize>(client: &Client, param: B) -> crate::Result<List<Self>> { client.get(UrlPath::Customers, vec![], param) } }
35.660819
100
0.686455
1d0340e7a6bff75feaa8ec0972b8284a34344131
1,953
extern crate gl; use std::os::raw::c_void; use graphics::{buffer, GLDataType}; pub struct VertexArrayObject { id: u32, } impl VertexArrayObject { pub fn new(vbo: &buffer::Buffer) -> Self { match vbo.target() { buffer::BufferTarget::ArrayBuffer => (), _ => { println!( "Warning: Trying to attach VAO to non-VBO buffer ({}:{}:{})", file!(), line!(), column!()); } } vbo.bind(); let mut id = 0; unsafe { gl::GenVertexArrays(1, &mut id); } vbo.unbind(); VertexArrayObject { id } } pub fn bind(&self) { unsafe { gl::BindVertexArray(self.id); } } pub fn unbind(&self) { unsafe { gl::BindVertexArray(0); } } pub fn set_attribute(&self, vbo: &buffer::Buffer, layout_index: u32, num_components: i32, data_type: GLDataType, normalized: bool, stride: isize, byte_offset: usize) { match vbo.target() { buffer::BufferTarget::ArrayBuffer => (), _ => { println!( "Warning: Trying to attach VAO to non-VBO buffer ({}:{}:{})", file!(), line!(), column!()); } } vbo.bind(); self.bind(); unsafe { gl::EnableVertexAttribArray(layout_index); gl::VertexAttribPointer( layout_index, num_components, data_type as u32, if normalized { gl::TRUE } else { gl::FALSE }, stride as gl::types::GLint, byte_offset as *const c_void ); } self.unbind(); vbo.unbind(); } } impl Drop for VertexArrayObject { fn drop(&mut self) { unsafe { gl::DeleteVertexArrays(1, &self.id); } } }
25.038462
82
0.46595
890d564b1ffc9e4a45a7d0857e0f2143f514c79a
9,166
use std::fmt::{self, Debug}; use std::io; use async_stream::try_stream; use futures_channel::mpsc; use futures_core::future::BoxFuture; use futures_core::stream::Stream; use crate::describe::Describe; use crate::executor::{Execute, Executor, RefExecutor}; use crate::pool::{Pool, PoolConnection}; use crate::postgres::protocol::{Message, NotificationResponse}; use crate::postgres::{PgConnection, PgCursor, Postgres}; /// A stream of asynchronous notifications from Postgres. /// /// This listener will auto-reconnect. If the active /// connection being used ever dies, this listener will detect that event, create a /// new connection, will re-subscribe to all of the originally specified channels, and will resume /// operations as normal. pub struct PgListener { pool: Pool<PgConnection>, connection: Option<PoolConnection<PgConnection>>, buffer_rx: mpsc::UnboundedReceiver<NotificationResponse<'static>>, buffer_tx: Option<mpsc::UnboundedSender<NotificationResponse<'static>>>, channels: Vec<String>, } /// An asynchronous notification from Postgres. pub struct PgNotification<'c>(NotificationResponse<'c>); impl PgListener { pub async fn new(url: &str) -> crate::Result<Self> { // Create a pool of 1 without timeouts (as they don't apply here) // We only use the pool to handle re-connections let pool = Pool::<PgConnection>::builder() .max_size(1) .max_lifetime(None) .idle_timeout(None) .build(url) .await?; Self::from_pool(&pool).await } pub async fn from_pool(pool: &Pool<PgConnection>) -> crate::Result<Self> { // Pull out an initial connection let mut connection = pool.acquire().await?; // Setup a notification buffer let (sender, receiver) = mpsc::unbounded(); connection.stream.notifications = Some(sender); Ok(Self { pool: pool.clone(), connection: Some(connection), buffer_rx: receiver, buffer_tx: None, channels: Vec::new(), }) } /// Starts listening for notifications on a channel. pub async fn listen(&mut self, channel: &str) -> crate::Result<()> { self.connection() .execute(&*format!("LISTEN {}", ident(channel))) .await?; self.channels.push(channel.to_owned()); Ok(()) } /// Starts listening for notifications on all channels. pub async fn listen_all( &mut self, channels: impl IntoIterator<Item = &str>, ) -> crate::Result<()> { let beg = self.channels.len(); self.channels.extend(channels.into_iter().map(|s| s.into())); self.connection .as_mut() .unwrap() .execute(&*build_listen_all_query(&self.channels[beg..])) .await?; Ok(()) } /// Stops listening for notifications on a channel. pub async fn unlisten(&mut self, channel: &str) -> crate::Result<()> { self.connection() .execute(&*format!("UNLISTEN {}", ident(channel))) .await?; if let Some(pos) = self.channels.iter().position(|s| s == channel) { self.channels.remove(pos); } Ok(()) } /// Stops listening for notifications on all channels. pub async fn unlisten_all(&mut self) -> crate::Result<()> { self.connection().execute("UNLISTEN *").await?; self.channels.clear(); Ok(()) } #[inline] async fn connect_if_needed(&mut self) -> crate::Result<()> { if let None = self.connection { let mut connection = self.pool.acquire().await?; connection.stream.notifications = self.buffer_tx.take(); connection .execute(&*build_listen_all_query(&self.channels)) .await?; self.connection = Some(connection); } Ok(()) } #[inline] fn connection(&mut self) -> &mut PgConnection { self.connection.as_mut().unwrap() } /// Receives the next notification available from any of the subscribed channels. pub async fn recv(&mut self) -> crate::Result<PgNotification<'_>> { // Flush the buffer first, if anything // This would only fill up if this listener is used as a connection if let Ok(Some(notification)) = self.buffer_rx.try_next() { return Ok(PgNotification(notification)); } loop { // Ensure we have an active connection to work with. self.connect_if_needed().await?; match self.connection().stream.read().await { // We've received an async notification, return it. Ok(Message::NotificationResponse) => { let notification = NotificationResponse::read(self.connection().stream.buffer())?; return Ok(PgNotification(notification)); } // Mark the connection as ready for another query Ok(Message::ReadyForQuery) => { self.connection().is_ready = true; } // Ignore unexpected messages Ok(_) => {} // The connection is dead, ensure that it is dropped, // update self state, and loop to try again. Err(crate::Error::Io(err)) if err.kind() == io::ErrorKind::ConnectionAborted => { self.buffer_tx = self.connection().stream.notifications.take(); self.connection = None; } // Forward other errors Err(error) => { return Err(error); } } } } /// Consume this listener, returning a `Stream` of notifications. pub fn into_stream( mut self, ) -> impl Stream<Item = crate::Result<PgNotification<'static>>> + Unpin { Box::pin(try_stream! { loop { let notification = self.recv().await?; yield notification.into_owned(); } }) } } impl Executor for PgListener { type Database = Postgres; fn execute<'e, 'q: 'e, 'c: 'e, E: 'e>( &'c mut self, query: E, ) -> BoxFuture<'e, crate::Result<u64>> where E: Execute<'q, Self::Database>, { self.connection().execute(query) } fn fetch<'q, E>(&mut self, query: E) -> PgCursor<'_, 'q> where E: Execute<'q, Self::Database>, { self.connection().fetch(query) } #[doc(hidden)] fn describe<'e, 'q, E: 'e>( &'e mut self, query: E, ) -> BoxFuture<'e, crate::Result<Describe<Self::Database>>> where E: Execute<'q, Self::Database>, { self.connection().describe(query) } } impl<'c> RefExecutor<'c> for &'c mut PgListener { type Database = Postgres; fn fetch_by_ref<'q, E>(self, query: E) -> PgCursor<'c, 'q> where E: Execute<'q, Self::Database>, { self.connection().fetch_by_ref(query) } } impl PgNotification<'_> { /// The process ID of the notifying backend process. #[inline] pub fn process_id(&self) -> u32 { self.0.process_id } /// The channel that the notify has been raised on. This can be thought /// of as the message topic. #[inline] pub fn channel(&self) -> &str { self.0.channel.as_ref() } /// The payload of the notification. An empty payload is received as an /// empty string. #[inline] pub fn payload(&self) -> &str { self.0.payload.as_ref() } fn into_owned(self) -> PgNotification<'static> { PgNotification(self.0.into_owned()) } } impl Debug for PgNotification<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PgNotification") .field("process_id", &self.process_id()) .field("channel", &self.channel()) .field("payload", &self.payload()) .finish() } } fn ident(mut name: &str) -> String { // If the input string contains a NUL byte, we should truncate the // identifier. if let Some(index) = name.find('\0') { name = &name[..index]; } // Any double quotes must be escaped name.replace('"', "\"\"") } fn build_listen_all_query(channels: impl IntoIterator<Item = impl AsRef<str>>) -> String { channels.into_iter().fold(String::new(), |mut acc, chan| { acc.push_str(r#"LISTEN ""#); acc.push_str(&ident(chan.as_ref())); acc.push_str(r#"";"#); acc }) } #[cfg(test)] mod tests { use super::*; #[test] fn build_listen_all_query_with_single_channel() { let output = build_listen_all_query(&["test"]); assert_eq!(output.as_str(), r#"LISTEN "test";"#); } #[test] fn build_listen_all_query_with_multiple_channels() { let output = build_listen_all_query(&["channel.0", "channel.1"]); assert_eq!(output.as_str(), r#"LISTEN "channel.0";LISTEN "channel.1";"#); } }
29.954248
98
0.572005
8a5b421953acd5a2ef36beb71fad53eeda99f053
16,221
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. //! Benchmarks for Merge performance //! //! Each benchmark: //! 1. Creates a sorted RecordBatch of some number of columns //! //! 2. Divides that `RecordBatch` into some number of "streams" //! (`RecordBatch`s with a subset of the rows, still ordered) //! //! 3. Times how long it takes for [`SortPreservingMergeExec`] to //! merge the "streams" back together into the original RecordBatch. //! //! Pictorally: //! //! ``` //! Rows are randombly //! divided into separate //! RecordBatch "streams", //! β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” preserving the order β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ ──────────────┐ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ └─────────────▢ β”‚ C1 β”‚ β”‚... β”‚ β”‚ CN β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ ───────────────┐ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Ά β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚ β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚ β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ │└───────────────▢│ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ ... β”‚ β”‚ C1 β”‚ β”‚... β”‚ β”‚ CN β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Ά β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ C1 β”‚ β”‚... β”‚ β”‚ CN β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ │───────────────┐│ β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚ ... //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ ────────────┼┼┐ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚β”‚ β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”˜β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ C1 β”‚ β”‚... β”‚ β”‚ CN β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ └─┼────────────▢ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ └─────────────▢ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ //! β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜ //! Input RecordBatch NUM_STREAMS input //! Columns 1..N RecordBatches //! INPUT_SIZE sorted rows (still INPUT_SIZE total //! ~10% duplicates rows) //! ``` use std::sync::Arc; use arrow::{ array::{Float64Array, Int64Array, StringArray, UInt64Array}, compute::{self, SortOptions, TakeOptions}, datatypes::Schema, record_batch::RecordBatch, }; /// Benchmarks for SortPreservingMerge stream use criterion::{criterion_group, criterion_main, Criterion}; use datafusion::{ execution::context::TaskContext, physical_plan::{ memory::MemoryExec, sorts::sort_preserving_merge::SortPreservingMergeExec, ExecutionPlan, }, prelude::SessionContext, }; use datafusion_physical_expr::{expressions::col, PhysicalSortExpr}; use futures::StreamExt; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; use tokio::runtime::Runtime; use lazy_static::lazy_static; /// Total number of streams to divide each input into /// models 8 partition plan (should it be 16??) const NUM_STREAMS: u64 = 8; /// Total number of input rows to generate const INPUT_SIZE: u64 = 100000; // cases: // * physical sort expr (X, Y Z, NULLS FIRST, ASC) (not parameterized) // // streams of distinct values // streams with 10% duplicated values (within each stream, and across streams) // These cases are intended to model important usecases in TPCH // parameters: // // Input schemas lazy_static! { static ref I64_STREAMS: Vec<Vec<RecordBatch>> = i64_streams(); static ref F64_STREAMS: Vec<Vec<RecordBatch>> = f64_streams(); // TODO: add dictionay encoded values static ref UTF8_LOW_CARDINALITY_STREAMS: Vec<Vec<RecordBatch>> = utf8_low_cardinality_streams(); static ref UTF8_HIGH_CARDINALITY_STREAMS: Vec<Vec<RecordBatch>> = utf8_high_cardinality_streams(); // * (string(low), string(low), string(high)) -- tpch q1 + iox static ref UTF8_TUPLE_STREAMS: Vec<Vec<RecordBatch>> = utf8_tuple_streams(); // * (f64, string, string, int) -- tpch q2 static ref MIXED_TUPLE_STREAMS: Vec<Vec<RecordBatch>> = mixed_tuple_streams(); } fn criterion_benchmark(c: &mut Criterion) { c.bench_function("merge i64", |b| { let case = MergeBenchCase::new(&I64_STREAMS); b.iter(move || case.run()) }); c.bench_function("merge f64", |b| { let case = MergeBenchCase::new(&F64_STREAMS); b.iter(move || case.run()) }); c.bench_function("merge utf8 low cardinality", |b| { let case = MergeBenchCase::new(&UTF8_LOW_CARDINALITY_STREAMS); b.iter(move || case.run()) }); c.bench_function("merge utf8 high cardinality", |b| { let case = MergeBenchCase::new(&UTF8_HIGH_CARDINALITY_STREAMS); b.iter(move || case.run()) }); c.bench_function("merge utf8 tuple", |b| { let case = MergeBenchCase::new(&UTF8_TUPLE_STREAMS); b.iter(move || case.run()) }); c.bench_function("merge mixed tuple", |b| { let case = MergeBenchCase::new(&MIXED_TUPLE_STREAMS); b.iter(move || case.run()) }); } /// Encapsulates running each test case struct MergeBenchCase { runtime: Runtime, task_ctx: Arc<TaskContext>, // The plan to run plan: Arc<dyn ExecutionPlan>, } impl MergeBenchCase { /// Prepare to run a benchmark that merges the specified /// partitions (streams) together using all keyes fn new(partitions: &[Vec<RecordBatch>]) -> Self { let runtime = tokio::runtime::Builder::new_multi_thread().build().unwrap(); let session_ctx = SessionContext::new(); let task_ctx = session_ctx.task_ctx(); let schema = partitions[0][0].schema(); let sort = make_sort_exprs(schema.as_ref()); let projection = None; let exec = MemoryExec::try_new(partitions, schema, projection).unwrap(); let plan = Arc::new(SortPreservingMergeExec::new(sort, Arc::new(exec))); Self { runtime, task_ctx, plan, } } /// runs the specified plan to completion, draining all input and /// panic'ing on error fn run(&self) { let plan = Arc::clone(&self.plan); let task_ctx = Arc::clone(&self.task_ctx); assert_eq!(plan.output_partitioning().partition_count(), 1); self.runtime.block_on(async move { let mut stream = plan.execute(0, task_ctx).unwrap(); while let Some(b) = stream.next().await { b.expect("unexpected execution error"); } }) } } /// Make sort exprs for each column in `schema` fn make_sort_exprs(schema: &Schema) -> Vec<PhysicalSortExpr> { schema .fields() .iter() .map(|f| PhysicalSortExpr { expr: col(f.name(), schema).unwrap(), options: SortOptions::default(), }) .collect() } /// Create streams of int64 (where approximately 1/3 values is repeated) fn i64_streams() -> Vec<Vec<RecordBatch>> { let array: Int64Array = DataGenerator::new().i64_values().into_iter().collect(); let batch = RecordBatch::try_from_iter(vec![("i64", Arc::new(array) as _)]).unwrap(); split_batch(batch) } /// Create streams of f64 (where approximately 1/3 values are repeated) /// with the same distribution as i64_streams fn f64_streams() -> Vec<Vec<RecordBatch>> { let array: Float64Array = DataGenerator::new().f64_values().into_iter().collect(); let batch = RecordBatch::try_from_iter(vec![("f64", Arc::new(array) as _)]).unwrap(); split_batch(batch) } /// Create streams of random low cardinality utf8 values fn utf8_low_cardinality_streams() -> Vec<Vec<RecordBatch>> { let array: StringArray = DataGenerator::new() .utf8_low_cardinality_values() .into_iter() .collect(); let batch = RecordBatch::try_from_iter(vec![("utf_low", Arc::new(array) as _)]).unwrap(); split_batch(batch) } /// Create streams of high cardinality (~ no duplicates) utf8 values fn utf8_high_cardinality_streams() -> Vec<Vec<RecordBatch>> { let array: StringArray = DataGenerator::new() .utf8_high_cardinality_values() .into_iter() .collect(); let batch = RecordBatch::try_from_iter(vec![("utf_high", Arc::new(array) as _)]).unwrap(); split_batch(batch) } /// Create a batch of (utf8_low, utf8_low, utf8_high) fn utf8_tuple_streams() -> Vec<Vec<RecordBatch>> { let mut gen = DataGenerator::new(); // need to sort by the combined key, so combine them together let mut tuples: Vec<_> = gen .utf8_low_cardinality_values() .into_iter() .zip(gen.utf8_low_cardinality_values().into_iter()) .zip(gen.utf8_high_cardinality_values().into_iter()) .collect(); tuples.sort_unstable(); let (tuples, utf8_high): (Vec<_>, Vec<_>) = tuples.into_iter().unzip(); let (utf8_low1, utf8_low2): (Vec<_>, Vec<_>) = tuples.into_iter().unzip(); let utf8_high: StringArray = utf8_high.into_iter().collect(); let utf8_low1: StringArray = utf8_low1.into_iter().collect(); let utf8_low2: StringArray = utf8_low2.into_iter().collect(); let batch = RecordBatch::try_from_iter(vec![ ("utf_low1", Arc::new(utf8_low1) as _), ("utf_low2", Arc::new(utf8_low2) as _), ("utf_high", Arc::new(utf8_high) as _), ]) .unwrap(); split_batch(batch) } /// Create a batch of (f64, utf8_low, utf8_low, i64) fn mixed_tuple_streams() -> Vec<Vec<RecordBatch>> { let mut gen = DataGenerator::new(); // need to sort by the combined key, so combine them together let mut tuples: Vec<_> = gen .i64_values() .into_iter() .zip(gen.utf8_low_cardinality_values().into_iter()) .zip(gen.utf8_low_cardinality_values().into_iter()) .zip(gen.i64_values().into_iter()) .collect(); tuples.sort_unstable(); let (tuples, i64_values): (Vec<_>, Vec<_>) = tuples.into_iter().unzip(); let (tuples, utf8_low2): (Vec<_>, Vec<_>) = tuples.into_iter().unzip(); let (f64_values, utf8_low1): (Vec<_>, Vec<_>) = tuples.into_iter().unzip(); let f64_values: Float64Array = f64_values.into_iter().map(|v| v as f64).collect(); let utf8_low1: StringArray = utf8_low1.into_iter().collect(); let utf8_low2: StringArray = utf8_low2.into_iter().collect(); let i64_values: Int64Array = i64_values.into_iter().collect(); let batch = RecordBatch::try_from_iter(vec![ ("f64", Arc::new(f64_values) as _), ("utf_low1", Arc::new(utf8_low1) as _), ("utf_low2", Arc::new(utf8_low2) as _), ("i64", Arc::new(i64_values) as _), ]) .unwrap(); split_batch(batch) } /// Encapsulates creating data for this test struct DataGenerator { rng: StdRng, } impl DataGenerator { fn new() -> Self { Self { rng: StdRng::seed_from_u64(42), } } /// Create an array of i64 sorted values (where approximately 1/3 values is repeated) fn i64_values(&mut self) -> Vec<i64> { let mut vec: Vec<_> = (0..INPUT_SIZE) .map(|_| self.rng.gen_range(0..INPUT_SIZE as i64)) .collect(); vec.sort_unstable(); // 6287 distinct / 10000 total //let num_distinct = vec.iter().collect::<HashSet<_>>().len(); //println!("{} distinct / {} total", num_distinct, vec.len()); vec } /// Create an array of f64 sorted values (with same distribution of `i64_values`) fn f64_values(&mut self) -> Vec<f64> { self.i64_values().into_iter().map(|v| v as f64).collect() } /// array of low cardinality (100 distinct) values fn utf8_low_cardinality_values(&mut self) -> Vec<Option<Arc<str>>> { let strings = (0..100).map(|s| format!("value{}", s)).collect::<Vec<_>>(); // pick from the 100 strings randomly let mut input = (0..INPUT_SIZE) .map(|_| { let idx = self.rng.gen_range(0..strings.len()); let s = Arc::from(strings[idx].as_str()); Some(s) }) .collect::<Vec<_>>(); input.sort_unstable(); input } /// Create sorted values of high cardinality (~ no duplicates) utf8 values fn utf8_high_cardinality_values(&mut self) -> Vec<Option<String>> { // make random strings let mut input = (0..INPUT_SIZE) .map(|_| Some(self.random_string())) .collect::<Vec<_>>(); input.sort_unstable(); input } fn random_string(&mut self) -> String { let rng = &mut self.rng; rng.sample_iter(rand::distributions::Alphanumeric) .filter(|c| c.is_ascii_alphabetic()) .take(20) .map(char::from) .collect::<String>() } } /// Splits the (sorted) `input_batch` randomly into `NUM_STREAMS` approximately evenly sorted streams fn split_batch(input_batch: RecordBatch) -> Vec<Vec<RecordBatch>> { // figure out which inputs go where let mut rng = StdRng::seed_from_u64(1337); // randomly assign rows to streams let stream_assignments = (0..input_batch.num_rows()) .map(|_| rng.gen_range(0..NUM_STREAMS)) .collect(); // split the inputs into streams (0..NUM_STREAMS) .map(|stream| { // make a "stream" of 1 record batch vec![take_columns(&input_batch, &stream_assignments, stream)] }) .collect::<Vec<_>>() } /// returns a record batch that contains all there values where /// stream_assignment[i] = stream (aka this is the equivalent of /// calling take(indicies) where indicies[i] == stream_index) fn take_columns( input_batch: &RecordBatch, stream_assignments: &UInt64Array, stream: u64, ) -> RecordBatch { // find just the indicies needed from record batches to extract let stream_indices: UInt64Array = stream_assignments .iter() .enumerate() .filter_map(|(idx, stream_idx)| { if stream_idx.unwrap() == stream { Some(idx as u64) } else { None } }) .collect(); let options = Some(TakeOptions { check_bounds: true }); // now, get the columns from each array let new_columns = input_batch .columns() .iter() .map(|array| compute::take(array, &stream_indices, options.clone()).unwrap()) .collect(); RecordBatch::try_new(input_batch.schema(), new_columns).unwrap() } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
35.572368
102
0.548055
1cb983a34bc7f7223abc2481636082f7dff8ed83
484
use machine::state::State; pub fn fint(state: &mut State, x: u8, y: u8, z: u8) { // Load operands let op1: f64 = state.gpr[z].into(); // Execute let res: f64 = match y { 1 => op1.round(), // round off 2 => op1.ceil(), // round up 3 => op1.floor(), // round down 4 => (op1 / 10.0).ceil() * 10.0, // round to nearest ten _ => panic!("no rounding mode"), }; // Store result state.gpr[x] = res.into(); }
25.473684
67
0.485537
d6f939bb621610c1e8b330f9b86642c2feb9a5f2
4,887
use std::fmt; use std::iter::Sum; use std::ops::{ Add, BitAnd, BitAndAssign, BitOr, BitOrAssign, Mul, Not, Shl, ShlAssign, Shr, ShrAssign, }; use num::{ traits::{CheckedShl, CheckedShr}, One, PrimInt, Zero, }; use crate::prefix::{IpPrefix, IpPrefixRange}; #[derive(Clone, Copy, Eq, PartialEq)] pub struct GlueMap<P: IpPrefix> { bitmap: P::Bits, hostbit: bool, } impl<P: IpPrefix> Zero for GlueMap<P> { fn zero() -> Self { Self { bitmap: P::Bits::zero(), hostbit: false, } } fn is_zero(&self) -> bool { self.bitmap == P::Bits::zero() && !self.hostbit } } impl<P: IpPrefix> One for GlueMap<P> { fn one() -> Self { Self { bitmap: !P::Bits::zero(), hostbit: true, } } } impl<P: IpPrefix> BitAnd for GlueMap<P> { type Output = Self; fn bitand(self, other: Self) -> Self::Output { Self { bitmap: self.bitmap & other.bitmap, hostbit: self.hostbit && other.hostbit, } } } impl<P: IpPrefix> BitOr for GlueMap<P> { type Output = Self; fn bitor(self, other: Self) -> Self::Output { Self { bitmap: self.bitmap | other.bitmap, hostbit: self.hostbit || other.hostbit, } } } impl<P: IpPrefix> Not for GlueMap<P> { type Output = Self; fn not(self) -> Self::Output { Self { bitmap: !self.bitmap, hostbit: !self.hostbit, } } } impl<P: IpPrefix> BitAndAssign for GlueMap<P> { fn bitand_assign(&mut self, other: Self) { *self = *self & other } } impl<P: IpPrefix> BitOrAssign for GlueMap<P> { fn bitor_assign(&mut self, other: Self) { *self = *self | other } } impl<P: IpPrefix> Add for GlueMap<P> { type Output = Self; #[allow(clippy::suspicious_arithmetic_impl)] fn add(self, other: Self) -> Self::Output { self | other } } impl<P: IpPrefix> Mul for GlueMap<P> { type Output = Self; #[allow(clippy::suspicious_arithmetic_impl)] fn mul(self, other: Self) -> Self::Output { self & other } } impl<P: IpPrefix> Shl<u8> for GlueMap<P> { type Output = Self; fn shl(self, rhs: u8) -> Self::Output { match self.bitmap.checked_shl(rhs.into()) { Some(result) => Self { bitmap: result, hostbit: self.hostbit.to_owned(), }, None => Self { bitmap: P::Bits::zero(), hostbit: true, }, } } } impl<P: IpPrefix> ShlAssign<u8> for GlueMap<P> { fn shl_assign(&mut self, rhs: u8) { *self = *self << rhs } } impl<P: IpPrefix> Shr<u8> for GlueMap<P> { type Output = Self; fn shr(self, rhs: u8) -> Self::Output { let (hostbit, shifted_hostbit) = if self.hostbit && rhs > 0 { ( false, if rhs > P::MAX_LENGTH { P::Bits::zero() } else { P::Bits::one() << (P::MAX_LENGTH - rhs) }, ) } else { (self.hostbit, P::Bits::zero()) }; let shifted_bitmap = match self.bitmap.checked_shr(rhs.into()) { Some(result) => result, None => P::Bits::zero(), }; Self { bitmap: shifted_bitmap + shifted_hostbit, hostbit, } } } impl<P: IpPrefix> ShrAssign<u8> for GlueMap<P> { fn shr_assign(&mut self, rhs: u8) { *self = *self >> rhs } } impl<P: IpPrefix> Sum for GlueMap<P> { fn sum<I>(iter: I) -> Self where I: Iterator<Item = Self>, { iter.fold(Self::zero(), |acc, item| acc + item) } } impl<P: IpPrefix> GlueMap<P> { pub fn singleton(length: u8) -> Self { Self { bitmap: P::Bits::one(), hostbit: false, } << length } pub fn trailing_zeros(self) -> u32 { let zeros = self.bitmap.trailing_zeros(); if zeros == P::MAX_LENGTH.into() && !self.hostbit { zeros + 1 } else { zeros } } pub fn count_ones(self) -> u32 { let ones = self.bitmap.count_ones(); if self.hostbit { ones + 1 } else { ones } } } impl<P: IpPrefix> From<IpPrefixRange<P>> for GlueMap<P> { fn from(r: IpPrefixRange<P>) -> Self { r.range().map(Self::singleton).sum() } } impl<P: IpPrefix> fmt::Debug for GlueMap<P> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("GlueMap") .field( "bitmap", &format_args!("{:#0w$b}", &self.bitmap, w = (P::MAX_LENGTH + 2).into()), ) .field("hostbit", &self.hostbit) .finish() } }
22.836449
92
0.500921
f86b5be23fd2c9ec3ba6a2d1daa0ffe9f096a55e
22,438
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT //! The Tauri window types and functions. pub(crate) mod menu; pub use menu::{MenuEvent, MenuHandle}; use crate::{ app::AppHandle, command::{CommandArg, CommandItem}, event::{Event, EventHandler}, hooks::{InvokePayload, InvokeResponder}, manager::WindowManager, runtime::{ monitor::Monitor as RuntimeMonitor, webview::{WebviewAttributes, WindowBuilder}, window::{ dpi::{PhysicalPosition, PhysicalSize, Position, Size}, DetachedWindow, JsEventListenerKey, PendingWindow, WindowEvent, }, Dispatch, Icon, Runtime, UserAttentionType, }, sealed::ManagerBase, sealed::RuntimeOrDispatch, utils::config::WindowUrl, Invoke, InvokeError, InvokeMessage, InvokeResolver, Manager, PageLoadPayload, }; use serde::Serialize; use tauri_macros::default_runtime; use std::{ hash::{Hash, Hasher}, sync::Arc, }; /// Monitor descriptor. #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Monitor { pub(crate) name: Option<String>, pub(crate) size: PhysicalSize<u32>, pub(crate) position: PhysicalPosition<i32>, pub(crate) scale_factor: f64, } impl From<RuntimeMonitor> for Monitor { fn from(monitor: RuntimeMonitor) -> Self { Self { name: monitor.name, size: monitor.size, position: monitor.position, scale_factor: monitor.scale_factor, } } } impl Monitor { /// Returns a human-readable name of the monitor. /// Returns None if the monitor doesn't exist anymore. pub fn name(&self) -> Option<&String> { self.name.as_ref() } /// Returns the monitor's resolution. pub fn size(&self) -> &PhysicalSize<u32> { &self.size } /// Returns the top-left corner position of the monitor relative to the larger full screen area. pub fn position(&self) -> &PhysicalPosition<i32> { &self.position } /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa. pub fn scale_factor(&self) -> f64 { self.scale_factor } } // TODO: expand these docs since this is a pretty important type /// A webview window managed by Tauri. /// /// This type also implements [`Manager`] which allows you to manage other windows attached to /// the same application. #[default_runtime(crate::Wry, wry)] #[derive(Debug)] pub struct Window<R: Runtime> { /// The webview window created by the runtime. window: DetachedWindow<R>, /// The manager to associate this webview window with. manager: WindowManager<R>, pub(crate) app_handle: AppHandle<R>, } #[cfg(any(windows, target_os = "macos"))] #[cfg_attr(doc_cfg, doc(cfg(any(windows, target_os = "macos"))))] unsafe impl<R: Runtime> raw_window_handle::HasRawWindowHandle for Window<R> { #[cfg(windows)] fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle { let mut handle = raw_window_handle::Win32Handle::empty(); handle.hwnd = self.hwnd().expect("failed to get window `hwnd`"); raw_window_handle::RawWindowHandle::Win32(handle) } #[cfg(target_os = "macos")] fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle { let mut handle = raw_window_handle::AppKitHandle::empty(); handle.ns_window = self .ns_window() .expect("failed to get window's `ns_window`"); raw_window_handle::RawWindowHandle::AppKit(handle) } } impl<R: Runtime> Clone for Window<R> { fn clone(&self) -> Self { Self { window: self.window.clone(), manager: self.manager.clone(), app_handle: self.app_handle.clone(), } } } impl<R: Runtime> Hash for Window<R> { /// Only use the [`Window`]'s label to represent its hash. fn hash<H: Hasher>(&self, state: &mut H) { self.window.label.hash(state) } } impl<R: Runtime> Eq for Window<R> {} impl<R: Runtime> PartialEq for Window<R> { /// Only use the [`Window`]'s label to compare equality. fn eq(&self, other: &Self) -> bool { self.window.label.eq(&other.window.label) } } impl<R: Runtime> Manager<R> for Window<R> {} impl<R: Runtime> ManagerBase<R> for Window<R> { fn manager(&self) -> &WindowManager<R> { &self.manager } fn runtime(&self) -> RuntimeOrDispatch<'_, R> { RuntimeOrDispatch::Dispatch(self.dispatcher()) } fn app_handle(&self) -> AppHandle<R> { self.app_handle.clone() } } impl<'de, R: Runtime> CommandArg<'de, R> for Window<R> { /// Grabs the [`Window`] from the [`CommandItem`]. This will never fail. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> { Ok(command.message.window()) } } impl<R: Runtime> Window<R> { /// Create a new window that is attached to the manager. pub(crate) fn new( manager: WindowManager<R>, window: DetachedWindow<R>, app_handle: AppHandle<R>, ) -> Self { Self { window, manager, app_handle, } } /// Creates a new webview window. /// /// Data URLs are only supported with the `window-data-url` feature flag. pub fn create_window<F>( &mut self, label: String, url: WindowUrl, setup: F, ) -> crate::Result<Window<R>> where F: FnOnce( <R::Dispatcher as Dispatch>::WindowBuilder, WebviewAttributes, ) -> ( <R::Dispatcher as Dispatch>::WindowBuilder, WebviewAttributes, ), { let (window_builder, webview_attributes) = setup( <R::Dispatcher as Dispatch>::WindowBuilder::new(), WebviewAttributes::new(url), ); self.create_new_window(PendingWindow::new( window_builder, webview_attributes, label, )) } pub(crate) fn invoke_responder(&self) -> Arc<InvokeResponder<R>> { self.manager.invoke_responder() } /// The current window's dispatcher. pub(crate) fn dispatcher(&self) -> R::Dispatcher { self.window.dispatcher.clone() } /// Runs the given closure on the main thread. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> { self .window .dispatcher .run_on_main_thread(f) .map_err(Into::into) } /// How to handle this window receiving an [`InvokeMessage`]. pub fn on_message(self, payload: InvokePayload) -> crate::Result<()> { let manager = self.manager.clone(); match payload.cmd.as_str() { "__initialized" => { let payload: PageLoadPayload = serde_json::from_value(payload.inner)?; manager.run_on_page_load(self, payload); } _ => { let message = InvokeMessage::new( self.clone(), manager.state(), payload.cmd.to_string(), payload.inner, ); let resolver = InvokeResolver::new(self, payload.callback, payload.error); let invoke = Invoke { message, resolver }; if let Some(module) = &payload.tauri_module { let module = module.to_string(); crate::endpoints::handle(module, invoke, manager.config(), manager.package_info()); } else if payload.cmd.starts_with("plugin:") { manager.extend_api(invoke); } else { manager.run_invoke_handler(invoke); } } } Ok(()) } /// The label of this window. pub fn label(&self) -> &str { &self.window.label } /// Emits an event to both the JavaScript and the Rust listeners. pub fn emit_and_trigger<S: Serialize + Clone>( &self, event: &str, payload: S, ) -> crate::Result<()> { self.trigger(event, Some(serde_json::to_string(&payload)?)); self.emit(event, payload) } pub(crate) fn emit_internal<S: Serialize>( &self, event: &str, source_window_label: Option<&str>, payload: S, ) -> crate::Result<()> { self.eval(&format!( "window['{}']({{event: {}, windowLabel: {}, payload: {}}})", self.manager.event_emit_function_name(), serde_json::to_string(event)?, serde_json::to_string(&source_window_label)?, serde_json::to_value(payload)?, ))?; Ok(()) } /// Emits an event to the JavaScript listeners on the current window. /// /// The event is only delivered to listeners that used the `WebviewWindow#listen` method on the @tauri-apps/api `window` module. pub fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> crate::Result<()> { self .manager .emit_filter(event, Some(self.label()), payload, |w| { w.has_js_listener(None, event) || w.has_js_listener(Some(self.label().into()), event) })?; Ok(()) } /// Listen to an event on this window. /// /// This listener only receives events that are triggered using the /// [`trigger`](Window#method.trigger) and [`emit_and_trigger`](Window#method.emit_and_trigger) methods or /// the `appWindow.emit` function from the @tauri-apps/api `window` module. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventHandler where F: Fn(Event) + Send + 'static, { let label = self.window.label.clone(); self.manager.listen(event.into(), Some(label), handler) } /// Unlisten to an event on this window. pub fn unlisten(&self, handler_id: EventHandler) { self.manager.unlisten(handler_id) } /// Listen to an event on this window a single time. pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventHandler where F: FnOnce(Event) + Send + 'static, { let label = self.window.label.clone(); self.manager.once(event.into(), Some(label), handler) } /// Triggers an event to the Rust listeners on this window. /// /// The event is only delivered to listeners that used the [`listen`](Window#method.listen) method. pub fn trigger(&self, event: &str, data: Option<String>) { let label = self.window.label.clone(); self.manager.trigger(event, Some(label), data) } /// Evaluates JavaScript on this window. pub fn eval(&self, js: &str) -> crate::Result<()> { self.window.dispatcher.eval_script(js).map_err(Into::into) } /// Registers a window event listener. pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) { self.window.dispatcher.on_window_event(f); } /// Registers a menu event listener. pub fn on_menu_event<F: Fn(MenuEvent) + Send + 'static>(&self, f: F) -> uuid::Uuid { let menu_ids = self.window.menu_ids.clone(); self.window.dispatcher.on_menu_event(move |event| { f(MenuEvent { menu_item_id: menu_ids .lock() .unwrap() .get(&event.menu_item_id) .unwrap() .clone(), }) }) } pub(crate) fn register_js_listener(&self, window_label: Option<String>, event: String, id: u64) { self .window .js_event_listeners .lock() .unwrap() .entry(JsEventListenerKey { window_label, event, }) .or_insert_with(Default::default) .insert(id); } pub(crate) fn unregister_js_listener(&self, id: u64) { let mut empty = None; let mut js_listeners = self.window.js_event_listeners.lock().unwrap(); for (key, ids) in js_listeners.iter_mut() { if ids.contains(&id) { ids.remove(&id); if ids.is_empty() { empty.replace(key.clone()); } break; } } if let Some(key) = empty { js_listeners.remove(&key); } } /// Whether this window registered a listener to an event from the given window and event name. pub(crate) fn has_js_listener(&self, window_label: Option<String>, event: &str) -> bool { self .window .js_event_listeners .lock() .unwrap() .contains_key(&JsEventListenerKey { window_label, event: event.into(), }) } /// Opens the developer tools window (Web Inspector). /// The devtools is only enabled on debug builds or with the `devtools` feature flag. /// /// ## Platform-specific /// /// - **macOS**: This is a private API on macOS, /// so you cannot use this if your application will be published on the App Store. /// /// # Example /// /// ```rust,no_run /// use tauri::Manager; /// tauri::Builder::default() /// .setup(|app| { /// #[cfg(debug_assertions)] /// app.get_window("main").unwrap().open_devtools(); /// Ok(()) /// }); /// ``` #[cfg(any(debug_assertions, feature = "devtools"))] #[cfg_attr(doc_cfg, doc(cfg(any(debug_assertions, feature = "devtools"))))] pub fn open_devtools(&self) { self.window.dispatcher.open_devtools(); } // Getters /// Gets a handle to the window menu. pub fn menu_handle(&self) -> MenuHandle<R> { MenuHandle { ids: self.window.menu_ids.clone(), dispatcher: self.dispatcher(), } } /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa. pub fn scale_factor(&self) -> crate::Result<f64> { self.window.dispatcher.scale_factor().map_err(Into::into) } /// Returns the position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop. pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> { self.window.dispatcher.inner_position().map_err(Into::into) } /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop. pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> { self.window.dispatcher.outer_position().map_err(Into::into) } /// Returns the physical size of the window's client area. /// /// The client area is the content of the window, excluding the title bar and borders. pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> { self.window.dispatcher.inner_size().map_err(Into::into) } /// Returns the physical size of the entire window. /// /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead. pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> { self.window.dispatcher.outer_size().map_err(Into::into) } /// Gets the window's current fullscreen state. pub fn is_fullscreen(&self) -> crate::Result<bool> { self.window.dispatcher.is_fullscreen().map_err(Into::into) } /// Gets the window's current maximized state. pub fn is_maximized(&self) -> crate::Result<bool> { self.window.dispatcher.is_maximized().map_err(Into::into) } /// Gets the window’s current decoration state. pub fn is_decorated(&self) -> crate::Result<bool> { self.window.dispatcher.is_decorated().map_err(Into::into) } /// Gets the window’s current resizable state. pub fn is_resizable(&self) -> crate::Result<bool> { self.window.dispatcher.is_resizable().map_err(Into::into) } /// Gets the window's current vibility state. pub fn is_visible(&self) -> crate::Result<bool> { self.window.dispatcher.is_visible().map_err(Into::into) } /// Returns the monitor on which the window currently resides. /// /// Returns None if current monitor can't be detected. pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> { self .window .dispatcher .current_monitor() .map(|m| m.map(Into::into)) .map_err(Into::into) } /// Returns the primary monitor of the system. /// /// Returns None if it can't identify any monitor as a primary one. pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> { self .window .dispatcher .primary_monitor() .map(|m| m.map(Into::into)) .map_err(Into::into) } /// Returns the list of all the monitors available on the system. pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> { self .window .dispatcher .available_monitors() .map(|m| m.into_iter().map(Into::into).collect()) .map_err(Into::into) } /// Returns the native handle that is used by this window. #[cfg(target_os = "macos")] pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> { self.window.dispatcher.ns_window().map_err(Into::into) } /// Returns the native handle that is used by this window. #[cfg(windows)] pub fn hwnd(&self) -> crate::Result<*mut std::ffi::c_void> { self .window .dispatcher .hwnd() .map(|hwnd| hwnd.0 as *mut _) .map_err(Into::into) } /// Returns the `ApplicatonWindow` from gtk crate that is used by this window. /// /// Note that this can only be used on the main thread. #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] pub fn gtk_window(&self) -> crate::Result<gtk::ApplicationWindow> { self.window.dispatcher.gtk_window().map_err(Into::into) } // Setters /// Centers the window. pub fn center(&self) -> crate::Result<()> { self.window.dispatcher.center().map_err(Into::into) } /// Requests user attention to the window, this has no effect if the application /// is already focused. How requesting for user attention manifests is platform dependent, /// see `UserAttentionType` for details. /// /// Providing `None` will unset the request for user attention. Unsetting the request for /// user attention might not be done automatically by the WM when the window receives input. /// /// ## Platform-specific /// /// - **macOS:** `None` has no effect. /// - **Linux:** Urgency levels have the same effect. pub fn request_user_attention( &self, request_type: Option<UserAttentionType>, ) -> crate::Result<()> { self .window .dispatcher .request_user_attention(request_type) .map_err(Into::into) } /// Opens the dialog to prints the contents of the webview. /// Currently only supported on macOS on `wry`. /// `window.print()` works on all platforms. pub fn print(&self) -> crate::Result<()> { self.window.dispatcher.print().map_err(Into::into) } /// Determines if this window should be resizable. pub fn set_resizable(&self, resizable: bool) -> crate::Result<()> { self .window .dispatcher .set_resizable(resizable) .map_err(Into::into) } /// Set this window's title. pub fn set_title(&self, title: &str) -> crate::Result<()> { self .window .dispatcher .set_title(title.to_string()) .map_err(Into::into) } /// Maximizes this window. pub fn maximize(&self) -> crate::Result<()> { self.window.dispatcher.maximize().map_err(Into::into) } /// Un-maximizes this window. pub fn unmaximize(&self) -> crate::Result<()> { self.window.dispatcher.unmaximize().map_err(Into::into) } /// Minimizes this window. pub fn minimize(&self) -> crate::Result<()> { self.window.dispatcher.minimize().map_err(Into::into) } /// Un-minimizes this window. pub fn unminimize(&self) -> crate::Result<()> { self.window.dispatcher.unminimize().map_err(Into::into) } /// Show this window. pub fn show(&self) -> crate::Result<()> { self.window.dispatcher.show().map_err(Into::into) } /// Hide this window. pub fn hide(&self) -> crate::Result<()> { self.window.dispatcher.hide().map_err(Into::into) } /// Closes this window. /// # Panics /// /// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure. /// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure. /// /// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic. pub fn close(&self) -> crate::Result<()> { self.window.dispatcher.close().map_err(Into::into) } /// Determines if this window should be [decorated]. /// /// [decorated]: https://en.wikipedia.org/wiki/Window_(computing)#Window_decoration pub fn set_decorations(&self, decorations: bool) -> crate::Result<()> { self .window .dispatcher .set_decorations(decorations) .map_err(Into::into) } /// Determines if this window should always be on top of other windows. pub fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> { self .window .dispatcher .set_always_on_top(always_on_top) .map_err(Into::into) } /// Resizes this window. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> { self .window .dispatcher .set_size(size.into()) .map_err(Into::into) } /// Sets this window's minimum size. pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> { self .window .dispatcher .set_min_size(size.map(|s| s.into())) .map_err(Into::into) } /// Sets this window's maximum size. pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> { self .window .dispatcher .set_max_size(size.map(|s| s.into())) .map_err(Into::into) } /// Sets this window's position. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> { self .window .dispatcher .set_position(position.into()) .map_err(Into::into) } /// Determines if this window should be fullscreen. pub fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> { self .window .dispatcher .set_fullscreen(fullscreen) .map_err(Into::into) } /// Bring the window to front and focus. pub fn set_focus(&self) -> crate::Result<()> { self.window.dispatcher.set_focus().map_err(Into::into) } /// Sets this window' icon. pub fn set_icon(&self, icon: Icon) -> crate::Result<()> { self.window.dispatcher.set_icon(icon).map_err(Into::into) } /// Whether to show the window icon in the task bar or not. pub fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> { self .window .dispatcher .set_skip_taskbar(skip) .map_err(Into::into) } /// Starts dragging the window. pub fn start_dragging(&self) -> crate::Result<()> { self.window.dispatcher.start_dragging().map_err(Into::into) } } #[cfg(test)] mod tests { #[test] fn window_is_send_sync() { crate::test_utils::assert_send::<super::Window>(); crate::test_utils::assert_sync::<super::Window>(); } }
29.758621
135
0.643016
e4d1b8d9ae806c95d2dabddbcc9ee02f2c96a01f
3,104
mod utils; use wasm_bindgen::prelude::*; use std::fmt; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Cell { Dead = 0, Alive = 1, } #[wasm_bindgen] pub struct Universe { width: u32, height: u32, cells: Vec<Cell>, } impl Universe { fn get_index(&self, row: u32, column: u32) -> usize { (row * self.width + column) as usize } fn live_neighbor_count(&self, row: u32, column: u32) -> u8 { let mut count = 0; for delta_row in [self.height -1, 0, 1].iter().cloned() { for delta_col in [self.width -1, 0, 1].iter().cloned() { if delta_row == 0 && delta_col == 0 { continue; } let neighbor_row = (row + delta_row) % self.height; let neighbor_col = (column + delta_col) % self.width; let idx = self.get_index(neighbor_row, neighbor_col); count += self.cells[idx] as u8; } } count } } #[wasm_bindgen] impl Universe { pub fn tick(&mut self) { let mut next_state = self.cells.clone(); for row in 0..self.height { for col in 0 ..self.width { let idx = self.get_index(row, col); let cell = self.cells[idx]; let live_neighbors = self.live_neighbor_count(row, col); let next_cell = match (cell, live_neighbors) { //RUL#1 (Cell::Alive, x) if x < 2 => Cell::Dead, //RUL#2 (Cell::Alive, x) if x == 2 || x == 3 => Cell::Alive, //RUL#3 (Cell::Alive, x) if x > 3 => Cell::Dead, //RUL#4 (Cell::Dead, 3) => Cell::Alive, //Default (otherwise, _) => otherwise, }; next_state[idx] = next_cell; } } self.cells = next_state; } pub fn new() -> Universe { let width = 64; let height = 64; let cells = (0..width * height) .map(|i| { if i % 2 == 0 || i % 7 == 0 { Cell::Alive } else { Cell::Dead } }) .collect(); Universe { width, height, cells, } } pub fn render(&self) -> String { self.to_string() } } impl fmt::Display for Universe { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.as_slice().chunks(self.width as usize) { for &cell in line { let symbol = if cell == Cell::Dead { 'β—»' } else { 'β—Ό' }; write!(f, "{}", symbol)?; } write!(f, "\n")?; } Ok(()) } }
25.866667
73
0.455863
0e75ef3d79657a7dc317352584414ed3745760a2
6,254
use crate::backend::input::{ self as backend, TabletToolCapabilitys, TabletToolDescriptor, TabletToolTipState, TabletToolType, }; use input as libinput; use input::event; use input::event::{tablet_tool, EventTrait}; use super::LibinputInputBackend; /// Marker for tablet tool events pub trait IsTabletEvent: tablet_tool::TabletToolEventTrait + EventTrait {} impl IsTabletEvent for tablet_tool::TabletToolAxisEvent {} impl IsTabletEvent for tablet_tool::TabletToolProximityEvent {} impl IsTabletEvent for tablet_tool::TabletToolTipEvent {} impl IsTabletEvent for tablet_tool::TabletToolButtonEvent {} impl<E> backend::Event<LibinputInputBackend> for E where E: IsTabletEvent, { fn time(&self) -> u32 { tablet_tool::TabletToolEventTrait::time(self) } fn device(&self) -> libinput::Device { event::EventTrait::device(self) } } impl backend::TabletToolAxisEvent<LibinputInputBackend> for tablet_tool::TabletToolAxisEvent {} impl backend::TabletToolProximityEvent<LibinputInputBackend> for tablet_tool::TabletToolProximityEvent { fn state(&self) -> backend::ProximityState { match tablet_tool::TabletToolProximityEvent::proximity_state(self) { tablet_tool::ProximityState::In => backend::ProximityState::In, tablet_tool::ProximityState::Out => backend::ProximityState::Out, } } } impl backend::TabletToolTipEvent<LibinputInputBackend> for tablet_tool::TabletToolTipEvent { fn tip_state(&self) -> TabletToolTipState { match tablet_tool::TabletToolTipEvent::tip_state(self) { tablet_tool::TipState::Up => backend::TabletToolTipState::Up, tablet_tool::TipState::Down => backend::TabletToolTipState::Down, } } } impl<E> backend::TabletToolEvent<LibinputInputBackend> for E where E: IsTabletEvent + event::EventTrait, { fn tool(&self) -> TabletToolDescriptor { let tool = self.tool(); let tool_type = match tool.tool_type() { Some(tablet_tool::TabletToolType::Pen) => TabletToolType::Pen, Some(tablet_tool::TabletToolType::Eraser) => TabletToolType::Eraser, Some(tablet_tool::TabletToolType::Brush) => TabletToolType::Brush, Some(tablet_tool::TabletToolType::Pencil) => TabletToolType::Pencil, Some(tablet_tool::TabletToolType::Airbrush) => TabletToolType::Airbrush, Some(tablet_tool::TabletToolType::Mouse) => TabletToolType::Mouse, Some(tablet_tool::TabletToolType::Lens) => TabletToolType::Lens, Some(tablet_tool::TabletToolType::Totem) => TabletToolType::Totem, _ => TabletToolType::Unknown, }; let hardware_serial = tool.serial(); let hardware_id_wacom = tool.tool_id(); let mut capabilitys = TabletToolCapabilitys::empty(); capabilitys.set(TabletToolCapabilitys::TILT, tool.has_tilt()); capabilitys.set(TabletToolCapabilitys::PRESSURE, tool.has_pressure()); capabilitys.set(TabletToolCapabilitys::DISTANCE, tool.has_distance()); capabilitys.set(TabletToolCapabilitys::ROTATION, tool.has_rotation()); capabilitys.set(TabletToolCapabilitys::SLIDER, tool.has_slider()); capabilitys.set(TabletToolCapabilitys::WHEEL, tool.has_wheel()); TabletToolDescriptor { tool_type, hardware_serial, hardware_id_wacom, capabilitys, } } fn delta_x(&self) -> f64 { tablet_tool::TabletToolEventTrait::dx(self) } fn delta_y(&self) -> f64 { tablet_tool::TabletToolEventTrait::dy(self) } fn x(&self) -> f64 { tablet_tool::TabletToolEventTrait::x(self) } fn y(&self) -> f64 { tablet_tool::TabletToolEventTrait::y(self) } fn x_transformed(&self, width: i32) -> f64 { tablet_tool::TabletToolEventTrait::x_transformed(self, width as u32) } fn y_transformed(&self, height: i32) -> f64 { tablet_tool::TabletToolEventTrait::y_transformed(self, height as u32) } fn distance(&self) -> f64 { tablet_tool::TabletToolEventTrait::distance(self) } fn distance_has_changed(&self) -> bool { tablet_tool::TabletToolEventTrait::distance_has_changed(self) } fn pressure(&self) -> f64 { tablet_tool::TabletToolEventTrait::pressure(self) } fn pressure_has_changed(&self) -> bool { tablet_tool::TabletToolEventTrait::pressure_has_changed(self) } fn slider_position(&self) -> f64 { tablet_tool::TabletToolEventTrait::slider_position(self) } fn slider_has_changed(&self) -> bool { tablet_tool::TabletToolEventTrait::slider_has_changed(self) } fn tilt_x(&self) -> f64 { tablet_tool::TabletToolEventTrait::dx(self) } fn tilt_x_has_changed(&self) -> bool { tablet_tool::TabletToolEventTrait::tilt_x_has_changed(self) } fn tilt_y(&self) -> f64 { tablet_tool::TabletToolEventTrait::dy(self) } fn tilt_y_has_changed(&self) -> bool { tablet_tool::TabletToolEventTrait::tilt_y_has_changed(self) } fn rotation(&self) -> f64 { tablet_tool::TabletToolEventTrait::rotation(self) } fn rotation_has_changed(&self) -> bool { tablet_tool::TabletToolEventTrait::rotation_has_changed(self) } fn wheel_delta(&self) -> f64 { tablet_tool::TabletToolEventTrait::wheel_delta(self) } fn wheel_delta_discrete(&self) -> i32 { // I have no idea why f64 is returend by this fn, in libinput's api wheel clicks are always i32 tablet_tool::TabletToolEventTrait::wheel_delta_discrete(self) as i32 } fn wheel_has_changed(&self) -> bool { tablet_tool::TabletToolEventTrait::wheel_has_changed(self) } } impl backend::TabletToolButtonEvent<LibinputInputBackend> for tablet_tool::TabletToolButtonEvent { fn button(&self) -> u32 { tablet_tool::TabletToolButtonEvent::button(self) } fn seat_button_count(&self) -> u32 { tablet_tool::TabletToolButtonEvent::seat_button_count(self) } fn button_state(&self) -> backend::ButtonState { tablet_tool::TabletToolButtonEvent::button_state(self).into() } }
32.915789
104
0.680205
fc66479080f178b1c468a28172b9cfad032d2c06
52,103
// Copyright 2018 The Grin Developers // // 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. //! Utility structs to handle the 3 MMRs (output, rangeproof, //! kernel) along the overall header MMR conveniently and transactionally. use crate::core::core::committed::Committed; use crate::core::core::hash::{Hash, Hashed}; use crate::core::core::merkle_proof::MerkleProof; use crate::core::core::pmmr::{self, Backend, ReadonlyPMMR, RewindablePMMR, PMMR}; use crate::core::core::{ Block, BlockHeader, Input, Output, OutputIdentifier, TxKernel, TxKernelEntry, }; use crate::core::global; use crate::core::ser::{PMMRIndexHashable, PMMRable}; use crate::error::{Error, ErrorKind}; use crate::store::{Batch, ChainStore}; use crate::txhashset::{RewindableKernelView, UTXOView}; use crate::types::{Tip, TxHashSetRoots, TxHashsetWriteStatus}; use crate::util::secp::pedersen::{Commitment, RangeProof}; use crate::util::{file, secp_static, zip}; use croaring::Bitmap; use grin_store; use grin_store::pmmr::{PMMRBackend, PMMR_FILES}; use std::collections::HashSet; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Instant, SystemTime, UNIX_EPOCH}; const HEADERHASHSET_SUBDIR: &'static str = "header"; const TXHASHSET_SUBDIR: &'static str = "txhashset"; const HEADER_HEAD_SUBDIR: &'static str = "header_head"; const SYNC_HEAD_SUBDIR: &'static str = "sync_head"; const OUTPUT_SUBDIR: &'static str = "output"; const RANGE_PROOF_SUBDIR: &'static str = "rangeproof"; const KERNEL_SUBDIR: &'static str = "kernel"; const TXHASHSET_ZIP: &'static str = "txhashset_snapshot"; struct PMMRHandle<T: PMMRable> { backend: PMMRBackend<T>, last_pos: u64, } impl<T: PMMRable> PMMRHandle<T> { fn new( root_dir: &str, sub_dir: &str, file_name: &str, prunable: bool, header: Option<&BlockHeader>, ) -> Result<PMMRHandle<T>, Error> { let path = Path::new(root_dir).join(sub_dir).join(file_name); fs::create_dir_all(path.clone())?; let path_str = path.to_str().ok_or(Error::from(ErrorKind::Other( "invalid file path".to_owned(), )))?; let backend = PMMRBackend::new(path_str.to_string(), prunable, header)?; let last_pos = backend.unpruned_size(); Ok(PMMRHandle { backend, last_pos }) } } /// An easy to manipulate structure holding the 3 sum trees necessary to /// validate blocks and capturing the Output set, the range proofs and the /// kernels. Also handles the index of Commitments to positions in the /// output and range proof pmmr trees. /// /// Note that the index is never authoritative, only the trees are /// guaranteed to indicate whether an output is spent or not. The index /// may have commitments that have already been spent, even with /// pruning enabled. pub struct TxHashSet { /// Header MMR to support the header_head chain. /// This is rewound and applied transactionally with the /// output, rangeproof and kernel MMRs during an extension or a /// readonly_extension. /// It can also be rewound and applied separately via a header_extension. header_pmmr_h: PMMRHandle<BlockHeader>, /// Header MMR to support exploratory sync_head. /// The header_head and sync_head chains can diverge so we need to maintain /// multiple header MMRs during the sync process. /// /// Note: this is rewound and applied separately to the other MMRs /// via a "sync_extension". sync_pmmr_h: PMMRHandle<BlockHeader>, output_pmmr_h: PMMRHandle<Output>, rproof_pmmr_h: PMMRHandle<RangeProof>, kernel_pmmr_h: PMMRHandle<TxKernel>, // chain store used as index of commitments to MMR positions commit_index: Arc<ChainStore>, } impl TxHashSet { /// Open an existing or new set of backends for the TxHashSet pub fn open( root_dir: String, commit_index: Arc<ChainStore>, header: Option<&BlockHeader>, ) -> Result<TxHashSet, Error> { Ok(TxHashSet { header_pmmr_h: PMMRHandle::new( &root_dir, HEADERHASHSET_SUBDIR, HEADER_HEAD_SUBDIR, false, None, )?, sync_pmmr_h: PMMRHandle::new( &root_dir, HEADERHASHSET_SUBDIR, SYNC_HEAD_SUBDIR, false, None, )?, output_pmmr_h: PMMRHandle::new( &root_dir, TXHASHSET_SUBDIR, OUTPUT_SUBDIR, true, header, )?, rproof_pmmr_h: PMMRHandle::new( &root_dir, TXHASHSET_SUBDIR, RANGE_PROOF_SUBDIR, true, header, )?, kernel_pmmr_h: PMMRHandle::new( &root_dir, TXHASHSET_SUBDIR, KERNEL_SUBDIR, false, None, )?, commit_index, }) } /// Close all backend file handles pub fn release_backend_files(&mut self) { self.header_pmmr_h.backend.release_files(); self.sync_pmmr_h.backend.release_files(); self.output_pmmr_h.backend.release_files(); self.rproof_pmmr_h.backend.release_files(); self.kernel_pmmr_h.backend.release_files(); } /// Check if an output is unspent. /// We look in the index to find the output MMR pos. /// Then we check the entry in the output MMR and confirm the hash matches. pub fn is_unspent(&self, output_id: &OutputIdentifier) -> Result<(Hash, u64), Error> { match self.commit_index.get_output_pos(&output_id.commit) { Ok(pos) => { let output_pmmr: ReadonlyPMMR<'_, Output, _> = ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos); if let Some(hash) = output_pmmr.get_hash(pos) { if hash == output_id.hash_with_index(pos - 1) { Ok((hash, pos)) } else { Err(ErrorKind::TxHashSetErr(format!("txhashset hash mismatch")).into()) } } else { Err(ErrorKind::OutputNotFound.into()) } } Err(grin_store::Error::NotFoundErr(_)) => Err(ErrorKind::OutputNotFound.into()), Err(e) => Err(ErrorKind::StoreErr(e, format!("txhashset unspent check")).into()), } } /// returns the last N nodes inserted into the tree (i.e. the 'bottom' /// nodes at level 0 /// TODO: These need to return the actual data from the flat-files instead /// of hashes now pub fn last_n_output(&self, distance: u64) -> Vec<(Hash, OutputIdentifier)> { ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos) .get_last_n_insertions(distance) } /// as above, for range proofs pub fn last_n_rangeproof(&self, distance: u64) -> Vec<(Hash, RangeProof)> { ReadonlyPMMR::at(&self.rproof_pmmr_h.backend, self.rproof_pmmr_h.last_pos) .get_last_n_insertions(distance) } /// as above, for kernels pub fn last_n_kernel(&self, distance: u64) -> Vec<(Hash, TxKernelEntry)> { ReadonlyPMMR::at(&self.kernel_pmmr_h.backend, self.kernel_pmmr_h.last_pos) .get_last_n_insertions(distance) } /// Get the header hash at the specified height based on the current state of the txhashset. pub fn get_header_hash_by_height(&self, height: u64) -> Result<Hash, Error> { let pos = pmmr::insertion_to_pmmr_index(height + 1); let header_pmmr = ReadonlyPMMR::at(&self.header_pmmr_h.backend, self.header_pmmr_h.last_pos); if let Some(entry) = header_pmmr.get_data(pos) { Ok(entry.hash()) } else { Err(ErrorKind::Other(format!("get header hash by height")).into()) } } /// Get the header at the specified height based on the current state of the txhashset. /// Derives the MMR pos from the height (insertion index) and retrieves the header hash. /// Looks the header up in the db by hash. pub fn get_header_by_height(&self, height: u64) -> Result<BlockHeader, Error> { let hash = self.get_header_hash_by_height(height)?; let header = self.commit_index.get_block_header(&hash)?; Ok(header) } /// returns outputs from the given insertion (leaf) index up to the /// specified limit. Also returns the last index actually populated pub fn outputs_by_insertion_index( &self, start_index: u64, max_count: u64, ) -> (u64, Vec<OutputIdentifier>) { ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos) .elements_from_insertion_index(start_index, max_count) } /// highest output insertion index available pub fn highest_output_insertion_index(&self) -> u64 { pmmr::n_leaves(self.output_pmmr_h.last_pos) } /// As above, for rangeproofs pub fn rangeproofs_by_insertion_index( &self, start_index: u64, max_count: u64, ) -> (u64, Vec<RangeProof>) { ReadonlyPMMR::at(&self.rproof_pmmr_h.backend, self.rproof_pmmr_h.last_pos) .elements_from_insertion_index(start_index, max_count) } /// Get MMR roots. pub fn roots(&self) -> TxHashSetRoots { let header_pmmr = ReadonlyPMMR::at(&self.header_pmmr_h.backend, self.header_pmmr_h.last_pos); let output_pmmr = ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos); let rproof_pmmr = ReadonlyPMMR::at(&self.rproof_pmmr_h.backend, self.rproof_pmmr_h.last_pos); let kernel_pmmr = ReadonlyPMMR::at(&self.kernel_pmmr_h.backend, self.kernel_pmmr_h.last_pos); TxHashSetRoots { header_root: header_pmmr.root(), output_root: output_pmmr.root(), rproof_root: rproof_pmmr.root(), kernel_root: kernel_pmmr.root(), } } /// Return Commit's MMR position pub fn get_output_pos(&self, commit: &Commitment) -> Result<u64, Error> { Ok(self.commit_index.get_output_pos(&commit)?) } /// build a new merkle proof for the given position. pub fn merkle_proof(&mut self, commit: Commitment) -> Result<MerkleProof, Error> { let pos = self.commit_index.get_output_pos(&commit)?; PMMR::at(&mut self.output_pmmr_h.backend, self.output_pmmr_h.last_pos) .merkle_proof(pos) .map_err(|_| ErrorKind::MerkleProof.into()) } /// Compact the MMR data files and flush the rm logs pub fn compact(&mut self, batch: &mut Batch<'_>) -> Result<(), Error> { debug!("txhashset: starting compaction..."); let head_header = batch.head_header()?; let current_height = head_header.height; // horizon for compacting is based on current_height let horizon_height = current_height.saturating_sub(global::cut_through_horizon().into()); let horizon_hash = self.get_header_hash_by_height(horizon_height)?; let horizon_header = batch.get_block_header(&horizon_hash)?; let rewind_rm_pos = input_pos_to_rewind(&horizon_header, &head_header, batch)?; debug!("txhashset: check_compact output mmr backend..."); self.output_pmmr_h .backend .check_compact(horizon_header.output_mmr_size, &rewind_rm_pos)?; debug!("txhashset: check_compact rangeproof mmr backend..."); self.rproof_pmmr_h .backend .check_compact(horizon_header.output_mmr_size, &rewind_rm_pos)?; debug!("txhashset: ... compaction finished"); Ok(()) } } /// Starts a new unit of work to extend (or rewind) the chain with additional /// blocks. Accepts a closure that will operate within that unit of work. /// The closure has access to an Extension object that allows the addition /// of blocks to the txhashset and the checking of the current tree roots. /// /// The unit of work is always discarded (always rollback) as this is read-only. pub fn extending_readonly<'a, F, T>(trees: &'a mut TxHashSet, inner: F) -> Result<T, Error> where F: FnOnce(&mut Extension<'_>) -> Result<T, Error>, { let commit_index = trees.commit_index.clone(); let batch = commit_index.batch()?; // We want to use the current head of the most work chain unless // we explicitly rewind the extension. let header = batch.head_header()?; trace!("Starting new txhashset (readonly) extension."); let res = { let mut extension = Extension::new(trees, &batch, header); extension.force_rollback(); // TODO - header_mmr may be out ahead via the header_head // TODO - do we need to handle this via an explicit rewind on the header_mmr? inner(&mut extension) }; trace!("Rollbacking txhashset (readonly) extension."); trees.header_pmmr_h.backend.discard(); trees.output_pmmr_h.backend.discard(); trees.rproof_pmmr_h.backend.discard(); trees.kernel_pmmr_h.backend.discard(); trace!("TxHashSet (readonly) extension done."); res } /// Readonly view on the UTXO set. /// Based on the current txhashset output_pmmr. pub fn utxo_view<'a, F, T>(trees: &'a TxHashSet, inner: F) -> Result<T, Error> where F: FnOnce(&UTXOView<'_>) -> Result<T, Error>, { let res: Result<T, Error>; { let output_pmmr = ReadonlyPMMR::at(&trees.output_pmmr_h.backend, trees.output_pmmr_h.last_pos); let header_pmmr = ReadonlyPMMR::at(&trees.header_pmmr_h.backend, trees.header_pmmr_h.last_pos); // Create a new batch here to pass into the utxo_view. // Discard it (rollback) after we finish with the utxo_view. let batch = trees.commit_index.batch()?; let utxo = UTXOView::new(output_pmmr, header_pmmr, &batch); res = inner(&utxo); } res } /// Rewindable (but still readonly) view on the kernel MMR. /// The underlying backend is readonly. But we permit the PMMR to be "rewound" /// via last_pos. /// We create a new db batch for this view and discard it (rollback) /// when we are done with the view. pub fn rewindable_kernel_view<'a, F, T>(trees: &'a TxHashSet, inner: F) -> Result<T, Error> where F: FnOnce(&mut RewindableKernelView<'_>) -> Result<T, Error>, { let res: Result<T, Error>; { let kernel_pmmr = RewindablePMMR::at(&trees.kernel_pmmr_h.backend, trees.kernel_pmmr_h.last_pos); // Create a new batch here to pass into the kernel_view. // Discard it (rollback) after we finish with the kernel_view. let batch = trees.commit_index.batch()?; let header = batch.head_header()?; let mut view = RewindableKernelView::new(kernel_pmmr, &batch, header); res = inner(&mut view); } res } /// Starts a new unit of work to extend the chain with additional blocks, /// accepting a closure that will work within that unit of work. The closure /// has access to an Extension object that allows the addition of blocks to /// the txhashset and the checking of the current tree roots. /// /// If the closure returns an error, modifications are canceled and the unit /// of work is abandoned. Otherwise, the unit of work is permanently applied. pub fn extending<'a, F, T>( trees: &'a mut TxHashSet, batch: &'a mut Batch<'_>, inner: F, ) -> Result<T, Error> where F: FnOnce(&mut Extension<'_>) -> Result<T, Error>, { let sizes: (u64, u64, u64, u64); let res: Result<T, Error>; let rollback: bool; // We want to use the current head of the most work chain unless // we explicitly rewind the extension. let header = batch.head_header()?; // create a child transaction so if the state is rolled back by itself, all // index saving can be undone let child_batch = batch.child()?; { trace!("Starting new txhashset extension."); // TODO - header_mmr may be out ahead via the header_head // TODO - do we need to handle this via an explicit rewind on the header_mmr? let mut extension = Extension::new(trees, &child_batch, header); res = inner(&mut extension); rollback = extension.rollback; sizes = extension.sizes(); } match res { Err(e) => { debug!("Error returned, discarding txhashset extension: {}", e); trees.header_pmmr_h.backend.discard(); trees.output_pmmr_h.backend.discard(); trees.rproof_pmmr_h.backend.discard(); trees.kernel_pmmr_h.backend.discard(); Err(e) } Ok(r) => { if rollback { trace!("Rollbacking txhashset extension. sizes {:?}", sizes); trees.header_pmmr_h.backend.discard(); trees.output_pmmr_h.backend.discard(); trees.rproof_pmmr_h.backend.discard(); trees.kernel_pmmr_h.backend.discard(); } else { trace!("Committing txhashset extension. sizes {:?}", sizes); child_batch.commit()?; trees.header_pmmr_h.backend.sync()?; trees.output_pmmr_h.backend.sync()?; trees.rproof_pmmr_h.backend.sync()?; trees.kernel_pmmr_h.backend.sync()?; trees.header_pmmr_h.last_pos = sizes.0; trees.output_pmmr_h.last_pos = sizes.1; trees.rproof_pmmr_h.last_pos = sizes.2; trees.kernel_pmmr_h.last_pos = sizes.3; } trace!("TxHashSet extension done."); Ok(r) } } } /// Start a new sync MMR unit of work. This MMR tracks the sync_head. /// This is used during header sync to validate batches of headers as they arrive /// without needing to repeatedly rewind the header MMR that continues to track /// the header_head as they diverge during sync. pub fn sync_extending<'a, F, T>( trees: &'a mut TxHashSet, batch: &'a mut Batch<'_>, inner: F, ) -> Result<T, Error> where F: FnOnce(&mut HeaderExtension<'_>) -> Result<T, Error>, { let size: u64; let res: Result<T, Error>; let rollback: bool; // We want to use the current sync_head unless // we explicitly rewind the extension. let head = batch.get_sync_head()?; let header = batch.get_block_header(&head.last_block_h)?; // create a child transaction so if the state is rolled back by itself, all // index saving can be undone let child_batch = batch.child()?; { trace!("Starting new txhashset sync_head extension."); let pmmr = PMMR::at(&mut trees.sync_pmmr_h.backend, trees.sync_pmmr_h.last_pos); let mut extension = HeaderExtension::new(pmmr, &child_batch, header); res = inner(&mut extension); rollback = extension.rollback; size = extension.size(); } match res { Err(e) => { debug!( "Error returned, discarding txhashset sync_head extension: {}", e ); trees.sync_pmmr_h.backend.discard(); Err(e) } Ok(r) => { if rollback { trace!("Rollbacking txhashset sync_head extension. size {:?}", size); trees.sync_pmmr_h.backend.discard(); } else { trace!("Committing txhashset sync_head extension. size {:?}", size); child_batch.commit()?; trees.sync_pmmr_h.backend.sync()?; trees.sync_pmmr_h.last_pos = size; } trace!("TxHashSet sync_head extension done."); Ok(r) } } } /// Start a new header MMR unit of work. This MMR tracks the header_head. /// This MMR can be extended individually beyond the other (output, rangeproof and kernel) MMRs /// to allow headers to be validated before we receive the full block data. pub fn header_extending<'a, F, T>( trees: &'a mut TxHashSet, batch: &'a mut Batch<'_>, inner: F, ) -> Result<T, Error> where F: FnOnce(&mut HeaderExtension<'_>) -> Result<T, Error>, { let size: u64; let res: Result<T, Error>; let rollback: bool; // We want to use the current head of the most work chain unless // we explicitly rewind the extension. let head = batch.head()?; let header = batch.get_block_header(&head.last_block_h)?; // create a child transaction so if the state is rolled back by itself, all // index saving can be undone let child_batch = batch.child()?; { trace!("Starting new txhashset header extension."); let pmmr = PMMR::at( &mut trees.header_pmmr_h.backend, trees.header_pmmr_h.last_pos, ); let mut extension = HeaderExtension::new(pmmr, &child_batch, header); res = inner(&mut extension); rollback = extension.rollback; size = extension.size(); } match res { Err(e) => { debug!( "Error returned, discarding txhashset header extension: {}", e ); trees.header_pmmr_h.backend.discard(); Err(e) } Ok(r) => { if rollback { trace!("Rollbacking txhashset header extension. size {:?}", size); trees.header_pmmr_h.backend.discard(); } else { trace!("Committing txhashset header extension. size {:?}", size); child_batch.commit()?; trees.header_pmmr_h.backend.sync()?; trees.header_pmmr_h.last_pos = size; } trace!("TxHashSet header extension done."); Ok(r) } } } /// A header extension to allow the header MMR to extend beyond the other MMRs individually. /// This is to allow headers to be validated against the MMR before we have the full block data. pub struct HeaderExtension<'a> { header: BlockHeader, pmmr: PMMR<'a, BlockHeader, PMMRBackend<BlockHeader>>, /// Rollback flag. rollback: bool, /// Batch in which the extension occurs, public so it can be used within /// an `extending` closure. Just be careful using it that way as it will /// get rolled back with the extension (i.e on a losing fork). pub batch: &'a Batch<'a>, } impl<'a> HeaderExtension<'a> { fn new( pmmr: PMMR<'a, BlockHeader, PMMRBackend<BlockHeader>>, batch: &'a Batch<'_>, header: BlockHeader, ) -> HeaderExtension<'a> { HeaderExtension { header, pmmr, rollback: false, batch, } } /// Get the header hash for the specified pos from the underlying MMR backend. fn get_header_hash(&self, pos: u64) -> Option<Hash> { self.pmmr.get_data(pos).map(|x| x.hash()) } /// Get the header at the specified height based on the current state of the header extension. /// Derives the MMR pos from the height (insertion index) and retrieves the header hash. /// Looks the header up in the db by hash. pub fn get_header_by_height(&mut self, height: u64) -> Result<BlockHeader, Error> { let pos = pmmr::insertion_to_pmmr_index(height + 1); if let Some(hash) = self.get_header_hash(pos) { let header = self.batch.get_block_header(&hash)?; Ok(header) } else { Err(ErrorKind::Other(format!("get header by height")).into()) } } /// Compares the provided header to the header in the header MMR at that height. /// If these match we know the header is on the current chain. pub fn is_on_current_chain(&mut self, header: &BlockHeader) -> Result<(), Error> { let chain_header = self.get_header_by_height(header.height)?; if chain_header.hash() == header.hash() { Ok(()) } else { Err(ErrorKind::Other(format!("not on current chain")).into()) } } /// Force the rollback of this extension, no matter the result. pub fn force_rollback(&mut self) { self.rollback = true; } /// Apply a new header to the header MMR extension. /// This may be either the header MMR or the sync MMR depending on the /// extension. pub fn apply_header(&mut self, header: &BlockHeader) -> Result<Hash, Error> { self.pmmr.push(header).map_err(&ErrorKind::TxHashSetErr)?; self.header = header.clone(); Ok(self.root()) } /// Rewind the header extension to the specified header. /// Note the close relationship between header height and insertion index. pub fn rewind(&mut self, header: &BlockHeader) -> Result<(), Error> { debug!( "Rewind header extension to {} at {}", header.hash(), header.height ); let header_pos = pmmr::insertion_to_pmmr_index(header.height + 1); self.pmmr .rewind(header_pos, &Bitmap::create()) .map_err(&ErrorKind::TxHashSetErr)?; // Update our header to reflect the one we rewound to. self.header = header.clone(); Ok(()) } /// Truncate the header MMR (rewind all the way back to pos 0). /// Used when rebuilding the header MMR by reapplying all headers /// including the genesis block header. pub fn truncate(&mut self) -> Result<(), Error> { debug!("Truncating header extension."); self.pmmr .rewind(0, &Bitmap::create()) .map_err(&ErrorKind::TxHashSetErr)?; Ok(()) } /// The size of the header MMR. pub fn size(&self) -> u64 { self.pmmr.unpruned_size() } /// TODO - think about how to optimize this. /// Requires *all* header hashes to be iterated over in ascending order. pub fn rebuild(&mut self, head: &Tip, genesis: &BlockHeader) -> Result<(), Error> { debug!( "About to rebuild header extension from {:?} to {:?}.", genesis.hash(), head.last_block_h, ); let mut header_hashes = vec![]; let mut current = self.batch.get_block_header(&head.last_block_h)?; while current.height > 0 { header_hashes.push(current.hash()); current = self.batch.get_previous_header(&current)?; } header_hashes.reverse(); // Trucate the extension (back to pos 0). self.truncate()?; // Re-apply the genesis header after truncation. self.apply_header(&genesis)?; if header_hashes.len() > 0 { debug!( "Re-applying {} headers to extension, from {:?} to {:?}.", header_hashes.len(), header_hashes.first().unwrap(), header_hashes.last().unwrap(), ); for h in header_hashes { let header = self.batch.get_block_header(&h)?; self.validate_root(&header)?; self.apply_header(&header)?; } } Ok(()) } /// The root of the header MMR for convenience. pub fn root(&self) -> Hash { self.pmmr.root() } /// Validate the prev_root of the header against the root of the current header MMR. pub fn validate_root(&self, header: &BlockHeader) -> Result<(), Error> { // If we are validating the genesis block then we have no prev_root. // So we are done here. if header.height == 0 { return Ok(()); } if self.root() != header.prev_root { Err(ErrorKind::InvalidRoot.into()) } else { Ok(()) } } } /// Allows the application of new blocks on top of the sum trees in a /// reversible manner within a unit of work provided by the `extending` /// function. pub struct Extension<'a> { header: BlockHeader, header_pmmr: PMMR<'a, BlockHeader, PMMRBackend<BlockHeader>>, output_pmmr: PMMR<'a, Output, PMMRBackend<Output>>, rproof_pmmr: PMMR<'a, RangeProof, PMMRBackend<RangeProof>>, kernel_pmmr: PMMR<'a, TxKernel, PMMRBackend<TxKernel>>, /// Rollback flag. rollback: bool, /// Batch in which the extension occurs, public so it can be used within /// an `extending` closure. Just be careful using it that way as it will /// get rolled back with the extension (i.e on a losing fork). pub batch: &'a Batch<'a>, } impl<'a> Committed for Extension<'a> { fn inputs_committed(&self) -> Vec<Commitment> { vec![] } fn outputs_committed(&self) -> Vec<Commitment> { let mut commitments = vec![]; for pos in self.output_pmmr.leaf_pos_iter() { if let Some(out) = self.output_pmmr.get_data(pos) { commitments.push(out.commit); } } commitments } fn kernels_committed(&self) -> Vec<Commitment> { let mut commitments = vec![]; for n in 1..self.kernel_pmmr.unpruned_size() + 1 { if pmmr::is_leaf(n) { if let Some(kernel) = self.kernel_pmmr.get_data(n) { commitments.push(kernel.excess()); } } } commitments } } impl<'a> Extension<'a> { fn new(trees: &'a mut TxHashSet, batch: &'a Batch<'_>, header: BlockHeader) -> Extension<'a> { Extension { header, header_pmmr: PMMR::at( &mut trees.header_pmmr_h.backend, trees.header_pmmr_h.last_pos, ), output_pmmr: PMMR::at( &mut trees.output_pmmr_h.backend, trees.output_pmmr_h.last_pos, ), rproof_pmmr: PMMR::at( &mut trees.rproof_pmmr_h.backend, trees.rproof_pmmr_h.last_pos, ), kernel_pmmr: PMMR::at( &mut trees.kernel_pmmr_h.backend, trees.kernel_pmmr_h.last_pos, ), rollback: false, batch, } } /// Build a view of the current UTXO set based on the output PMMR. pub fn utxo_view(&'a self) -> UTXOView<'a> { UTXOView::new( self.output_pmmr.readonly_pmmr(), self.header_pmmr.readonly_pmmr(), self.batch, ) } /// Apply a new block to the existing state. /// /// Applies the following - /// * header /// * outputs /// * inputs /// * kernels /// pub fn apply_block(&mut self, b: &Block) -> Result<(), Error> { self.apply_header(&b.header)?; for out in b.outputs() { let pos = self.apply_output(out)?; // Update the output_pos index for the new output. self.batch.save_output_pos(&out.commitment(), pos)?; } for input in b.inputs() { self.apply_input(input)?; } for kernel in b.kernels() { self.apply_kernel(kernel)?; } // Update the header on the extension to reflect the block we just applied. self.header = b.header.clone(); Ok(()) } fn apply_input(&mut self, input: &Input) -> Result<(), Error> { let commit = input.commitment(); let pos_res = self.batch.get_output_pos(&commit); if let Ok(pos) = pos_res { // First check this input corresponds to an existing entry in the output MMR. if let Some(hash) = self.output_pmmr.get_hash(pos) { if hash != input.hash_with_index(pos - 1) { return Err( ErrorKind::TxHashSetErr(format!("output pmmr hash mismatch")).into(), ); } } // Now prune the output_pmmr, rproof_pmmr and their storage. // Input is not valid if we cannot prune successfully (to spend an unspent // output). match self.output_pmmr.prune(pos) { Ok(true) => { self.rproof_pmmr .prune(pos) .map_err(|e| ErrorKind::TxHashSetErr(e))?; } Ok(false) => return Err(ErrorKind::AlreadySpent(commit).into()), Err(e) => return Err(ErrorKind::TxHashSetErr(e).into()), } } else { return Err(ErrorKind::AlreadySpent(commit).into()); } Ok(()) } fn apply_output(&mut self, out: &Output) -> Result<(u64), Error> { let commit = out.commitment(); if let Ok(pos) = self.batch.get_output_pos(&commit) { if let Some(out_mmr) = self.output_pmmr.get_data(pos) { if out_mmr.commitment() == commit { return Err(ErrorKind::DuplicateCommitment(commit).into()); } } } // push the new output to the MMR. let output_pos = self .output_pmmr .push(out) .map_err(&ErrorKind::TxHashSetErr)?; // push the rangeproof to the MMR. let rproof_pos = self .rproof_pmmr .push(&out.proof) .map_err(&ErrorKind::TxHashSetErr)?; // The output and rproof MMRs should be exactly the same size // and we should have inserted to both in exactly the same pos. { if self.output_pmmr.unpruned_size() != self.rproof_pmmr.unpruned_size() { return Err( ErrorKind::Other(format!("output vs rproof MMRs different sizes")).into(), ); } if output_pos != rproof_pos { return Err(ErrorKind::Other(format!("output vs rproof MMRs different pos")).into()); } } Ok(output_pos) } /// Push kernel onto MMR (hash and data files). fn apply_kernel(&mut self, kernel: &TxKernel) -> Result<(), Error> { self.kernel_pmmr .push(kernel) .map_err(&ErrorKind::TxHashSetErr)?; Ok(()) } fn apply_header(&mut self, header: &BlockHeader) -> Result<(), Error> { self.header_pmmr .push(header) .map_err(&ErrorKind::TxHashSetErr)?; Ok(()) } /// Get the header hash for the specified pos from the underlying MMR backend. fn get_header_hash(&self, pos: u64) -> Option<Hash> { self.header_pmmr.get_data(pos).map(|x| x.hash()) } /// Get the header at the specified height based on the current state of the extension. /// Derives the MMR pos from the height (insertion index) and retrieves the header hash. /// Looks the header up in the db by hash. pub fn get_header_by_height(&self, height: u64) -> Result<BlockHeader, Error> { let pos = pmmr::insertion_to_pmmr_index(height + 1); if let Some(hash) = self.get_header_hash(pos) { let header = self.batch.get_block_header(&hash)?; Ok(header) } else { Err(ErrorKind::Other(format!("get header by height")).into()) } } /// Compares the provided header to the header in the header MMR at that height. /// If these match we know the header is on the current chain. pub fn is_on_current_chain(&mut self, header: &BlockHeader) -> Result<(), Error> { let chain_header = self.get_header_by_height(header.height)?; if chain_header.hash() == header.hash() { Ok(()) } else { Err(ErrorKind::Other(format!("not on current chain")).into()) } } /// Build a Merkle proof for the given output and the block /// this extension is currently referencing. /// Note: this relies on the MMR being stable even after pruning/compaction. /// We need the hash of each sibling pos from the pos up to the peak /// including the sibling leaf node which may have been removed. pub fn merkle_proof(&self, output: &OutputIdentifier) -> Result<MerkleProof, Error> { debug!("txhashset: merkle_proof: output: {:?}", output.commit,); // then calculate the Merkle Proof based on the known pos let pos = self.batch.get_output_pos(&output.commit)?; let merkle_proof = self .output_pmmr .merkle_proof(pos) .map_err(&ErrorKind::TxHashSetErr)?; Ok(merkle_proof) } /// Saves a snapshot of the output and rangeproof MMRs to disk. /// Specifically - saves a snapshot of the utxo file, tagged with /// the block hash as filename suffix. /// Needed for fast-sync (utxo file needs to be rewound before sending /// across). pub fn snapshot(&mut self) -> Result<(), Error> { self.output_pmmr .snapshot(&self.header) .map_err(|e| ErrorKind::Other(e))?; self.rproof_pmmr .snapshot(&self.header) .map_err(|e| ErrorKind::Other(e))?; Ok(()) } /// Rewinds the MMRs to the provided block, rewinding to the last output pos /// and last kernel pos of that block. pub fn rewind(&mut self, header: &BlockHeader) -> Result<(), Error> { debug!("Rewind to header {} at {}", header.hash(), header.height,); // We need to build bitmaps of added and removed output positions // so we can correctly rewind all operations applied to the output MMR // after the position we are rewinding to (these operations will be // undone during rewind). // Rewound output pos will be removed from the MMR. // Rewound input (spent) pos will be added back to the MMR. let rewind_rm_pos = input_pos_to_rewind(header, &self.header, &self.batch)?; let header_pos = pmmr::insertion_to_pmmr_index(header.height + 1); self.rewind_to_pos( header_pos, header.output_mmr_size, header.kernel_mmr_size, &rewind_rm_pos, )?; // Update our header to reflect the one we rewound to. self.header = header.clone(); Ok(()) } /// Rewinds the MMRs to the provided positions, given the output and /// kernel we want to rewind to. fn rewind_to_pos( &mut self, header_pos: u64, output_pos: u64, kernel_pos: u64, rewind_rm_pos: &Bitmap, ) -> Result<(), Error> { debug!( "txhashset: rewind_to_pos: header {}, output {}, kernel {}", header_pos, output_pos, kernel_pos, ); self.header_pmmr .rewind(header_pos, &Bitmap::create()) .map_err(&ErrorKind::TxHashSetErr)?; self.output_pmmr .rewind(output_pos, rewind_rm_pos) .map_err(&ErrorKind::TxHashSetErr)?; self.rproof_pmmr .rewind(output_pos, rewind_rm_pos) .map_err(&ErrorKind::TxHashSetErr)?; self.kernel_pmmr .rewind(kernel_pos, &Bitmap::create()) .map_err(&ErrorKind::TxHashSetErr)?; Ok(()) } /// Current root hashes and sums (if applicable) for the Output, range proof /// and kernel sum trees. pub fn roots(&self) -> TxHashSetRoots { TxHashSetRoots { header_root: self.header_pmmr.root(), output_root: self.output_pmmr.root(), rproof_root: self.rproof_pmmr.root(), kernel_root: self.kernel_pmmr.root(), } } /// Get the root of the current header MMR. pub fn header_root(&self) -> Hash { self.header_pmmr.root() } /// Validate the following MMR roots against the latest header applied - /// * output /// * rangeproof /// * kernel /// /// Note we do not validate the header MMR root here as we need to validate /// a header against the state of the MMR *prior* to applying it. /// Each header commits to the root of the MMR of all previous headers, /// not including the header itself. /// pub fn validate_roots(&self) -> Result<(), Error> { // If we are validating the genesis block then we have no outputs or // kernels. So we are done here. if self.header.height == 0 { return Ok(()); } let roots = self.roots(); if roots.output_root != self.header.output_root || roots.rproof_root != self.header.range_proof_root || roots.kernel_root != self.header.kernel_root { Err(ErrorKind::InvalidRoot.into()) } else { Ok(()) } } /// Validate the provided header by comparing its prev_root to the /// root of the current header MMR. pub fn validate_header_root(&self, header: &BlockHeader) -> Result<(), Error> { if header.height == 0 { return Ok(()); } let roots = self.roots(); if roots.header_root != header.prev_root { Err(ErrorKind::InvalidRoot.into()) } else { Ok(()) } } /// Validate the header, output and kernel MMR sizes against the block header. pub fn validate_sizes(&self) -> Result<(), Error> { // If we are validating the genesis block then we have no outputs or // kernels. So we are done here. if self.header.height == 0 { return Ok(()); } let (header_mmr_size, output_mmr_size, rproof_mmr_size, kernel_mmr_size) = self.sizes(); let expected_header_mmr_size = pmmr::insertion_to_pmmr_index(self.header.height + 2) - 1; if header_mmr_size != expected_header_mmr_size { Err(ErrorKind::InvalidMMRSize.into()) } else if output_mmr_size != self.header.output_mmr_size { Err(ErrorKind::InvalidMMRSize.into()) } else if kernel_mmr_size != self.header.kernel_mmr_size { Err(ErrorKind::InvalidMMRSize.into()) } else if output_mmr_size != rproof_mmr_size { Err(ErrorKind::InvalidMMRSize.into()) } else { Ok(()) } } fn validate_mmrs(&self) -> Result<(), Error> { let now = Instant::now(); // validate all hashes and sums within the trees if let Err(e) = self.header_pmmr.validate() { return Err(ErrorKind::InvalidTxHashSet(e).into()); } if let Err(e) = self.output_pmmr.validate() { return Err(ErrorKind::InvalidTxHashSet(e).into()); } if let Err(e) = self.rproof_pmmr.validate() { return Err(ErrorKind::InvalidTxHashSet(e).into()); } if let Err(e) = self.kernel_pmmr.validate() { return Err(ErrorKind::InvalidTxHashSet(e).into()); } debug!( "txhashset: validated the header {}, output {}, rproof {}, kernel {} mmrs, took {}s", self.header_pmmr.unpruned_size(), self.output_pmmr.unpruned_size(), self.rproof_pmmr.unpruned_size(), self.kernel_pmmr.unpruned_size(), now.elapsed().as_secs(), ); Ok(()) } /// Validate full kernel sums against the provided header (for overage and kernel_offset). /// This is an expensive operation as we need to retrieve all the UTXOs and kernels /// from the respective MMRs. /// For a significantly faster way of validating full kernel sums see BlockSums. pub fn validate_kernel_sums(&self) -> Result<((Commitment, Commitment)), Error> { let now = Instant::now(); let genesis = self.get_header_by_height(0)?; let (utxo_sum, kernel_sum) = self.verify_kernel_sums( self.header.total_overage(genesis.kernel_mmr_size > 0), self.header.total_kernel_offset(), )?; debug!( "txhashset: validated total kernel sums, took {}s", now.elapsed().as_secs(), ); Ok((utxo_sum, kernel_sum)) } /// Validate the txhashset state against the provided block header. /// A "fast validation" will skip rangeproof verification and kernel signature verification. pub fn validate( &self, fast_validation: bool, status: &dyn TxHashsetWriteStatus, ) -> Result<((Commitment, Commitment)), Error> { self.validate_mmrs()?; self.validate_roots()?; self.validate_sizes()?; if self.header.height == 0 { let zero_commit = secp_static::commit_to_zero_value(); return Ok((zero_commit.clone(), zero_commit.clone())); } // The real magicking happens here. Sum of kernel excesses should equal // sum of unspent outputs minus total supply. let (output_sum, kernel_sum) = self.validate_kernel_sums()?; // These are expensive verification step (skipped for "fast validation"). if !fast_validation { // Verify the rangeproof associated with each unspent output. self.verify_rangeproofs(status)?; // Verify all the kernel signatures. self.verify_kernel_signatures(status)?; } Ok((output_sum, kernel_sum)) } /// Rebuild the index of MMR positions to the corresponding UTXOs. /// This is a costly operation performed only when we receive a full new chain state. pub fn rebuild_index(&self) -> Result<(), Error> { let now = Instant::now(); self.batch.clear_output_pos()?; let mut count = 0; for pos in self.output_pmmr.leaf_pos_iter() { if let Some(out) = self.output_pmmr.get_data(pos) { self.batch.save_output_pos(&out.commit, pos)?; count += 1; } } debug!( "txhashset: rebuild_index: {} UTXOs, took {}s", count, now.elapsed().as_secs(), ); Ok(()) } /// Force the rollback of this extension, no matter the result pub fn force_rollback(&mut self) { self.rollback = true; } /// Dumps the output MMR. /// We use this after compacting for visual confirmation that it worked. pub fn dump_output_pmmr(&self) { debug!("-- outputs --"); self.output_pmmr.dump_from_file(false); debug!("--"); self.output_pmmr.dump_stats(); debug!("-- end of outputs --"); } /// Dumps the state of the 3 sum trees to stdout for debugging. Short /// version only prints the Output tree. pub fn dump(&self, short: bool) { debug!("-- outputs --"); self.output_pmmr.dump(short); if !short { debug!("-- range proofs --"); self.rproof_pmmr.dump(short); debug!("-- kernels --"); self.kernel_pmmr.dump(short); } } /// Sizes of each of the sum trees pub fn sizes(&self) -> (u64, u64, u64, u64) { ( self.header_pmmr.unpruned_size(), self.output_pmmr.unpruned_size(), self.rproof_pmmr.unpruned_size(), self.kernel_pmmr.unpruned_size(), ) } fn verify_kernel_signatures(&self, status: &dyn TxHashsetWriteStatus) -> Result<(), Error> { let now = Instant::now(); let mut kern_count = 0; let total_kernels = pmmr::n_leaves(self.kernel_pmmr.unpruned_size()); for n in 1..self.kernel_pmmr.unpruned_size() + 1 { if pmmr::is_leaf(n) { let kernel = self .kernel_pmmr .get_data(n) .ok_or::<Error>(ErrorKind::TxKernelNotFound.into())?; kernel.verify()?; kern_count += 1; if kern_count % 20 == 0 { status.on_validation(kern_count, total_kernels, 0, 0); } if kern_count % 1_000 == 0 { debug!( "txhashset: verify_kernel_signatures: verified {} signatures", kern_count, ); } } } debug!( "txhashset: verified {} kernel signatures, pmmr size {}, took {}s", kern_count, self.kernel_pmmr.unpruned_size(), now.elapsed().as_secs(), ); Ok(()) } fn verify_rangeproofs(&self, status: &dyn TxHashsetWriteStatus) -> Result<(), Error> { let now = Instant::now(); let mut commits: Vec<Commitment> = vec![]; let mut proofs: Vec<RangeProof> = vec![]; let mut proof_count = 0; let total_rproofs = pmmr::n_leaves(self.output_pmmr.unpruned_size()); for pos in self.output_pmmr.leaf_pos_iter() { let output = self.output_pmmr.get_data(pos); let proof = self.rproof_pmmr.get_data(pos); // Output and corresponding rangeproof *must* exist. // It is invalid for either to be missing and we fail immediately in this case. match (output, proof) { (None, _) => return Err(ErrorKind::OutputNotFound.into()), (_, None) => return Err(ErrorKind::RangeproofNotFound.into()), (Some(output), Some(proof)) => { commits.push(output.commit); proofs.push(proof); } } proof_count += 1; if proofs.len() >= 1_000 { Output::batch_verify_proofs(&commits, &proofs)?; commits.clear(); proofs.clear(); debug!( "txhashset: verify_rangeproofs: verified {} rangeproofs", proof_count, ); } if proof_count % 20 == 0 { status.on_validation(0, 0, proof_count, total_rproofs); } } // remaining part which not full of 1000 range proofs if proofs.len() > 0 { Output::batch_verify_proofs(&commits, &proofs)?; commits.clear(); proofs.clear(); debug!( "txhashset: verify_rangeproofs: verified {} rangeproofs", proof_count, ); } debug!( "txhashset: verified {} rangeproofs, pmmr size {}, took {}s", proof_count, self.rproof_pmmr.unpruned_size(), now.elapsed().as_secs(), ); Ok(()) } } /// Packages the txhashset data files into a zip and returns a Read to the /// resulting file pub fn zip_read(root_dir: String, header: &BlockHeader, rand: Option<u32>) -> Result<File, Error> { let ts = if let None = rand { let now = SystemTime::now(); now.duration_since(UNIX_EPOCH).unwrap().subsec_micros() } else { rand.unwrap() }; let txhashset_zip = format!("{}_{}.zip", TXHASHSET_ZIP, ts); let txhashset_path = Path::new(&root_dir).join(TXHASHSET_SUBDIR); let zip_path = Path::new(&root_dir).join(txhashset_zip); // create the zip archive { // Temp txhashset directory let temp_txhashset_path = Path::new(&root_dir).join(format!("{}_zip_{}", TXHASHSET_SUBDIR, ts)); // Remove temp dir if it exist if temp_txhashset_path.exists() { fs::remove_dir_all(&temp_txhashset_path)?; } // Copy file to another dir file::copy_dir_to(&txhashset_path, &temp_txhashset_path)?; // Check and remove file that are not supposed to be there check_and_remove_files(&temp_txhashset_path, header)?; // Compress zip zip::compress(&temp_txhashset_path, &File::create(zip_path.clone())?) .map_err(|ze| ErrorKind::Other(ze.to_string()))?; } // open it again to read it back let zip_file = File::open(zip_path)?; Ok(zip_file) } /// Extract the txhashset data from a zip file and writes the content into the /// txhashset storage dir pub fn zip_write( root_dir: PathBuf, txhashset_data: File, header: &BlockHeader, ) -> Result<(), Error> { debug!("zip_write on path: {:?}", root_dir); let txhashset_path = root_dir.clone().join(TXHASHSET_SUBDIR); fs::create_dir_all(txhashset_path.clone())?; zip::decompress(txhashset_data, &txhashset_path, expected_file) .map_err(|ze| ErrorKind::Other(ze.to_string()))?; check_and_remove_files(&txhashset_path, header) } /// Overwrite txhashset folders in "to" folder with "from" folder pub fn txhashset_replace(from: PathBuf, to: PathBuf) -> Result<(), Error> { debug!("txhashset_replace: move from {:?} to {:?}", from, to); // clean the 'to' folder firstly clean_txhashset_folder(&to); // rename the 'from' folder as the 'to' folder if let Err(e) = fs::rename( from.clone().join(TXHASHSET_SUBDIR), to.clone().join(TXHASHSET_SUBDIR), ) { error!("hashset_replace fail on {}. err: {}", TXHASHSET_SUBDIR, e); Err(ErrorKind::TxHashSetErr(format!("txhashset replacing fail")).into()) } else { Ok(()) } } /// Clean the txhashset folder pub fn clean_txhashset_folder(root_dir: &PathBuf) { let txhashset_path = root_dir.clone().join(TXHASHSET_SUBDIR); if txhashset_path.exists() { if let Err(e) = fs::remove_dir_all(txhashset_path.clone()) { warn!( "clean_txhashset_folder: fail on {:?}. err: {}", txhashset_path, e ); } } } /// Clean the header folder pub fn clean_header_folder(root_dir: &PathBuf) { let header_path = root_dir.clone().join(HEADERHASHSET_SUBDIR); if header_path.exists() { if let Err(e) = fs::remove_dir_all(header_path.clone()) { warn!("clean_header_folder: fail on {:?}. err: {}", header_path, e); } } } fn expected_file(path: &Path) -> bool { use lazy_static::lazy_static; use regex::Regex; let s_path = path.to_str().unwrap_or_else(|| ""); lazy_static! { static ref RE: Regex = Regex::new( format!( r#"^({}|{}|{})((/|\\)pmmr_(hash|data|leaf|prun)\.bin(\.\w*)?)?$"#, OUTPUT_SUBDIR, KERNEL_SUBDIR, RANGE_PROOF_SUBDIR ) .as_str() ) .expect("invalid txhashset regular expression"); } RE.is_match(&s_path) } /// Check a txhashset directory and remove any unexpected fn check_and_remove_files(txhashset_path: &PathBuf, header: &BlockHeader) -> Result<(), Error> { // First compare the subdirectories let subdirectories_expected: HashSet<_> = [OUTPUT_SUBDIR, KERNEL_SUBDIR, RANGE_PROOF_SUBDIR] .iter() .cloned() .map(|s| String::from(s)) .collect(); let subdirectories_found: HashSet<_> = fs::read_dir(txhashset_path)? .filter_map(|entry| { entry.ok().and_then(|e| { e.path() .file_name() .and_then(|n| n.to_str().map(|s| String::from(s))) }) }) .collect(); let dir_difference: Vec<String> = subdirectories_found .difference(&subdirectories_expected) .cloned() .collect(); // Removing unexpected directories if needed if !dir_difference.is_empty() { debug!("Unexpected folder(s) found in txhashset folder, removing."); for diff in dir_difference { let diff_path = txhashset_path.join(diff); file::delete(diff_path)?; } } // Then compare the files found in the subdirectories let pmmr_files_expected: HashSet<_> = PMMR_FILES .iter() .cloned() .map(|s| { if s.contains("pmmr_leaf.bin") { format!("{}.{}", s, header.hash()) } else { String::from(s) } }) .collect(); let subdirectories = fs::read_dir(txhashset_path)?; for subdirectory in subdirectories { let subdirectory_path = subdirectory?.path(); let pmmr_files = fs::read_dir(&subdirectory_path)?; let pmmr_files_found: HashSet<_> = pmmr_files .filter_map(|entry| { entry.ok().and_then(|e| { e.path() .file_name() .and_then(|n| n.to_str().map(|s| String::from(s))) }) }) .collect(); let difference: Vec<String> = pmmr_files_found .difference(&pmmr_files_expected) .cloned() .collect(); let mut removed = 0; if !difference.is_empty() { for diff in &difference { let diff_path = subdirectory_path.join(diff); match file::delete(diff_path.clone()) { Err(e) => error!( "check_and_remove_files: fail to remove file '{:?}', Err: {:?}", diff_path, e, ), Ok(_) => { removed += 1; trace!("check_and_remove_files: file '{:?}' removed", diff_path); } } } debug!( "{} tmp file(s) found in txhashset subfolder {:?}, {} removed.", difference.len(), &subdirectory_path, removed, ); } } Ok(()) } /// Given a block header to rewind to and the block header at the /// head of the current chain state, we need to calculate the positions /// of all inputs (spent outputs) we need to "undo" during a rewind. /// We do this by leveraging the "block_input_bitmap" cache and OR'ing /// the set of bitmaps together for the set of blocks being rewound. pub fn input_pos_to_rewind( block_header: &BlockHeader, head_header: &BlockHeader, batch: &Batch<'_>, ) -> Result<Bitmap, Error> { if head_header.height < block_header.height { debug!( "input_pos_to_rewind: {} < {}, nothing to rewind", head_header.height, block_header.height ); return Ok(Bitmap::create()); } // Batching up the block input bitmaps, and running fast_or() on every batch of 256 bitmaps. // so to avoid maintaining a huge vec of bitmaps. let bitmap_fast_or = |b_res, block_input_bitmaps: &mut Vec<Bitmap>| -> Option<Bitmap> { if let Some(b) = b_res { block_input_bitmaps.push(b); if block_input_bitmaps.len() < 256 { return None; } } let bitmap = Bitmap::fast_or(&block_input_bitmaps.iter().collect::<Vec<&Bitmap>>()); block_input_bitmaps.clear(); block_input_bitmaps.push(bitmap.clone()); Some(bitmap) }; let mut block_input_bitmaps: Vec<Bitmap> = vec![]; let mut current = head_header.clone(); while current.hash() != block_header.hash() { if current.height < 1 { break; } // I/O should be minimized or eliminated here for most // rewind scenarios. if let Ok(b_res) = batch.get_block_input_bitmap(&current.hash()) { bitmap_fast_or(Some(b_res), &mut block_input_bitmaps); } current = batch.get_previous_header(&current)?; } bitmap_fast_or(None, &mut block_input_bitmaps).ok_or_else(|| ErrorKind::Bitmap.into()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_expected_files() { assert!(!expected_file(Path::new("kernels"))); assert!(!expected_file(Path::new("xkernel"))); assert!(expected_file(Path::new("kernel"))); assert!(expected_file(Path::new("kernel\\pmmr_data.bin"))); assert!(expected_file(Path::new("kernel/pmmr_hash.bin"))); assert!(expected_file(Path::new("kernel/pmmr_leaf.bin"))); assert!(expected_file(Path::new("kernel/pmmr_prun.bin"))); assert!(expected_file(Path::new("kernel/pmmr_leaf.bin.deadbeef"))); assert!(!expected_file(Path::new("xkernel/pmmr_data.bin"))); assert!(!expected_file(Path::new("kernel/pmmrx_data.bin"))); assert!(!expected_file(Path::new("kernel/pmmr_data.binx"))); } }
30.940024
99
0.688386
2ff47a3a992fcea22a98368f8749222951885aff
741
use pipebased_common::{ grpc::{ client::{DaemonClientBuilder, RpcClientConfig}, daemon::daemon_client::DaemonClient, }, read_yml, Result, }; use std::path::Path; use tokio::time::{sleep, Duration}; use tonic::transport::Channel; #[allow(dead_code)] pub(crate) async fn build_client<P>(path: P) -> Result<DaemonClient<Channel>> where P: AsRef<Path>, { let config: RpcClientConfig = read_yml(path)?; let protocol = config.protocol; let address = config.address; DaemonClientBuilder::default() .protocol(protocol) .address(address.as_str()) .build() .await } #[allow(dead_code)] pub async fn wait(millis: u64) { sleep(Duration::from_millis(millis)).await; }
23.903226
77
0.65587
1e7411ce7f4ab445ac118fd1c27e09dadb5146a2
5,566
//! [`DeleteObjects`](https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObjects.html) use super::{wrap_internal_error, ReqContext, S3Handler}; use crate::dto::{ Delete, DeleteObjectsError, DeleteObjectsOutput, DeleteObjectsRequest, ObjectIdentifier, }; use crate::errors::{S3Error, S3Result}; use crate::headers::{ X_AMZ_BYPASS_GOVERNANCE_RETENTION, X_AMZ_MFA, X_AMZ_REQUEST_CHARGED, X_AMZ_REQUEST_PAYER, }; use crate::output::S3Output; use crate::storage::S3Storage; use crate::utils::body::deserialize_xml_body; use crate::utils::{ResponseExt, XmlWriterExt}; use crate::{async_trait, Method, Response}; /// `DeleteObject` handler pub struct Handler; #[async_trait] impl S3Handler for Handler { fn is_match(&self, ctx: &'_ ReqContext<'_>) -> bool { bool_try!(ctx.req.method() == Method::POST); bool_try!(ctx.path.is_bucket()); let qs = bool_try_some!(ctx.query_strings.as_ref()); qs.get("delete").is_some() } async fn handle( &self, ctx: &mut ReqContext<'_>, storage: &(dyn S3Storage + Send + Sync), ) -> S3Result<Response> { let input = extract(ctx).await?; let output = storage.delete_objects(input).await; output.try_into_response() } } /// extract operation request pub async fn extract(ctx: &mut ReqContext<'_>) -> S3Result<DeleteObjectsRequest> { let bucket = ctx.unwrap_bucket_path(); let delete: self::xml::Delete = deserialize_xml_body(ctx.take_body()) .await .map_err(|err| invalid_request!("Invalid xml format", err))?; let mut input: DeleteObjectsRequest = DeleteObjectsRequest { delete: delete.into(), bucket: bucket.into(), ..DeleteObjectsRequest::default() }; let h = &ctx.headers; h.assign_str(X_AMZ_MFA, &mut input.mfa); h.assign_str(X_AMZ_REQUEST_PAYER, &mut input.request_payer); h.assign( X_AMZ_BYPASS_GOVERNANCE_RETENTION, &mut input.bypass_governance_retention, ) .map_err(|err| invalid_request!("Invalid header: x-amz-bypass-governance-retention", err))?; Ok(input) } impl S3Output for DeleteObjectsOutput { #[allow(clippy::shadow_unrelated)] fn try_into_response(self) -> S3Result<Response> { wrap_internal_error(|res| { res.set_optional_header(X_AMZ_REQUEST_CHARGED, self.request_charged)?; let deleted = self.deleted; let errors = self.errors; res.set_xml_body(4096, |w| { w.stack("DeleteResult", |w| { if let Some(deleted) = deleted { w.iter_element(deleted.into_iter(), |w, deleted_object| { w.stack("Deleted", |w| { w.opt_element( "DeleteMarker", deleted_object.delete_marker.map(|b| b.to_string()), )?; w.opt_element( "DeleteMarkerVersionId", deleted_object.delete_marker_version_id, )?; w.opt_element("Key", deleted_object.key)?; w.opt_element("VersionId", deleted_object.version_id)?; Ok(()) }) })?; } if let Some(errors) = errors { w.iter_element(errors.into_iter(), |w, error| { w.stack("Error", |w| { w.opt_element("Code", error.code)?; w.opt_element("Key", error.key)?; w.opt_element("Message", error.message)?; w.opt_element("VersionId", error.version_id)?; Ok(()) }) })?; } Ok(()) }) })?; Ok(()) }) } } impl From<DeleteObjectsError> for S3Error { fn from(e: DeleteObjectsError) -> Self { match e {} } } mod xml { //! Xml repr use serde::Deserialize; /// Object Identifier is unique value to identify objects. #[derive(Debug, Deserialize)] pub struct ObjectIdentifier { /// Key name of the object to delete. #[serde(rename = "Key")] pub key: String, /// VersionId for the specific version of the object to delete. #[serde(rename = "VersionId")] pub version_id: Option<String>, } /// Container for the objects to delete. #[derive(Debug, Deserialize)] pub struct Delete { /// The objects to delete. #[serde(rename = "Object")] pub objects: Vec<ObjectIdentifier>, /// Element to enable quiet mode for the request. When you add this element, you must set its value to true. #[serde(rename = "Quiet")] pub quiet: Option<bool>, } impl From<ObjectIdentifier> for super::ObjectIdentifier { fn from(ObjectIdentifier { key, version_id }: ObjectIdentifier) -> Self { Self { key, version_id } } } impl From<Delete> for super::Delete { fn from(delete: Delete) -> Self { Self { quiet: delete.quiet, objects: delete.objects.into_iter().map(Into::into).collect(), } } } }
34.358025
116
0.541143
79d91125ec4c463a50089c8161cc9655b2bf32f2
71,655
// The Rust abstract syntax tree. pub use GenericArgs::*; pub use UnsafeSource::*; pub use crate::symbol::{Ident, Symbol as Name}; pub use crate::util::parser::ExprPrecedence; use crate::ext::hygiene::ExpnId; use crate::parse::token::{self, DelimToken}; use crate::ptr::P; use crate::source_map::{dummy_spanned, respan, Spanned}; use crate::symbol::{kw, sym, Symbol}; use crate::tokenstream::TokenStream; use crate::ThinVec; use rustc_index::vec::Idx; #[cfg(target_arch = "x86_64")] use rustc_data_structures::static_assert_size; use rustc_target::spec::abi::Abi; use syntax_pos::{Span, DUMMY_SP}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::sync::Lrc; use rustc_serialize::{self, Decoder, Encoder}; use std::fmt; pub use rustc_target::abi::FloatTy; #[cfg(test)] mod tests; #[derive(Clone, RustcEncodable, RustcDecodable, Copy)] pub struct Label { pub ident: Ident, } impl fmt::Debug for Label { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "label({:?})", self.ident) } } #[derive(Clone, RustcEncodable, RustcDecodable, Copy)] pub struct Lifetime { pub id: NodeId, pub ident: Ident, } impl fmt::Debug for Lifetime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "lifetime({}: {})", self.id, self ) } } impl fmt::Display for Lifetime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.ident.name.as_str()) } } /// A "Path" is essentially Rust's notion of a name. /// /// It's represented as a sequence of identifiers, /// along with a bunch of supporting information. /// /// E.g., `std::cmp::PartialEq`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Path { pub span: Span, /// The segments in the path: the things separated by `::`. /// Global paths begin with `kw::PathRoot`. pub segments: Vec<PathSegment>, } impl PartialEq<Symbol> for Path { fn eq(&self, symbol: &Symbol) -> bool { self.segments.len() == 1 && { self.segments[0].ident.name == *symbol } } } impl Path { // Convert a span and an identifier to the corresponding // one-segment path. pub fn from_ident(ident: Ident) -> Path { Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, } } pub fn is_global(&self) -> bool { !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot } } /// A segment of a path: an identifier, an optional lifetime, and a set of types. /// /// E.g., `std`, `String` or `Box<T>`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct PathSegment { /// The identifier portion of this path segment. pub ident: Ident, pub id: NodeId, /// Type/lifetime parameters attached to this path. They come in /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. /// `None` means that no parameter list is supplied (`Path`), /// `Some` means that parameter list is supplied (`Path<X, Y>`) /// but it can be empty (`Path<>`). /// `P` is used as a size optimization for the common case with no parameters. pub args: Option<P<GenericArgs>>, } impl PathSegment { pub fn from_ident(ident: Ident) -> Self { PathSegment { ident, id: DUMMY_NODE_ID, args: None } } pub fn path_root(span: Span) -> Self { PathSegment::from_ident(Ident::new(kw::PathRoot, span)) } } /// The arguments of a path segment. /// /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum GenericArgs { /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`. AngleBracketed(AngleBracketedArgs), /// The `(A, B)` and `C` in `Foo(A, B) -> C`. Parenthesized(ParenthesizedArgs), } impl GenericArgs { pub fn is_parenthesized(&self) -> bool { match *self { Parenthesized(..) => true, _ => false, } } pub fn is_angle_bracketed(&self) -> bool { match *self { AngleBracketed(..) => true, _ => false, } } pub fn span(&self) -> Span { match *self { AngleBracketed(ref data) => data.span, Parenthesized(ref data) => data.span, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum GenericArg { Lifetime(Lifetime), Type(P<Ty>), Const(AnonConst), } impl GenericArg { pub fn span(&self) -> Span { match self { GenericArg::Lifetime(lt) => lt.ident.span, GenericArg::Type(ty) => ty.span, GenericArg::Const(ct) => ct.value.span, } } } /// A path like `Foo<'a, T>`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)] pub struct AngleBracketedArgs { /// The overall span. pub span: Span, /// The arguments for this path segment. pub args: Vec<GenericArg>, /// Constraints on associated types, if any. /// E.g., `Foo<A = Bar, B: Baz>`. pub constraints: Vec<AssocTyConstraint>, } impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs { fn into(self) -> Option<P<GenericArgs>> { Some(P(GenericArgs::AngleBracketed(self))) } } impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs { fn into(self) -> Option<P<GenericArgs>> { Some(P(GenericArgs::Parenthesized(self))) } } /// A path like `Foo(A, B) -> C`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ParenthesizedArgs { /// Overall span pub span: Span, /// `(A, B)` pub inputs: Vec<P<Ty>>, /// `C` pub output: Option<P<Ty>>, } impl ParenthesizedArgs { pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs { AngleBracketedArgs { span: self.span, args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(), constraints: vec![], } } } // hack to ensure that we don't try to access the private parts of `NodeId` in this module mod node_id_inner { use rustc_index::vec::Idx; rustc_index::newtype_index! { pub struct NodeId { ENCODABLE = custom DEBUG_FORMAT = "NodeId({})" } } } pub use node_id_inner::NodeId; impl NodeId { pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self { NodeId::from_u32(expn_id.as_u32()) } pub fn placeholder_to_expn_id(self) -> ExpnId { ExpnId::from_u32(self.as_u32()) } } impl fmt::Display for NodeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.as_u32(), f) } } impl rustc_serialize::UseSpecializedEncodable for NodeId { fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u32(self.as_u32()) } } impl rustc_serialize::UseSpecializedDecodable for NodeId { fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> { d.read_u32().map(NodeId::from_u32) } } /// `NodeId` used to represent the root of the crate. pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0); /// When parsing and doing expansions, we initially give all AST nodes this AST /// node value. Then later, in the renumber pass, we renumber them to have /// small, positive ids. pub const DUMMY_NODE_ID: NodeId = NodeId::MAX; /// A modifier on a bound, currently this is only used for `?Sized`, where the /// modifier is `Maybe`. Negative bounds should also be handled here. #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)] pub enum TraitBoundModifier { None, Maybe, } /// The AST represents all type param bounds as types. /// `typeck::collect::compute_bounds` matches these against /// the "special" built-in traits (see `middle::lang_items`) and /// detects `Copy`, `Send` and `Sync`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum GenericBound { Trait(PolyTraitRef, TraitBoundModifier), Outlives(Lifetime), } impl GenericBound { pub fn span(&self) -> Span { match self { &GenericBound::Trait(ref t, ..) => t.span, &GenericBound::Outlives(ref l) => l.ident.span, } } } pub type GenericBounds = Vec<GenericBound>; /// Specifies the enforced ordering for generic parameters. In the future, /// if we wanted to relax this order, we could override `PartialEq` and /// `PartialOrd`, to allow the kinds to be unordered. #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] pub enum ParamKindOrd { Lifetime, Type, Const, } impl fmt::Display for ParamKindOrd { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ParamKindOrd::Lifetime => "lifetime".fmt(f), ParamKindOrd::Type => "type".fmt(f), ParamKindOrd::Const => "const".fmt(f), } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum GenericParamKind { /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). Lifetime, Type { default: Option<P<Ty>> }, Const { ty: P<Ty> }, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct GenericParam { pub id: NodeId, pub ident: Ident, pub attrs: ThinVec<Attribute>, pub bounds: GenericBounds, pub is_placeholder: bool, pub kind: GenericParamKind, } /// Represents lifetime, type and const parameters attached to a declaration of /// a function, enum, trait, etc. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Generics { pub params: Vec<GenericParam>, pub where_clause: WhereClause, pub span: Span, } impl Default for Generics { /// Creates an instance of `Generics`. fn default() -> Generics { Generics { params: Vec::new(), where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP, }, span: DUMMY_SP, } } } /// A where-clause in a definition. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereClause { pub predicates: Vec<WherePredicate>, pub span: Span, } /// A single predicate in a where-clause. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum WherePredicate { /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`). BoundPredicate(WhereBoundPredicate), /// A lifetime predicate (e.g., `'a: 'b + 'c`). RegionPredicate(WhereRegionPredicate), /// An equality predicate (unsupported). EqPredicate(WhereEqPredicate), } impl WherePredicate { pub fn span(&self) -> Span { match self { &WherePredicate::BoundPredicate(ref p) => p.span, &WherePredicate::RegionPredicate(ref p) => p.span, &WherePredicate::EqPredicate(ref p) => p.span, } } } /// A type bound. /// /// E.g., `for<'c> Foo: Send + Clone + 'c`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereBoundPredicate { pub span: Span, /// Any generics from a `for` binding. pub bound_generic_params: Vec<GenericParam>, /// The type being bounded. pub bounded_ty: P<Ty>, /// Trait and lifetime bounds (`Clone + Send + 'static`). pub bounds: GenericBounds, } /// A lifetime predicate. /// /// E.g., `'a: 'b + 'c`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereRegionPredicate { pub span: Span, pub lifetime: Lifetime, pub bounds: GenericBounds, } /// An equality predicate (unsupported). /// /// E.g., `T = int`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereEqPredicate { pub id: NodeId, pub span: Span, pub lhs_ty: P<Ty>, pub rhs_ty: P<Ty>, } /// The set of `MetaItem`s that define the compilation environment of the crate, /// used to drive conditional compilation. pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>; #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Crate { pub module: Mod, pub attrs: Vec<Attribute>, pub span: Span, } /// Possible values inside of compile-time attribute lists. /// /// E.g., the '..' in `#[name(..)]`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum NestedMetaItem { /// A full MetaItem, for recursive meta items. MetaItem(MetaItem), /// A literal. /// /// E.g., `"foo"`, `64`, `true`. Literal(Lit), } /// A spanned compile-time attribute item. /// /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct MetaItem { pub path: Path, pub kind: MetaItemKind, pub span: Span, } /// A compile-time attribute item. /// /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum MetaItemKind { /// Word meta item. /// /// E.g., `test` as in `#[test]`. Word, /// List meta item. /// /// E.g., `derive(..)` as in `#[derive(..)]`. List(Vec<NestedMetaItem>), /// Name value meta item. /// /// E.g., `feature = "foo"` as in `#[feature = "foo"]`. NameValue(Lit), } /// A block (`{ .. }`). /// /// E.g., `{ .. }` as in `fn foo() { .. }`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Block { /// The statements in the block. pub stmts: Vec<Stmt>, pub id: NodeId, /// Distinguishes between `unsafe { ... }` and `{ ... }`. pub rules: BlockCheckMode, pub span: Span, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Pat { pub id: NodeId, pub kind: PatKind, pub span: Span, } impl Pat { /// Attempt reparsing the pattern as a type. /// This is intended for use by diagnostics. pub(super) fn to_ty(&self) -> Option<P<Ty>> { let kind = match &self.kind { // In a type expression `_` is an inference variable. PatKind::Wild => TyKind::Infer, // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`. PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => { TyKind::Path(None, Path::from_ident(*ident)) } PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), PatKind::Mac(mac) => TyKind::Mac(mac.clone()), // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type. PatKind::Ref(pat, mutbl) => pat .to_ty() .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?, // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array, // when `P` can be reparsed as a type `T`. PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?, // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)` // assuming `T0` to `Tn` are all syntactically valid as types. PatKind::Tuple(pats) => { let mut tys = Vec::with_capacity(pats.len()); // FIXME(#48994) - could just be collected into an Option<Vec> for pat in pats { tys.push(pat.to_ty()?); } TyKind::Tup(tys) } _ => return None, }; Some(P(Ty { kind, id: self.id, span: self.span, })) } /// Walk top-down and call `it` in each place where a pattern occurs /// starting with the root pattern `walk` is called on. If `it` returns /// false then we will descend no further but siblings will be processed. pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) { if !it(self) { return; } match &self.kind { PatKind::Ident(_, _, Some(p)) => p.walk(it), PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)), PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)), PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it), PatKind::Wild | PatKind::Rest | PatKind::Lit(_) | PatKind::Range(..) | PatKind::Ident(..) | PatKind::Path(..) | PatKind::Mac(_) => {}, } } /// Is this a `..` pattern? pub fn is_rest(&self) -> bool { match self.kind { PatKind::Rest => true, _ => false, } } } /// A single field in a struct pattern /// /// Patterns like the fields of Foo `{ x, ref y, ref mut z }` /// are treated the same as` x: x, y: ref y, z: ref mut z`, /// except is_shorthand is true #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct FieldPat { /// The identifier for the field pub ident: Ident, /// The pattern the field is destructured to pub pat: P<Pat>, pub is_shorthand: bool, pub attrs: ThinVec<Attribute>, pub id: NodeId, pub span: Span, pub is_placeholder: bool, } #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum BindingMode { ByRef(Mutability), ByValue(Mutability), } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum RangeEnd { Included(RangeSyntax), Excluded, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum RangeSyntax { DotDotDot, DotDotEq, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum PatKind { /// Represents a wildcard pattern (`_`). Wild, /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`), /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens /// during name resolution. Ident(BindingMode, Ident, Option<P<Pat>>), /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`). /// The `bool` is `true` in the presence of a `..`. Struct(Path, Vec<FieldPat>, /* recovered */ bool), /// A tuple struct/variant pattern (`Variant(x, y, .., z)`). TupleStruct(Path, Vec<P<Pat>>), /// An or-pattern `A | B | C`. /// Invariant: `pats.len() >= 2`. Or(Vec<P<Pat>>), /// A possibly qualified path pattern. /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can /// only legally refer to associated constants. Path(Option<QSelf>, Path), /// A tuple pattern (`(a, b)`). Tuple(Vec<P<Pat>>), /// A `box` pattern. Box(P<Pat>), /// A reference pattern (e.g., `&mut (a, b)`). Ref(P<Pat>, Mutability), /// A literal. Lit(P<Expr>), /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`). Range(P<Expr>, P<Expr>, Spanned<RangeEnd>), /// A slice pattern `[a, b, c]`. Slice(Vec<P<Pat>>), /// A rest pattern `..`. /// /// Syntactically it is valid anywhere. /// /// Semantically however, it only has meaning immediately inside: /// - a slice pattern: `[a, .., b]`, /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`, /// - a tuple pattern: `(a, .., b)`, /// - a tuple struct/variant pattern: `$path(a, .., b)`. /// /// In all of these cases, an additional restriction applies, /// only one rest pattern may occur in the pattern sequences. Rest, /// Parentheses in patterns used for grouping (i.e., `(PAT)`). Paren(P<Pat>), /// A macro pattern; pre-expansion. Mac(Mac), } #[derive( Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy, )] pub enum Mutability { Mutable, Immutable, } #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum BinOpKind { /// The `+` operator (addition) Add, /// The `-` operator (subtraction) Sub, /// The `*` operator (multiplication) Mul, /// The `/` operator (division) Div, /// The `%` operator (modulus) Rem, /// The `&&` operator (logical and) And, /// The `||` operator (logical or) Or, /// The `^` operator (bitwise xor) BitXor, /// The `&` operator (bitwise and) BitAnd, /// The `|` operator (bitwise or) BitOr, /// The `<<` operator (shift left) Shl, /// The `>>` operator (shift right) Shr, /// The `==` operator (equality) Eq, /// The `<` operator (less than) Lt, /// The `<=` operator (less than or equal to) Le, /// The `!=` operator (not equal to) Ne, /// The `>=` operator (greater than or equal to) Ge, /// The `>` operator (greater than) Gt, } impl BinOpKind { pub fn to_string(&self) -> &'static str { use BinOpKind::*; match *self { Add => "+", Sub => "-", Mul => "*", Div => "/", Rem => "%", And => "&&", Or => "||", BitXor => "^", BitAnd => "&", BitOr => "|", Shl => "<<", Shr => ">>", Eq => "==", Lt => "<", Le => "<=", Ne => "!=", Ge => ">=", Gt => ">", } } pub fn lazy(&self) -> bool { match *self { BinOpKind::And | BinOpKind::Or => true, _ => false, } } pub fn is_shift(&self) -> bool { match *self { BinOpKind::Shl | BinOpKind::Shr => true, _ => false, } } pub fn is_comparison(&self) -> bool { use BinOpKind::*; match *self { Eq | Lt | Le | Ne | Gt | Ge => true, And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false, } } /// Returns `true` if the binary operator takes its arguments by value pub fn is_by_value(&self) -> bool { !self.is_comparison() } } pub type BinOp = Spanned<BinOpKind>; #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum UnOp { /// The `*` operator for dereferencing Deref, /// The `!` operator for logical inversion Not, /// The `-` operator for negation Neg, } impl UnOp { /// Returns `true` if the unary operator takes its argument by value pub fn is_by_value(u: UnOp) -> bool { match u { UnOp::Neg | UnOp::Not => true, _ => false, } } pub fn to_string(op: UnOp) -> &'static str { match op { UnOp::Deref => "*", UnOp::Not => "!", UnOp::Neg => "-", } } } /// A statement #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Stmt { pub id: NodeId, pub kind: StmtKind, pub span: Span, } impl Stmt { pub fn add_trailing_semicolon(mut self) -> Self { self.kind = match self.kind { StmtKind::Expr(expr) => StmtKind::Semi(expr), StmtKind::Mac(mac) => { StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs))) } kind => kind, }; self } pub fn is_item(&self) -> bool { match self.kind { StmtKind::Item(_) => true, _ => false, } } pub fn is_expr(&self) -> bool { match self.kind { StmtKind::Expr(_) => true, _ => false, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum StmtKind { /// A local (let) binding. Local(P<Local>), /// An item definition. Item(P<Item>), /// Expr without trailing semi-colon. Expr(P<Expr>), /// Expr with a trailing semi-colon. Semi(P<Expr>), /// Macro. Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>), } #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum MacStmtStyle { /// The macro statement had a trailing semicolon (e.g., `foo! { ... };` /// `foo!(...);`, `foo![...];`). Semicolon, /// The macro statement had braces (e.g., `foo! { ... }`). Braces, /// The macro statement had parentheses or brackets and no semicolon (e.g., /// `foo!(...)`). All of these will end up being converted into macro /// expressions. NoBraces, } /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Local { pub id: NodeId, pub pat: P<Pat>, pub ty: Option<P<Ty>>, /// Initializer expression to set the value, if any. pub init: Option<P<Expr>>, pub span: Span, pub attrs: ThinVec<Attribute>, } /// An arm of a 'match'. /// /// E.g., `0..=10 => { println!("match!") }` as in /// /// ``` /// match 123 { /// 0..=10 => { println!("match!") }, /// _ => { println!("no match!") }, /// } /// ``` #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Arm { pub attrs: Vec<Attribute>, pub pat: P<Pat>, pub guard: Option<P<Expr>>, pub body: P<Expr>, pub span: Span, pub id: NodeId, pub is_placeholder: bool, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Field { pub ident: Ident, pub expr: P<Expr>, pub span: Span, pub is_shorthand: bool, pub attrs: ThinVec<Attribute>, pub id: NodeId, pub is_placeholder: bool, } #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum BlockCheckMode { Default, Unsafe(UnsafeSource), } #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum UnsafeSource { CompilerGenerated, UserProvided, } /// A constant (expression) that's not an item or associated item, /// but needs its own `DefId` for type-checking, const-eval, etc. /// These are usually found nested inside types (e.g., array lengths) /// or expressions (e.g., repeat counts), and also used to define /// explicit discriminant values for enum variants. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct AnonConst { pub id: NodeId, pub value: P<Expr>, } /// An expression. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Expr { pub id: NodeId, pub kind: ExprKind, pub span: Span, pub attrs: ThinVec<Attribute>, } // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] static_assert_size!(Expr, 96); impl Expr { /// Returns `true` if this expression would be valid somewhere that expects a value; /// for example, an `if` condition. pub fn returns(&self) -> bool { if let ExprKind::Block(ref block, _) = self.kind { match block.stmts.last().map(|last_stmt| &last_stmt.kind) { // Implicit return Some(&StmtKind::Expr(_)) => true, Some(&StmtKind::Semi(ref expr)) => { if let ExprKind::Ret(_) = expr.kind { // Last statement is explicit return. true } else { false } } // This is a block that doesn't end in either an implicit or explicit return. _ => false, } } else { // This is not a block, it is a value. true } } fn to_bound(&self) -> Option<GenericBound> { match &self.kind { ExprKind::Path(None, path) => Some(GenericBound::Trait( PolyTraitRef::new(Vec::new(), path.clone(), self.span), TraitBoundModifier::None, )), _ => None, } } pub(super) fn to_ty(&self) -> Option<P<Ty>> { let kind = match &self.kind { ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), ExprKind::Mac(mac) => TyKind::Mac(mac.clone()), ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?, ExprKind::AddrOf(mutbl, expr) => expr .to_ty() .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?, ExprKind::Repeat(expr, expr_len) => { expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))? } ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?, ExprKind::Tup(exprs) => { let tys = exprs .iter() .map(|expr| expr.to_ty()) .collect::<Option<Vec<_>>>()?; TyKind::Tup(tys) } ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => { if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) { TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None) } else { return None; } } _ => return None, }; Some(P(Ty { kind, id: self.id, span: self.span, })) } pub fn precedence(&self) -> ExprPrecedence { match self.kind { ExprKind::Box(_) => ExprPrecedence::Box, ExprKind::Array(_) => ExprPrecedence::Array, ExprKind::Call(..) => ExprPrecedence::Call, ExprKind::MethodCall(..) => ExprPrecedence::MethodCall, ExprKind::Tup(_) => ExprPrecedence::Tup, ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node), ExprKind::Unary(..) => ExprPrecedence::Unary, ExprKind::Lit(_) => ExprPrecedence::Lit, ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast, ExprKind::Let(..) => ExprPrecedence::Let, ExprKind::If(..) => ExprPrecedence::If, ExprKind::While(..) => ExprPrecedence::While, ExprKind::ForLoop(..) => ExprPrecedence::ForLoop, ExprKind::Loop(..) => ExprPrecedence::Loop, ExprKind::Match(..) => ExprPrecedence::Match, ExprKind::Closure(..) => ExprPrecedence::Closure, ExprKind::Block(..) => ExprPrecedence::Block, ExprKind::TryBlock(..) => ExprPrecedence::TryBlock, ExprKind::Async(..) => ExprPrecedence::Async, ExprKind::Await(..) => ExprPrecedence::Await, ExprKind::Assign(..) => ExprPrecedence::Assign, ExprKind::AssignOp(..) => ExprPrecedence::AssignOp, ExprKind::Field(..) => ExprPrecedence::Field, ExprKind::Index(..) => ExprPrecedence::Index, ExprKind::Range(..) => ExprPrecedence::Range, ExprKind::Path(..) => ExprPrecedence::Path, ExprKind::AddrOf(..) => ExprPrecedence::AddrOf, ExprKind::Break(..) => ExprPrecedence::Break, ExprKind::Continue(..) => ExprPrecedence::Continue, ExprKind::Ret(..) => ExprPrecedence::Ret, ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm, ExprKind::Mac(..) => ExprPrecedence::Mac, ExprKind::Struct(..) => ExprPrecedence::Struct, ExprKind::Repeat(..) => ExprPrecedence::Repeat, ExprKind::Paren(..) => ExprPrecedence::Paren, ExprKind::Try(..) => ExprPrecedence::Try, ExprKind::Yield(..) => ExprPrecedence::Yield, ExprKind::Err => ExprPrecedence::Err, } } } /// Limit types of a range (inclusive or exclusive) #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum RangeLimits { /// Inclusive at the beginning, exclusive at the end HalfOpen, /// Inclusive at the beginning and end Closed, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum ExprKind { /// A `box x` expression. Box(P<Expr>), /// An array (`[a, b, c, d]`) Array(Vec<P<Expr>>), /// A function call /// /// The first field resolves to the function itself, /// and the second field is the list of arguments. /// This also represents calling the constructor of /// tuple-like ADTs such as tuple structs and enum variants. Call(P<Expr>, Vec<P<Expr>>), /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`) /// /// The `PathSegment` represents the method name and its generic arguments /// (within the angle brackets). /// The first element of the vector of an `Expr` is the expression that evaluates /// to the object on which the method is being called on (the receiver), /// and the remaining elements are the rest of the arguments. /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`. MethodCall(PathSegment, Vec<P<Expr>>), /// A tuple (e.g., `(a, b, c, d)`). Tup(Vec<P<Expr>>), /// A binary operation (e.g., `a + b`, `a * b`). Binary(BinOp, P<Expr>, P<Expr>), /// A unary operation (e.g., `!x`, `*x`). Unary(UnOp, P<Expr>), /// A literal (e.g., `1`, `"foo"`). Lit(Lit), /// A cast (e.g., `foo as f64`). Cast(P<Expr>, P<Ty>), /// A type ascription (e.g., `42: usize`). Type(P<Expr>, P<Ty>), /// A `let pat = expr` expression that is only semantically allowed in the condition /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`). Let(P<Pat>, P<Expr>), /// An `if` block, with an optional `else` block. /// /// `if expr { block } else { expr }` If(P<Expr>, P<Block>, Option<P<Expr>>), /// A while loop, with an optional label. /// /// `'label: while expr { block }` While(P<Expr>, P<Block>, Option<Label>), /// A `for` loop, with an optional label. /// /// `'label: for pat in expr { block }` /// /// This is desugared to a combination of `loop` and `match` expressions. ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>), /// Conditionless loop (can be exited with `break`, `continue`, or `return`). /// /// `'label: loop { block }` Loop(P<Block>, Option<Label>), /// A `match` block. Match(P<Expr>, Vec<Arm>), /// A closure (e.g., `move |a, b, c| a + b + c`). /// /// The final span is the span of the argument block `|...|`. Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span), /// A block (`'label: { ... }`). Block(P<Block>, Option<Label>), /// An async block (`async move { ... }`). /// /// The `NodeId` is the `NodeId` for the closure that results from /// desugaring an async block, just like the NodeId field in the /// `IsAsync` enum. This is necessary in order to create a def for the /// closure which can be used as a parent of any child defs. Defs /// created during lowering cannot be made the parent of any other /// preexisting defs. Async(CaptureBy, NodeId, P<Block>), /// An await expression (`my_future.await`). Await(P<Expr>), /// A try block (`try { ... }`). TryBlock(P<Block>), /// An assignment (`a = foo()`). Assign(P<Expr>, P<Expr>), /// An assignment with an operator. /// /// E.g., `a += 1`. AssignOp(BinOp, P<Expr>, P<Expr>), /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field. Field(P<Expr>, Ident), /// An indexing operation (e.g., `foo[2]`). Index(P<Expr>, P<Expr>), /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`). Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits), /// Variable reference, possibly containing `::` and/or type /// parameters (e.g., `foo::bar::<baz>`). /// /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`). Path(Option<QSelf>, Path), /// A referencing operation (`&a` or `&mut a`). AddrOf(Mutability, P<Expr>), /// A `break`, with an optional label to break, and an optional expression. Break(Option<Label>, Option<P<Expr>>), /// A `continue`, with an optional label. Continue(Option<Label>), /// A `return`, with an optional value to be returned. Ret(Option<P<Expr>>), /// Output of the `asm!()` macro. InlineAsm(P<InlineAsm>), /// A macro invocation; pre-expansion. Mac(Mac), /// A struct literal expression. /// /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`, /// where `base` is the `Option<Expr>`. Struct(Path, Vec<Field>, Option<P<Expr>>), /// An array literal constructed from one repeated element. /// /// E.g., `[1; 5]`. The expression is the element to be /// repeated; the constant is the number of times to repeat it. Repeat(P<Expr>, AnonConst), /// No-op: used solely so we can pretty-print faithfully. Paren(P<Expr>), /// A try expression (`expr?`). Try(P<Expr>), /// A `yield`, with an optional value to be yielded. Yield(Option<P<Expr>>), /// Placeholder for an expression that wasn't syntactically well formed in some way. Err, } /// The explicit `Self` type in a "qualified path". The actual /// path, including the trait and the associated item, is stored /// separately. `position` represents the index of the associated /// item qualified with this `Self` type. /// /// ```ignore (only-for-syntax-highlight) /// <Vec<T> as a::b::Trait>::AssociatedItem /// ^~~~~ ~~~~~~~~~~~~~~^ /// ty position = 3 /// /// <Vec<T>>::AssociatedItem /// ^~~~~ ^ /// ty position = 0 /// ``` #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct QSelf { pub ty: P<Ty>, /// The span of `a::b::Trait` in a path like `<Vec<T> as /// a::b::Trait>::AssociatedItem`; in the case where `position == /// 0`, this is an empty span. pub path_span: Span, pub position: usize, } /// A capture clause. #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum CaptureBy { Value, Ref, } /// The movability of a generator / closure literal. #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum Movability { Static, Movable, } /// Represents a macro invocation. The `Path` indicates which macro /// is being invoked, and the vector of token-trees contains the source /// of the macro invocation. /// /// N.B., the additional ident for a `macro_rules`-style macro is actually /// stored in the enclosing item. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Mac { pub path: Path, pub delim: MacDelimiter, pub tts: TokenStream, pub span: Span, pub prior_type_ascription: Option<(Span, bool)>, } #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)] pub enum MacDelimiter { Parenthesis, Bracket, Brace, } impl Mac { pub fn stream(&self) -> TokenStream { self.tts.clone() } } impl MacDelimiter { crate fn to_token(self) -> DelimToken { match self { MacDelimiter::Parenthesis => DelimToken::Paren, MacDelimiter::Bracket => DelimToken::Bracket, MacDelimiter::Brace => DelimToken::Brace, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct MacroDef { pub tokens: TokenStream, pub legacy: bool, } impl MacroDef { pub fn stream(&self) -> TokenStream { self.tokens.clone().into() } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)] pub enum StrStyle { /// A regular string, like `"foo"`. Cooked, /// A raw string, like `r##"foo"##`. /// /// The value is the number of `#` symbols used. Raw(u16), } /// An AST literal. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Lit { /// The original literal token as written in source code. pub token: token::Lit, /// The "semantic" representation of the literal lowered from the original tokens. /// Strings are unescaped, hexadecimal forms are eliminated, etc. /// FIXME: Remove this and only create the semantic representation during lowering to HIR. pub kind: LitKind, pub span: Span, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)] pub enum LitIntType { Signed(IntTy), Unsigned(UintTy), Unsuffixed, } /// Literal kind. /// /// E.g., `"foo"`, `42`, `12.34`, or `bool`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)] pub enum LitKind { /// A string literal (`"foo"`). Str(Symbol, StrStyle), /// A byte string (`b"foo"`). ByteStr(Lrc<Vec<u8>>), /// A byte char (`b'f'`). Byte(u8), /// A character literal (`'a'`). Char(char), /// An integer literal (`1`). Int(u128, LitIntType), /// A float literal (`1f64` or `1E10f64`). Float(Symbol, FloatTy), /// A float literal without a suffix (`1.0 or 1.0E10`). FloatUnsuffixed(Symbol), /// A boolean literal. Bool(bool), /// Placeholder for a literal that wasn't well-formed in some way. Err(Symbol), } impl LitKind { /// Returns `true` if this literal is a string. pub fn is_str(&self) -> bool { match *self { LitKind::Str(..) => true, _ => false, } } /// Returns `true` if this literal is byte literal string. pub fn is_bytestr(&self) -> bool { match self { LitKind::ByteStr(_) => true, _ => false, } } /// Returns `true` if this is a numeric literal. pub fn is_numeric(&self) -> bool { match *self { LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true, _ => false, } } /// Returns `true` if this literal has no suffix. /// Note: this will return true for literals with prefixes such as raw strings and byte strings. pub fn is_unsuffixed(&self) -> bool { match *self { // unsuffixed variants LitKind::Str(..) | LitKind::ByteStr(..) | LitKind::Byte(..) | LitKind::Char(..) | LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(..) | LitKind::Bool(..) | LitKind::Err(..) => true, // suffixed variants LitKind::Int(_, LitIntType::Signed(..)) | LitKind::Int(_, LitIntType::Unsigned(..)) | LitKind::Float(..) => false, } } /// Returns `true` if this literal has a suffix. pub fn is_suffixed(&self) -> bool { !self.is_unsuffixed() } } // N.B., If you change this, you'll probably want to change the corresponding // type structure in `middle/ty.rs` as well. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct MutTy { pub ty: P<Ty>, pub mutbl: Mutability, } /// Represents a method's signature in a trait declaration, /// or in an implementation. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct MethodSig { pub header: FnHeader, pub decl: P<FnDecl>, } /// Represents an item declaration within a trait declaration, /// possibly including a default implementation. A trait item is /// either required (meaning it doesn't have an implementation, just a /// signature) or provided (meaning it has a default implementation). #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct TraitItem { pub id: NodeId, pub ident: Ident, pub attrs: Vec<Attribute>, pub generics: Generics, pub kind: TraitItemKind, pub span: Span, /// See `Item::tokens` for what this is. pub tokens: Option<TokenStream>, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum TraitItemKind { Const(P<Ty>, Option<P<Expr>>), Method(MethodSig, Option<P<Block>>), Type(GenericBounds, Option<P<Ty>>), Macro(Mac), } /// Represents anything within an `impl` block. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ImplItem { pub id: NodeId, pub ident: Ident, pub vis: Visibility, pub defaultness: Defaultness, pub attrs: Vec<Attribute>, pub generics: Generics, pub kind: ImplItemKind, pub span: Span, /// See `Item::tokens` for what this is. pub tokens: Option<TokenStream>, } /// Represents various kinds of content within an `impl`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum ImplItemKind { Const(P<Ty>, P<Expr>), Method(MethodSig, P<Block>), TyAlias(P<Ty>), OpaqueTy(GenericBounds), Macro(Mac), } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)] pub enum IntTy { Isize, I8, I16, I32, I64, I128, } impl fmt::Debug for IntTy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(self, f) } } impl fmt::Display for IntTy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.ty_to_string()) } } impl IntTy { pub fn ty_to_string(&self) -> &'static str { match *self { IntTy::Isize => "isize", IntTy::I8 => "i8", IntTy::I16 => "i16", IntTy::I32 => "i32", IntTy::I64 => "i64", IntTy::I128 => "i128", } } pub fn to_symbol(&self) -> Symbol { match *self { IntTy::Isize => sym::isize, IntTy::I8 => sym::i8, IntTy::I16 => sym::i16, IntTy::I32 => sym::i32, IntTy::I64 => sym::i64, IntTy::I128 => sym::i128, } } pub fn val_to_string(&self, val: i128) -> String { // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types // are parsed as `u128`, so we wouldn't want to print an extra negative // sign. format!("{}{}", val as u128, self.ty_to_string()) } pub fn bit_width(&self) -> Option<usize> { Some(match *self { IntTy::Isize => return None, IntTy::I8 => 8, IntTy::I16 => 16, IntTy::I32 => 32, IntTy::I64 => 64, IntTy::I128 => 128, }) } } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)] pub enum UintTy { Usize, U8, U16, U32, U64, U128, } impl UintTy { pub fn ty_to_string(&self) -> &'static str { match *self { UintTy::Usize => "usize", UintTy::U8 => "u8", UintTy::U16 => "u16", UintTy::U32 => "u32", UintTy::U64 => "u64", UintTy::U128 => "u128", } } pub fn to_symbol(&self) -> Symbol { match *self { UintTy::Usize => sym::usize, UintTy::U8 => sym::u8, UintTy::U16 => sym::u16, UintTy::U32 => sym::u32, UintTy::U64 => sym::u64, UintTy::U128 => sym::u128, } } pub fn val_to_string(&self, val: u128) -> String { format!("{}{}", val, self.ty_to_string()) } pub fn bit_width(&self) -> Option<usize> { Some(match *self { UintTy::Usize => return None, UintTy::U8 => 8, UintTy::U16 => 16, UintTy::U32 => 32, UintTy::U64 => 64, UintTy::U128 => 128, }) } } impl fmt::Debug for UintTy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(self, f) } } impl fmt::Display for UintTy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.ty_to_string()) } } /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`). #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct AssocTyConstraint { pub id: NodeId, pub ident: Ident, pub kind: AssocTyConstraintKind, pub span: Span, } /// The kinds of an `AssocTyConstraint`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum AssocTyConstraintKind { /// E.g., `A = Bar` in `Foo<A = Bar>`. Equality { ty: P<Ty>, }, /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`. Bound { bounds: GenericBounds, }, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Ty { pub id: NodeId, pub kind: TyKind, pub span: Span, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct BareFnTy { pub unsafety: Unsafety, pub abi: Abi, pub generic_params: Vec<GenericParam>, pub decl: P<FnDecl>, } /// The various kinds of type recognized by the compiler. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum TyKind { /// A variable-length slice (`[T]`). Slice(P<Ty>), /// A fixed length array (`[T; n]`). Array(P<Ty>, AnonConst), /// A raw pointer (`*const T` or `*mut T`). Ptr(MutTy), /// A reference (`&'a T` or `&'a mut T`). Rptr(Option<Lifetime>, MutTy), /// A bare function (e.g., `fn(usize) -> bool`). BareFn(P<BareFnTy>), /// The never type (`!`). Never, /// A tuple (`(A, B, C, D,...)`). Tup(Vec<P<Ty>>), /// A path (`module::module::...::Type`), optionally /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`. /// /// Type parameters are stored in the `Path` itself. Path(Option<QSelf>, Path), /// A trait object type `Bound1 + Bound2 + Bound3` /// where `Bound` is a trait or a lifetime. TraitObject(GenericBounds, TraitObjectSyntax), /// An `impl Bound1 + Bound2 + Bound3` type /// where `Bound` is a trait or a lifetime. /// /// The `NodeId` exists to prevent lowering from having to /// generate `NodeId`s on the fly, which would complicate /// the generation of opaque `type Foo = impl Trait` items significantly. ImplTrait(NodeId, GenericBounds), /// No-op; kept solely so that we can pretty-print faithfully. Paren(P<Ty>), /// Unused for now. Typeof(AnonConst), /// This means the type should be inferred instead of it having been /// specified. This can appear anywhere in a type. Infer, /// Inferred type of a `self` or `&self` argument in a method. ImplicitSelf, /// A macro in the type position. Mac(Mac), /// Placeholder for a kind that has failed to be defined. Err, /// Placeholder for a `va_list`. CVarArgs, } impl TyKind { pub fn is_implicit_self(&self) -> bool { if let TyKind::ImplicitSelf = *self { true } else { false } } pub fn is_unit(&self) -> bool { if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false } } } /// Syntax used to declare a trait object. #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum TraitObjectSyntax { Dyn, None, } /// Inline assembly dialect. /// /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`. #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum AsmDialect { Att, Intel, } /// Inline assembly. /// /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct InlineAsmOutput { pub constraint: Symbol, pub expr: P<Expr>, pub is_rw: bool, pub is_indirect: bool, } /// Inline assembly. /// /// E.g., `asm!("NOP");`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct InlineAsm { pub asm: Symbol, pub asm_str_style: StrStyle, pub outputs: Vec<InlineAsmOutput>, pub inputs: Vec<(Symbol, P<Expr>)>, pub clobbers: Vec<Symbol>, pub volatile: bool, pub alignstack: bool, pub dialect: AsmDialect, } /// A parameter in a function header. /// /// E.g., `bar: usize` as in `fn foo(bar: usize)`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Param { pub attrs: ThinVec<Attribute>, pub ty: P<Ty>, pub pat: P<Pat>, pub id: NodeId, pub span: Span, pub is_placeholder: bool, } /// Alternative representation for `Arg`s describing `self` parameter of methods. /// /// E.g., `&mut self` as in `fn foo(&mut self)`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum SelfKind { /// `self`, `mut self` Value(Mutability), /// `&'lt self`, `&'lt mut self` Region(Option<Lifetime>, Mutability), /// `self: TYPE`, `mut self: TYPE` Explicit(P<Ty>, Mutability), } pub type ExplicitSelf = Spanned<SelfKind>; impl Param { pub fn to_self(&self) -> Option<ExplicitSelf> { if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind { if ident.name == kw::SelfLower { return match self.ty.kind { TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))), TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => { Some(respan(self.pat.span, SelfKind::Region(lt, mutbl))) } _ => Some(respan( self.pat.span.to(self.ty.span), SelfKind::Explicit(self.ty.clone(), mutbl), )), }; } } None } pub fn is_self(&self) -> bool { if let PatKind::Ident(_, ident, _) = self.pat.kind { ident.name == kw::SelfLower } else { false } } pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param { let span = eself.span.to(eself_ident.span); let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, }); let param = |mutbl, ty| Param { attrs, pat: P(Pat { id: DUMMY_NODE_ID, kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None), span, }), span, ty, id: DUMMY_NODE_ID, is_placeholder: false }; match eself.node { SelfKind::Explicit(ty, mutbl) => param(mutbl, ty), SelfKind::Value(mutbl) => param(mutbl, infer_ty), SelfKind::Region(lt, mutbl) => param( Mutability::Immutable, P(Ty { id: DUMMY_NODE_ID, kind: TyKind::Rptr( lt, MutTy { ty: infer_ty, mutbl, }, ), span, }), ), } } } /// A header (not the body) of a function declaration. /// /// E.g., `fn foo(bar: baz)`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct FnDecl { pub inputs: Vec<Param>, pub output: FunctionRetTy, } impl FnDecl { pub fn get_self(&self) -> Option<ExplicitSelf> { self.inputs.get(0).and_then(Param::to_self) } pub fn has_self(&self) -> bool { self.inputs.get(0).map(Param::is_self).unwrap_or(false) } pub fn c_variadic(&self) -> bool { self.inputs.last().map(|arg| match arg.ty.kind { TyKind::CVarArgs => true, _ => false, }).unwrap_or(false) } } /// Is the trait definition an auto trait? #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum IsAuto { Yes, No, } #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum Unsafety { Unsafe, Normal, } #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)] pub enum IsAsync { Async { closure_id: NodeId, return_impl_trait_id: NodeId, }, NotAsync, } impl IsAsync { pub fn is_async(self) -> bool { if let IsAsync::Async { .. } = self { true } else { false } } /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item. pub fn opt_return_id(self) -> Option<NodeId> { match self { IsAsync::Async { return_impl_trait_id, .. } => Some(return_impl_trait_id), IsAsync::NotAsync => None, } } } #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum Constness { Const, NotConst, } #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum Defaultness { Default, Final, } impl fmt::Display for Unsafety { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt( match *self { Unsafety::Normal => "normal", Unsafety::Unsafe => "unsafe", }, f, ) } } #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)] pub enum ImplPolarity { /// `impl Trait for Type` Positive, /// `impl !Trait for Type` Negative, } impl fmt::Debug for ImplPolarity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ImplPolarity::Positive => "positive".fmt(f), ImplPolarity::Negative => "negative".fmt(f), } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum FunctionRetTy { /// Returns type is not specified. /// /// Functions default to `()` and closures default to inference. /// Span points to where return type would be inserted. Default(Span), /// Everything else. Ty(P<Ty>), } impl FunctionRetTy { pub fn span(&self) -> Span { match *self { FunctionRetTy::Default(span) => span, FunctionRetTy::Ty(ref ty) => ty.span, } } } /// Module declaration. /// /// E.g., `mod foo;` or `mod foo { .. }`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Mod { /// A span from the first token past `{` to the last token until `}`. /// For `mod foo;`, the inner span ranges from the first token /// to the last token in the external file. pub inner: Span, pub items: Vec<P<Item>>, /// `true` for `mod foo { .. }`; `false` for `mod foo;`. pub inline: bool, } /// Foreign module declaration. /// /// E.g., `extern { .. }` or `extern C { .. }`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ForeignMod { pub abi: Abi, pub items: Vec<ForeignItem>, } /// Global inline assembly. /// /// Also known as "module-level assembly" or "file-scoped assembly". #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)] pub struct GlobalAsm { pub asm: Symbol, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct EnumDef { pub variants: Vec<Variant>, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Variant { /// Name of the variant. pub ident: Ident, /// Attributes of the variant. pub attrs: Vec<Attribute>, /// Id of the variant (not the constructor, see `VariantData::ctor_id()`). pub id: NodeId, /// Fields and constructor id of the variant. pub data: VariantData, /// Explicit discriminant, e.g., `Foo = 1`. pub disr_expr: Option<AnonConst>, /// Span pub span: Span, /// Is a macro placeholder pub is_placeholder: bool, } /// Part of `use` item to the right of its prefix. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum UseTreeKind { /// `use prefix` or `use prefix as rename` /// /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each /// namespace. Simple(Option<Ident>, NodeId, NodeId), /// `use prefix::{...}` Nested(Vec<(UseTree, NodeId)>), /// `use prefix::*` Glob, } /// A tree of paths sharing common prefixes. /// Used in `use` items both at top-level and inside of braces in import groups. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct UseTree { pub prefix: Path, pub kind: UseTreeKind, pub span: Span, } impl UseTree { pub fn ident(&self) -> Ident { match self.kind { UseTreeKind::Simple(Some(rename), ..) => rename, UseTreeKind::Simple(None, ..) => { self.prefix .segments .last() .expect("empty prefix in a simple import") .ident } _ => panic!("`UseTree::ident` can only be used on a simple import"), } } } /// Distinguishes between `Attribute`s that decorate items and Attributes that /// are contained as statements within items. These two cases need to be /// distinguished for pretty-printing. #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum AttrStyle { Outer, Inner, } #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)] pub struct AttrId(pub usize); impl Idx for AttrId { fn new(idx: usize) -> Self { AttrId(idx) } fn index(self) -> usize { self.0 } } impl rustc_serialize::Encodable for AttrId { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_unit() } } impl rustc_serialize::Decodable for AttrId { fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> { d.read_nil().map(|_| crate::attr::mk_attr_id()) } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct AttrItem { pub path: Path, pub tokens: TokenStream, } /// Metadata associated with an item. /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Attribute { pub item: AttrItem, pub id: AttrId, pub style: AttrStyle, pub is_sugared_doc: bool, pub span: Span, } // Compatibility impl to avoid churn, consider removing. impl std::ops::Deref for Attribute { type Target = AttrItem; fn deref(&self) -> &Self::Target { &self.item } } /// `TraitRef`s appear in impls. /// /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl. /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the /// same as the impl's `NodeId`). #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct TraitRef { pub path: Path, pub ref_id: NodeId, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct PolyTraitRef { /// The `'a` in `<'a> Foo<&'a T>`. pub bound_generic_params: Vec<GenericParam>, /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`. pub trait_ref: TraitRef, pub span: Span, } impl PolyTraitRef { pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self { PolyTraitRef { bound_generic_params: generic_params, trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID, }, span, } } } #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)] pub enum CrateSugar { /// Source is `pub(crate)`. PubCrate, /// Source is (just) `crate`. JustCrate, } pub type Visibility = Spanned<VisibilityKind>; #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum VisibilityKind { Public, Crate(CrateSugar), Restricted { path: P<Path>, id: NodeId }, Inherited, } impl VisibilityKind { pub fn is_pub(&self) -> bool { if let VisibilityKind::Public = *self { true } else { false } } } /// Field of a struct. /// /// E.g., `bar: usize` as in `struct Foo { bar: usize }`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct StructField { pub span: Span, pub ident: Option<Ident>, pub vis: Visibility, pub id: NodeId, pub ty: P<Ty>, pub attrs: Vec<Attribute>, pub is_placeholder: bool, } /// Fields and constructor ids of enum variants and structs. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum VariantData { /// Struct variant. /// /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`. Struct(Vec<StructField>, bool), /// Tuple variant. /// /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`. Tuple(Vec<StructField>, NodeId), /// Unit variant. /// /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`. Unit(NodeId), } impl VariantData { /// Return the fields of this variant. pub fn fields(&self) -> &[StructField] { match *self { VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields, _ => &[], } } /// Return the `NodeId` of this variant's constructor, if it has one. pub fn ctor_id(&self) -> Option<NodeId> { match *self { VariantData::Struct(..) => None, VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id), } } } /// An item. /// /// The name might be a dummy name in case of anonymous items. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Item { pub ident: Ident, pub attrs: Vec<Attribute>, pub id: NodeId, pub kind: ItemKind, pub vis: Visibility, pub span: Span, /// Original tokens this item was parsed from. This isn't necessarily /// available for all items, although over time more and more items should /// have this be `Some`. Right now this is primarily used for procedural /// macros, notably custom attributes. /// /// Note that the tokens here do not include the outer attributes, but will /// include inner attributes. pub tokens: Option<TokenStream>, } impl Item { /// Return the span that encompasses the attributes. pub fn span_with_attributes(&self) -> Span { self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span)) } } /// A function header. /// /// All the information between the visibility and the name of the function is /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`). #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)] pub struct FnHeader { pub unsafety: Unsafety, pub asyncness: Spanned<IsAsync>, pub constness: Spanned<Constness>, pub abi: Abi, } impl Default for FnHeader { fn default() -> FnHeader { FnHeader { unsafety: Unsafety::Normal, asyncness: dummy_spanned(IsAsync::NotAsync), constness: dummy_spanned(Constness::NotConst), abi: Abi::Rust, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum ItemKind { /// An `extern crate` item, with the optional *original* crate name if the crate was renamed. /// /// E.g., `extern crate foo` or `extern crate foo_bar as foo`. ExternCrate(Option<Name>), /// A use declaration item (`use`). /// /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`. Use(P<UseTree>), /// A static item (`static`). /// /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`. Static(P<Ty>, Mutability, P<Expr>), /// A constant item (`const`). /// /// E.g., `const FOO: i32 = 42;`. Const(P<Ty>, P<Expr>), /// A function declaration (`fn`). /// /// E.g., `fn foo(bar: usize) -> usize { .. }`. Fn(P<FnDecl>, FnHeader, Generics, P<Block>), /// A module declaration (`mod`). /// /// E.g., `mod foo;` or `mod foo { .. }`. Mod(Mod), /// An external module (`extern`). /// /// E.g., `extern {}` or `extern "C" {}`. ForeignMod(ForeignMod), /// Module-level inline assembly (from `global_asm!()`). GlobalAsm(P<GlobalAsm>), /// A type alias (`type`). /// /// E.g., `type Foo = Bar<u8>;`. TyAlias(P<Ty>, Generics), /// An opaque `impl Trait` type alias. /// /// E.g., `type Foo = impl Bar + Boo;`. OpaqueTy(GenericBounds, Generics), /// An enum definition (`enum`). /// /// E.g., `enum Foo<A, B> { C<A>, D<B> }`. Enum(EnumDef, Generics), /// A struct definition (`struct`). /// /// E.g., `struct Foo<A> { x: A }`. Struct(VariantData, Generics), /// A union definition (`union`). /// /// E.g., `union Foo<A, B> { x: A, y: B }`. Union(VariantData, Generics), /// A trait declaration (`trait`). /// /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`. Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>), /// Trait alias /// /// E.g., `trait Foo = Bar + Quux;`. TraitAlias(Generics, GenericBounds), /// An implementation. /// /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`. Impl( Unsafety, ImplPolarity, Defaultness, Generics, Option<TraitRef>, // (optional) trait this impl implements P<Ty>, // self Vec<ImplItem>, ), /// A macro invocation. /// /// E.g., `foo!(..)`. Mac(Mac), /// A macro definition. MacroDef(MacroDef), } impl ItemKind { pub fn descriptive_variant(&self) -> &str { match *self { ItemKind::ExternCrate(..) => "extern crate", ItemKind::Use(..) => "use", ItemKind::Static(..) => "static item", ItemKind::Const(..) => "constant item", ItemKind::Fn(..) => "function", ItemKind::Mod(..) => "module", ItemKind::ForeignMod(..) => "foreign module", ItemKind::GlobalAsm(..) => "global asm", ItemKind::TyAlias(..) => "type alias", ItemKind::OpaqueTy(..) => "opaque type", ItemKind::Enum(..) => "enum", ItemKind::Struct(..) => "struct", ItemKind::Union(..) => "union", ItemKind::Trait(..) => "trait", ItemKind::TraitAlias(..) => "trait alias", ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item", } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ForeignItem { pub ident: Ident, pub attrs: Vec<Attribute>, pub kind: ForeignItemKind, pub id: NodeId, pub span: Span, pub vis: Visibility, } /// An item within an `extern` block. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum ForeignItemKind { /// A foreign function. Fn(P<FnDecl>, Generics), /// A foreign static item (`static ext: u8`). Static(P<Ty>, Mutability), /// A foreign type. Ty, /// A macro invocation. Macro(Mac), } impl ForeignItemKind { pub fn descriptive_variant(&self) -> &str { match *self { ForeignItemKind::Fn(..) => "foreign function", ForeignItemKind::Static(..) => "foreign static item", ForeignItemKind::Ty => "foreign type", ForeignItemKind::Macro(..) => "macro in foreign module", } } }
29.536274
100
0.571698
fbc6e0152e00ca9f184b9cc348218ad6016fee98
3,743
use std::fmt; use url::Url; use crate::environment::CanonicalizedPathBuf; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum PathSource { /// From the local file system. Local(LocalPathSource), /// From the internet. Remote(RemotePathSource), } impl PathSource { pub fn new_local(path: CanonicalizedPathBuf) -> PathSource { PathSource::Local(LocalPathSource { path }) } pub fn new_remote(url: Url) -> PathSource { PathSource::Remote(RemotePathSource { url }) } #[cfg(test)] pub fn new_remote_from_str(url: &str) -> PathSource { PathSource::Remote(RemotePathSource { url: Url::parse(url).unwrap() }) } pub fn parent(&self) -> PathSource { match self { PathSource::Local(local) => { if let Some(parent) = local.path.parent() { PathSource::new_local(parent) } else { PathSource::new_local(local.path.clone()) } } PathSource::Remote(remote) => { let mut parent_url = remote.url.join("./").expect("Expected to be able to go back a directory in the url."); parent_url.set_query(None); PathSource::new_remote(parent_url) } } } pub fn unwrap_local(&self) -> LocalPathSource { if let PathSource::Local(local_path_source) = self { local_path_source.clone() } else { panic!("Attempted to unwrap a path source as local that was not local."); } } pub fn unwrap_remote(&self) -> RemotePathSource { if let PathSource::Remote(remote_path_source) = self { remote_path_source.clone() } else { panic!("Attempted to unwrap a path source as remote that was not remote."); } } pub fn display(&self) -> String { match self { PathSource::Local(local) => local.path.display().to_string(), PathSource::Remote(remote) => remote.url.to_string(), } } pub fn is_wasm_plugin(&self) -> bool { self.display().to_lowercase().ends_with(".wasm") } pub fn is_process_plugin(&self) -> bool { self.display().to_lowercase().ends_with(".exe-plugin") } } impl fmt::Display for PathSource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { PathSource::Local(local) => local.path.to_string_lossy().to_string(), PathSource::Remote(remote) => remote.url.to_string(), } ) } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct LocalPathSource { pub path: CanonicalizedPathBuf, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct RemotePathSource { pub url: Url, } #[cfg(test)] mod tests { use super::*; use url::Url; #[test] fn should_get_parent_for_url() { let source = PathSource::new_remote(Url::parse("https://dprint.dev/test/test.json").unwrap()); let parent = source.parent(); assert_eq!(parent, PathSource::new_remote(Url::parse("https://dprint.dev/test/").unwrap())) } #[test] fn should_get_parent_for_file_path() { let source = PathSource::new_local(CanonicalizedPathBuf::new_for_testing("/test/test/asdf.json")); let parent = source.parent(); assert_eq!(parent, PathSource::new_local(CanonicalizedPathBuf::new_for_testing("/test/test"))) } #[test] fn should_get_parent_for_root_dir_file() { let source = PathSource::new_local(CanonicalizedPathBuf::new_for_testing("/test.json")); let parent = source.parent(); assert_eq!(parent, PathSource::new_local(CanonicalizedPathBuf::new_for_testing("/"))) } #[test] fn should_get_parent_for_root_dir() { let source = PathSource::new_local(CanonicalizedPathBuf::new_for_testing("/")); let parent = source.parent(); assert_eq!(parent, PathSource::new_local(CanonicalizedPathBuf::new_for_testing("/"))) } }
27.932836
116
0.656425
0a6bf112b8558edd8a2c06c54ff3f3ebd475900c
1,847
use std::array::IntoIter; use ockam_core::compat::collections::HashMap; use ockam_transport_core::TransportError; use tokio_tungstenite::tungstenite::{http::Response, Error as TungsteniteError}; use crate::WebSocketError; #[test] fn code_and_domain() { let ws_errors_map = IntoIter::new([ (13, WebSocketError::Transport(TransportError::GenericIo)), (0, WebSocketError::Http), (1, WebSocketError::Tls), ]) .collect::<HashMap<_, _>>(); for (expected_code, ws_err) in ws_errors_map { let err: ockam_core::Error = ws_err.into(); match ws_err { WebSocketError::Transport(_) => { assert_eq!(err.domain(), TransportError::DOMAIN_NAME); assert_eq!(err.code(), TransportError::DOMAIN_CODE + expected_code); } _ => { assert_eq!(err.domain(), WebSocketError::DOMAIN_NAME); assert_eq!(err.code(), WebSocketError::DOMAIN_CODE + expected_code); } } } } #[test] fn from_tungstenite_error_to_transport_error() { let ts_err = TungsteniteError::ConnectionClosed; let ws_err: WebSocketError = ts_err.into(); let err: ockam_core::Error = ws_err.into(); let expected_err_code = TransportError::ConnectionDrop as u32; assert_eq!(err.domain(), TransportError::DOMAIN_NAME); assert_eq!(err.code(), TransportError::DOMAIN_CODE + expected_err_code); } #[test] fn from_tungstenite_error_to_websocket_error() { let ts_err = TungsteniteError::Http(Response::new(None)); let ws_err: WebSocketError = ts_err.into(); let err: ockam_core::Error = ws_err.into(); let expected_err_code = (WebSocketError::Http).code(); assert_eq!(err.domain(), WebSocketError::DOMAIN_NAME); assert_eq!(err.code(), WebSocketError::DOMAIN_CODE + expected_err_code); }
36.215686
84
0.667028
ed34a080185111fc79d6e85129ff96c916e4de1e
10,531
#![forbid(unsafe_code)] #![cfg_attr(feature = "bench", feature(test))] //! This crate provides a macro to add static, const, or lazy-initialized //! properties to enum variants. //! //! This is a variation on the //! [`enum_properties`](https://github.com/cofinite/enum_properties) crate. //! It extends it and allows additionally to define multiple property structs //! onto the same enum and adds support for `static` (instead of `const`) //! properties as well as lazily initialized properties. However, this //! additional features set comes with a syntax that is a bit more verbose, //! hence, if you just need a single const-initialized property, you might find //! `enum_properties` more concise. Nevertheless, you can also combine this //! crate with `enum_properties` using the best of both as shown in the //! [enum_props_combo example](https://github.com/Cryptjar/enumeraties/blob/master/examples/enum_props_combo.rs). //! //! See the [`props`](crate::props) macro for more details. //! //! # Example //! //! ``` //! use enumeraties::props; //! //! // A property struct //! struct Prop { name: &'static str } //! //! // An enum //! enum Foo {A} //! //! // Defining `Prop` on `Foo` via Deref //! props! { //! impl Deref for Foo as const Prop { //! Self::A => { //! name: "Foo", //! } //! } //! } //! //! // Accessing the property on `Foo` //! assert_eq!(Foo::A.name, "Foo"); //! ``` /// The trait that is implemented through [`props`] macro. /// /// This trait allows to write generic code that uses arbitrary enums that /// happen to have specific properties defined on them. /// /// # Example /// /// ``` /// use enumeraties::props; /// use enumeraties::EnumProp; /// /// struct Prop { /// name: &'static str, /// } /// /// // A generic function that works for any enum that has the `Prop` property /// fn to_name<E>(e: E) -> &'static str /// where /// E: EnumProp<Prop>, /// { /// // The `Prop` struct can be accessed via the `property` method /// e.property().name /// } /// /// // One enum that will get the props /// enum Foo { /// A, /// B, /// } /// props! { /// impl Deref for Foo as const Prop { /// Self::A => { /// name: "Foo", /// } /// Self::B => { /// name: "Foobar", /// } /// } /// } /// /// // Another enum that will get the same props /// enum Bar { /// C, /// D, /// } /// props! { /// impl Deref for Bar as const Prop { /// Self::C => { /// name: "Bar", /// } /// Self::D => { /// name: "Barfoo", /// } /// } /// } /// /// // Both enum can be used to call that function /// assert_eq!(to_name(Foo::A), "Foo"); /// assert_eq!(to_name(Bar::C), "Bar"); /// ``` /// pub trait EnumProp<Prop> { fn property(&self) -> &'static Prop; } // For the macro #[doc(hidden)] pub use core::ops::Deref; // Could still be feature gated #[doc(hidden)] pub use lazy_static; // 1.4.0 // The public front-end macro /// Adds a property onto an enum /// /// # Const, Static, Lazy /// /// This macro allows implement properties in three different ways: /// * as `const`, a constant /// * as `static`, a global variable /// * as `lazy`, a lazily initialized static /// /// `const` and `static` are very similar, but have subtle difference: /// the property type put into a `static` must implement `Send`. However, /// with a `static` it is guaranteed that for each variant there is exactly one /// unique property value and thus a unique reference address. /// With `const` the compiler is allowed to merge properties (if they are equal) /// or to inline and instantiated the same logical property multiple times, /// i.e. the same logical property might be accessed via different reference /// addresses. /// In the very most cases, the actual reference address should not be of any /// concern and thus it is recommended to use `const` over `static`. /// /// One notable use-case for `static` is when the property contains interior /// mutability. /// In these cases, `const` shouldn't even compile. /// /// `lazy`, on the other hand, is quite different from the `const` and `static`. /// While `const` and `static` require constant initialized values computed at /// compile-time, `lazy` allows to evaluate the value lazily at runtime, /// instead. However, this feature incurs some overhead at each access, because /// it must be checked that the value was indeed already initialized. /// And of course, the first access to a `lazy` value, will incur the additional /// delay to initialize the value. /// /// /// # Syntax /// /// This macro comes with essentially three different syntaxes: to implement /// `Deref` (for the primary property), add an inherent access method /// (for secondary properties), or just implementing `EnumProp` onto it (e.g., /// if only used by generic code). /// /// ## Implementing [Deref](core::ops::Deref) /// /// Syntax: /// /// ```text /// impl Deref for <ENUM> as (const|static|lazy) <PROPERTY> { /// <VARIANT> => { /// <FIELD> : <VALUE>, /// ... /// }, /// ... /// } /// ``` /// /// Example: /// /// ``` /// # use enumeraties::props; /// struct Prop { name: &'static str } /// enum Foo {A} /// props! { /// impl Deref for Foo as const Prop { /// Self::A => { /// name: "Foo", /// } /// } /// } /// // Direct access due to deref /// assert_eq!(Foo::A.name, "Foo"); /// ``` /// /// /// ## Implementing an inherent method /// /// Syntax: /// /// ```text /// impl <ENUM> : <VIS> fn <FN_NAME> as (const|static|lazy) <PROPERTY> { /// <VARIANT> => { /// <FIELD> : <VALUE>, /// ... /// }, /// ... /// } /// ``` /// /// Example: /// /// ``` /// # use enumeraties::props; /// struct Prop { name: &'static str } /// enum Foo {A} /// props! { /// // Of course, an arbitrary function names can be used instead of `getter` /// impl Foo : fn getter as const Prop { /// Self::A => { /// name: "Foo", /// } /// } /// } /// // Access via inherent method /// assert_eq!(Foo::A.getter().name, "Foo"); /// ``` /// /// ## Implementing only `EnumProp` /// /// Syntax: /// /// ```text /// impl EnumProp for <ENUM> as (const|static|lazy) <PROPERTY> { /// <VARIANT> => { /// <FIELD> : <VALUE>, /// ... /// }, /// ... /// } /// ``` /// /// Example: /// /// ``` /// # use enumeraties::props; /// struct Prop { name: &'static str } /// enum Foo {A} /// props! { /// impl EnumProp for Foo as const Prop { /// Self::A => { /// name: "Foo", /// } /// } /// } /// // Access via universal function call /// use enumeraties::EnumProp; /// assert_eq!(EnumProp::<Prop>::property(&Foo::A).name, "Foo"); /// ``` /// #[macro_export] macro_rules! props { ( // A lazy/const impl that will be promoted to `Deref` (also impls `EnumProp`) impl Deref for $enum_name:ty as $modifier:ident $prop_name:path { $($matching:tt)* } ) => { // Add the EnumProp impl $crate::internal_props_impl_macro!{ @EnumProp mod($modifier) ($prop_name) for $enum_name { $($matching)* } } // Add the deref forwarding impl $crate::Deref for $enum_name { type Target = $prop_name; fn deref(&self) -> &Self::Target { $crate::EnumProp::<$prop_name>::property(self) } } }; ( // The lazy/const impl via inherent method (also impls `EnumProp`) impl $enum_name:ty : $fn_vis:vis fn $fn_name:ident as $modifier:ident $prop_name:path { $($matching:tt)* } ) => { // Add the EnumProp impl $crate::internal_props_impl_macro!{ @EnumProp mod($modifier) ($prop_name) for $enum_name { $($matching)* } } // Add the inherent method forwarding impl $enum_name { $fn_vis fn $fn_name(&self) -> &'static $prop_name { $crate::EnumProp::<$prop_name>::property(self) } } }; ( // The lazy/const impl `EnumProp` only impl EnumProp for $enum_name:ty as $modifier:ident $prop_name:path { $($matching:tt)* } ) => { // Add the EnumProp impl $crate::internal_props_impl_macro!{ @EnumProp mod($modifier) ($prop_name) for $enum_name { $($matching)* } } }; } // The internal marco impl, used by `props`, do not use, its API may change // at any time #[doc(hidden)] #[macro_export] macro_rules! internal_props_impl_macro { ( // The enum prop impl, entry rule @EnumProp mod($modifier:ident) ($prop_name:path) for $enum_name:ty { $( // True match branches, could be simplified to `ident`, but then // one can on longer identify e.g. `Beta(42)` (maybe one shouldn't) $branch:pat => { $( $struct_fields:tt )* } $(,)? )* } ) => { impl $crate::EnumProp<$prop_name> for $enum_name { fn property(&self) -> &'static $prop_name { #[deny(unreachable_patterns)] // Remember the `Self` prefix match self { $( $branch => { $crate::internal_props_impl_macro!( @Branch mod($modifier) $prop_name { $( $struct_fields )* } ) }, )* } } } }; ( // A single *const* prop value @Branch mod(const) $prop_name:path { $( $field:ident : $value:expr ),* $(,)? } ) => {{ // A const reference, given that all `$value`s are const-init // Notice, having the explicit constant gives clearer error messages. // `BAR` is rather arbitrary here, maybe different name would be better const BAR : $prop_name = { $prop_name { $( $field : $value , )* } }; & BAR }}; ( // A single *static* prop value @Branch mod(static) $prop_name:path { $( $field:ident : $value:expr ),* $(,)? } ) => {{ // A static reference given, that all `$value`s are const-init // `BAZ` is rather arbitrary here, maybe different name would be better static BAZ : $prop_name = { $prop_name { $( $field : $value , )* } }; & BAZ }}; ( // A single *const* prop value @Branch mod(lazy) $prop_name:path { $( $field:ident : $value:expr ),* $(,)? } ) => {{ // A static reference via lazy_static. // `FOO` is rather arbitrary here, maybe different name would be better $crate::lazy_static::lazy_static!{ static ref FOO: $prop_name = { $prop_name { $( $field : $value , )* } }; } &*FOO }}; } // Some testing modules mod benchs; mod test_static; #[cfg(test)] mod tests { #[test] fn it_works() { let result = 2 + 2; assert_eq!(result, 4); } }
24.098398
113
0.578672
e533175bcba961faccd4c7f63d98508a49edb759
163
mod binary; pub use self::binary::*; mod timeout; pub use self::timeout::*; mod optimization; pub use self::optimization::*; mod spans; pub use self::spans::*;
13.583333
30
0.687117
62e874819959f59d4c6267982e9cae9d5859b21f
5,230
use crate::{account::Account, program_error::ProgramError, pubkey::Pubkey}; use std::{ cell::{Ref, RefCell, RefMut}, cmp, fmt, rc::Rc, }; /// Account information #[derive(Clone)] pub struct AccountInfo<'a> { /// Public key of the account pub key: &'a Pubkey, // Was the transaction signed by this account's public key? pub is_signer: bool, /// Account members that are mutable by the program pub lamports: Rc<RefCell<&'a mut u64>>, /// Account members that are mutable by the program pub data: Rc<RefCell<&'a mut [u8]>>, /// Program that owns this account pub owner: &'a Pubkey, } impl<'a> fmt::Debug for AccountInfo<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data_len = cmp::min(64, self.data_len()); let data_str = if data_len > 0 { format!( " data: {}", hex::encode(self.data.borrow()[..data_len].to_vec()) ) } else { "".to_string() }; write!( f, "AccountInfo {{ lamports: {} data.len: {} owner: {} {} }}", self.lamports(), self.data_len(), self.owner, data_str, ) } } impl<'a> AccountInfo<'a> { pub fn signer_key(&self) -> Option<&Pubkey> { if self.is_signer { Some(self.key) } else { None } } pub fn unsigned_key(&self) -> &Pubkey { self.key } pub fn lamports(&self) -> u64 { **self.lamports.borrow() } pub fn try_lamports(&self) -> Result<u64, ProgramError> { Ok(**self.try_borrow_lamports()?) } pub fn data_len(&self) -> usize { self.data.borrow().len() } pub fn try_data_len(&self) -> Result<usize, ProgramError> { Ok(self.try_borrow_data()?.len()) } pub fn data_is_empty(&self) -> bool { self.data.borrow().is_empty() } pub fn try_data_is_empty(&self) -> Result<bool, ProgramError> { Ok(self.try_borrow_data()?.is_empty()) } pub fn try_borrow_lamports(&self) -> Result<Ref<&mut u64>, ProgramError> { self.lamports .try_borrow() .map_err(|_| ProgramError::AccountBorrowFailed) } pub fn try_borrow_mut_lamports(&self) -> Result<RefMut<&'a mut u64>, ProgramError> { self.lamports .try_borrow_mut() .map_err(|_| ProgramError::AccountBorrowFailed) } pub fn try_borrow_data(&self) -> Result<Ref<&mut [u8]>, ProgramError> { self.data .try_borrow() .map_err(|_| ProgramError::AccountBorrowFailed) } pub fn try_borrow_mut_data(&self) -> Result<RefMut<&'a mut [u8]>, ProgramError> { self.data .try_borrow_mut() .map_err(|_| ProgramError::AccountBorrowFailed) } pub fn new( key: &'a Pubkey, is_signer: bool, lamports: &'a mut u64, data: &'a mut [u8], owner: &'a Pubkey, ) -> Self { Self { key, is_signer, lamports: Rc::new(RefCell::new(lamports)), data: Rc::new(RefCell::new(data)), owner, } } pub fn deserialize_data<T: serde::de::DeserializeOwned>(&self) -> Result<T, bincode::Error> { bincode::deserialize(&self.data.borrow()) } pub fn serialize_data<T: serde::Serialize>(&mut self, state: &T) -> Result<(), bincode::Error> { if bincode::serialized_size(state)? > self.data_len() as u64 { return Err(Box::new(bincode::ErrorKind::SizeLimit)); } bincode::serialize_into(&mut self.data.borrow_mut()[..], state) } } impl<'a> From<(&'a Pubkey, &'a mut Account)> for AccountInfo<'a> { fn from((key, account): (&'a Pubkey, &'a mut Account)) -> Self { Self::new( key, false, &mut account.lamports, &mut account.data, &account.owner, ) } } impl<'a> From<(&'a Pubkey, bool, &'a mut Account)> for AccountInfo<'a> { fn from((key, is_signer, account): (&'a Pubkey, bool, &'a mut Account)) -> Self { Self::new( key, is_signer, &mut account.lamports, &mut account.data, &account.owner, ) } } impl<'a> From<&'a mut (Pubkey, Account)> for AccountInfo<'a> { fn from((key, account): &'a mut (Pubkey, Account)) -> Self { Self::new( key, false, &mut account.lamports, &mut account.data, &account.owner, ) } } pub fn create_account_infos(accounts: &mut [(Pubkey, Account)]) -> Vec<AccountInfo> { accounts.iter_mut().map(Into::into).collect() } pub fn create_is_signer_account_infos<'a>( accounts: &'a mut [(&'a Pubkey, bool, &'a mut Account)], ) -> Vec<AccountInfo<'a>> { accounts .iter_mut() .map(|(key, is_signer, account)| { AccountInfo::new( key, *is_signer, &mut account.lamports, &mut account.data, &account.owner, ) }) .collect() }
27.526316
100
0.528872
623a32c0accbd25143a5375f621ef99f20e12650
2,168
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Data structures to operate on contract memory during contract execution. //! //! These definitions are useful since we are operating in a `no_std` environment //! and should be used by all ink! crates instead of directly using `std` or `alloc` //! crates. If needed we shall instead enhance the exposed types here. //! //! The `ink_prelude` crate guarantees a stable interface between `std` and `no_std` mode. #![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] extern crate alloc; use cfg_if::cfg_if; cfg_if! { if #[cfg(feature = "std")] { pub use std::{ borrow, boxed, format, string, vec, }; /// Collection types. pub mod collections { pub use self::{ binary_heap::BinaryHeap, btree_map::BTreeMap, btree_set::BTreeSet, linked_list::LinkedList, vec_deque::VecDeque, Bound, }; pub use std::collections::*; } } else { pub use alloc::{ borrow, boxed, format, string, vec, }; /// Collection types. pub mod collections { pub use self::{ BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque, }; pub use alloc::collections::*; pub use core::ops::Bound; } } }
28.906667
90
0.563653
bf3670a3c8c4439ed967a636c57aff8022cceb50
7,791
//! Serialize a Rust data structure into JSON data. use std::io; use serde_json::error::Result; use serde::ser::Serialize; pub use serde_json::ser::Formatter; /// A structure for serializing Rust values into JSON. #[allow(non_snake_case)] pub mod Serializer { use super::{io, Formatter, CompactV8Formatter, PrettyV8Formatter}; /// Creates a new JSON serializer. #[inline] pub fn new<W>(writer: W) -> serde_json::ser::Serializer<W, CompactV8Formatter> where W: io::Write, { with_formatter(writer, CompactV8Formatter) } /// Creates a new JSON pretty print serializer. #[inline] pub fn pretty<'a, W>(writer: W) -> serde_json::ser::Serializer<W, PrettyV8Formatter<'a>> where W: io::Write, { with_formatter(writer, PrettyV8Formatter::new()) } /// Creates a new JSON visitor whose output will be written to the writer /// specified. #[inline] pub fn with_formatter<W, F>(writer: W, formatter: F) -> serde_json::ser::Serializer<W, F> where W: io::Write, F: Formatter, { serde_json::ser::Serializer::with_formatter(writer, formatter) } } /// This structure compacts a JSON value with no extra whitespace. #[derive(Clone, Debug)] pub struct CompactV8Formatter; impl Formatter for CompactV8Formatter { #[inline] fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> io::Result<()> where W: io::Write, { let mut buffer = ryu_js::Buffer::new(); let s = buffer.format(f64::from(value)); writer.write_all(s.as_bytes()) } #[inline] fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> io::Result<()> where W: io::Write, { let mut buffer = ryu_js::Buffer::new(); let s = buffer.format(value); writer.write_all(s.as_bytes()) } } /// This structure pretty prints a JSON value to make it human readable. #[derive(Clone, Debug)] pub struct PrettyV8Formatter<'a> { inner: serde_json::ser::PrettyFormatter<'a> } impl<'a> PrettyV8Formatter<'a> { /// Construct a pretty printer formatter that defaults to using two spaces for indentation. pub fn new() -> Self { PrettyV8Formatter { inner: serde_json::ser::PrettyFormatter::new() } } /// Construct a pretty printer formatter that uses the `indent` string for indentation. pub fn with_indent(indent: &'a [u8]) -> Self { PrettyV8Formatter { inner: serde_json::ser::PrettyFormatter::with_indent(indent) } } } impl<'a> Default for PrettyV8Formatter<'a> { fn default() -> Self { PrettyV8Formatter::new() } } impl<'a> Formatter for PrettyV8Formatter<'a> { #[inline] fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> io::Result<()> where W: io::Write, { let mut buffer = ryu_js::Buffer::new(); let s = buffer.format(f64::from(value)); writer.write_all(s.as_bytes()) } #[inline] fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> io::Result<()> where W: io::Write, { let mut buffer = ryu_js::Buffer::new(); let s = buffer.format(value); writer.write_all(s.as_bytes()) } #[inline] fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: io::Write, { self.inner.begin_array(writer) } #[inline] fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: io::Write, { self.inner.end_array(writer) } #[inline] fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> where W: io::Write, { self.inner.begin_array_value(writer, first) } #[inline] fn end_array_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: io::Write, { self.inner.end_array_value(writer) } #[inline] fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: io::Write, { self.inner.begin_object(writer) } #[inline] fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: io::Write, { self.inner.end_object(writer) } #[inline] fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> where W: io::Write, { self.inner.begin_object_key(writer, first) } #[inline] fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: io::Write, { self.inner.begin_object_value(writer) } #[inline] fn end_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: io::Write, { self.inner.end_object_value(writer) } } /// Serialize the given data structure as JSON into the IO stream. /// /// # Errors /// /// Serialization can fail if `T`'s implementation of `Serialize` decides to /// fail, or if `T` contains a map with non-string keys. #[inline] pub fn to_writer<W, T: ?Sized>(writer: W, value: &T) -> Result<()> where W: io::Write, T: Serialize, { let mut ser = Serializer::new(writer); try!(value.serialize(&mut ser)); Ok(()) } /// Serialize the given data structure as pretty-printed JSON into the IO /// stream. /// /// # Errors /// /// Serialization can fail if `T`'s implementation of `Serialize` decides to /// fail, or if `T` contains a map with non-string keys. #[inline] pub fn to_writer_pretty<W, T: ?Sized>(writer: W, value: &T) -> Result<()> where W: io::Write, T: Serialize, { let mut ser = Serializer::pretty(writer); try!(value.serialize(&mut ser)); Ok(()) } /// Serialize the given data structure as a JSON byte vector. /// /// # Errors /// /// Serialization can fail if `T`'s implementation of `Serialize` decides to /// fail, or if `T` contains a map with non-string keys. #[inline] pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>> where T: Serialize, { let mut writer = Vec::with_capacity(128); try!(to_writer(&mut writer, value)); Ok(writer) } /// Serialize the given data structure as a pretty-printed JSON byte vector. /// /// # Errors /// /// Serialization can fail if `T`'s implementation of `Serialize` decides to /// fail, or if `T` contains a map with non-string keys. #[inline] pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>> where T: Serialize, { let mut writer = Vec::with_capacity(128); try!(to_writer_pretty(&mut writer, value)); Ok(writer) } /// Serialize the given data structure as a String of JSON. /// /// # Errors /// /// Serialization can fail if `T`'s implementation of `Serialize` decides to /// fail, or if `T` contains a map with non-string keys. #[inline] pub fn to_string<T: ?Sized>(value: &T) -> Result<String> where T: Serialize, { let vec = try!(to_vec(value)); let string = unsafe { // We do not emit invalid UTF-8. String::from_utf8_unchecked(vec) }; Ok(string) } /// Serialize the given data structure as a pretty-printed String of JSON. /// /// # Errors /// /// Serialization can fail if `T`'s implementation of `Serialize` decides to /// fail, or if `T` contains a map with non-string keys. #[inline] pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String> where T: Serialize, { let vec = try!(to_vec_pretty(value)); let string = unsafe { // We do not emit invalid UTF-8. String::from_utf8_unchecked(vec) }; Ok(string) }
26.056856
95
0.599025
8ff5a8e9e65be4c52f7cd5c13ab53822796c454c
20,458
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: 5/12/2017 Last Modified: 12/10/2018 License: MIT Notes: The 3D space-filling nature of point clouds under heavy forest cover do not lend themselves to useful estimation of point normal vectors. As such, this tool will not work satisfactory under dense forest cover. Tree cover should first be removed using the LidarGroundPointRemoval or similar tool. */ use self::na::Vector3; use self::rand::Rng; use crate::lidar::*; use crate::na; use crate::structures::{DistanceMetric, FixedRadiusSearch3D}; use crate::tools::*; use num_cpus; use rand; use std::cmp; use std::env; use std::f64; use std::f64::NEG_INFINITY; use std::io::{Error, ErrorKind}; use std::path; use std::sync::mpsc; use std::sync::Arc; use std::thread; /// Segments a LiDAR point cloud based on normal vectors. pub struct LidarSegmentation { name: String, description: String, toolbox: String, parameters: Vec<ToolParameter>, example_usage: String, } impl LidarSegmentation { pub fn new() -> LidarSegmentation { // public constructor let name = "LidarSegmentation".to_string(); let toolbox = "LiDAR Tools".to_string(); let description = "Segments a LiDAR point cloud based on normal vectors.".to_string(); let mut parameters = vec![]; parameters.push(ToolParameter { name: "Input LiDAR File".to_owned(), flags: vec!["-i".to_owned(), "--input".to_owned()], description: "Input LiDAR file.".to_owned(), parameter_type: ParameterType::ExistingFile(ParameterFileType::Lidar), default_value: None, optional: false, }); parameters.push(ToolParameter { name: "Output File".to_owned(), flags: vec!["-o".to_owned(), "--output".to_owned()], description: "Output file.".to_owned(), parameter_type: ParameterType::NewFile(ParameterFileType::Lidar), default_value: None, optional: false, }); parameters.push(ToolParameter { name: "Search Radius".to_owned(), flags: vec!["--dist".to_owned(), "--radius".to_owned()], description: "Search Radius.".to_owned(), parameter_type: ParameterType::Float, default_value: Some("5.0".to_owned()), optional: false, }); parameters.push(ToolParameter { name: "Normal Difference Threshold".to_owned(), flags: vec!["--norm_diff".to_owned()], description: "Maximum difference in normal vectors, in degrees.".to_owned(), parameter_type: ParameterType::Float, default_value: Some("10.0".to_owned()), optional: false, }); parameters.push(ToolParameter{ name: "Maximum Elevation Difference Between Points".to_owned(), flags: vec!["--maxzdiff".to_owned()], description: "Maximum difference in elevation (z units) between neighbouring points of the same segment.".to_owned(), parameter_type: ParameterType::Float, default_value: Some("1.0".to_owned()), optional: false }); let sep: String = path::MAIN_SEPARATOR.to_string(); let p = format!("{}", env::current_dir().unwrap().display()); let e = format!("{}", env::current_exe().unwrap().display()); let mut short_exe = e .replace(&p, "") .replace(".exe", "") .replace(".", "") .replace(&sep, ""); if e.contains(".exe") { short_exe += ".exe"; } let usage = format!(">>.*{0} -r={1} -v --wd=\"*path*to*data*\" -i=\"input.las\" -o=\"output.las\" --radius=10.0 --norm_diff=2.5 --maxzdiff=0.75", short_exe, name).replace("*", &sep); LidarSegmentation { name: name, description: description, toolbox: toolbox, parameters: parameters, example_usage: usage, } } } impl WhiteboxTool for LidarSegmentation { fn get_source_file(&self) -> String { String::from(file!()) } fn get_tool_name(&self) -> String { self.name.clone() } fn get_tool_description(&self) -> String { self.description.clone() } fn get_tool_parameters(&self) -> String { let mut s = String::from("{\"parameters\": ["); for i in 0..self.parameters.len() { if i < self.parameters.len() - 1 { s.push_str(&(self.parameters[i].to_string())); s.push_str(","); } else { s.push_str(&(self.parameters[i].to_string())); } } s.push_str("]}"); s } fn get_example_usage(&self) -> String { self.example_usage.clone() } fn get_toolbox(&self) -> String { self.toolbox.clone() } fn run<'a>( &self, args: Vec<String>, working_directory: &'a str, verbose: bool, ) -> Result<(), Error> { let mut input_file: String = "".to_string(); let mut output_file: String = "".to_string(); let mut search_radius = 5f64; let mut max_norm_diff = 2f64; let mut max_z_diff = 1f64; // read the arguments if args.len() == 0 { return Err(Error::new( ErrorKind::InvalidInput, "Tool run with no paramters.", )); } for i in 0..args.len() { let mut arg = args[i].replace("\"", ""); arg = arg.replace("\'", ""); let cmd = arg.split("="); // in case an equals sign was used let vec = cmd.collect::<Vec<&str>>(); let mut keyval = false; if vec.len() > 1 { keyval = true; } let flag_val = vec[0].to_lowercase().replace("--", "-"); if flag_val == "-i" || flag_val == "-input" { if keyval { input_file = vec[1].to_string(); } else { input_file = args[i + 1].to_string(); } } else if flag_val == "-o" || flag_val == "-output" { if keyval { output_file = vec[1].to_string(); } else { output_file = args[i + 1].to_string(); } } else if flag_val == "-dist" || flag_val == "-radius" { if keyval { search_radius = vec[1].to_string().parse::<f64>().unwrap(); } else { search_radius = args[i + 1].to_string().parse::<f64>().unwrap(); } } else if flag_val == "-norm_diff" { if keyval { max_norm_diff = vec[1].to_string().parse::<f64>().unwrap(); } else { max_norm_diff = args[i + 1].to_string().parse::<f64>().unwrap(); } } else if flag_val == "-maxzdiff" { if keyval { max_z_diff = vec[1].to_string().parse::<f64>().unwrap(); } else { max_z_diff = args[i + 1].to_string().parse::<f64>().unwrap(); } } } if verbose { println!("***************{}", "*".repeat(self.get_tool_name().len())); println!("* Welcome to {} *", self.get_tool_name()); println!("***************{}", "*".repeat(self.get_tool_name().len())); } let sep = path::MAIN_SEPARATOR; if !input_file.contains(sep) && !input_file.contains("/") { input_file = format!("{}{}", working_directory, input_file); } if !output_file.contains(sep) && !output_file.contains("/") { output_file = format!("{}{}", working_directory, output_file); } if verbose { println!("Reading input LAS file..."); } let input = match LasFile::new(&input_file, "r") { Ok(lf) => lf, Err(err) => panic!("Error reading file {}: {}", input_file, err), }; let n_points = input.header.number_of_points as usize; let num_points = n_points as f64; let start = Instant::now(); if max_norm_diff < 0f64 { max_norm_diff = 0f64; } if max_norm_diff > 90f64 { max_norm_diff = 90f64; } max_norm_diff = max_norm_diff.to_radians(); let mut progress: i32; let mut old_progress: i32 = -1; let num_procs = num_cpus::get(); let input = Arc::new(input); // wrap input in an Arc ///////////////////////////////////////////////////////// // Calculate the normals for each point in the dataset // ///////////////////////////////////////////////////////// if verbose { println!("Calculating point normals..."); } let mut frs3d: FixedRadiusSearch3D<usize> = FixedRadiusSearch3D::new(search_radius, DistanceMetric::SquaredEuclidean); for point_num in 0..n_points { let p: PointData = input.get_point_info(point_num); frs3d.insert(p.x, p.y, p.z, point_num); if verbose { progress = (100.0_f64 * point_num as f64 / num_points) as i32; if progress != old_progress { println!("Binning points in 3D: {}%", progress); old_progress = progress; } } } let frs = Arc::new(frs3d); // wrap FRS in an Arc let (tx, rx) = mpsc::channel(); for tid in 0..num_procs { let frs = frs.clone(); let input = input.clone(); let tx = tx.clone(); thread::spawn(move || { let mut index_n: usize; let mut height_diff: f64; for point_num in (0..n_points).filter(|point_num| point_num % num_procs == tid) { let p: PointData = input.get_point_info(point_num); let ret = frs.search(p.x, p.y, p.z); let mut data: Vec<Vector3<f64>> = Vec::with_capacity(ret.len()); for j in 0..ret.len() { index_n = ret[j].0; let pn: PointData = input.get_point_info(index_n); height_diff = (pn.z - p.z).abs(); if height_diff < max_z_diff { data.push(Vector3::new(pn.x, pn.y, pn.z)); } } tx.send((point_num, plane_from_points(&data))).unwrap(); } }); } let mut normal_vectors = vec![Normal::new(); n_points]; for point_num in 0..n_points { let data = rx.recv().unwrap(); normal_vectors[data.0] = data.1; if verbose { progress = (100.0_f64 * point_num as f64 / num_points) as i32; if progress != old_progress { println!("Calculating point normals: {}%", progress); old_progress = progress; } } } //////////////////////////////////////// // Perform the segmentation operation // //////////////////////////////////////// if verbose { println!("Segmenting the point cloud..."); } let mut segment_id = vec![0usize; n_points]; let mut current_segment = 0usize; let mut point_id: usize; let mut norm_diff: f64; let mut height_diff: f64; let mut index_n: usize; let mut solved_points = 0; let mut stack = vec![]; let mut last_seed = 0; while solved_points < n_points { // Find a seed-point for a segment for i in last_seed..n_points { if segment_id[i] == 0 { // No segment ID has yet been assigned to this point. current_segment += 1; segment_id[i] = current_segment; stack.push(i); last_seed = i; break; } } while !stack.is_empty() { solved_points += 1; if verbose { progress = (100f64 * solved_points as f64 / num_points) as i32; if progress != old_progress { println!("Segmenting the point cloud: {}%", progress); old_progress = progress; } } point_id = stack.pop().unwrap(); /* Check the neighbours to see if there are any points that have similar normal vectors and heights. */ let p: PointData = input.get_point_info(point_id); let ret = frs.search(p.x, p.y, p.z); for j in 0..ret.len() { index_n = ret[j].0; if segment_id[index_n] == 0 { // It hasn't already been placed in a segment. let pn: PointData = input.get_point_info(index_n); // Calculate height difference. height_diff = (pn.z - p.z).abs(); if height_diff < max_z_diff { // Check the difference in normal vectors. norm_diff = normal_vectors[point_id].angle_between(normal_vectors[index_n]); if norm_diff < max_norm_diff { // This neighbour is part of the ground. segment_id[index_n] = current_segment; stack.push(index_n); } } } } } } ///////////////////// // Output the data // ///////////////////// let mut clrs: Vec<(u16, u16, u16)> = Vec::new(); let mut rng = rand::thread_rng(); let (mut r, mut g, mut b): (u16, u16, u16) = (0u16, 0u16, 0u16); for _ in 0..current_segment + 1 as usize { let mut flag = false; while !flag { r = rng.gen::<u8>() as u16 * 256u16; g = rng.gen::<u8>() as u16 * 256u16; b = rng.gen::<u8>() as u16 * 256u16; let max_val = cmp::max(cmp::max(r, g), b); //let min_val = cmp::min(cmp::min(r, g), b); if max_val >= u16::max_value() / 2 { // && min_val >= u16::max_value() / 4 { flag = true; } } clrs.push((r, g, b)); } let mut output = LasFile::initialize_using_file(&output_file, &input); output.header.point_format = 2; for point_num in 0..n_points { let p: PointData = input[point_num]; let seg_val = segment_id[point_num]; let rgb: ColourData = ColourData { red: clrs[seg_val].0, green: clrs[seg_val].1, blue: clrs[seg_val].2, nir: 0u16, }; let lpr: LidarPointRecord = LidarPointRecord::PointRecord2 { point_data: p, colour_data: rgb, }; output.add_point_record(lpr); if verbose { progress = (100.0_f64 * point_num as f64 / num_points) as i32; if progress != old_progress { println!("Saving data: {}%", progress); old_progress = progress; } } } // let (mut r, mut g, mut b): (u16, u16, u16); // for i in 0..n_points { // let p: PointData = input.get_point_info(i); // r = ((1.0 + normal_values[i].x) / 2.0 * 255.0) as u16 * 256u16; //((1.0 + normal_values[i].x) / 2.0 * 65535.0) as u16; // g = ((1.0 + normal_values[i].y) / 2.0 * 255.0) as u16 * 256u16; //((1.0 + normal_values[i].y) / 2.0 * 65535.0) as u16; // b = ((1.0 + normal_values[i].z) / 2.0 * 255.0) as u16 * 256u16; //((1.0 + normal_values[i].z) / 2.0 * 65535.0) as u16; // let rgb: RgbData = RgbData{ red: r, green: g, blue: b }; // let lpr = LidarPointRecord::PointRecord2 { point_data: p, rgb_data: rgb }; // output.add_point_record(lpr); // if verbose { // progress = (100.0_f64 * i as f64 / num_points) as i32; // if progress != old_progress { // println!("Saving data: {}%", progress); // old_progress = progress; // } // } // } let elapsed_time = get_formatted_elapsed_time(start); println!(""); if verbose { println!("Writing output LAS file..."); } let _ = match output.write() { Ok(_) => println!("Complete!"), Err(e) => println!("error while writing: {:?}", e), }; if verbose { println!( "{}", &format!("Elapsed Time (excluding I/O): {}", elapsed_time) ); } Ok(()) } } #[derive(Clone, Copy, Debug)] struct Normal { a: f64, b: f64, c: f64, } impl Normal { fn new() -> Normal { // angle_between won't work with perfectly flat normals so add a small delta. Normal { a: 0.0000001, b: 0f64, c: 0f64, } } // fn from_vector3(v: Vector3<f64>) -> Normal { // if v.x == 0f64 && v.y == 0f64 && v.z == 0f64 { // return Normal { a: 0.0000001, b: 0f64, c: 0f64}; // // angle_between won't work with perfectly flat normals so add a small delta. // } // Normal { a: v.x, b: v.y, c: v.z } // } fn angle_between(self, other: Normal) -> f64 { let numerator = self.a * other.a + self.b * other.b + self.c * other.c; let denom1 = (self.a * self.a + self.b * self.b + self.c * self.c).sqrt(); let denom2 = (other.a * other.a + other.b * other.b + other.c * other.c).sqrt(); if denom1 * denom2 != 0f64 { return (numerator / (denom1 * denom2)).acos(); } NEG_INFINITY } } // Constructs a plane from a collection of points // so that the summed squared distance to all points is minimzized #[inline] fn plane_from_points(points: &Vec<Vector3<f64>>) -> Normal { let n = points.len(); // assert!(n >= 3, "At least three points required"); if n < 3 { return Normal { a: 0f64, b: 0f64, c: 0f64, }; } let mut sum = Vector3::new(0.0, 0.0, 0.0); for p in points { sum = sum + *p; } let centroid = sum * (1.0 / (n as f64)); // Calc full 3x3 covariance matrix, excluding symmetries: let mut xx = 0.0; let mut xy = 0.0; let mut xz = 0.0; let mut yy = 0.0; let mut yz = 0.0; let mut zz = 0.0; for p in points { let r = p - &centroid; xx += r.x * r.x; xy += r.x * r.y; xz += r.x * r.z; yy += r.y * r.y; yz += r.y * r.z; zz += r.z * r.z; } let det_x = yy * zz - yz * yz; let det_y = xx * zz - xz * xz; let det_z = xx * yy - xy * xy; let det_max = det_x.max(det_y).max(det_z); // Pick path with best conditioning: let dir = if det_max == det_x { let a = (xz * yz - xy * zz) / det_x; let b = (xy * yz - xz * yy) / det_x; Vector3::new(1.0, a, b) } else if det_max == det_y { let a = (yz * xz - xy * zz) / det_y; let b = (xy * xz - yz * xx) / det_y; Vector3::new(a, 1.0, b) } else { let a = (yz * xy - xz * yy) / det_z; let b = (xz * xy - yz * xx) / det_z; Vector3::new(a, b, 1.0) }; normalize(dir) } #[inline] fn normalize(v: Vector3<f64>) -> Normal { let norm = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt(); Normal { a: v.x / norm, b: v.y / norm, c: v.z / norm, } }
35.828371
190
0.479372
2f5f41da62c3a326897a5ed98dd2dca7acfb15c5
2,353
// Copyright 2020-2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use identity::core::decode_b58; use identity::core::encode_b58; use identity::crypto::KeyPair as KeyPair_; use identity::crypto::PrivateKey; use identity::crypto::PublicKey; use wasm_bindgen::prelude::*; use crate::crypto::KeyType; use crate::error::wasm_error; #[derive(Deserialize, Serialize)] struct JsonData { #[serde(rename = "type")] type_: KeyType, public: String, private: String, } // ============================================================================= // ============================================================================= #[wasm_bindgen(inspectable)] #[derive(Clone, Debug)] pub struct KeyPair(pub(crate) KeyPair_); #[wasm_bindgen] impl KeyPair { /// Generates a new `KeyPair` object. #[wasm_bindgen(constructor)] pub fn new(type_: KeyType) -> Result<KeyPair, JsValue> { KeyPair_::new(type_.into()).map_err(wasm_error).map(Self) } /// Parses a `KeyPair` object from base58-encoded public/private keys. #[wasm_bindgen(js_name = fromBase58)] pub fn from_base58(type_: KeyType, public_key: &str, private_key: &str) -> Result<KeyPair, JsValue> { let public: PublicKey = decode_b58(public_key).map_err(wasm_error)?.into(); let private: PrivateKey = decode_b58(private_key).map_err(wasm_error)?.into(); Ok(Self((type_.into(), public, private).into())) } /// Returns the public key as a base58-encoded string. #[wasm_bindgen(getter)] pub fn public(&self) -> String { encode_b58(self.0.public()) } /// Returns the private key as a base58-encoded string. #[wasm_bindgen(getter)] pub fn private(&self) -> String { encode_b58(self.0.private()) } /// Serializes a `KeyPair` object as a JSON object. #[wasm_bindgen(js_name = toJSON)] pub fn to_json(&self) -> Result<JsValue, JsValue> { let data: JsonData = JsonData { type_: self.0.type_().into(), public: self.public(), private: self.private(), }; JsValue::from_serde(&data).map_err(wasm_error) } /// Deserializes a `KeyPair` object from a JSON object. #[wasm_bindgen(js_name = fromJSON)] pub fn from_json(json: &JsValue) -> Result<KeyPair, JsValue> { let data: JsonData = json.into_serde().map_err(wasm_error)?; Self::from_base58(data.type_, &data.public, &data.private) } }
30.166667
103
0.642584
1eb156cedb5347ecbc9783b1fe1447c083e8f59d
550
pub enum Opcode { Add, Sub, Mul, Div, } pub enum Expr { Num(i32), Op(Box<Expr>, Opcode, Box<Expr>), Paren(Box<Expr>), } pub fn calc(e: Expr) -> i32 { match e { Expr::Num(i) => i, Expr::Op(left, op, right) => match op { Opcode::Add => calc(*left) + calc(*right), Opcode::Sub => calc(*left) - calc(*right), Opcode::Mul => calc(*left) * calc(*right), Opcode::Div => calc(*left) / calc(*right), }, Expr::Paren(expr) => calc(*expr), } }
21.153846
54
0.467273
5d2b791535d14e832c1a7f7ec7c16f9f09fe38e0
42,262
#[doc = "Reader of register PADREGG"] pub type R = crate::R<u32, super::PADREGG>; #[doc = "Writer for register PADREGG"] pub type W = crate::W<u32, super::PADREGG>; #[doc = "Register PADREGG `reset()`'s with value 0x1818_1818"] impl crate::ResetValue for super::PADREGG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x1818_1818 } } #[doc = "Pad 27 function select\n\nValue on reset: 3"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PAD27FNCSEL_A { #[doc = "0: Configure as the external HFRC clock signal"] EXTHF = 0, #[doc = "1: Configure as the SPI channel 4 nCE signal from IOMSTR1"] M1NCE4 = 1, #[doc = "2: Configure as the input/output signal from CTIMER A1"] TCTA1 = 2, #[doc = "3: Configure as GPIO27"] GPIO27 = 3, } impl From<PAD27FNCSEL_A> for u8 { #[inline(always)] fn from(variant: PAD27FNCSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `PAD27FNCSEL`"] pub type PAD27FNCSEL_R = crate::R<u8, PAD27FNCSEL_A>; impl PAD27FNCSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD27FNCSEL_A { match self.bits { 0 => PAD27FNCSEL_A::EXTHF, 1 => PAD27FNCSEL_A::M1NCE4, 2 => PAD27FNCSEL_A::TCTA1, 3 => PAD27FNCSEL_A::GPIO27, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EXTHF`"] #[inline(always)] pub fn is_exthf(&self) -> bool { *self == PAD27FNCSEL_A::EXTHF } #[doc = "Checks if the value of the field is `M1NCE4`"] #[inline(always)] pub fn is_m1n_ce4(&self) -> bool { *self == PAD27FNCSEL_A::M1NCE4 } #[doc = "Checks if the value of the field is `TCTA1`"] #[inline(always)] pub fn is_tcta1(&self) -> bool { *self == PAD27FNCSEL_A::TCTA1 } #[doc = "Checks if the value of the field is `GPIO27`"] #[inline(always)] pub fn is_gpio27(&self) -> bool { *self == PAD27FNCSEL_A::GPIO27 } } #[doc = "Write proxy for field `PAD27FNCSEL`"] pub struct PAD27FNCSEL_W<'a> { w: &'a mut W, } impl<'a> PAD27FNCSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD27FNCSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Configure as the external HFRC clock signal"] #[inline(always)] pub fn exthf(self) -> &'a mut W { self.variant(PAD27FNCSEL_A::EXTHF) } #[doc = "Configure as the SPI channel 4 nCE signal from IOMSTR1"] #[inline(always)] pub fn m1n_ce4(self) -> &'a mut W { self.variant(PAD27FNCSEL_A::M1NCE4) } #[doc = "Configure as the input/output signal from CTIMER A1"] #[inline(always)] pub fn tcta1(self) -> &'a mut W { self.variant(PAD27FNCSEL_A::TCTA1) } #[doc = "Configure as GPIO27"] #[inline(always)] pub fn gpio27(self) -> &'a mut W { self.variant(PAD27FNCSEL_A::GPIO27) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 27)) | (((value as u32) & 0x03) << 27); self.w } } #[doc = "Pad 27 drive strentgh\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD27STRNG_A { #[doc = "0: Low drive strength"] LOW = 0, #[doc = "1: High drive strength"] HIGH = 1, } impl From<PAD27STRNG_A> for bool { #[inline(always)] fn from(variant: PAD27STRNG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD27STRNG`"] pub type PAD27STRNG_R = crate::R<bool, PAD27STRNG_A>; impl PAD27STRNG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD27STRNG_A { match self.bits { false => PAD27STRNG_A::LOW, true => PAD27STRNG_A::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline(always)] pub fn is_low(&self) -> bool { *self == PAD27STRNG_A::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline(always)] pub fn is_high(&self) -> bool { *self == PAD27STRNG_A::HIGH } } #[doc = "Write proxy for field `PAD27STRNG`"] pub struct PAD27STRNG_W<'a> { w: &'a mut W, } impl<'a> PAD27STRNG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD27STRNG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Low drive strength"] #[inline(always)] pub fn low(self) -> &'a mut W { self.variant(PAD27STRNG_A::LOW) } #[doc = "High drive strength"] #[inline(always)] pub fn high(self) -> &'a mut W { self.variant(PAD27STRNG_A::HIGH) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Pad 27 input enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD27INPEN_A { #[doc = "0: Pad input disabled"] DIS = 0, #[doc = "1: Pad input enabled"] EN = 1, } impl From<PAD27INPEN_A> for bool { #[inline(always)] fn from(variant: PAD27INPEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD27INPEN`"] pub type PAD27INPEN_R = crate::R<bool, PAD27INPEN_A>; impl PAD27INPEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD27INPEN_A { match self.bits { false => PAD27INPEN_A::DIS, true => PAD27INPEN_A::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD27INPEN_A::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline(always)] pub fn is_en(&self) -> bool { *self == PAD27INPEN_A::EN } } #[doc = "Write proxy for field `PAD27INPEN`"] pub struct PAD27INPEN_W<'a> { w: &'a mut W, } impl<'a> PAD27INPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD27INPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pad input disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD27INPEN_A::DIS) } #[doc = "Pad input enabled"] #[inline(always)] pub fn en(self) -> &'a mut W { self.variant(PAD27INPEN_A::EN) } #[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 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Pad 27 pullup enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD27PULL_A { #[doc = "0: Pullup disabled"] DIS = 0, #[doc = "1: Pullup enabled"] EN = 1, } impl From<PAD27PULL_A> for bool { #[inline(always)] fn from(variant: PAD27PULL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD27PULL`"] pub type PAD27PULL_R = crate::R<bool, PAD27PULL_A>; impl PAD27PULL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD27PULL_A { match self.bits { false => PAD27PULL_A::DIS, true => PAD27PULL_A::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD27PULL_A::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline(always)] pub fn is_en(&self) -> bool { *self == PAD27PULL_A::EN } } #[doc = "Write proxy for field `PAD27PULL`"] pub struct PAD27PULL_W<'a> { w: &'a mut W, } impl<'a> PAD27PULL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD27PULL_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pullup disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD27PULL_A::DIS) } #[doc = "Pullup enabled"] #[inline(always)] pub fn en(self) -> &'a mut W { self.variant(PAD27PULL_A::EN) } #[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 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Pad 26 function select\n\nValue on reset: 3"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PAD26FNCSEL_A { #[doc = "0: Configure as the external LFRC clock signal"] EXTLF = 0, #[doc = "1: Configure as the SPI channel 3 nCE signal from IOMSTR0"] M0NCE3 = 1, #[doc = "2: Configure as the input/output signal from CTIMER B0"] TCTB0 = 2, #[doc = "3: Configure as GPIO26"] GPIO26 = 3, } impl From<PAD26FNCSEL_A> for u8 { #[inline(always)] fn from(variant: PAD26FNCSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `PAD26FNCSEL`"] pub type PAD26FNCSEL_R = crate::R<u8, PAD26FNCSEL_A>; impl PAD26FNCSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD26FNCSEL_A { match self.bits { 0 => PAD26FNCSEL_A::EXTLF, 1 => PAD26FNCSEL_A::M0NCE3, 2 => PAD26FNCSEL_A::TCTB0, 3 => PAD26FNCSEL_A::GPIO26, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EXTLF`"] #[inline(always)] pub fn is_extlf(&self) -> bool { *self == PAD26FNCSEL_A::EXTLF } #[doc = "Checks if the value of the field is `M0NCE3`"] #[inline(always)] pub fn is_m0n_ce3(&self) -> bool { *self == PAD26FNCSEL_A::M0NCE3 } #[doc = "Checks if the value of the field is `TCTB0`"] #[inline(always)] pub fn is_tctb0(&self) -> bool { *self == PAD26FNCSEL_A::TCTB0 } #[doc = "Checks if the value of the field is `GPIO26`"] #[inline(always)] pub fn is_gpio26(&self) -> bool { *self == PAD26FNCSEL_A::GPIO26 } } #[doc = "Write proxy for field `PAD26FNCSEL`"] pub struct PAD26FNCSEL_W<'a> { w: &'a mut W, } impl<'a> PAD26FNCSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD26FNCSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Configure as the external LFRC clock signal"] #[inline(always)] pub fn extlf(self) -> &'a mut W { self.variant(PAD26FNCSEL_A::EXTLF) } #[doc = "Configure as the SPI channel 3 nCE signal from IOMSTR0"] #[inline(always)] pub fn m0n_ce3(self) -> &'a mut W { self.variant(PAD26FNCSEL_A::M0NCE3) } #[doc = "Configure as the input/output signal from CTIMER B0"] #[inline(always)] pub fn tctb0(self) -> &'a mut W { self.variant(PAD26FNCSEL_A::TCTB0) } #[doc = "Configure as GPIO26"] #[inline(always)] pub fn gpio26(self) -> &'a mut W { self.variant(PAD26FNCSEL_A::GPIO26) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 19)) | (((value as u32) & 0x03) << 19); self.w } } #[doc = "Pad 26 drive strength\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD26STRNG_A { #[doc = "0: Low drive strength"] LOW = 0, #[doc = "1: High drive strength"] HIGH = 1, } impl From<PAD26STRNG_A> for bool { #[inline(always)] fn from(variant: PAD26STRNG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD26STRNG`"] pub type PAD26STRNG_R = crate::R<bool, PAD26STRNG_A>; impl PAD26STRNG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD26STRNG_A { match self.bits { false => PAD26STRNG_A::LOW, true => PAD26STRNG_A::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline(always)] pub fn is_low(&self) -> bool { *self == PAD26STRNG_A::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline(always)] pub fn is_high(&self) -> bool { *self == PAD26STRNG_A::HIGH } } #[doc = "Write proxy for field `PAD26STRNG`"] pub struct PAD26STRNG_W<'a> { w: &'a mut W, } impl<'a> PAD26STRNG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD26STRNG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Low drive strength"] #[inline(always)] pub fn low(self) -> &'a mut W { self.variant(PAD26STRNG_A::LOW) } #[doc = "High drive strength"] #[inline(always)] pub fn high(self) -> &'a mut W { self.variant(PAD26STRNG_A::HIGH) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Pad 26 input enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD26INPEN_A { #[doc = "0: Pad input disabled"] DIS = 0, #[doc = "1: Pad input enabled"] EN = 1, } impl From<PAD26INPEN_A> for bool { #[inline(always)] fn from(variant: PAD26INPEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD26INPEN`"] pub type PAD26INPEN_R = crate::R<bool, PAD26INPEN_A>; impl PAD26INPEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD26INPEN_A { match self.bits { false => PAD26INPEN_A::DIS, true => PAD26INPEN_A::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD26INPEN_A::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline(always)] pub fn is_en(&self) -> bool { *self == PAD26INPEN_A::EN } } #[doc = "Write proxy for field `PAD26INPEN`"] pub struct PAD26INPEN_W<'a> { w: &'a mut W, } impl<'a> PAD26INPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD26INPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pad input disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD26INPEN_A::DIS) } #[doc = "Pad input enabled"] #[inline(always)] pub fn en(self) -> &'a mut W { self.variant(PAD26INPEN_A::EN) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Pad 26 pullup enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD26PULL_A { #[doc = "0: Pullup disabled"] DIS = 0, #[doc = "1: Pullup enabled"] EN = 1, } impl From<PAD26PULL_A> for bool { #[inline(always)] fn from(variant: PAD26PULL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD26PULL`"] pub type PAD26PULL_R = crate::R<bool, PAD26PULL_A>; impl PAD26PULL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD26PULL_A { match self.bits { false => PAD26PULL_A::DIS, true => PAD26PULL_A::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD26PULL_A::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline(always)] pub fn is_en(&self) -> bool { *self == PAD26PULL_A::EN } } #[doc = "Write proxy for field `PAD26PULL`"] pub struct PAD26PULL_W<'a> { w: &'a mut W, } impl<'a> PAD26PULL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD26PULL_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pullup disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD26PULL_A::DIS) } #[doc = "Pullup enabled"] #[inline(always)] pub fn en(self) -> &'a mut W { self.variant(PAD26PULL_A::EN) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Pad 25 function select\n\nValue on reset: 3"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PAD25FNCSEL_A { #[doc = "0: Configure as the external XT clock signal"] EXTXT = 0, #[doc = "1: Configure as the SPI channel 2 nCE signal from IOMSTR0"] M0NCE2 = 1, #[doc = "2: Configure as the input/output signal from CTIMER A0"] TCTA0 = 2, #[doc = "3: Configure as GPIO25"] GPIO25 = 3, } impl From<PAD25FNCSEL_A> for u8 { #[inline(always)] fn from(variant: PAD25FNCSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `PAD25FNCSEL`"] pub type PAD25FNCSEL_R = crate::R<u8, PAD25FNCSEL_A>; impl PAD25FNCSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD25FNCSEL_A { match self.bits { 0 => PAD25FNCSEL_A::EXTXT, 1 => PAD25FNCSEL_A::M0NCE2, 2 => PAD25FNCSEL_A::TCTA0, 3 => PAD25FNCSEL_A::GPIO25, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EXTXT`"] #[inline(always)] pub fn is_extxt(&self) -> bool { *self == PAD25FNCSEL_A::EXTXT } #[doc = "Checks if the value of the field is `M0NCE2`"] #[inline(always)] pub fn is_m0n_ce2(&self) -> bool { *self == PAD25FNCSEL_A::M0NCE2 } #[doc = "Checks if the value of the field is `TCTA0`"] #[inline(always)] pub fn is_tcta0(&self) -> bool { *self == PAD25FNCSEL_A::TCTA0 } #[doc = "Checks if the value of the field is `GPIO25`"] #[inline(always)] pub fn is_gpio25(&self) -> bool { *self == PAD25FNCSEL_A::GPIO25 } } #[doc = "Write proxy for field `PAD25FNCSEL`"] pub struct PAD25FNCSEL_W<'a> { w: &'a mut W, } impl<'a> PAD25FNCSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD25FNCSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Configure as the external XT clock signal"] #[inline(always)] pub fn extxt(self) -> &'a mut W { self.variant(PAD25FNCSEL_A::EXTXT) } #[doc = "Configure as the SPI channel 2 nCE signal from IOMSTR0"] #[inline(always)] pub fn m0n_ce2(self) -> &'a mut W { self.variant(PAD25FNCSEL_A::M0NCE2) } #[doc = "Configure as the input/output signal from CTIMER A0"] #[inline(always)] pub fn tcta0(self) -> &'a mut W { self.variant(PAD25FNCSEL_A::TCTA0) } #[doc = "Configure as GPIO25"] #[inline(always)] pub fn gpio25(self) -> &'a mut W { self.variant(PAD25FNCSEL_A::GPIO25) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 11)) | (((value as u32) & 0x03) << 11); self.w } } #[doc = "Pad 25 drive strength\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD25STRNG_A { #[doc = "0: Low drive strength"] LOW = 0, #[doc = "1: High drive strength"] HIGH = 1, } impl From<PAD25STRNG_A> for bool { #[inline(always)] fn from(variant: PAD25STRNG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD25STRNG`"] pub type PAD25STRNG_R = crate::R<bool, PAD25STRNG_A>; impl PAD25STRNG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD25STRNG_A { match self.bits { false => PAD25STRNG_A::LOW, true => PAD25STRNG_A::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline(always)] pub fn is_low(&self) -> bool { *self == PAD25STRNG_A::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline(always)] pub fn is_high(&self) -> bool { *self == PAD25STRNG_A::HIGH } } #[doc = "Write proxy for field `PAD25STRNG`"] pub struct PAD25STRNG_W<'a> { w: &'a mut W, } impl<'a> PAD25STRNG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD25STRNG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Low drive strength"] #[inline(always)] pub fn low(self) -> &'a mut W { self.variant(PAD25STRNG_A::LOW) } #[doc = "High drive strength"] #[inline(always)] pub fn high(self) -> &'a mut W { self.variant(PAD25STRNG_A::HIGH) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Pad 25 input enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD25INPEN_A { #[doc = "0: Pad input disabled"] DIS = 0, #[doc = "1: Pad input enabled"] EN = 1, } impl From<PAD25INPEN_A> for bool { #[inline(always)] fn from(variant: PAD25INPEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD25INPEN`"] pub type PAD25INPEN_R = crate::R<bool, PAD25INPEN_A>; impl PAD25INPEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD25INPEN_A { match self.bits { false => PAD25INPEN_A::DIS, true => PAD25INPEN_A::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD25INPEN_A::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline(always)] pub fn is_en(&self) -> bool { *self == PAD25INPEN_A::EN } } #[doc = "Write proxy for field `PAD25INPEN`"] pub struct PAD25INPEN_W<'a> { w: &'a mut W, } impl<'a> PAD25INPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD25INPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pad input disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD25INPEN_A::DIS) } #[doc = "Pad input enabled"] #[inline(always)] pub fn en(self) -> &'a mut W { self.variant(PAD25INPEN_A::EN) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Pad 25 pullup enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD25PULL_A { #[doc = "0: Pullup disabled"] DIS = 0, #[doc = "1: Pullup enabled"] EN = 1, } impl From<PAD25PULL_A> for bool { #[inline(always)] fn from(variant: PAD25PULL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD25PULL`"] pub type PAD25PULL_R = crate::R<bool, PAD25PULL_A>; impl PAD25PULL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD25PULL_A { match self.bits { false => PAD25PULL_A::DIS, true => PAD25PULL_A::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD25PULL_A::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline(always)] pub fn is_en(&self) -> bool { *self == PAD25PULL_A::EN } } #[doc = "Write proxy for field `PAD25PULL`"] pub struct PAD25PULL_W<'a> { w: &'a mut W, } impl<'a> PAD25PULL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD25PULL_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pullup disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD25PULL_A::DIS) } #[doc = "Pullup enabled"] #[inline(always)] pub fn en(self) -> &'a mut W { self.variant(PAD25PULL_A::EN) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Pad 24 function select\n\nValue on reset: 3"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PAD24FNCSEL_A { #[doc = "0: Pad disabled"] DIS = 0, #[doc = "1: Configure as the SPI channel 1 nCE signal from IOMSTR0"] M0NCE1 = 1, #[doc = "2: Configure as the CLKOUT signal"] CLKOUT = 2, #[doc = "3: Configure as GPIO24"] GPIO24 = 3, } impl From<PAD24FNCSEL_A> for u8 { #[inline(always)] fn from(variant: PAD24FNCSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `PAD24FNCSEL`"] pub type PAD24FNCSEL_R = crate::R<u8, PAD24FNCSEL_A>; impl PAD24FNCSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD24FNCSEL_A { match self.bits { 0 => PAD24FNCSEL_A::DIS, 1 => PAD24FNCSEL_A::M0NCE1, 2 => PAD24FNCSEL_A::CLKOUT, 3 => PAD24FNCSEL_A::GPIO24, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD24FNCSEL_A::DIS } #[doc = "Checks if the value of the field is `M0NCE1`"] #[inline(always)] pub fn is_m0n_ce1(&self) -> bool { *self == PAD24FNCSEL_A::M0NCE1 } #[doc = "Checks if the value of the field is `CLKOUT`"] #[inline(always)] pub fn is_clkout(&self) -> bool { *self == PAD24FNCSEL_A::CLKOUT } #[doc = "Checks if the value of the field is `GPIO24`"] #[inline(always)] pub fn is_gpio24(&self) -> bool { *self == PAD24FNCSEL_A::GPIO24 } } #[doc = "Write proxy for field `PAD24FNCSEL`"] pub struct PAD24FNCSEL_W<'a> { w: &'a mut W, } impl<'a> PAD24FNCSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD24FNCSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Pad disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD24FNCSEL_A::DIS) } #[doc = "Configure as the SPI channel 1 nCE signal from IOMSTR0"] #[inline(always)] pub fn m0n_ce1(self) -> &'a mut W { self.variant(PAD24FNCSEL_A::M0NCE1) } #[doc = "Configure as the CLKOUT signal"] #[inline(always)] pub fn clkout(self) -> &'a mut W { self.variant(PAD24FNCSEL_A::CLKOUT) } #[doc = "Configure as GPIO24"] #[inline(always)] pub fn gpio24(self) -> &'a mut W { self.variant(PAD24FNCSEL_A::GPIO24) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 3)) | (((value as u32) & 0x03) << 3); self.w } } #[doc = "Pad 24 drive strength\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD24STRNG_A { #[doc = "0: Low drive strength"] LOW = 0, #[doc = "1: High drive strength"] HIGH = 1, } impl From<PAD24STRNG_A> for bool { #[inline(always)] fn from(variant: PAD24STRNG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD24STRNG`"] pub type PAD24STRNG_R = crate::R<bool, PAD24STRNG_A>; impl PAD24STRNG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD24STRNG_A { match self.bits { false => PAD24STRNG_A::LOW, true => PAD24STRNG_A::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline(always)] pub fn is_low(&self) -> bool { *self == PAD24STRNG_A::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline(always)] pub fn is_high(&self) -> bool { *self == PAD24STRNG_A::HIGH } } #[doc = "Write proxy for field `PAD24STRNG`"] pub struct PAD24STRNG_W<'a> { w: &'a mut W, } impl<'a> PAD24STRNG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD24STRNG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Low drive strength"] #[inline(always)] pub fn low(self) -> &'a mut W { self.variant(PAD24STRNG_A::LOW) } #[doc = "High drive strength"] #[inline(always)] pub fn high(self) -> &'a mut W { self.variant(PAD24STRNG_A::HIGH) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Pad 24 input enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD24INPEN_A { #[doc = "0: Pad input disabled"] DIS = 0, #[doc = "1: Pad input enabled"] EN = 1, } impl From<PAD24INPEN_A> for bool { #[inline(always)] fn from(variant: PAD24INPEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD24INPEN`"] pub type PAD24INPEN_R = crate::R<bool, PAD24INPEN_A>; impl PAD24INPEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD24INPEN_A { match self.bits { false => PAD24INPEN_A::DIS, true => PAD24INPEN_A::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD24INPEN_A::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline(always)] pub fn is_en(&self) -> bool { *self == PAD24INPEN_A::EN } } #[doc = "Write proxy for field `PAD24INPEN`"] pub struct PAD24INPEN_W<'a> { w: &'a mut W, } impl<'a> PAD24INPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD24INPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pad input disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD24INPEN_A::DIS) } #[doc = "Pad input enabled"] #[inline(always)] pub fn en(self) -> &'a mut W { self.variant(PAD24INPEN_A::EN) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Pad 24 pullup enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD24PULL_A { #[doc = "0: Pullup disabled"] DIS = 0, #[doc = "1: Pullup enabled"] EN = 1, } impl From<PAD24PULL_A> for bool { #[inline(always)] fn from(variant: PAD24PULL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PAD24PULL`"] pub type PAD24PULL_R = crate::R<bool, PAD24PULL_A>; impl PAD24PULL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAD24PULL_A { match self.bits { false => PAD24PULL_A::DIS, true => PAD24PULL_A::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline(always)] pub fn is_dis(&self) -> bool { *self == PAD24PULL_A::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline(always)] pub fn is_en(&self) -> bool { *self == PAD24PULL_A::EN } } #[doc = "Write proxy for field `PAD24PULL`"] pub struct PAD24PULL_W<'a> { w: &'a mut W, } impl<'a> PAD24PULL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAD24PULL_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pullup disabled"] #[inline(always)] pub fn dis(self) -> &'a mut W { self.variant(PAD24PULL_A::DIS) } #[doc = "Pullup enabled"] #[inline(always)] pub fn en(self) -> &'a mut W { self.variant(PAD24PULL_A::EN) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bits 27:28 - Pad 27 function select"] #[inline(always)] pub fn pad27fncsel(&self) -> PAD27FNCSEL_R { PAD27FNCSEL_R::new(((self.bits >> 27) & 0x03) as u8) } #[doc = "Bit 26 - Pad 27 drive strentgh"] #[inline(always)] pub fn pad27strng(&self) -> PAD27STRNG_R { PAD27STRNG_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - Pad 27 input enable"] #[inline(always)] pub fn pad27inpen(&self) -> PAD27INPEN_R { PAD27INPEN_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 24 - Pad 27 pullup enable"] #[inline(always)] pub fn pad27pull(&self) -> PAD27PULL_R { PAD27PULL_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bits 19:20 - Pad 26 function select"] #[inline(always)] pub fn pad26fncsel(&self) -> PAD26FNCSEL_R { PAD26FNCSEL_R::new(((self.bits >> 19) & 0x03) as u8) } #[doc = "Bit 18 - Pad 26 drive strength"] #[inline(always)] pub fn pad26strng(&self) -> PAD26STRNG_R { PAD26STRNG_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - Pad 26 input enable"] #[inline(always)] pub fn pad26inpen(&self) -> PAD26INPEN_R { PAD26INPEN_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - Pad 26 pullup enable"] #[inline(always)] pub fn pad26pull(&self) -> PAD26PULL_R { PAD26PULL_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bits 11:12 - Pad 25 function select"] #[inline(always)] pub fn pad25fncsel(&self) -> PAD25FNCSEL_R { PAD25FNCSEL_R::new(((self.bits >> 11) & 0x03) as u8) } #[doc = "Bit 10 - Pad 25 drive strength"] #[inline(always)] pub fn pad25strng(&self) -> PAD25STRNG_R { PAD25STRNG_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - Pad 25 input enable"] #[inline(always)] pub fn pad25inpen(&self) -> PAD25INPEN_R { PAD25INPEN_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - Pad 25 pullup enable"] #[inline(always)] pub fn pad25pull(&self) -> PAD25PULL_R { PAD25PULL_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bits 3:4 - Pad 24 function select"] #[inline(always)] pub fn pad24fncsel(&self) -> PAD24FNCSEL_R { PAD24FNCSEL_R::new(((self.bits >> 3) & 0x03) as u8) } #[doc = "Bit 2 - Pad 24 drive strength"] #[inline(always)] pub fn pad24strng(&self) -> PAD24STRNG_R { PAD24STRNG_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Pad 24 input enable"] #[inline(always)] pub fn pad24inpen(&self) -> PAD24INPEN_R { PAD24INPEN_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Pad 24 pullup enable"] #[inline(always)] pub fn pad24pull(&self) -> PAD24PULL_R { PAD24PULL_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bits 27:28 - Pad 27 function select"] #[inline(always)] pub fn pad27fncsel(&mut self) -> PAD27FNCSEL_W { PAD27FNCSEL_W { w: self } } #[doc = "Bit 26 - Pad 27 drive strentgh"] #[inline(always)] pub fn pad27strng(&mut self) -> PAD27STRNG_W { PAD27STRNG_W { w: self } } #[doc = "Bit 25 - Pad 27 input enable"] #[inline(always)] pub fn pad27inpen(&mut self) -> PAD27INPEN_W { PAD27INPEN_W { w: self } } #[doc = "Bit 24 - Pad 27 pullup enable"] #[inline(always)] pub fn pad27pull(&mut self) -> PAD27PULL_W { PAD27PULL_W { w: self } } #[doc = "Bits 19:20 - Pad 26 function select"] #[inline(always)] pub fn pad26fncsel(&mut self) -> PAD26FNCSEL_W { PAD26FNCSEL_W { w: self } } #[doc = "Bit 18 - Pad 26 drive strength"] #[inline(always)] pub fn pad26strng(&mut self) -> PAD26STRNG_W { PAD26STRNG_W { w: self } } #[doc = "Bit 17 - Pad 26 input enable"] #[inline(always)] pub fn pad26inpen(&mut self) -> PAD26INPEN_W { PAD26INPEN_W { w: self } } #[doc = "Bit 16 - Pad 26 pullup enable"] #[inline(always)] pub fn pad26pull(&mut self) -> PAD26PULL_W { PAD26PULL_W { w: self } } #[doc = "Bits 11:12 - Pad 25 function select"] #[inline(always)] pub fn pad25fncsel(&mut self) -> PAD25FNCSEL_W { PAD25FNCSEL_W { w: self } } #[doc = "Bit 10 - Pad 25 drive strength"] #[inline(always)] pub fn pad25strng(&mut self) -> PAD25STRNG_W { PAD25STRNG_W { w: self } } #[doc = "Bit 9 - Pad 25 input enable"] #[inline(always)] pub fn pad25inpen(&mut self) -> PAD25INPEN_W { PAD25INPEN_W { w: self } } #[doc = "Bit 8 - Pad 25 pullup enable"] #[inline(always)] pub fn pad25pull(&mut self) -> PAD25PULL_W { PAD25PULL_W { w: self } } #[doc = "Bits 3:4 - Pad 24 function select"] #[inline(always)] pub fn pad24fncsel(&mut self) -> PAD24FNCSEL_W { PAD24FNCSEL_W { w: self } } #[doc = "Bit 2 - Pad 24 drive strength"] #[inline(always)] pub fn pad24strng(&mut self) -> PAD24STRNG_W { PAD24STRNG_W { w: self } } #[doc = "Bit 1 - Pad 24 input enable"] #[inline(always)] pub fn pad24inpen(&mut self) -> PAD24INPEN_W { PAD24INPEN_W { w: self } } #[doc = "Bit 0 - Pad 24 pullup enable"] #[inline(always)] pub fn pad24pull(&mut self) -> PAD24PULL_W { PAD24PULL_W { w: self } } }
29.166322
86
0.555061
61729a08060129c1fdfe70436dbe49f170749a2d
11,046
use crate::parse::token::{Token, BinOpToken}; use crate::symbol::keywords; use crate::ast::{self, BinOpKind}; /// Associative operator with precedence. /// /// This is the enum which specifies operator precedence and fixity to the parser. #[derive(PartialEq, Debug)] pub enum AssocOp { /// `+` Add, /// `-` Subtract, /// `*` Multiply, /// `/` Divide, /// `%` Modulus, /// `&&` LAnd, /// `||` LOr, /// `^` BitXor, /// `&` BitAnd, /// `|` BitOr, /// `<<` ShiftLeft, /// `>>` ShiftRight, /// `==` Equal, /// `<` Less, /// `<=` LessEqual, /// `!=` NotEqual, /// `>` Greater, /// `>=` GreaterEqual, /// `=` Assign, /// `<-` ObsoleteInPlace, /// `?=` where ? is one of the BinOpToken AssignOp(BinOpToken), /// `as` As, /// `..` range DotDot, /// `..=` range DotDotEq, /// `:` Colon, } #[derive(PartialEq, Debug)] pub enum Fixity { /// The operator is left-associative Left, /// The operator is right-associative Right, /// The operator is not associative None } impl AssocOp { /// Create a new AssocOP from a token pub fn from_token(t: &Token) -> Option<AssocOp> { use AssocOp::*; match *t { Token::BinOpEq(k) => Some(AssignOp(k)), Token::LArrow => Some(ObsoleteInPlace), Token::Eq => Some(Assign), Token::BinOp(BinOpToken::Star) => Some(Multiply), Token::BinOp(BinOpToken::Slash) => Some(Divide), Token::BinOp(BinOpToken::Percent) => Some(Modulus), Token::BinOp(BinOpToken::Plus) => Some(Add), Token::BinOp(BinOpToken::Minus) => Some(Subtract), Token::BinOp(BinOpToken::Shl) => Some(ShiftLeft), Token::BinOp(BinOpToken::Shr) => Some(ShiftRight), Token::BinOp(BinOpToken::And) => Some(BitAnd), Token::BinOp(BinOpToken::Caret) => Some(BitXor), Token::BinOp(BinOpToken::Or) => Some(BitOr), Token::Lt => Some(Less), Token::Le => Some(LessEqual), Token::Ge => Some(GreaterEqual), Token::Gt => Some(Greater), Token::EqEq => Some(Equal), Token::Ne => Some(NotEqual), Token::AndAnd => Some(LAnd), Token::OrOr => Some(LOr), Token::DotDot => Some(DotDot), Token::DotDotEq => Some(DotDotEq), // DotDotDot is no longer supported, but we need some way to display the error Token::DotDotDot => Some(DotDotEq), Token::Colon => Some(Colon), _ if t.is_keyword(keywords::As) => Some(As), _ => None } } /// Create a new AssocOp from ast::BinOpKind. pub fn from_ast_binop(op: BinOpKind) -> Self { use AssocOp::*; match op { BinOpKind::Lt => Less, BinOpKind::Gt => Greater, BinOpKind::Le => LessEqual, BinOpKind::Ge => GreaterEqual, BinOpKind::Eq => Equal, BinOpKind::Ne => NotEqual, BinOpKind::Mul => Multiply, BinOpKind::Div => Divide, BinOpKind::Rem => Modulus, BinOpKind::Add => Add, BinOpKind::Sub => Subtract, BinOpKind::Shl => ShiftLeft, BinOpKind::Shr => ShiftRight, BinOpKind::BitAnd => BitAnd, BinOpKind::BitXor => BitXor, BinOpKind::BitOr => BitOr, BinOpKind::And => LAnd, BinOpKind::Or => LOr } } /// Gets the precedence of this operator pub fn precedence(&self) -> usize { use AssocOp::*; match *self { As | Colon => 14, Multiply | Divide | Modulus => 13, Add | Subtract => 12, ShiftLeft | ShiftRight => 11, BitAnd => 10, BitXor => 9, BitOr => 8, Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual => 7, LAnd => 6, LOr => 5, DotDot | DotDotEq => 4, ObsoleteInPlace => 3, Assign | AssignOp(_) => 2, } } /// Gets the fixity of this operator pub fn fixity(&self) -> Fixity { use AssocOp::*; // NOTE: it is a bug to have an operators that has same precedence but different fixities! match *self { ObsoleteInPlace | Assign | AssignOp(_) => Fixity::Right, As | Multiply | Divide | Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd | BitXor | BitOr | Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual | LAnd | LOr | Colon => Fixity::Left, DotDot | DotDotEq => Fixity::None } } pub fn is_comparison(&self) -> bool { use AssocOp::*; match *self { Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual => true, ObsoleteInPlace | Assign | AssignOp(_) | As | Multiply | Divide | Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd | BitXor | BitOr | LAnd | LOr | DotDot | DotDotEq | Colon => false } } pub fn is_assign_like(&self) -> bool { use AssocOp::*; match *self { Assign | AssignOp(_) | ObsoleteInPlace => true, Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual | As | Multiply | Divide | Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd | BitXor | BitOr | LAnd | LOr | DotDot | DotDotEq | Colon => false } } pub fn to_ast_binop(&self) -> Option<BinOpKind> { use AssocOp::*; match *self { Less => Some(BinOpKind::Lt), Greater => Some(BinOpKind::Gt), LessEqual => Some(BinOpKind::Le), GreaterEqual => Some(BinOpKind::Ge), Equal => Some(BinOpKind::Eq), NotEqual => Some(BinOpKind::Ne), Multiply => Some(BinOpKind::Mul), Divide => Some(BinOpKind::Div), Modulus => Some(BinOpKind::Rem), Add => Some(BinOpKind::Add), Subtract => Some(BinOpKind::Sub), ShiftLeft => Some(BinOpKind::Shl), ShiftRight => Some(BinOpKind::Shr), BitAnd => Some(BinOpKind::BitAnd), BitXor => Some(BinOpKind::BitXor), BitOr => Some(BinOpKind::BitOr), LAnd => Some(BinOpKind::And), LOr => Some(BinOpKind::Or), ObsoleteInPlace | Assign | AssignOp(_) | As | DotDot | DotDotEq | Colon => None } } } pub const PREC_RESET: i8 = -100; pub const PREC_CLOSURE: i8 = -40; pub const PREC_JUMP: i8 = -30; pub const PREC_RANGE: i8 = -10; // The range 2 ... 14 is reserved for AssocOp binary operator precedences. pub const PREC_PREFIX: i8 = 50; pub const PREC_POSTFIX: i8 = 60; pub const PREC_PAREN: i8 = 99; pub const PREC_FORCE_PAREN: i8 = 100; #[derive(Debug, Clone, Copy)] pub enum ExprPrecedence { Closure, Break, Continue, Ret, Yield, Range, Binary(BinOpKind), ObsoleteInPlace, Cast, Type, Assign, AssignOp, Box, AddrOf, Unary, Call, MethodCall, Field, Index, Try, InlineAsm, Mac, Array, Repeat, Tup, Lit, Path, Paren, If, IfLet, While, WhileLet, ForLoop, Loop, Match, Block, TryBlock, Struct, Async, Err, } impl ExprPrecedence { pub fn order(self) -> i8 { match self { ExprPrecedence::Closure => PREC_CLOSURE, ExprPrecedence::Break | ExprPrecedence::Continue | ExprPrecedence::Ret | ExprPrecedence::Yield => PREC_JUMP, // `Range` claims to have higher precedence than `Assign`, but `x .. x = x` fails to // parse, instead of parsing as `(x .. x) = x`. Giving `Range` a lower precedence // ensures that `pprust` will add parentheses in the right places to get the desired // parse. ExprPrecedence::Range => PREC_RANGE, // Binop-like expr kinds, handled by `AssocOp`. ExprPrecedence::Binary(op) => AssocOp::from_ast_binop(op).precedence() as i8, ExprPrecedence::ObsoleteInPlace => AssocOp::ObsoleteInPlace.precedence() as i8, ExprPrecedence::Cast => AssocOp::As.precedence() as i8, ExprPrecedence::Type => AssocOp::Colon.precedence() as i8, ExprPrecedence::Assign | ExprPrecedence::AssignOp => AssocOp::Assign.precedence() as i8, // Unary, prefix ExprPrecedence::Box | ExprPrecedence::AddrOf | ExprPrecedence::Unary => PREC_PREFIX, // Unary, postfix ExprPrecedence::Call | ExprPrecedence::MethodCall | ExprPrecedence::Field | ExprPrecedence::Index | ExprPrecedence::Try | ExprPrecedence::InlineAsm | ExprPrecedence::Mac => PREC_POSTFIX, // Never need parens ExprPrecedence::Array | ExprPrecedence::Repeat | ExprPrecedence::Tup | ExprPrecedence::Lit | ExprPrecedence::Path | ExprPrecedence::Paren | ExprPrecedence::If | ExprPrecedence::IfLet | ExprPrecedence::While | ExprPrecedence::WhileLet | ExprPrecedence::ForLoop | ExprPrecedence::Loop | ExprPrecedence::Match | ExprPrecedence::Block | ExprPrecedence::TryBlock | ExprPrecedence::Async | ExprPrecedence::Struct | ExprPrecedence::Err => PREC_PAREN, } } } /// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not. pub fn contains_exterior_struct_lit(value: &ast::Expr) -> bool { match value.node { ast::ExprKind::Struct(..) => true, ast::ExprKind::Assign(ref lhs, ref rhs) | ast::ExprKind::AssignOp(_, ref lhs, ref rhs) | ast::ExprKind::Binary(_, ref lhs, ref rhs) => { // X { y: 1 } + X { y: 2 } contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs) } ast::ExprKind::Unary(_, ref x) | ast::ExprKind::Cast(ref x, _) | ast::ExprKind::Type(ref x, _) | ast::ExprKind::Field(ref x, _) | ast::ExprKind::Index(ref x, _) => { // &X { y: 1 }, X { y: 1 }.y contains_exterior_struct_lit(&x) } ast::ExprKind::MethodCall(.., ref exprs) => { // X { y: 1 }.bar(...) contains_exterior_struct_lit(&exprs[0]) } _ => false, } }
30.180328
99
0.525439
09dae02529a3044423100a61359d9ef0205208e6
357
use crate::scanner::token::Token; use thiserror::Error; #[derive(Error, Debug)] #[error("{message}")] pub struct InterpreterError { pub token: Token, pub message: String, } impl InterpreterError { pub fn new(token: Token, message: &str) -> Self { Self { token, message: String::from(message), } } }
18.789474
53
0.585434
dd423afc95f83e842aa8527188d18f5c8bdf2d37
148,348
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>Represents a matched event.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct MetricFilterMatchRecord { /// <p>The event number.</p> pub event_number: i64, /// <p>The raw event data.</p> pub event_message: std::option::Option<std::string::String>, /// <p>The values extracted from the event data by the filter.</p> pub extracted_values: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl MetricFilterMatchRecord { /// <p>The event number.</p> pub fn event_number(&self) -> i64 { self.event_number } /// <p>The raw event data.</p> pub fn event_message(&self) -> std::option::Option<&str> { self.event_message.as_deref() } /// <p>The values extracted from the event data by the filter.</p> pub fn extracted_values( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.extracted_values.as_ref() } } impl std::fmt::Debug for MetricFilterMatchRecord { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("MetricFilterMatchRecord"); formatter.field("event_number", &self.event_number); formatter.field("event_message", &self.event_message); formatter.field("extracted_values", &self.extracted_values); formatter.finish() } } /// See [`MetricFilterMatchRecord`](crate::model::MetricFilterMatchRecord) pub mod metric_filter_match_record { /// A builder for [`MetricFilterMatchRecord`](crate::model::MetricFilterMatchRecord) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) event_number: std::option::Option<i64>, pub(crate) event_message: std::option::Option<std::string::String>, pub(crate) extracted_values: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The event number.</p> pub fn event_number(mut self, input: i64) -> Self { self.event_number = Some(input); self } /// <p>The event number.</p> pub fn set_event_number(mut self, input: std::option::Option<i64>) -> Self { self.event_number = input; self } /// <p>The raw event data.</p> pub fn event_message(mut self, input: impl Into<std::string::String>) -> Self { self.event_message = Some(input.into()); self } /// <p>The raw event data.</p> pub fn set_event_message( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.event_message = input; self } /// Adds a key-value pair to `extracted_values`. /// /// To override the contents of this collection use [`set_extracted_values`](Self::set_extracted_values). /// /// <p>The values extracted from the event data by the filter.</p> pub fn extracted_values( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.extracted_values.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.extracted_values = Some(hash_map); self } /// <p>The values extracted from the event data by the filter.</p> pub fn set_extracted_values( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.extracted_values = input; self } /// Consumes the builder and constructs a [`MetricFilterMatchRecord`](crate::model::MetricFilterMatchRecord) pub fn build(self) -> crate::model::MetricFilterMatchRecord { crate::model::MetricFilterMatchRecord { event_number: self.event_number.unwrap_or_default(), event_message: self.event_message, extracted_values: self.extracted_values, } } } } impl MetricFilterMatchRecord { /// Creates a new builder-style object to manufacture [`MetricFilterMatchRecord`](crate::model::MetricFilterMatchRecord) pub fn builder() -> crate::model::metric_filter_match_record::Builder { crate::model::metric_filter_match_record::Builder::default() } } /// <p>Reserved.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct QueryCompileError { /// <p>Reserved.</p> pub location: std::option::Option<crate::model::QueryCompileErrorLocation>, /// <p>Reserved.</p> pub message: std::option::Option<std::string::String>, } impl QueryCompileError { /// <p>Reserved.</p> pub fn location(&self) -> std::option::Option<&crate::model::QueryCompileErrorLocation> { self.location.as_ref() } /// <p>Reserved.</p> pub fn message(&self) -> std::option::Option<&str> { self.message.as_deref() } } impl std::fmt::Debug for QueryCompileError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("QueryCompileError"); formatter.field("location", &self.location); formatter.field("message", &self.message); formatter.finish() } } /// See [`QueryCompileError`](crate::model::QueryCompileError) pub mod query_compile_error { /// A builder for [`QueryCompileError`](crate::model::QueryCompileError) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) location: std::option::Option<crate::model::QueryCompileErrorLocation>, pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>Reserved.</p> pub fn location(mut self, input: crate::model::QueryCompileErrorLocation) -> Self { self.location = Some(input); self } /// <p>Reserved.</p> pub fn set_location( mut self, input: std::option::Option<crate::model::QueryCompileErrorLocation>, ) -> Self { self.location = input; self } /// <p>Reserved.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>Reserved.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`QueryCompileError`](crate::model::QueryCompileError) pub fn build(self) -> crate::model::QueryCompileError { crate::model::QueryCompileError { location: self.location, message: self.message, } } } } impl QueryCompileError { /// Creates a new builder-style object to manufacture [`QueryCompileError`](crate::model::QueryCompileError) pub fn builder() -> crate::model::query_compile_error::Builder { crate::model::query_compile_error::Builder::default() } } /// <p>Reserved.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct QueryCompileErrorLocation { /// <p>Reserved.</p> pub start_char_offset: std::option::Option<i32>, /// <p>Reserved.</p> pub end_char_offset: std::option::Option<i32>, } impl QueryCompileErrorLocation { /// <p>Reserved.</p> pub fn start_char_offset(&self) -> std::option::Option<i32> { self.start_char_offset } /// <p>Reserved.</p> pub fn end_char_offset(&self) -> std::option::Option<i32> { self.end_char_offset } } impl std::fmt::Debug for QueryCompileErrorLocation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("QueryCompileErrorLocation"); formatter.field("start_char_offset", &self.start_char_offset); formatter.field("end_char_offset", &self.end_char_offset); formatter.finish() } } /// See [`QueryCompileErrorLocation`](crate::model::QueryCompileErrorLocation) pub mod query_compile_error_location { /// A builder for [`QueryCompileErrorLocation`](crate::model::QueryCompileErrorLocation) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) start_char_offset: std::option::Option<i32>, pub(crate) end_char_offset: std::option::Option<i32>, } impl Builder { /// <p>Reserved.</p> pub fn start_char_offset(mut self, input: i32) -> Self { self.start_char_offset = Some(input); self } /// <p>Reserved.</p> pub fn set_start_char_offset(mut self, input: std::option::Option<i32>) -> Self { self.start_char_offset = input; self } /// <p>Reserved.</p> pub fn end_char_offset(mut self, input: i32) -> Self { self.end_char_offset = Some(input); self } /// <p>Reserved.</p> pub fn set_end_char_offset(mut self, input: std::option::Option<i32>) -> Self { self.end_char_offset = input; self } /// Consumes the builder and constructs a [`QueryCompileErrorLocation`](crate::model::QueryCompileErrorLocation) pub fn build(self) -> crate::model::QueryCompileErrorLocation { crate::model::QueryCompileErrorLocation { start_char_offset: self.start_char_offset, end_char_offset: self.end_char_offset, } } } } impl QueryCompileErrorLocation { /// Creates a new builder-style object to manufacture [`QueryCompileErrorLocation`](crate::model::QueryCompileErrorLocation) pub fn builder() -> crate::model::query_compile_error_location::Builder { crate::model::query_compile_error_location::Builder::default() } } /// <p>The method used to distribute log data to the destination, which can be either /// random or grouped by log stream.</p> #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum Distribution { #[allow(missing_docs)] // documentation missing in model ByLogStream, #[allow(missing_docs)] // documentation missing in model Random, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for Distribution { fn from(s: &str) -> Self { match s { "ByLogStream" => Distribution::ByLogStream, "Random" => Distribution::Random, other => Distribution::Unknown(other.to_owned()), } } } impl std::str::FromStr for Distribution { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(Distribution::from(s)) } } impl Distribution { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { Distribution::ByLogStream => "ByLogStream", Distribution::Random => "Random", Distribution::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["ByLogStream", "Random"] } } impl AsRef<str> for Distribution { fn as_ref(&self) -> &str { self.as_str() } } /// <p>A policy enabling one or more entities to put logs to a log group in this account.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResourcePolicy { /// <p>The name of the resource policy.</p> pub policy_name: std::option::Option<std::string::String>, /// <p>The details of the policy.</p> pub policy_document: std::option::Option<std::string::String>, /// <p>Timestamp showing when this policy was last updated, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub last_updated_time: std::option::Option<i64>, } impl ResourcePolicy { /// <p>The name of the resource policy.</p> pub fn policy_name(&self) -> std::option::Option<&str> { self.policy_name.as_deref() } /// <p>The details of the policy.</p> pub fn policy_document(&self) -> std::option::Option<&str> { self.policy_document.as_deref() } /// <p>Timestamp showing when this policy was last updated, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn last_updated_time(&self) -> std::option::Option<i64> { self.last_updated_time } } impl std::fmt::Debug for ResourcePolicy { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResourcePolicy"); formatter.field("policy_name", &self.policy_name); formatter.field("policy_document", &self.policy_document); formatter.field("last_updated_time", &self.last_updated_time); formatter.finish() } } /// See [`ResourcePolicy`](crate::model::ResourcePolicy) pub mod resource_policy { /// A builder for [`ResourcePolicy`](crate::model::ResourcePolicy) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) policy_name: std::option::Option<std::string::String>, pub(crate) policy_document: std::option::Option<std::string::String>, pub(crate) last_updated_time: std::option::Option<i64>, } impl Builder { /// <p>The name of the resource policy.</p> pub fn policy_name(mut self, input: impl Into<std::string::String>) -> Self { self.policy_name = Some(input.into()); self } /// <p>The name of the resource policy.</p> pub fn set_policy_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.policy_name = input; self } /// <p>The details of the policy.</p> pub fn policy_document(mut self, input: impl Into<std::string::String>) -> Self { self.policy_document = Some(input.into()); self } /// <p>The details of the policy.</p> pub fn set_policy_document( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.policy_document = input; self } /// <p>Timestamp showing when this policy was last updated, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn last_updated_time(mut self, input: i64) -> Self { self.last_updated_time = Some(input); self } /// <p>Timestamp showing when this policy was last updated, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_last_updated_time(mut self, input: std::option::Option<i64>) -> Self { self.last_updated_time = input; self } /// Consumes the builder and constructs a [`ResourcePolicy`](crate::model::ResourcePolicy) pub fn build(self) -> crate::model::ResourcePolicy { crate::model::ResourcePolicy { policy_name: self.policy_name, policy_document: self.policy_document, last_updated_time: self.last_updated_time, } } } } impl ResourcePolicy { /// Creates a new builder-style object to manufacture [`ResourcePolicy`](crate::model::ResourcePolicy) pub fn builder() -> crate::model::resource_policy::Builder { crate::model::resource_policy::Builder::default() } } /// <p>Indicates how to transform ingested log events to metric data in a CloudWatch metric.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct MetricTransformation { /// <p>The name of the CloudWatch metric.</p> pub metric_name: std::option::Option<std::string::String>, /// <p>A custom namespace to contain your metric in CloudWatch. Use namespaces to group together metrics that are similar. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Namespace">Namespaces</a>.</p> pub metric_namespace: std::option::Option<std::string::String>, /// <p>The value to publish to the CloudWatch metric when a filter pattern matches a log event.</p> pub metric_value: std::option::Option<std::string::String>, /// <p>(Optional) The value to emit when a filter pattern does not match a log event. This value can be null.</p> pub default_value: std::option::Option<f64>, /// <p>The fields to use as dimensions for the metric. One metric filter can include as many as three dimensions.</p> <important> /// <p>Metrics extracted from log events are charged as custom metrics. To prevent unexpected high charges, do not specify high-cardinality fields such as <code>IPAddress</code> or <code>requestID</code> as dimensions. Each different value found for a dimension is treated as a separate metric and accrues charges as a separate custom metric. </p> /// <p>To help prevent accidental high charges, Amazon disables a metric filter if it generates 1000 different name/value pairs for the dimensions that you have specified within a certain amount of time.</p> /// <p>You can also set up a billing alarm to alert you if your charges are higher than expected. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html"> Creating a Billing Alarm to Monitor Your Estimated Amazon Web Services Charges</a>. </p> /// </important> pub dimensions: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, /// <p>The unit to assign to the metric. If you omit this, the unit is set as <code>None</code>.</p> pub unit: std::option::Option<crate::model::StandardUnit>, } impl MetricTransformation { /// <p>The name of the CloudWatch metric.</p> pub fn metric_name(&self) -> std::option::Option<&str> { self.metric_name.as_deref() } /// <p>A custom namespace to contain your metric in CloudWatch. Use namespaces to group together metrics that are similar. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Namespace">Namespaces</a>.</p> pub fn metric_namespace(&self) -> std::option::Option<&str> { self.metric_namespace.as_deref() } /// <p>The value to publish to the CloudWatch metric when a filter pattern matches a log event.</p> pub fn metric_value(&self) -> std::option::Option<&str> { self.metric_value.as_deref() } /// <p>(Optional) The value to emit when a filter pattern does not match a log event. This value can be null.</p> pub fn default_value(&self) -> std::option::Option<f64> { self.default_value } /// <p>The fields to use as dimensions for the metric. One metric filter can include as many as three dimensions.</p> <important> /// <p>Metrics extracted from log events are charged as custom metrics. To prevent unexpected high charges, do not specify high-cardinality fields such as <code>IPAddress</code> or <code>requestID</code> as dimensions. Each different value found for a dimension is treated as a separate metric and accrues charges as a separate custom metric. </p> /// <p>To help prevent accidental high charges, Amazon disables a metric filter if it generates 1000 different name/value pairs for the dimensions that you have specified within a certain amount of time.</p> /// <p>You can also set up a billing alarm to alert you if your charges are higher than expected. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html"> Creating a Billing Alarm to Monitor Your Estimated Amazon Web Services Charges</a>. </p> /// </important> pub fn dimensions( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.dimensions.as_ref() } /// <p>The unit to assign to the metric. If you omit this, the unit is set as <code>None</code>.</p> pub fn unit(&self) -> std::option::Option<&crate::model::StandardUnit> { self.unit.as_ref() } } impl std::fmt::Debug for MetricTransformation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("MetricTransformation"); formatter.field("metric_name", &self.metric_name); formatter.field("metric_namespace", &self.metric_namespace); formatter.field("metric_value", &self.metric_value); formatter.field("default_value", &self.default_value); formatter.field("dimensions", &self.dimensions); formatter.field("unit", &self.unit); formatter.finish() } } /// See [`MetricTransformation`](crate::model::MetricTransformation) pub mod metric_transformation { /// A builder for [`MetricTransformation`](crate::model::MetricTransformation) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) metric_name: std::option::Option<std::string::String>, pub(crate) metric_namespace: std::option::Option<std::string::String>, pub(crate) metric_value: std::option::Option<std::string::String>, pub(crate) default_value: std::option::Option<f64>, pub(crate) dimensions: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, pub(crate) unit: std::option::Option<crate::model::StandardUnit>, } impl Builder { /// <p>The name of the CloudWatch metric.</p> pub fn metric_name(mut self, input: impl Into<std::string::String>) -> Self { self.metric_name = Some(input.into()); self } /// <p>The name of the CloudWatch metric.</p> pub fn set_metric_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.metric_name = input; self } /// <p>A custom namespace to contain your metric in CloudWatch. Use namespaces to group together metrics that are similar. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Namespace">Namespaces</a>.</p> pub fn metric_namespace(mut self, input: impl Into<std::string::String>) -> Self { self.metric_namespace = Some(input.into()); self } /// <p>A custom namespace to contain your metric in CloudWatch. Use namespaces to group together metrics that are similar. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Namespace">Namespaces</a>.</p> pub fn set_metric_namespace( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.metric_namespace = input; self } /// <p>The value to publish to the CloudWatch metric when a filter pattern matches a log event.</p> pub fn metric_value(mut self, input: impl Into<std::string::String>) -> Self { self.metric_value = Some(input.into()); self } /// <p>The value to publish to the CloudWatch metric when a filter pattern matches a log event.</p> pub fn set_metric_value(mut self, input: std::option::Option<std::string::String>) -> Self { self.metric_value = input; self } /// <p>(Optional) The value to emit when a filter pattern does not match a log event. This value can be null.</p> pub fn default_value(mut self, input: f64) -> Self { self.default_value = Some(input); self } /// <p>(Optional) The value to emit when a filter pattern does not match a log event. This value can be null.</p> pub fn set_default_value(mut self, input: std::option::Option<f64>) -> Self { self.default_value = input; self } /// Adds a key-value pair to `dimensions`. /// /// To override the contents of this collection use [`set_dimensions`](Self::set_dimensions). /// /// <p>The fields to use as dimensions for the metric. One metric filter can include as many as three dimensions.</p> <important> /// <p>Metrics extracted from log events are charged as custom metrics. To prevent unexpected high charges, do not specify high-cardinality fields such as <code>IPAddress</code> or <code>requestID</code> as dimensions. Each different value found for a dimension is treated as a separate metric and accrues charges as a separate custom metric. </p> /// <p>To help prevent accidental high charges, Amazon disables a metric filter if it generates 1000 different name/value pairs for the dimensions that you have specified within a certain amount of time.</p> /// <p>You can also set up a billing alarm to alert you if your charges are higher than expected. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html"> Creating a Billing Alarm to Monitor Your Estimated Amazon Web Services Charges</a>. </p> /// </important> pub fn dimensions( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.dimensions.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.dimensions = Some(hash_map); self } /// <p>The fields to use as dimensions for the metric. One metric filter can include as many as three dimensions.</p> <important> /// <p>Metrics extracted from log events are charged as custom metrics. To prevent unexpected high charges, do not specify high-cardinality fields such as <code>IPAddress</code> or <code>requestID</code> as dimensions. Each different value found for a dimension is treated as a separate metric and accrues charges as a separate custom metric. </p> /// <p>To help prevent accidental high charges, Amazon disables a metric filter if it generates 1000 different name/value pairs for the dimensions that you have specified within a certain amount of time.</p> /// <p>You can also set up a billing alarm to alert you if your charges are higher than expected. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html"> Creating a Billing Alarm to Monitor Your Estimated Amazon Web Services Charges</a>. </p> /// </important> pub fn set_dimensions( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.dimensions = input; self } /// <p>The unit to assign to the metric. If you omit this, the unit is set as <code>None</code>.</p> pub fn unit(mut self, input: crate::model::StandardUnit) -> Self { self.unit = Some(input); self } /// <p>The unit to assign to the metric. If you omit this, the unit is set as <code>None</code>.</p> pub fn set_unit(mut self, input: std::option::Option<crate::model::StandardUnit>) -> Self { self.unit = input; self } /// Consumes the builder and constructs a [`MetricTransformation`](crate::model::MetricTransformation) pub fn build(self) -> crate::model::MetricTransformation { crate::model::MetricTransformation { metric_name: self.metric_name, metric_namespace: self.metric_namespace, metric_value: self.metric_value, default_value: self.default_value, dimensions: self.dimensions, unit: self.unit, } } } } impl MetricTransformation { /// Creates a new builder-style object to manufacture [`MetricTransformation`](crate::model::MetricTransformation) pub fn builder() -> crate::model::metric_transformation::Builder { crate::model::metric_transformation::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum StandardUnit { #[allow(missing_docs)] // documentation missing in model Bits, #[allow(missing_docs)] // documentation missing in model BitsSecond, #[allow(missing_docs)] // documentation missing in model Bytes, #[allow(missing_docs)] // documentation missing in model BytesSecond, #[allow(missing_docs)] // documentation missing in model Count, #[allow(missing_docs)] // documentation missing in model CountSecond, #[allow(missing_docs)] // documentation missing in model Gigabits, #[allow(missing_docs)] // documentation missing in model GigabitsSecond, #[allow(missing_docs)] // documentation missing in model Gigabytes, #[allow(missing_docs)] // documentation missing in model GigabytesSecond, #[allow(missing_docs)] // documentation missing in model Kilobits, #[allow(missing_docs)] // documentation missing in model KilobitsSecond, #[allow(missing_docs)] // documentation missing in model Kilobytes, #[allow(missing_docs)] // documentation missing in model KilobytesSecond, #[allow(missing_docs)] // documentation missing in model Megabits, #[allow(missing_docs)] // documentation missing in model MegabitsSecond, #[allow(missing_docs)] // documentation missing in model Megabytes, #[allow(missing_docs)] // documentation missing in model MegabytesSecond, #[allow(missing_docs)] // documentation missing in model Microseconds, #[allow(missing_docs)] // documentation missing in model Milliseconds, #[allow(missing_docs)] // documentation missing in model None, #[allow(missing_docs)] // documentation missing in model Percent, #[allow(missing_docs)] // documentation missing in model Seconds, #[allow(missing_docs)] // documentation missing in model Terabits, #[allow(missing_docs)] // documentation missing in model TerabitsSecond, #[allow(missing_docs)] // documentation missing in model Terabytes, #[allow(missing_docs)] // documentation missing in model TerabytesSecond, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for StandardUnit { fn from(s: &str) -> Self { match s { "Bits" => StandardUnit::Bits, "Bits/Second" => StandardUnit::BitsSecond, "Bytes" => StandardUnit::Bytes, "Bytes/Second" => StandardUnit::BytesSecond, "Count" => StandardUnit::Count, "Count/Second" => StandardUnit::CountSecond, "Gigabits" => StandardUnit::Gigabits, "Gigabits/Second" => StandardUnit::GigabitsSecond, "Gigabytes" => StandardUnit::Gigabytes, "Gigabytes/Second" => StandardUnit::GigabytesSecond, "Kilobits" => StandardUnit::Kilobits, "Kilobits/Second" => StandardUnit::KilobitsSecond, "Kilobytes" => StandardUnit::Kilobytes, "Kilobytes/Second" => StandardUnit::KilobytesSecond, "Megabits" => StandardUnit::Megabits, "Megabits/Second" => StandardUnit::MegabitsSecond, "Megabytes" => StandardUnit::Megabytes, "Megabytes/Second" => StandardUnit::MegabytesSecond, "Microseconds" => StandardUnit::Microseconds, "Milliseconds" => StandardUnit::Milliseconds, "None" => StandardUnit::None, "Percent" => StandardUnit::Percent, "Seconds" => StandardUnit::Seconds, "Terabits" => StandardUnit::Terabits, "Terabits/Second" => StandardUnit::TerabitsSecond, "Terabytes" => StandardUnit::Terabytes, "Terabytes/Second" => StandardUnit::TerabytesSecond, other => StandardUnit::Unknown(other.to_owned()), } } } impl std::str::FromStr for StandardUnit { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(StandardUnit::from(s)) } } impl StandardUnit { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { StandardUnit::Bits => "Bits", StandardUnit::BitsSecond => "Bits/Second", StandardUnit::Bytes => "Bytes", StandardUnit::BytesSecond => "Bytes/Second", StandardUnit::Count => "Count", StandardUnit::CountSecond => "Count/Second", StandardUnit::Gigabits => "Gigabits", StandardUnit::GigabitsSecond => "Gigabits/Second", StandardUnit::Gigabytes => "Gigabytes", StandardUnit::GigabytesSecond => "Gigabytes/Second", StandardUnit::Kilobits => "Kilobits", StandardUnit::KilobitsSecond => "Kilobits/Second", StandardUnit::Kilobytes => "Kilobytes", StandardUnit::KilobytesSecond => "Kilobytes/Second", StandardUnit::Megabits => "Megabits", StandardUnit::MegabitsSecond => "Megabits/Second", StandardUnit::Megabytes => "Megabytes", StandardUnit::MegabytesSecond => "Megabytes/Second", StandardUnit::Microseconds => "Microseconds", StandardUnit::Milliseconds => "Milliseconds", StandardUnit::None => "None", StandardUnit::Percent => "Percent", StandardUnit::Seconds => "Seconds", StandardUnit::Terabits => "Terabits", StandardUnit::TerabitsSecond => "Terabits/Second", StandardUnit::Terabytes => "Terabytes", StandardUnit::TerabytesSecond => "Terabytes/Second", StandardUnit::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &[ "Bits", "Bits/Second", "Bytes", "Bytes/Second", "Count", "Count/Second", "Gigabits", "Gigabits/Second", "Gigabytes", "Gigabytes/Second", "Kilobits", "Kilobits/Second", "Kilobytes", "Kilobytes/Second", "Megabits", "Megabits/Second", "Megabytes", "Megabytes/Second", "Microseconds", "Milliseconds", "None", "Percent", "Seconds", "Terabits", "Terabits/Second", "Terabytes", "Terabytes/Second", ] } } impl AsRef<str> for StandardUnit { fn as_ref(&self) -> &str { self.as_str() } } /// <p>Represents the rejected events.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RejectedLogEventsInfo { /// <p>The log events that are too new.</p> pub too_new_log_event_start_index: std::option::Option<i32>, /// <p>The log events that are too old.</p> pub too_old_log_event_end_index: std::option::Option<i32>, /// <p>The expired log events.</p> pub expired_log_event_end_index: std::option::Option<i32>, } impl RejectedLogEventsInfo { /// <p>The log events that are too new.</p> pub fn too_new_log_event_start_index(&self) -> std::option::Option<i32> { self.too_new_log_event_start_index } /// <p>The log events that are too old.</p> pub fn too_old_log_event_end_index(&self) -> std::option::Option<i32> { self.too_old_log_event_end_index } /// <p>The expired log events.</p> pub fn expired_log_event_end_index(&self) -> std::option::Option<i32> { self.expired_log_event_end_index } } impl std::fmt::Debug for RejectedLogEventsInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RejectedLogEventsInfo"); formatter.field( "too_new_log_event_start_index", &self.too_new_log_event_start_index, ); formatter.field( "too_old_log_event_end_index", &self.too_old_log_event_end_index, ); formatter.field( "expired_log_event_end_index", &self.expired_log_event_end_index, ); formatter.finish() } } /// See [`RejectedLogEventsInfo`](crate::model::RejectedLogEventsInfo) pub mod rejected_log_events_info { /// A builder for [`RejectedLogEventsInfo`](crate::model::RejectedLogEventsInfo) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) too_new_log_event_start_index: std::option::Option<i32>, pub(crate) too_old_log_event_end_index: std::option::Option<i32>, pub(crate) expired_log_event_end_index: std::option::Option<i32>, } impl Builder { /// <p>The log events that are too new.</p> pub fn too_new_log_event_start_index(mut self, input: i32) -> Self { self.too_new_log_event_start_index = Some(input); self } /// <p>The log events that are too new.</p> pub fn set_too_new_log_event_start_index( mut self, input: std::option::Option<i32>, ) -> Self { self.too_new_log_event_start_index = input; self } /// <p>The log events that are too old.</p> pub fn too_old_log_event_end_index(mut self, input: i32) -> Self { self.too_old_log_event_end_index = Some(input); self } /// <p>The log events that are too old.</p> pub fn set_too_old_log_event_end_index(mut self, input: std::option::Option<i32>) -> Self { self.too_old_log_event_end_index = input; self } /// <p>The expired log events.</p> pub fn expired_log_event_end_index(mut self, input: i32) -> Self { self.expired_log_event_end_index = Some(input); self } /// <p>The expired log events.</p> pub fn set_expired_log_event_end_index(mut self, input: std::option::Option<i32>) -> Self { self.expired_log_event_end_index = input; self } /// Consumes the builder and constructs a [`RejectedLogEventsInfo`](crate::model::RejectedLogEventsInfo) pub fn build(self) -> crate::model::RejectedLogEventsInfo { crate::model::RejectedLogEventsInfo { too_new_log_event_start_index: self.too_new_log_event_start_index, too_old_log_event_end_index: self.too_old_log_event_end_index, expired_log_event_end_index: self.expired_log_event_end_index, } } } } impl RejectedLogEventsInfo { /// Creates a new builder-style object to manufacture [`RejectedLogEventsInfo`](crate::model::RejectedLogEventsInfo) pub fn builder() -> crate::model::rejected_log_events_info::Builder { crate::model::rejected_log_events_info::Builder::default() } } /// <p>Represents a log event, which is a record of activity that was recorded by the application or resource being monitored.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InputLogEvent { /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub timestamp: std::option::Option<i64>, /// <p>The raw event message.</p> pub message: std::option::Option<std::string::String>, } impl InputLogEvent { /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn timestamp(&self) -> std::option::Option<i64> { self.timestamp } /// <p>The raw event message.</p> pub fn message(&self) -> std::option::Option<&str> { self.message.as_deref() } } impl std::fmt::Debug for InputLogEvent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InputLogEvent"); formatter.field("timestamp", &self.timestamp); formatter.field("message", &self.message); formatter.finish() } } /// See [`InputLogEvent`](crate::model::InputLogEvent) pub mod input_log_event { /// A builder for [`InputLogEvent`](crate::model::InputLogEvent) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) timestamp: std::option::Option<i64>, pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn timestamp(mut self, input: i64) -> Self { self.timestamp = Some(input); self } /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_timestamp(mut self, input: std::option::Option<i64>) -> Self { self.timestamp = input; self } /// <p>The raw event message.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The raw event message.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`InputLogEvent`](crate::model::InputLogEvent) pub fn build(self) -> crate::model::InputLogEvent { crate::model::InputLogEvent { timestamp: self.timestamp, message: self.message, } } } } impl InputLogEvent { /// Creates a new builder-style object to manufacture [`InputLogEvent`](crate::model::InputLogEvent) pub fn builder() -> crate::model::input_log_event::Builder { crate::model::input_log_event::Builder::default() } } /// <p>Represents a cross-account destination that receives subscription log events.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct Destination { /// <p>The name of the destination.</p> pub destination_name: std::option::Option<std::string::String>, /// <p>The Amazon Resource Name (ARN) of the physical target where the log events are delivered (for example, a Kinesis stream).</p> pub target_arn: std::option::Option<std::string::String>, /// <p>A role for impersonation, used when delivering log events to the target.</p> pub role_arn: std::option::Option<std::string::String>, /// <p>An IAM policy document that governs which Amazon Web Services accounts can create subscription filters against this destination.</p> pub access_policy: std::option::Option<std::string::String>, /// <p>The ARN of this destination.</p> pub arn: std::option::Option<std::string::String>, /// <p>The creation time of the destination, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub creation_time: std::option::Option<i64>, } impl Destination { /// <p>The name of the destination.</p> pub fn destination_name(&self) -> std::option::Option<&str> { self.destination_name.as_deref() } /// <p>The Amazon Resource Name (ARN) of the physical target where the log events are delivered (for example, a Kinesis stream).</p> pub fn target_arn(&self) -> std::option::Option<&str> { self.target_arn.as_deref() } /// <p>A role for impersonation, used when delivering log events to the target.</p> pub fn role_arn(&self) -> std::option::Option<&str> { self.role_arn.as_deref() } /// <p>An IAM policy document that governs which Amazon Web Services accounts can create subscription filters against this destination.</p> pub fn access_policy(&self) -> std::option::Option<&str> { self.access_policy.as_deref() } /// <p>The ARN of this destination.</p> pub fn arn(&self) -> std::option::Option<&str> { self.arn.as_deref() } /// <p>The creation time of the destination, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(&self) -> std::option::Option<i64> { self.creation_time } } impl std::fmt::Debug for Destination { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("Destination"); formatter.field("destination_name", &self.destination_name); formatter.field("target_arn", &self.target_arn); formatter.field("role_arn", &self.role_arn); formatter.field("access_policy", &self.access_policy); formatter.field("arn", &self.arn); formatter.field("creation_time", &self.creation_time); formatter.finish() } } /// See [`Destination`](crate::model::Destination) pub mod destination { /// A builder for [`Destination`](crate::model::Destination) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) destination_name: std::option::Option<std::string::String>, pub(crate) target_arn: std::option::Option<std::string::String>, pub(crate) role_arn: std::option::Option<std::string::String>, pub(crate) access_policy: std::option::Option<std::string::String>, pub(crate) arn: std::option::Option<std::string::String>, pub(crate) creation_time: std::option::Option<i64>, } impl Builder { /// <p>The name of the destination.</p> pub fn destination_name(mut self, input: impl Into<std::string::String>) -> Self { self.destination_name = Some(input.into()); self } /// <p>The name of the destination.</p> pub fn set_destination_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.destination_name = input; self } /// <p>The Amazon Resource Name (ARN) of the physical target where the log events are delivered (for example, a Kinesis stream).</p> pub fn target_arn(mut self, input: impl Into<std::string::String>) -> Self { self.target_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the physical target where the log events are delivered (for example, a Kinesis stream).</p> pub fn set_target_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.target_arn = input; self } /// <p>A role for impersonation, used when delivering log events to the target.</p> pub fn role_arn(mut self, input: impl Into<std::string::String>) -> Self { self.role_arn = Some(input.into()); self } /// <p>A role for impersonation, used when delivering log events to the target.</p> pub fn set_role_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.role_arn = input; self } /// <p>An IAM policy document that governs which Amazon Web Services accounts can create subscription filters against this destination.</p> pub fn access_policy(mut self, input: impl Into<std::string::String>) -> Self { self.access_policy = Some(input.into()); self } /// <p>An IAM policy document that governs which Amazon Web Services accounts can create subscription filters against this destination.</p> pub fn set_access_policy( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.access_policy = input; self } /// <p>The ARN of this destination.</p> pub fn arn(mut self, input: impl Into<std::string::String>) -> Self { self.arn = Some(input.into()); self } /// <p>The ARN of this destination.</p> pub fn set_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.arn = input; self } /// <p>The creation time of the destination, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(mut self, input: i64) -> Self { self.creation_time = Some(input); self } /// <p>The creation time of the destination, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_creation_time(mut self, input: std::option::Option<i64>) -> Self { self.creation_time = input; self } /// Consumes the builder and constructs a [`Destination`](crate::model::Destination) pub fn build(self) -> crate::model::Destination { crate::model::Destination { destination_name: self.destination_name, target_arn: self.target_arn, role_arn: self.role_arn, access_policy: self.access_policy, arn: self.arn, creation_time: self.creation_time, } } } } impl Destination { /// Creates a new builder-style object to manufacture [`Destination`](crate::model::Destination) pub fn builder() -> crate::model::destination::Builder { crate::model::destination::Builder::default() } } /// _Note: `QueryStatus::Unknown` has been renamed to `::UnknownValue`._ #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum QueryStatus { #[allow(missing_docs)] // documentation missing in model Cancelled, #[allow(missing_docs)] // documentation missing in model Complete, #[allow(missing_docs)] // documentation missing in model Failed, #[allow(missing_docs)] // documentation missing in model Running, #[allow(missing_docs)] // documentation missing in model Scheduled, #[allow(missing_docs)] // documentation missing in model Timeout, /// _Note: `::Unknown` has been renamed to `::UnknownValue`._ UnknownValue, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for QueryStatus { fn from(s: &str) -> Self { match s { "Cancelled" => QueryStatus::Cancelled, "Complete" => QueryStatus::Complete, "Failed" => QueryStatus::Failed, "Running" => QueryStatus::Running, "Scheduled" => QueryStatus::Scheduled, "Timeout" => QueryStatus::Timeout, "Unknown" => QueryStatus::UnknownValue, other => QueryStatus::Unknown(other.to_owned()), } } } impl std::str::FromStr for QueryStatus { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(QueryStatus::from(s)) } } impl QueryStatus { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { QueryStatus::Cancelled => "Cancelled", QueryStatus::Complete => "Complete", QueryStatus::Failed => "Failed", QueryStatus::Running => "Running", QueryStatus::Scheduled => "Scheduled", QueryStatus::Timeout => "Timeout", QueryStatus::UnknownValue => "Unknown", QueryStatus::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &[ "Cancelled", "Complete", "Failed", "Running", "Scheduled", "Timeout", "Unknown", ] } } impl AsRef<str> for QueryStatus { fn as_ref(&self) -> &str { self.as_str() } } /// <p>Contains the number of log events scanned by the query, the number of log events that matched the query criteria, and the total number of bytes in the log events that were scanned.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct QueryStatistics { /// <p>The number of log events that matched the query string.</p> pub records_matched: f64, /// <p>The total number of log events scanned during the query.</p> pub records_scanned: f64, /// <p>The total number of bytes in the log events scanned during the query.</p> pub bytes_scanned: f64, } impl QueryStatistics { /// <p>The number of log events that matched the query string.</p> pub fn records_matched(&self) -> f64 { self.records_matched } /// <p>The total number of log events scanned during the query.</p> pub fn records_scanned(&self) -> f64 { self.records_scanned } /// <p>The total number of bytes in the log events scanned during the query.</p> pub fn bytes_scanned(&self) -> f64 { self.bytes_scanned } } impl std::fmt::Debug for QueryStatistics { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("QueryStatistics"); formatter.field("records_matched", &self.records_matched); formatter.field("records_scanned", &self.records_scanned); formatter.field("bytes_scanned", &self.bytes_scanned); formatter.finish() } } /// See [`QueryStatistics`](crate::model::QueryStatistics) pub mod query_statistics { /// A builder for [`QueryStatistics`](crate::model::QueryStatistics) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) records_matched: std::option::Option<f64>, pub(crate) records_scanned: std::option::Option<f64>, pub(crate) bytes_scanned: std::option::Option<f64>, } impl Builder { /// <p>The number of log events that matched the query string.</p> pub fn records_matched(mut self, input: f64) -> Self { self.records_matched = Some(input); self } /// <p>The number of log events that matched the query string.</p> pub fn set_records_matched(mut self, input: std::option::Option<f64>) -> Self { self.records_matched = input; self } /// <p>The total number of log events scanned during the query.</p> pub fn records_scanned(mut self, input: f64) -> Self { self.records_scanned = Some(input); self } /// <p>The total number of log events scanned during the query.</p> pub fn set_records_scanned(mut self, input: std::option::Option<f64>) -> Self { self.records_scanned = input; self } /// <p>The total number of bytes in the log events scanned during the query.</p> pub fn bytes_scanned(mut self, input: f64) -> Self { self.bytes_scanned = Some(input); self } /// <p>The total number of bytes in the log events scanned during the query.</p> pub fn set_bytes_scanned(mut self, input: std::option::Option<f64>) -> Self { self.bytes_scanned = input; self } /// Consumes the builder and constructs a [`QueryStatistics`](crate::model::QueryStatistics) pub fn build(self) -> crate::model::QueryStatistics { crate::model::QueryStatistics { records_matched: self.records_matched.unwrap_or_default(), records_scanned: self.records_scanned.unwrap_or_default(), bytes_scanned: self.bytes_scanned.unwrap_or_default(), } } } } impl QueryStatistics { /// Creates a new builder-style object to manufacture [`QueryStatistics`](crate::model::QueryStatistics) pub fn builder() -> crate::model::query_statistics::Builder { crate::model::query_statistics::Builder::default() } } /// <p>Contains one field from one log event returned by a CloudWatch Logs Insights query, along with the value of that field.</p> /// <p>For more information about the fields that are generated by CloudWatch logs, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_AnalyzeLogData-discoverable-fields.html">Supported Logs and Discovered Fields</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResultField { /// <p>The log event field.</p> pub field: std::option::Option<std::string::String>, /// <p>The value of this field.</p> pub value: std::option::Option<std::string::String>, } impl ResultField { /// <p>The log event field.</p> pub fn field(&self) -> std::option::Option<&str> { self.field.as_deref() } /// <p>The value of this field.</p> pub fn value(&self) -> std::option::Option<&str> { self.value.as_deref() } } impl std::fmt::Debug for ResultField { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResultField"); formatter.field("field", &self.field); formatter.field("value", &self.value); formatter.finish() } } /// See [`ResultField`](crate::model::ResultField) pub mod result_field { /// A builder for [`ResultField`](crate::model::ResultField) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) field: std::option::Option<std::string::String>, pub(crate) value: std::option::Option<std::string::String>, } impl Builder { /// <p>The log event field.</p> pub fn field(mut self, input: impl Into<std::string::String>) -> Self { self.field = Some(input.into()); self } /// <p>The log event field.</p> pub fn set_field(mut self, input: std::option::Option<std::string::String>) -> Self { self.field = input; self } /// <p>The value of this field.</p> pub fn value(mut self, input: impl Into<std::string::String>) -> Self { self.value = Some(input.into()); self } /// <p>The value of this field.</p> pub fn set_value(mut self, input: std::option::Option<std::string::String>) -> Self { self.value = input; self } /// Consumes the builder and constructs a [`ResultField`](crate::model::ResultField) pub fn build(self) -> crate::model::ResultField { crate::model::ResultField { field: self.field, value: self.value, } } } } impl ResultField { /// Creates a new builder-style object to manufacture [`ResultField`](crate::model::ResultField) pub fn builder() -> crate::model::result_field::Builder { crate::model::result_field::Builder::default() } } /// <p>The fields contained in log events found by a <code>GetLogGroupFields</code> operation, along with the percentage of queried log events in which each field appears.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LogGroupField { /// <p>The name of a log field.</p> pub name: std::option::Option<std::string::String>, /// <p>The percentage of log events queried that contained the field.</p> pub percent: i32, } impl LogGroupField { /// <p>The name of a log field.</p> pub fn name(&self) -> std::option::Option<&str> { self.name.as_deref() } /// <p>The percentage of log events queried that contained the field.</p> pub fn percent(&self) -> i32 { self.percent } } impl std::fmt::Debug for LogGroupField { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LogGroupField"); formatter.field("name", &self.name); formatter.field("percent", &self.percent); formatter.finish() } } /// See [`LogGroupField`](crate::model::LogGroupField) pub mod log_group_field { /// A builder for [`LogGroupField`](crate::model::LogGroupField) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) name: std::option::Option<std::string::String>, pub(crate) percent: std::option::Option<i32>, } impl Builder { /// <p>The name of a log field.</p> pub fn name(mut self, input: impl Into<std::string::String>) -> Self { self.name = Some(input.into()); self } /// <p>The name of a log field.</p> pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.name = input; self } /// <p>The percentage of log events queried that contained the field.</p> pub fn percent(mut self, input: i32) -> Self { self.percent = Some(input); self } /// <p>The percentage of log events queried that contained the field.</p> pub fn set_percent(mut self, input: std::option::Option<i32>) -> Self { self.percent = input; self } /// Consumes the builder and constructs a [`LogGroupField`](crate::model::LogGroupField) pub fn build(self) -> crate::model::LogGroupField { crate::model::LogGroupField { name: self.name, percent: self.percent.unwrap_or_default(), } } } } impl LogGroupField { /// Creates a new builder-style object to manufacture [`LogGroupField`](crate::model::LogGroupField) pub fn builder() -> crate::model::log_group_field::Builder { crate::model::log_group_field::Builder::default() } } /// <p>Represents a log event.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct OutputLogEvent { /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub timestamp: std::option::Option<i64>, /// <p>The data contained in the log event.</p> pub message: std::option::Option<std::string::String>, /// <p>The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub ingestion_time: std::option::Option<i64>, } impl OutputLogEvent { /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn timestamp(&self) -> std::option::Option<i64> { self.timestamp } /// <p>The data contained in the log event.</p> pub fn message(&self) -> std::option::Option<&str> { self.message.as_deref() } /// <p>The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn ingestion_time(&self) -> std::option::Option<i64> { self.ingestion_time } } impl std::fmt::Debug for OutputLogEvent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("OutputLogEvent"); formatter.field("timestamp", &self.timestamp); formatter.field("message", &self.message); formatter.field("ingestion_time", &self.ingestion_time); formatter.finish() } } /// See [`OutputLogEvent`](crate::model::OutputLogEvent) pub mod output_log_event { /// A builder for [`OutputLogEvent`](crate::model::OutputLogEvent) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) timestamp: std::option::Option<i64>, pub(crate) message: std::option::Option<std::string::String>, pub(crate) ingestion_time: std::option::Option<i64>, } impl Builder { /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn timestamp(mut self, input: i64) -> Self { self.timestamp = Some(input); self } /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_timestamp(mut self, input: std::option::Option<i64>) -> Self { self.timestamp = input; self } /// <p>The data contained in the log event.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The data contained in the log event.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// <p>The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn ingestion_time(mut self, input: i64) -> Self { self.ingestion_time = Some(input); self } /// <p>The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_ingestion_time(mut self, input: std::option::Option<i64>) -> Self { self.ingestion_time = input; self } /// Consumes the builder and constructs a [`OutputLogEvent`](crate::model::OutputLogEvent) pub fn build(self) -> crate::model::OutputLogEvent { crate::model::OutputLogEvent { timestamp: self.timestamp, message: self.message, ingestion_time: self.ingestion_time, } } } } impl OutputLogEvent { /// Creates a new builder-style object to manufacture [`OutputLogEvent`](crate::model::OutputLogEvent) pub fn builder() -> crate::model::output_log_event::Builder { crate::model::output_log_event::Builder::default() } } /// <p>Represents the search status of a log stream.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SearchedLogStream { /// <p>The name of the log stream.</p> pub log_stream_name: std::option::Option<std::string::String>, /// <p>Indicates whether all the events in this log stream were searched.</p> pub searched_completely: std::option::Option<bool>, } impl SearchedLogStream { /// <p>The name of the log stream.</p> pub fn log_stream_name(&self) -> std::option::Option<&str> { self.log_stream_name.as_deref() } /// <p>Indicates whether all the events in this log stream were searched.</p> pub fn searched_completely(&self) -> std::option::Option<bool> { self.searched_completely } } impl std::fmt::Debug for SearchedLogStream { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SearchedLogStream"); formatter.field("log_stream_name", &self.log_stream_name); formatter.field("searched_completely", &self.searched_completely); formatter.finish() } } /// See [`SearchedLogStream`](crate::model::SearchedLogStream) pub mod searched_log_stream { /// A builder for [`SearchedLogStream`](crate::model::SearchedLogStream) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) log_stream_name: std::option::Option<std::string::String>, pub(crate) searched_completely: std::option::Option<bool>, } impl Builder { /// <p>The name of the log stream.</p> pub fn log_stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.log_stream_name = Some(input.into()); self } /// <p>The name of the log stream.</p> pub fn set_log_stream_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.log_stream_name = input; self } /// <p>Indicates whether all the events in this log stream were searched.</p> pub fn searched_completely(mut self, input: bool) -> Self { self.searched_completely = Some(input); self } /// <p>Indicates whether all the events in this log stream were searched.</p> pub fn set_searched_completely(mut self, input: std::option::Option<bool>) -> Self { self.searched_completely = input; self } /// Consumes the builder and constructs a [`SearchedLogStream`](crate::model::SearchedLogStream) pub fn build(self) -> crate::model::SearchedLogStream { crate::model::SearchedLogStream { log_stream_name: self.log_stream_name, searched_completely: self.searched_completely, } } } } impl SearchedLogStream { /// Creates a new builder-style object to manufacture [`SearchedLogStream`](crate::model::SearchedLogStream) pub fn builder() -> crate::model::searched_log_stream::Builder { crate::model::searched_log_stream::Builder::default() } } /// <p>Represents a matched event.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct FilteredLogEvent { /// <p>The name of the log stream to which this event belongs.</p> pub log_stream_name: std::option::Option<std::string::String>, /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub timestamp: std::option::Option<i64>, /// <p>The data contained in the log event.</p> pub message: std::option::Option<std::string::String>, /// <p>The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub ingestion_time: std::option::Option<i64>, /// <p>The ID of the event.</p> pub event_id: std::option::Option<std::string::String>, } impl FilteredLogEvent { /// <p>The name of the log stream to which this event belongs.</p> pub fn log_stream_name(&self) -> std::option::Option<&str> { self.log_stream_name.as_deref() } /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn timestamp(&self) -> std::option::Option<i64> { self.timestamp } /// <p>The data contained in the log event.</p> pub fn message(&self) -> std::option::Option<&str> { self.message.as_deref() } /// <p>The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn ingestion_time(&self) -> std::option::Option<i64> { self.ingestion_time } /// <p>The ID of the event.</p> pub fn event_id(&self) -> std::option::Option<&str> { self.event_id.as_deref() } } impl std::fmt::Debug for FilteredLogEvent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("FilteredLogEvent"); formatter.field("log_stream_name", &self.log_stream_name); formatter.field("timestamp", &self.timestamp); formatter.field("message", &self.message); formatter.field("ingestion_time", &self.ingestion_time); formatter.field("event_id", &self.event_id); formatter.finish() } } /// See [`FilteredLogEvent`](crate::model::FilteredLogEvent) pub mod filtered_log_event { /// A builder for [`FilteredLogEvent`](crate::model::FilteredLogEvent) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) log_stream_name: std::option::Option<std::string::String>, pub(crate) timestamp: std::option::Option<i64>, pub(crate) message: std::option::Option<std::string::String>, pub(crate) ingestion_time: std::option::Option<i64>, pub(crate) event_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the log stream to which this event belongs.</p> pub fn log_stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.log_stream_name = Some(input.into()); self } /// <p>The name of the log stream to which this event belongs.</p> pub fn set_log_stream_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.log_stream_name = input; self } /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn timestamp(mut self, input: i64) -> Self { self.timestamp = Some(input); self } /// <p>The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_timestamp(mut self, input: std::option::Option<i64>) -> Self { self.timestamp = input; self } /// <p>The data contained in the log event.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The data contained in the log event.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// <p>The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn ingestion_time(mut self, input: i64) -> Self { self.ingestion_time = Some(input); self } /// <p>The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_ingestion_time(mut self, input: std::option::Option<i64>) -> Self { self.ingestion_time = input; self } /// <p>The ID of the event.</p> pub fn event_id(mut self, input: impl Into<std::string::String>) -> Self { self.event_id = Some(input.into()); self } /// <p>The ID of the event.</p> pub fn set_event_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.event_id = input; self } /// Consumes the builder and constructs a [`FilteredLogEvent`](crate::model::FilteredLogEvent) pub fn build(self) -> crate::model::FilteredLogEvent { crate::model::FilteredLogEvent { log_stream_name: self.log_stream_name, timestamp: self.timestamp, message: self.message, ingestion_time: self.ingestion_time, event_id: self.event_id, } } } } impl FilteredLogEvent { /// Creates a new builder-style object to manufacture [`FilteredLogEvent`](crate::model::FilteredLogEvent) pub fn builder() -> crate::model::filtered_log_event::Builder { crate::model::filtered_log_event::Builder::default() } } /// <p>Represents a subscription filter.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SubscriptionFilter { /// <p>The name of the subscription filter.</p> pub filter_name: std::option::Option<std::string::String>, /// <p>The name of the log group.</p> pub log_group_name: std::option::Option<std::string::String>, /// <p>A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event can contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message.</p> pub filter_pattern: std::option::Option<std::string::String>, /// <p>The Amazon Resource Name (ARN) of the destination.</p> pub destination_arn: std::option::Option<std::string::String>, /// <p></p> pub role_arn: std::option::Option<std::string::String>, /// <p>The method used to distribute log data to the destination, which can be either random or grouped by log stream.</p> pub distribution: std::option::Option<crate::model::Distribution>, /// <p>The creation time of the subscription filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub creation_time: std::option::Option<i64>, } impl SubscriptionFilter { /// <p>The name of the subscription filter.</p> pub fn filter_name(&self) -> std::option::Option<&str> { self.filter_name.as_deref() } /// <p>The name of the log group.</p> pub fn log_group_name(&self) -> std::option::Option<&str> { self.log_group_name.as_deref() } /// <p>A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event can contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message.</p> pub fn filter_pattern(&self) -> std::option::Option<&str> { self.filter_pattern.as_deref() } /// <p>The Amazon Resource Name (ARN) of the destination.</p> pub fn destination_arn(&self) -> std::option::Option<&str> { self.destination_arn.as_deref() } /// <p></p> pub fn role_arn(&self) -> std::option::Option<&str> { self.role_arn.as_deref() } /// <p>The method used to distribute log data to the destination, which can be either random or grouped by log stream.</p> pub fn distribution(&self) -> std::option::Option<&crate::model::Distribution> { self.distribution.as_ref() } /// <p>The creation time of the subscription filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(&self) -> std::option::Option<i64> { self.creation_time } } impl std::fmt::Debug for SubscriptionFilter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SubscriptionFilter"); formatter.field("filter_name", &self.filter_name); formatter.field("log_group_name", &self.log_group_name); formatter.field("filter_pattern", &self.filter_pattern); formatter.field("destination_arn", &self.destination_arn); formatter.field("role_arn", &self.role_arn); formatter.field("distribution", &self.distribution); formatter.field("creation_time", &self.creation_time); formatter.finish() } } /// See [`SubscriptionFilter`](crate::model::SubscriptionFilter) pub mod subscription_filter { /// A builder for [`SubscriptionFilter`](crate::model::SubscriptionFilter) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) filter_name: std::option::Option<std::string::String>, pub(crate) log_group_name: std::option::Option<std::string::String>, pub(crate) filter_pattern: std::option::Option<std::string::String>, pub(crate) destination_arn: std::option::Option<std::string::String>, pub(crate) role_arn: std::option::Option<std::string::String>, pub(crate) distribution: std::option::Option<crate::model::Distribution>, pub(crate) creation_time: std::option::Option<i64>, } impl Builder { /// <p>The name of the subscription filter.</p> pub fn filter_name(mut self, input: impl Into<std::string::String>) -> Self { self.filter_name = Some(input.into()); self } /// <p>The name of the subscription filter.</p> pub fn set_filter_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.filter_name = input; self } /// <p>The name of the log group.</p> pub fn log_group_name(mut self, input: impl Into<std::string::String>) -> Self { self.log_group_name = Some(input.into()); self } /// <p>The name of the log group.</p> pub fn set_log_group_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.log_group_name = input; self } /// <p>A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event can contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message.</p> pub fn filter_pattern(mut self, input: impl Into<std::string::String>) -> Self { self.filter_pattern = Some(input.into()); self } /// <p>A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event can contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message.</p> pub fn set_filter_pattern( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.filter_pattern = input; self } /// <p>The Amazon Resource Name (ARN) of the destination.</p> pub fn destination_arn(mut self, input: impl Into<std::string::String>) -> Self { self.destination_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the destination.</p> pub fn set_destination_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.destination_arn = input; self } /// <p></p> pub fn role_arn(mut self, input: impl Into<std::string::String>) -> Self { self.role_arn = Some(input.into()); self } /// <p></p> pub fn set_role_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.role_arn = input; self } /// <p>The method used to distribute log data to the destination, which can be either random or grouped by log stream.</p> pub fn distribution(mut self, input: crate::model::Distribution) -> Self { self.distribution = Some(input); self } /// <p>The method used to distribute log data to the destination, which can be either random or grouped by log stream.</p> pub fn set_distribution( mut self, input: std::option::Option<crate::model::Distribution>, ) -> Self { self.distribution = input; self } /// <p>The creation time of the subscription filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(mut self, input: i64) -> Self { self.creation_time = Some(input); self } /// <p>The creation time of the subscription filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_creation_time(mut self, input: std::option::Option<i64>) -> Self { self.creation_time = input; self } /// Consumes the builder and constructs a [`SubscriptionFilter`](crate::model::SubscriptionFilter) pub fn build(self) -> crate::model::SubscriptionFilter { crate::model::SubscriptionFilter { filter_name: self.filter_name, log_group_name: self.log_group_name, filter_pattern: self.filter_pattern, destination_arn: self.destination_arn, role_arn: self.role_arn, distribution: self.distribution, creation_time: self.creation_time, } } } } impl SubscriptionFilter { /// Creates a new builder-style object to manufacture [`SubscriptionFilter`](crate::model::SubscriptionFilter) pub fn builder() -> crate::model::subscription_filter::Builder { crate::model::subscription_filter::Builder::default() } } /// <p>This structure contains details about a saved CloudWatch Logs Insights query definition.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct QueryDefinition { /// <p>The unique ID of the query definition.</p> pub query_definition_id: std::option::Option<std::string::String>, /// <p>The name of the query definition.</p> pub name: std::option::Option<std::string::String>, /// <p>The query string to use for this definition. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html">CloudWatch Logs Insights Query Syntax</a>.</p> pub query_string: std::option::Option<std::string::String>, /// <p>The date that the query definition was most recently modified.</p> pub last_modified: std::option::Option<i64>, /// <p>If this query definition contains a list of log groups that it is limited to, that list appears here.</p> pub log_group_names: std::option::Option<std::vec::Vec<std::string::String>>, } impl QueryDefinition { /// <p>The unique ID of the query definition.</p> pub fn query_definition_id(&self) -> std::option::Option<&str> { self.query_definition_id.as_deref() } /// <p>The name of the query definition.</p> pub fn name(&self) -> std::option::Option<&str> { self.name.as_deref() } /// <p>The query string to use for this definition. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html">CloudWatch Logs Insights Query Syntax</a>.</p> pub fn query_string(&self) -> std::option::Option<&str> { self.query_string.as_deref() } /// <p>The date that the query definition was most recently modified.</p> pub fn last_modified(&self) -> std::option::Option<i64> { self.last_modified } /// <p>If this query definition contains a list of log groups that it is limited to, that list appears here.</p> pub fn log_group_names(&self) -> std::option::Option<&[std::string::String]> { self.log_group_names.as_deref() } } impl std::fmt::Debug for QueryDefinition { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("QueryDefinition"); formatter.field("query_definition_id", &self.query_definition_id); formatter.field("name", &self.name); formatter.field("query_string", &self.query_string); formatter.field("last_modified", &self.last_modified); formatter.field("log_group_names", &self.log_group_names); formatter.finish() } } /// See [`QueryDefinition`](crate::model::QueryDefinition) pub mod query_definition { /// A builder for [`QueryDefinition`](crate::model::QueryDefinition) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) query_definition_id: std::option::Option<std::string::String>, pub(crate) name: std::option::Option<std::string::String>, pub(crate) query_string: std::option::Option<std::string::String>, pub(crate) last_modified: std::option::Option<i64>, pub(crate) log_group_names: std::option::Option<std::vec::Vec<std::string::String>>, } impl Builder { /// <p>The unique ID of the query definition.</p> pub fn query_definition_id(mut self, input: impl Into<std::string::String>) -> Self { self.query_definition_id = Some(input.into()); self } /// <p>The unique ID of the query definition.</p> pub fn set_query_definition_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.query_definition_id = input; self } /// <p>The name of the query definition.</p> pub fn name(mut self, input: impl Into<std::string::String>) -> Self { self.name = Some(input.into()); self } /// <p>The name of the query definition.</p> pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.name = input; self } /// <p>The query string to use for this definition. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html">CloudWatch Logs Insights Query Syntax</a>.</p> pub fn query_string(mut self, input: impl Into<std::string::String>) -> Self { self.query_string = Some(input.into()); self } /// <p>The query string to use for this definition. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html">CloudWatch Logs Insights Query Syntax</a>.</p> pub fn set_query_string(mut self, input: std::option::Option<std::string::String>) -> Self { self.query_string = input; self } /// <p>The date that the query definition was most recently modified.</p> pub fn last_modified(mut self, input: i64) -> Self { self.last_modified = Some(input); self } /// <p>The date that the query definition was most recently modified.</p> pub fn set_last_modified(mut self, input: std::option::Option<i64>) -> Self { self.last_modified = input; self } /// Appends an item to `log_group_names`. /// /// To override the contents of this collection use [`set_log_group_names`](Self::set_log_group_names). /// /// <p>If this query definition contains a list of log groups that it is limited to, that list appears here.</p> pub fn log_group_names(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.log_group_names.unwrap_or_default(); v.push(input.into()); self.log_group_names = Some(v); self } /// <p>If this query definition contains a list of log groups that it is limited to, that list appears here.</p> pub fn set_log_group_names( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.log_group_names = input; self } /// Consumes the builder and constructs a [`QueryDefinition`](crate::model::QueryDefinition) pub fn build(self) -> crate::model::QueryDefinition { crate::model::QueryDefinition { query_definition_id: self.query_definition_id, name: self.name, query_string: self.query_string, last_modified: self.last_modified, log_group_names: self.log_group_names, } } } } impl QueryDefinition { /// Creates a new builder-style object to manufacture [`QueryDefinition`](crate::model::QueryDefinition) pub fn builder() -> crate::model::query_definition::Builder { crate::model::query_definition::Builder::default() } } /// <p>Information about one CloudWatch Logs Insights query that matches the request in a <code>DescribeQueries</code> operation. </p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct QueryInfo { /// <p>The unique ID number of this query.</p> pub query_id: std::option::Option<std::string::String>, /// <p>The query string used in this query.</p> pub query_string: std::option::Option<std::string::String>, /// <p>The status of this query. Possible values are <code>Cancelled</code>, <code>Complete</code>, <code>Failed</code>, <code>Running</code>, <code>Scheduled</code>, and <code>Unknown</code>.</p> pub status: std::option::Option<crate::model::QueryStatus>, /// <p>The date and time that this query was created.</p> pub create_time: std::option::Option<i64>, /// <p>The name of the log group scanned by this query.</p> pub log_group_name: std::option::Option<std::string::String>, } impl QueryInfo { /// <p>The unique ID number of this query.</p> pub fn query_id(&self) -> std::option::Option<&str> { self.query_id.as_deref() } /// <p>The query string used in this query.</p> pub fn query_string(&self) -> std::option::Option<&str> { self.query_string.as_deref() } /// <p>The status of this query. Possible values are <code>Cancelled</code>, <code>Complete</code>, <code>Failed</code>, <code>Running</code>, <code>Scheduled</code>, and <code>Unknown</code>.</p> pub fn status(&self) -> std::option::Option<&crate::model::QueryStatus> { self.status.as_ref() } /// <p>The date and time that this query was created.</p> pub fn create_time(&self) -> std::option::Option<i64> { self.create_time } /// <p>The name of the log group scanned by this query.</p> pub fn log_group_name(&self) -> std::option::Option<&str> { self.log_group_name.as_deref() } } impl std::fmt::Debug for QueryInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("QueryInfo"); formatter.field("query_id", &self.query_id); formatter.field("query_string", &self.query_string); formatter.field("status", &self.status); formatter.field("create_time", &self.create_time); formatter.field("log_group_name", &self.log_group_name); formatter.finish() } } /// See [`QueryInfo`](crate::model::QueryInfo) pub mod query_info { /// A builder for [`QueryInfo`](crate::model::QueryInfo) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) query_id: std::option::Option<std::string::String>, pub(crate) query_string: std::option::Option<std::string::String>, pub(crate) status: std::option::Option<crate::model::QueryStatus>, pub(crate) create_time: std::option::Option<i64>, pub(crate) log_group_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The unique ID number of this query.</p> pub fn query_id(mut self, input: impl Into<std::string::String>) -> Self { self.query_id = Some(input.into()); self } /// <p>The unique ID number of this query.</p> pub fn set_query_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.query_id = input; self } /// <p>The query string used in this query.</p> pub fn query_string(mut self, input: impl Into<std::string::String>) -> Self { self.query_string = Some(input.into()); self } /// <p>The query string used in this query.</p> pub fn set_query_string(mut self, input: std::option::Option<std::string::String>) -> Self { self.query_string = input; self } /// <p>The status of this query. Possible values are <code>Cancelled</code>, <code>Complete</code>, <code>Failed</code>, <code>Running</code>, <code>Scheduled</code>, and <code>Unknown</code>.</p> pub fn status(mut self, input: crate::model::QueryStatus) -> Self { self.status = Some(input); self } /// <p>The status of this query. Possible values are <code>Cancelled</code>, <code>Complete</code>, <code>Failed</code>, <code>Running</code>, <code>Scheduled</code>, and <code>Unknown</code>.</p> pub fn set_status(mut self, input: std::option::Option<crate::model::QueryStatus>) -> Self { self.status = input; self } /// <p>The date and time that this query was created.</p> pub fn create_time(mut self, input: i64) -> Self { self.create_time = Some(input); self } /// <p>The date and time that this query was created.</p> pub fn set_create_time(mut self, input: std::option::Option<i64>) -> Self { self.create_time = input; self } /// <p>The name of the log group scanned by this query.</p> pub fn log_group_name(mut self, input: impl Into<std::string::String>) -> Self { self.log_group_name = Some(input.into()); self } /// <p>The name of the log group scanned by this query.</p> pub fn set_log_group_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.log_group_name = input; self } /// Consumes the builder and constructs a [`QueryInfo`](crate::model::QueryInfo) pub fn build(self) -> crate::model::QueryInfo { crate::model::QueryInfo { query_id: self.query_id, query_string: self.query_string, status: self.status, create_time: self.create_time, log_group_name: self.log_group_name, } } } } impl QueryInfo { /// Creates a new builder-style object to manufacture [`QueryInfo`](crate::model::QueryInfo) pub fn builder() -> crate::model::query_info::Builder { crate::model::query_info::Builder::default() } } /// <p>Metric filters express how CloudWatch Logs would extract metric observations from ingested log events and transform them into metric data in a CloudWatch metric.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct MetricFilter { /// <p>The name of the metric filter.</p> pub filter_name: std::option::Option<std::string::String>, /// <p>A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event can contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message.</p> pub filter_pattern: std::option::Option<std::string::String>, /// <p>The metric transformations.</p> pub metric_transformations: std::option::Option<std::vec::Vec<crate::model::MetricTransformation>>, /// <p>The creation time of the metric filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub creation_time: std::option::Option<i64>, /// <p>The name of the log group.</p> pub log_group_name: std::option::Option<std::string::String>, } impl MetricFilter { /// <p>The name of the metric filter.</p> pub fn filter_name(&self) -> std::option::Option<&str> { self.filter_name.as_deref() } /// <p>A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event can contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message.</p> pub fn filter_pattern(&self) -> std::option::Option<&str> { self.filter_pattern.as_deref() } /// <p>The metric transformations.</p> pub fn metric_transformations( &self, ) -> std::option::Option<&[crate::model::MetricTransformation]> { self.metric_transformations.as_deref() } /// <p>The creation time of the metric filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(&self) -> std::option::Option<i64> { self.creation_time } /// <p>The name of the log group.</p> pub fn log_group_name(&self) -> std::option::Option<&str> { self.log_group_name.as_deref() } } impl std::fmt::Debug for MetricFilter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("MetricFilter"); formatter.field("filter_name", &self.filter_name); formatter.field("filter_pattern", &self.filter_pattern); formatter.field("metric_transformations", &self.metric_transformations); formatter.field("creation_time", &self.creation_time); formatter.field("log_group_name", &self.log_group_name); formatter.finish() } } /// See [`MetricFilter`](crate::model::MetricFilter) pub mod metric_filter { /// A builder for [`MetricFilter`](crate::model::MetricFilter) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) filter_name: std::option::Option<std::string::String>, pub(crate) filter_pattern: std::option::Option<std::string::String>, pub(crate) metric_transformations: std::option::Option<std::vec::Vec<crate::model::MetricTransformation>>, pub(crate) creation_time: std::option::Option<i64>, pub(crate) log_group_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the metric filter.</p> pub fn filter_name(mut self, input: impl Into<std::string::String>) -> Self { self.filter_name = Some(input.into()); self } /// <p>The name of the metric filter.</p> pub fn set_filter_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.filter_name = input; self } /// <p>A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event can contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message.</p> pub fn filter_pattern(mut self, input: impl Into<std::string::String>) -> Self { self.filter_pattern = Some(input.into()); self } /// <p>A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event can contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message.</p> pub fn set_filter_pattern( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.filter_pattern = input; self } /// Appends an item to `metric_transformations`. /// /// To override the contents of this collection use [`set_metric_transformations`](Self::set_metric_transformations). /// /// <p>The metric transformations.</p> pub fn metric_transformations(mut self, input: crate::model::MetricTransformation) -> Self { let mut v = self.metric_transformations.unwrap_or_default(); v.push(input); self.metric_transformations = Some(v); self } /// <p>The metric transformations.</p> pub fn set_metric_transformations( mut self, input: std::option::Option<std::vec::Vec<crate::model::MetricTransformation>>, ) -> Self { self.metric_transformations = input; self } /// <p>The creation time of the metric filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(mut self, input: i64) -> Self { self.creation_time = Some(input); self } /// <p>The creation time of the metric filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_creation_time(mut self, input: std::option::Option<i64>) -> Self { self.creation_time = input; self } /// <p>The name of the log group.</p> pub fn log_group_name(mut self, input: impl Into<std::string::String>) -> Self { self.log_group_name = Some(input.into()); self } /// <p>The name of the log group.</p> pub fn set_log_group_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.log_group_name = input; self } /// Consumes the builder and constructs a [`MetricFilter`](crate::model::MetricFilter) pub fn build(self) -> crate::model::MetricFilter { crate::model::MetricFilter { filter_name: self.filter_name, filter_pattern: self.filter_pattern, metric_transformations: self.metric_transformations, creation_time: self.creation_time, log_group_name: self.log_group_name, } } } } impl MetricFilter { /// Creates a new builder-style object to manufacture [`MetricFilter`](crate::model::MetricFilter) pub fn builder() -> crate::model::metric_filter::Builder { crate::model::metric_filter::Builder::default() } } /// <p>Represents a log stream, which is a sequence of log events from a single emitter of logs.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LogStream { /// <p>The name of the log stream.</p> pub log_stream_name: std::option::Option<std::string::String>, /// <p>The creation time of the stream, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub creation_time: std::option::Option<i64>, /// <p>The time of the first event, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub first_event_timestamp: std::option::Option<i64>, /// <p>The time of the most recent log event in the log stream in CloudWatch Logs. This number is expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. The <code>lastEventTime</code> value updates on an eventual consistency basis. It typically updates in less than an hour from ingestion, but in rare situations might take longer.</p> pub last_event_timestamp: std::option::Option<i64>, /// <p>The ingestion time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub last_ingestion_time: std::option::Option<i64>, /// <p>The sequence token.</p> pub upload_sequence_token: std::option::Option<std::string::String>, /// <p>The Amazon Resource Name (ARN) of the log stream.</p> pub arn: std::option::Option<std::string::String>, /// <p>The number of bytes stored.</p> /// <p> <b>Important:</b> On June 17, 2019, this parameter was deprecated for log streams, and is always reported as zero. This change applies only to log streams. The <code>storedBytes</code> parameter for log groups is not affected.</p> pub stored_bytes: std::option::Option<i64>, } impl LogStream { /// <p>The name of the log stream.</p> pub fn log_stream_name(&self) -> std::option::Option<&str> { self.log_stream_name.as_deref() } /// <p>The creation time of the stream, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(&self) -> std::option::Option<i64> { self.creation_time } /// <p>The time of the first event, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn first_event_timestamp(&self) -> std::option::Option<i64> { self.first_event_timestamp } /// <p>The time of the most recent log event in the log stream in CloudWatch Logs. This number is expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. The <code>lastEventTime</code> value updates on an eventual consistency basis. It typically updates in less than an hour from ingestion, but in rare situations might take longer.</p> pub fn last_event_timestamp(&self) -> std::option::Option<i64> { self.last_event_timestamp } /// <p>The ingestion time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn last_ingestion_time(&self) -> std::option::Option<i64> { self.last_ingestion_time } /// <p>The sequence token.</p> pub fn upload_sequence_token(&self) -> std::option::Option<&str> { self.upload_sequence_token.as_deref() } /// <p>The Amazon Resource Name (ARN) of the log stream.</p> pub fn arn(&self) -> std::option::Option<&str> { self.arn.as_deref() } /// <p>The number of bytes stored.</p> /// <p> <b>Important:</b> On June 17, 2019, this parameter was deprecated for log streams, and is always reported as zero. This change applies only to log streams. The <code>storedBytes</code> parameter for log groups is not affected.</p> pub fn stored_bytes(&self) -> std::option::Option<i64> { self.stored_bytes } } impl std::fmt::Debug for LogStream { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LogStream"); formatter.field("log_stream_name", &self.log_stream_name); formatter.field("creation_time", &self.creation_time); formatter.field("first_event_timestamp", &self.first_event_timestamp); formatter.field("last_event_timestamp", &self.last_event_timestamp); formatter.field("last_ingestion_time", &self.last_ingestion_time); formatter.field("upload_sequence_token", &self.upload_sequence_token); formatter.field("arn", &self.arn); formatter.field("stored_bytes", &self.stored_bytes); formatter.finish() } } /// See [`LogStream`](crate::model::LogStream) pub mod log_stream { /// A builder for [`LogStream`](crate::model::LogStream) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) log_stream_name: std::option::Option<std::string::String>, pub(crate) creation_time: std::option::Option<i64>, pub(crate) first_event_timestamp: std::option::Option<i64>, pub(crate) last_event_timestamp: std::option::Option<i64>, pub(crate) last_ingestion_time: std::option::Option<i64>, pub(crate) upload_sequence_token: std::option::Option<std::string::String>, pub(crate) arn: std::option::Option<std::string::String>, pub(crate) stored_bytes: std::option::Option<i64>, } impl Builder { /// <p>The name of the log stream.</p> pub fn log_stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.log_stream_name = Some(input.into()); self } /// <p>The name of the log stream.</p> pub fn set_log_stream_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.log_stream_name = input; self } /// <p>The creation time of the stream, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(mut self, input: i64) -> Self { self.creation_time = Some(input); self } /// <p>The creation time of the stream, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_creation_time(mut self, input: std::option::Option<i64>) -> Self { self.creation_time = input; self } /// <p>The time of the first event, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn first_event_timestamp(mut self, input: i64) -> Self { self.first_event_timestamp = Some(input); self } /// <p>The time of the first event, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_first_event_timestamp(mut self, input: std::option::Option<i64>) -> Self { self.first_event_timestamp = input; self } /// <p>The time of the most recent log event in the log stream in CloudWatch Logs. This number is expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. The <code>lastEventTime</code> value updates on an eventual consistency basis. It typically updates in less than an hour from ingestion, but in rare situations might take longer.</p> pub fn last_event_timestamp(mut self, input: i64) -> Self { self.last_event_timestamp = Some(input); self } /// <p>The time of the most recent log event in the log stream in CloudWatch Logs. This number is expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. The <code>lastEventTime</code> value updates on an eventual consistency basis. It typically updates in less than an hour from ingestion, but in rare situations might take longer.</p> pub fn set_last_event_timestamp(mut self, input: std::option::Option<i64>) -> Self { self.last_event_timestamp = input; self } /// <p>The ingestion time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn last_ingestion_time(mut self, input: i64) -> Self { self.last_ingestion_time = Some(input); self } /// <p>The ingestion time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_last_ingestion_time(mut self, input: std::option::Option<i64>) -> Self { self.last_ingestion_time = input; self } /// <p>The sequence token.</p> pub fn upload_sequence_token(mut self, input: impl Into<std::string::String>) -> Self { self.upload_sequence_token = Some(input.into()); self } /// <p>The sequence token.</p> pub fn set_upload_sequence_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.upload_sequence_token = input; self } /// <p>The Amazon Resource Name (ARN) of the log stream.</p> pub fn arn(mut self, input: impl Into<std::string::String>) -> Self { self.arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the log stream.</p> pub fn set_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.arn = input; self } /// <p>The number of bytes stored.</p> /// <p> <b>Important:</b> On June 17, 2019, this parameter was deprecated for log streams, and is always reported as zero. This change applies only to log streams. The <code>storedBytes</code> parameter for log groups is not affected.</p> pub fn stored_bytes(mut self, input: i64) -> Self { self.stored_bytes = Some(input); self } /// <p>The number of bytes stored.</p> /// <p> <b>Important:</b> On June 17, 2019, this parameter was deprecated for log streams, and is always reported as zero. This change applies only to log streams. The <code>storedBytes</code> parameter for log groups is not affected.</p> pub fn set_stored_bytes(mut self, input: std::option::Option<i64>) -> Self { self.stored_bytes = input; self } /// Consumes the builder and constructs a [`LogStream`](crate::model::LogStream) pub fn build(self) -> crate::model::LogStream { crate::model::LogStream { log_stream_name: self.log_stream_name, creation_time: self.creation_time, first_event_timestamp: self.first_event_timestamp, last_event_timestamp: self.last_event_timestamp, last_ingestion_time: self.last_ingestion_time, upload_sequence_token: self.upload_sequence_token, arn: self.arn, stored_bytes: self.stored_bytes, } } } } impl LogStream { /// Creates a new builder-style object to manufacture [`LogStream`](crate::model::LogStream) pub fn builder() -> crate::model::log_stream::Builder { crate::model::log_stream::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum OrderBy { #[allow(missing_docs)] // documentation missing in model LastEventTime, #[allow(missing_docs)] // documentation missing in model LogStreamName, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for OrderBy { fn from(s: &str) -> Self { match s { "LastEventTime" => OrderBy::LastEventTime, "LogStreamName" => OrderBy::LogStreamName, other => OrderBy::Unknown(other.to_owned()), } } } impl std::str::FromStr for OrderBy { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(OrderBy::from(s)) } } impl OrderBy { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { OrderBy::LastEventTime => "LastEventTime", OrderBy::LogStreamName => "LogStreamName", OrderBy::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["LastEventTime", "LogStreamName"] } } impl AsRef<str> for OrderBy { fn as_ref(&self) -> &str { self.as_str() } } /// <p>Represents a log group.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LogGroup { /// <p>The name of the log group.</p> pub log_group_name: std::option::Option<std::string::String>, /// <p>The creation time of the log group, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub creation_time: std::option::Option<i64>, /// <p>The number of days to retain the log events in the specified log group. Possible values are: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, and 3653.</p> /// <p>To set a log group to never have log events expire, use <a href="https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteRetentionPolicy.html">DeleteRetentionPolicy</a>. </p> pub retention_in_days: std::option::Option<i32>, /// <p>The number of metric filters.</p> pub metric_filter_count: std::option::Option<i32>, /// <p>The Amazon Resource Name (ARN) of the log group.</p> pub arn: std::option::Option<std::string::String>, /// <p>The number of bytes stored.</p> pub stored_bytes: std::option::Option<i64>, /// <p>The Amazon Resource Name (ARN) of the CMK to use when encrypting log data.</p> pub kms_key_id: std::option::Option<std::string::String>, } impl LogGroup { /// <p>The name of the log group.</p> pub fn log_group_name(&self) -> std::option::Option<&str> { self.log_group_name.as_deref() } /// <p>The creation time of the log group, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(&self) -> std::option::Option<i64> { self.creation_time } /// <p>The number of days to retain the log events in the specified log group. Possible values are: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, and 3653.</p> /// <p>To set a log group to never have log events expire, use <a href="https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteRetentionPolicy.html">DeleteRetentionPolicy</a>. </p> pub fn retention_in_days(&self) -> std::option::Option<i32> { self.retention_in_days } /// <p>The number of metric filters.</p> pub fn metric_filter_count(&self) -> std::option::Option<i32> { self.metric_filter_count } /// <p>The Amazon Resource Name (ARN) of the log group.</p> pub fn arn(&self) -> std::option::Option<&str> { self.arn.as_deref() } /// <p>The number of bytes stored.</p> pub fn stored_bytes(&self) -> std::option::Option<i64> { self.stored_bytes } /// <p>The Amazon Resource Name (ARN) of the CMK to use when encrypting log data.</p> pub fn kms_key_id(&self) -> std::option::Option<&str> { self.kms_key_id.as_deref() } } impl std::fmt::Debug for LogGroup { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LogGroup"); formatter.field("log_group_name", &self.log_group_name); formatter.field("creation_time", &self.creation_time); formatter.field("retention_in_days", &self.retention_in_days); formatter.field("metric_filter_count", &self.metric_filter_count); formatter.field("arn", &self.arn); formatter.field("stored_bytes", &self.stored_bytes); formatter.field("kms_key_id", &self.kms_key_id); formatter.finish() } } /// See [`LogGroup`](crate::model::LogGroup) pub mod log_group { /// A builder for [`LogGroup`](crate::model::LogGroup) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) log_group_name: std::option::Option<std::string::String>, pub(crate) creation_time: std::option::Option<i64>, pub(crate) retention_in_days: std::option::Option<i32>, pub(crate) metric_filter_count: std::option::Option<i32>, pub(crate) arn: std::option::Option<std::string::String>, pub(crate) stored_bytes: std::option::Option<i64>, pub(crate) kms_key_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the log group.</p> pub fn log_group_name(mut self, input: impl Into<std::string::String>) -> Self { self.log_group_name = Some(input.into()); self } /// <p>The name of the log group.</p> pub fn set_log_group_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.log_group_name = input; self } /// <p>The creation time of the log group, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(mut self, input: i64) -> Self { self.creation_time = Some(input); self } /// <p>The creation time of the log group, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_creation_time(mut self, input: std::option::Option<i64>) -> Self { self.creation_time = input; self } /// <p>The number of days to retain the log events in the specified log group. Possible values are: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, and 3653.</p> /// <p>To set a log group to never have log events expire, use <a href="https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteRetentionPolicy.html">DeleteRetentionPolicy</a>. </p> pub fn retention_in_days(mut self, input: i32) -> Self { self.retention_in_days = Some(input); self } /// <p>The number of days to retain the log events in the specified log group. Possible values are: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, and 3653.</p> /// <p>To set a log group to never have log events expire, use <a href="https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteRetentionPolicy.html">DeleteRetentionPolicy</a>. </p> pub fn set_retention_in_days(mut self, input: std::option::Option<i32>) -> Self { self.retention_in_days = input; self } /// <p>The number of metric filters.</p> pub fn metric_filter_count(mut self, input: i32) -> Self { self.metric_filter_count = Some(input); self } /// <p>The number of metric filters.</p> pub fn set_metric_filter_count(mut self, input: std::option::Option<i32>) -> Self { self.metric_filter_count = input; self } /// <p>The Amazon Resource Name (ARN) of the log group.</p> pub fn arn(mut self, input: impl Into<std::string::String>) -> Self { self.arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the log group.</p> pub fn set_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.arn = input; self } /// <p>The number of bytes stored.</p> pub fn stored_bytes(mut self, input: i64) -> Self { self.stored_bytes = Some(input); self } /// <p>The number of bytes stored.</p> pub fn set_stored_bytes(mut self, input: std::option::Option<i64>) -> Self { self.stored_bytes = input; self } /// <p>The Amazon Resource Name (ARN) of the CMK to use when encrypting log data.</p> pub fn kms_key_id(mut self, input: impl Into<std::string::String>) -> Self { self.kms_key_id = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the CMK to use when encrypting log data.</p> pub fn set_kms_key_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.kms_key_id = input; self } /// Consumes the builder and constructs a [`LogGroup`](crate::model::LogGroup) pub fn build(self) -> crate::model::LogGroup { crate::model::LogGroup { log_group_name: self.log_group_name, creation_time: self.creation_time, retention_in_days: self.retention_in_days, metric_filter_count: self.metric_filter_count, arn: self.arn, stored_bytes: self.stored_bytes, kms_key_id: self.kms_key_id, } } } } impl LogGroup { /// Creates a new builder-style object to manufacture [`LogGroup`](crate::model::LogGroup) pub fn builder() -> crate::model::log_group::Builder { crate::model::log_group::Builder::default() } } /// <p>Represents an export task.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ExportTask { /// <p>The ID of the export task.</p> pub task_id: std::option::Option<std::string::String>, /// <p>The name of the export task.</p> pub task_name: std::option::Option<std::string::String>, /// <p>The name of the log group from which logs data was exported.</p> pub log_group_name: std::option::Option<std::string::String>, /// <p>The start time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp before this time are not exported.</p> pub from: std::option::Option<i64>, /// <p>The end time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time are not exported.</p> pub to: std::option::Option<i64>, /// <p>The name of the S3 bucket to which the log data was exported.</p> pub destination: std::option::Option<std::string::String>, /// <p>The prefix that was used as the start of Amazon S3 key for every object exported.</p> pub destination_prefix: std::option::Option<std::string::String>, /// <p>The status of the export task.</p> pub status: std::option::Option<crate::model::ExportTaskStatus>, /// <p>Execution information about the export task.</p> pub execution_info: std::option::Option<crate::model::ExportTaskExecutionInfo>, } impl ExportTask { /// <p>The ID of the export task.</p> pub fn task_id(&self) -> std::option::Option<&str> { self.task_id.as_deref() } /// <p>The name of the export task.</p> pub fn task_name(&self) -> std::option::Option<&str> { self.task_name.as_deref() } /// <p>The name of the log group from which logs data was exported.</p> pub fn log_group_name(&self) -> std::option::Option<&str> { self.log_group_name.as_deref() } /// <p>The start time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp before this time are not exported.</p> pub fn from(&self) -> std::option::Option<i64> { self.from } /// <p>The end time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time are not exported.</p> pub fn to(&self) -> std::option::Option<i64> { self.to } /// <p>The name of the S3 bucket to which the log data was exported.</p> pub fn destination(&self) -> std::option::Option<&str> { self.destination.as_deref() } /// <p>The prefix that was used as the start of Amazon S3 key for every object exported.</p> pub fn destination_prefix(&self) -> std::option::Option<&str> { self.destination_prefix.as_deref() } /// <p>The status of the export task.</p> pub fn status(&self) -> std::option::Option<&crate::model::ExportTaskStatus> { self.status.as_ref() } /// <p>Execution information about the export task.</p> pub fn execution_info(&self) -> std::option::Option<&crate::model::ExportTaskExecutionInfo> { self.execution_info.as_ref() } } impl std::fmt::Debug for ExportTask { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ExportTask"); formatter.field("task_id", &self.task_id); formatter.field("task_name", &self.task_name); formatter.field("log_group_name", &self.log_group_name); formatter.field("from", &self.from); formatter.field("to", &self.to); formatter.field("destination", &self.destination); formatter.field("destination_prefix", &self.destination_prefix); formatter.field("status", &self.status); formatter.field("execution_info", &self.execution_info); formatter.finish() } } /// See [`ExportTask`](crate::model::ExportTask) pub mod export_task { /// A builder for [`ExportTask`](crate::model::ExportTask) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) task_id: std::option::Option<std::string::String>, pub(crate) task_name: std::option::Option<std::string::String>, pub(crate) log_group_name: std::option::Option<std::string::String>, pub(crate) from: std::option::Option<i64>, pub(crate) to: std::option::Option<i64>, pub(crate) destination: std::option::Option<std::string::String>, pub(crate) destination_prefix: std::option::Option<std::string::String>, pub(crate) status: std::option::Option<crate::model::ExportTaskStatus>, pub(crate) execution_info: std::option::Option<crate::model::ExportTaskExecutionInfo>, } impl Builder { /// <p>The ID of the export task.</p> pub fn task_id(mut self, input: impl Into<std::string::String>) -> Self { self.task_id = Some(input.into()); self } /// <p>The ID of the export task.</p> pub fn set_task_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.task_id = input; self } /// <p>The name of the export task.</p> pub fn task_name(mut self, input: impl Into<std::string::String>) -> Self { self.task_name = Some(input.into()); self } /// <p>The name of the export task.</p> pub fn set_task_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.task_name = input; self } /// <p>The name of the log group from which logs data was exported.</p> pub fn log_group_name(mut self, input: impl Into<std::string::String>) -> Self { self.log_group_name = Some(input.into()); self } /// <p>The name of the log group from which logs data was exported.</p> pub fn set_log_group_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.log_group_name = input; self } /// <p>The start time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp before this time are not exported.</p> pub fn from(mut self, input: i64) -> Self { self.from = Some(input); self } /// <p>The start time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp before this time are not exported.</p> pub fn set_from(mut self, input: std::option::Option<i64>) -> Self { self.from = input; self } /// <p>The end time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time are not exported.</p> pub fn to(mut self, input: i64) -> Self { self.to = Some(input); self } /// <p>The end time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time are not exported.</p> pub fn set_to(mut self, input: std::option::Option<i64>) -> Self { self.to = input; self } /// <p>The name of the S3 bucket to which the log data was exported.</p> pub fn destination(mut self, input: impl Into<std::string::String>) -> Self { self.destination = Some(input.into()); self } /// <p>The name of the S3 bucket to which the log data was exported.</p> pub fn set_destination(mut self, input: std::option::Option<std::string::String>) -> Self { self.destination = input; self } /// <p>The prefix that was used as the start of Amazon S3 key for every object exported.</p> pub fn destination_prefix(mut self, input: impl Into<std::string::String>) -> Self { self.destination_prefix = Some(input.into()); self } /// <p>The prefix that was used as the start of Amazon S3 key for every object exported.</p> pub fn set_destination_prefix( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.destination_prefix = input; self } /// <p>The status of the export task.</p> pub fn status(mut self, input: crate::model::ExportTaskStatus) -> Self { self.status = Some(input); self } /// <p>The status of the export task.</p> pub fn set_status( mut self, input: std::option::Option<crate::model::ExportTaskStatus>, ) -> Self { self.status = input; self } /// <p>Execution information about the export task.</p> pub fn execution_info(mut self, input: crate::model::ExportTaskExecutionInfo) -> Self { self.execution_info = Some(input); self } /// <p>Execution information about the export task.</p> pub fn set_execution_info( mut self, input: std::option::Option<crate::model::ExportTaskExecutionInfo>, ) -> Self { self.execution_info = input; self } /// Consumes the builder and constructs a [`ExportTask`](crate::model::ExportTask) pub fn build(self) -> crate::model::ExportTask { crate::model::ExportTask { task_id: self.task_id, task_name: self.task_name, log_group_name: self.log_group_name, from: self.from, to: self.to, destination: self.destination, destination_prefix: self.destination_prefix, status: self.status, execution_info: self.execution_info, } } } } impl ExportTask { /// Creates a new builder-style object to manufacture [`ExportTask`](crate::model::ExportTask) pub fn builder() -> crate::model::export_task::Builder { crate::model::export_task::Builder::default() } } /// <p>Represents the status of an export task.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ExportTaskExecutionInfo { /// <p>The creation time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub creation_time: std::option::Option<i64>, /// <p>The completion time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub completion_time: std::option::Option<i64>, } impl ExportTaskExecutionInfo { /// <p>The creation time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(&self) -> std::option::Option<i64> { self.creation_time } /// <p>The completion time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn completion_time(&self) -> std::option::Option<i64> { self.completion_time } } impl std::fmt::Debug for ExportTaskExecutionInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ExportTaskExecutionInfo"); formatter.field("creation_time", &self.creation_time); formatter.field("completion_time", &self.completion_time); formatter.finish() } } /// See [`ExportTaskExecutionInfo`](crate::model::ExportTaskExecutionInfo) pub mod export_task_execution_info { /// A builder for [`ExportTaskExecutionInfo`](crate::model::ExportTaskExecutionInfo) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) creation_time: std::option::Option<i64>, pub(crate) completion_time: std::option::Option<i64>, } impl Builder { /// <p>The creation time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn creation_time(mut self, input: i64) -> Self { self.creation_time = Some(input); self } /// <p>The creation time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_creation_time(mut self, input: std::option::Option<i64>) -> Self { self.creation_time = input; self } /// <p>The completion time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn completion_time(mut self, input: i64) -> Self { self.completion_time = Some(input); self } /// <p>The completion time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.</p> pub fn set_completion_time(mut self, input: std::option::Option<i64>) -> Self { self.completion_time = input; self } /// Consumes the builder and constructs a [`ExportTaskExecutionInfo`](crate::model::ExportTaskExecutionInfo) pub fn build(self) -> crate::model::ExportTaskExecutionInfo { crate::model::ExportTaskExecutionInfo { creation_time: self.creation_time, completion_time: self.completion_time, } } } } impl ExportTaskExecutionInfo { /// Creates a new builder-style object to manufacture [`ExportTaskExecutionInfo`](crate::model::ExportTaskExecutionInfo) pub fn builder() -> crate::model::export_task_execution_info::Builder { crate::model::export_task_execution_info::Builder::default() } } /// <p>Represents the status of an export task.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ExportTaskStatus { /// <p>The status code of the export task.</p> pub code: std::option::Option<crate::model::ExportTaskStatusCode>, /// <p>The status message related to the status code.</p> pub message: std::option::Option<std::string::String>, } impl ExportTaskStatus { /// <p>The status code of the export task.</p> pub fn code(&self) -> std::option::Option<&crate::model::ExportTaskStatusCode> { self.code.as_ref() } /// <p>The status message related to the status code.</p> pub fn message(&self) -> std::option::Option<&str> { self.message.as_deref() } } impl std::fmt::Debug for ExportTaskStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ExportTaskStatus"); formatter.field("code", &self.code); formatter.field("message", &self.message); formatter.finish() } } /// See [`ExportTaskStatus`](crate::model::ExportTaskStatus) pub mod export_task_status { /// A builder for [`ExportTaskStatus`](crate::model::ExportTaskStatus) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) code: std::option::Option<crate::model::ExportTaskStatusCode>, pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The status code of the export task.</p> pub fn code(mut self, input: crate::model::ExportTaskStatusCode) -> Self { self.code = Some(input); self } /// <p>The status code of the export task.</p> pub fn set_code( mut self, input: std::option::Option<crate::model::ExportTaskStatusCode>, ) -> Self { self.code = input; self } /// <p>The status message related to the status code.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The status message related to the status code.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ExportTaskStatus`](crate::model::ExportTaskStatus) pub fn build(self) -> crate::model::ExportTaskStatus { crate::model::ExportTaskStatus { code: self.code, message: self.message, } } } } impl ExportTaskStatus { /// Creates a new builder-style object to manufacture [`ExportTaskStatus`](crate::model::ExportTaskStatus) pub fn builder() -> crate::model::export_task_status::Builder { crate::model::export_task_status::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum ExportTaskStatusCode { #[allow(missing_docs)] // documentation missing in model Cancelled, #[allow(missing_docs)] // documentation missing in model Completed, #[allow(missing_docs)] // documentation missing in model Failed, #[allow(missing_docs)] // documentation missing in model Pending, #[allow(missing_docs)] // documentation missing in model PendingCancel, #[allow(missing_docs)] // documentation missing in model Running, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for ExportTaskStatusCode { fn from(s: &str) -> Self { match s { "CANCELLED" => ExportTaskStatusCode::Cancelled, "COMPLETED" => ExportTaskStatusCode::Completed, "FAILED" => ExportTaskStatusCode::Failed, "PENDING" => ExportTaskStatusCode::Pending, "PENDING_CANCEL" => ExportTaskStatusCode::PendingCancel, "RUNNING" => ExportTaskStatusCode::Running, other => ExportTaskStatusCode::Unknown(other.to_owned()), } } } impl std::str::FromStr for ExportTaskStatusCode { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(ExportTaskStatusCode::from(s)) } } impl ExportTaskStatusCode { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { ExportTaskStatusCode::Cancelled => "CANCELLED", ExportTaskStatusCode::Completed => "COMPLETED", ExportTaskStatusCode::Failed => "FAILED", ExportTaskStatusCode::Pending => "PENDING", ExportTaskStatusCode::PendingCancel => "PENDING_CANCEL", ExportTaskStatusCode::Running => "RUNNING", ExportTaskStatusCode::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &[ "CANCELLED", "COMPLETED", "FAILED", "PENDING", "PENDING_CANCEL", "RUNNING", ] } } impl AsRef<str> for ExportTaskStatusCode { fn as_ref(&self) -> &str { self.as_str() } }
46.070807
360
0.622671
f963caf350ed865eb90b338c5f131e792362219f
585
#[macro_export] macro_rules! io_write_port { (u8, $port:expr, $value:expr) => { asm!("out %al, %dx" :: "{dx}"($port), "{al}"($value) :: "volatile") }; (u16, $port:expr, $value:expr) => { asm!("out %ax, %dx" :: "{dx}"($port), "{ax}"($value) :: "volatile") }; (u32, $port:expr, $value:expr) => { asm!("out %eax, %dx" :: "{dx}"($port), "{eax}"($value) :: "volatile") }; } #[macro_export] macro_rules! io_read_port { (u8, $port:expr) => { let result: u8; asm!("in %dx, %al" : "={al}"($result) : "{dx}"($port) :: "volatile"); result }; }
34.411765
112
0.483761
64cf02f932bf18791e891e893d4ec94782528fc7
299
mod salle_a_manger { pub mod accueil { pub fn ajouter_a_la_liste_attente() {} } } use crate::salle_a_manger::accueil; pub fn manger_au_restaurant() { accueil::ajouter_a_la_liste_attente(); accueil::ajouter_a_la_liste_attente(); accueil::ajouter_a_la_liste_attente(); }
21.357143
46
0.715719
01fbc01cf75f4147ea6651028f161131a87752c0
30,959
//! Fixtures for testing Raft. #![allow(dead_code)] use std::collections::BTreeMap; use std::collections::BTreeSet; use std::collections::HashSet; use std::env; use std::sync::Arc; use std::sync::Mutex; use std::sync::Once; use std::time::Duration; use anyerror::AnyError; use anyhow::Context; use anyhow::Result; use lazy_static::lazy_static; use maplit::btreeset; use memstore::ClientRequest as MemClientRequest; use memstore::ClientRequest; use memstore::ClientResponse; use memstore::ClientResponse as MemClientResponse; use memstore::MemStore; use openraft::async_trait::async_trait; use openraft::error::AddLearnerError; use openraft::error::AppendEntriesError; use openraft::error::ClientReadError; use openraft::error::ClientWriteError; use openraft::error::InstallSnapshotError; use openraft::error::NetworkError; use openraft::error::NodeNotFound; use openraft::error::RPCError; use openraft::error::RemoteError; use openraft::error::VoteError; use openraft::metrics::Wait; use openraft::raft::AddLearnerResponse; use openraft::raft::AppendEntriesRequest; use openraft::raft::AppendEntriesResponse; use openraft::raft::ClientWriteRequest; use openraft::raft::Entry; use openraft::raft::EntryPayload; use openraft::raft::InstallSnapshotRequest; use openraft::raft::InstallSnapshotResponse; use openraft::raft::VoteRequest; use openraft::raft::VoteResponse; use openraft::storage::RaftStorage; use openraft::AppData; use openraft::Config; use openraft::DefensiveCheck; use openraft::LeaderId; use openraft::LogId; use openraft::LogIdOptionExt; use openraft::Node; use openraft::NodeId; use openraft::Raft; use openraft::RaftMetrics; use openraft::RaftNetwork; use openraft::State; use openraft::StoreExt; #[allow(unused_imports)] use pretty_assertions::assert_eq; #[allow(unused_imports)] use pretty_assertions::assert_ne; use tracing_appender::non_blocking::WorkerGuard; use crate::fixtures::logging::init_file_logging; pub mod logging; macro_rules! func_name { () => {{ fn f() {} fn type_name_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } let name = type_name_of(f); let n = &name[..name.len() - 3]; let nn = n.replace("::{{closure}}", ""); nn }}; } macro_rules! init_ut { () => {{ let name = func_name!(); let last = name.split("::").last().unwrap(); let g = crate::fixtures::init_default_ut_tracing(); let span = tracing::debug_span!("ut", "{}", last); (g, span) }}; } pub type StoreWithDefensive = StoreExt<ClientRequest, ClientResponse, MemStore>; /// A concrete Raft type used during testing. pub type MemRaft = Raft<MemClientRequest, MemClientResponse, RaftRouter, StoreWithDefensive>; pub fn init_default_ut_tracing() { static START: Once = Once::new(); START.call_once(|| { let mut g = GLOBAL_UT_LOG_GUARD.as_ref().lock().unwrap(); *g = Some(init_global_tracing("ut", "_log", "DEBUG")); }); } lazy_static! { static ref GLOBAL_UT_LOG_GUARD: Arc<Mutex<Option<WorkerGuard>>> = Arc::new(Mutex::new(None)); } pub fn init_global_tracing(app_name: &str, dir: &str, level: &str) -> WorkerGuard { let (g, sub) = init_file_logging(app_name, dir, level); tracing::subscriber::set_global_default(sub).expect("error setting global tracing subscriber"); tracing::info!("initialized global tracing: in {}/{} at {}", dir, app_name, level); g } /// A type which emulates a network transport and implements the `RaftNetwork` trait. pub struct RaftRouter { /// The Raft runtime config which all nodes are using. config: Arc<Config>, /// The table of all nodes currently known to this router instance. routing_table: Mutex<BTreeMap<NodeId, (MemRaft, Arc<StoreWithDefensive>)>>, /// Nodes which are isolated can neither send nor receive frames. isolated_nodes: Mutex<HashSet<NodeId>>, /// To enumlate network delay for sending, in milli second. /// 0 means no delay. send_delay: u64, } pub struct Builder { config: Arc<Config>, send_delay: u64, } impl Builder { pub fn send_delay(mut self, ms: u64) -> Self { self.send_delay = ms; self } pub fn build(self) -> RaftRouter { RaftRouter { config: self.config, routing_table: Default::default(), isolated_nodes: Default::default(), send_delay: self.send_delay, } } } impl RaftRouter { pub fn builder(config: Arc<Config>) -> Builder { Builder { config, send_delay: 0 } } /// Create a new instance. pub fn new(config: Arc<Config>) -> Self { Self::builder(config).build() } pub fn network_send_delay(&mut self, ms: u64) { self.send_delay = ms; } #[tracing::instrument(level = "debug", skip(self))] async fn rand_send_delay(&self) { if self.send_delay == 0 { return; } let r = rand::random::<u64>() % self.send_delay; let timeout = Duration::from_millis(r); tokio::time::sleep(timeout).await; } /// Create a cluster: 0 is the initial leader, others are voters and learners /// NOTE: it create a single node cluster first, then change it to a multi-voter cluster. #[tracing::instrument(level = "debug", skip(self))] pub async fn new_nodes_from_single( self: &Arc<Self>, node_ids: BTreeSet<NodeId>, learners: BTreeSet<NodeId>, ) -> anyhow::Result<u64> { assert!(node_ids.contains(&0)); self.new_raft_node(0).await; tracing::info!("--- wait for init node to ready"); self.wait_for_log(&btreeset![0], None, timeout(), "empty").await?; self.wait_for_state(&btreeset![0], State::Learner, timeout(), "empty").await?; tracing::info!("--- initializing single node cluster: {}", 0); self.initialize_from_single_node(0).await?; let mut log_index = 1; // log 0: initial membership log; log 1: leader initial log tracing::info!("--- wait for init node to become leader"); self.wait_for_log(&btreeset![0], Some(log_index), timeout(), "init").await?; self.assert_stable_cluster(Some(1), Some(log_index)).await; for id in node_ids.iter() { if *id == 0 { continue; } tracing::info!("--- add voter: {}", id); self.new_raft_node(*id).await; self.add_learner(0, *id).await?; log_index += 1; } self.wait_for_log( &node_ids, Some(log_index), timeout(), &format!("learners of {:?}", node_ids), ) .await?; if node_ids.len() > 1 { tracing::info!("--- change membership to setup voters: {:?}", node_ids); let node = self.get_raft_handle(&0)?; node.change_membership(node_ids.clone(), true, false).await?; log_index += 2; self.wait_for_log( &node_ids, Some(log_index), timeout(), &format!("cluster of {:?}", node_ids), ) .await?; } for id in learners.clone() { tracing::info!("--- add learner: {}", id); self.new_raft_node(id).await; self.add_learner(0, id).await?; log_index += 1; } self.wait_for_log( &learners, Some(log_index), timeout(), &format!("learners of {:?}", learners), ) .await?; Ok(log_index) } /// Create and register a new Raft node bearing the given ID. pub async fn new_raft_node(self: &Arc<Self>, id: NodeId) { let memstore = self.new_store().await; self.new_raft_node_with_sto(id, memstore).await } pub async fn new_store(self: &Arc<Self>) -> Arc<StoreWithDefensive> { let defensive = env::var("RAFT_STORE_DEFENSIVE").ok(); let sto = Arc::new(StoreExt::new(MemStore::new().await)); if let Some(d) = defensive { tracing::info!("RAFT_STORE_DEFENSIVE set store defensive to {}", d); let want = if d == "on" { true } else if d == "off" { false } else { tracing::warn!("unknown value of RAFT_STORE_DEFENSIVE: {}", d); return sto; }; sto.set_defensive(want); if sto.is_defensive() != want { tracing::error!("failure to set store defensive to {}", want); } } sto } #[tracing::instrument(level = "debug", skip(self, sto))] pub async fn new_raft_node_with_sto(self: &Arc<Self>, id: NodeId, sto: Arc<StoreWithDefensive>) { let node = Raft::new(id, self.config.clone(), self.clone(), sto.clone()); let mut rt = self.routing_table.lock().unwrap(); rt.insert(id, (node, sto)); } /// Remove the target node from the routing table & isolation. pub async fn remove_node(&self, id: NodeId) -> Option<(MemRaft, Arc<StoreWithDefensive>)> { let opt_handles = { let mut rt = self.routing_table.lock().unwrap(); rt.remove(&id) }; { let mut isolated = self.isolated_nodes.lock().unwrap(); isolated.remove(&id); } opt_handles } /// Initialize all nodes based on the config in the routing table. pub async fn initialize_from_single_node(&self, node_id: NodeId) -> Result<()> { tracing::info!({ node_id }, "initializing cluster from single node"); let members: BTreeSet<NodeId> = { let rt = self.routing_table.lock().unwrap(); rt.keys().cloned().collect() }; let node = self.get_raft_handle(&node_id)?; node.initialize(members.clone()).await?; Ok(()) } /// Initialize cluster with specified node ids. pub async fn initialize_with(&self, node_id: NodeId, members: BTreeSet<NodeId>) -> Result<()> { tracing::info!({ node_id }, "initializing cluster from single node"); let n = self.get_raft_handle(&node_id)?; n.initialize(members.clone()).await?; Ok(()) } /// Isolate the network of the specified node. #[tracing::instrument(level = "debug", skip(self))] pub async fn isolate_node(&self, id: NodeId) { self.isolated_nodes.lock().unwrap().insert(id); } /// Get a payload of the latest metrics from each node in the cluster. pub fn latest_metrics(&self) -> Vec<RaftMetrics> { let rt = self.routing_table.lock().unwrap(); let mut metrics = vec![]; for node in rt.values() { metrics.push(node.0.metrics().borrow().clone()); } metrics } pub fn get_metrics(&self, node_id: &NodeId) -> Result<RaftMetrics> { let node = self.get_raft_handle(node_id)?; let metrics = node.metrics().borrow().clone(); Ok(metrics) } #[tracing::instrument(level = "debug", skip(self))] pub fn get_raft_handle(&self, node_id: &NodeId) -> std::result::Result<MemRaft, NodeNotFound> { let rt = self.routing_table.lock().unwrap(); let raft_and_sto = rt.get(node_id).ok_or_else(|| NodeNotFound { node_id: *node_id, source: AnyError::error(""), })?; let r = raft_and_sto.clone().0; Ok(r) } pub fn get_storage_handle(&self, node_id: &NodeId) -> Result<Arc<StoreWithDefensive>> { let rt = self.routing_table.lock().unwrap(); let addr = rt.get(node_id).with_context(|| format!("could not find node {} in routing table", node_id))?; let sto = addr.clone().1; Ok(sto) } /// Wait for metrics until it satisfies some condition. #[tracing::instrument(level = "info", skip(self, func))] pub async fn wait_for_metrics<T>( &self, node_id: &NodeId, func: T, timeout: Option<Duration>, msg: &str, ) -> Result<RaftMetrics> where T: Fn(&RaftMetrics) -> bool + Send, { let wait = self.wait(node_id, timeout).await?; let rst = wait.metrics(func, format!("node-{} {}", node_id, msg)).await?; Ok(rst) } pub async fn wait(&self, node_id: &NodeId, timeout: Option<Duration>) -> Result<Wait> { let node = { let rt = self.routing_table.lock().unwrap(); rt.get(node_id).expect("target node not found in routing table").clone().0 }; Ok(node.wait(timeout)) } /// Wait for specified nodes until they applied upto `want_log`(inclusive) logs. #[tracing::instrument(level = "info", skip(self))] pub async fn wait_for_log( &self, node_ids: &BTreeSet<u64>, want_log: Option<u64>, timeout: Option<Duration>, msg: &str, ) -> Result<()> { for i in node_ids.iter() { self.wait(i, timeout).await?.log(want_log, msg).await?; } Ok(()) } #[tracing::instrument(level = "info", skip(self))] pub async fn wait_for_members( &self, node_ids: &BTreeSet<u64>, members: BTreeSet<u64>, timeout: Option<Duration>, msg: &str, ) -> Result<()> { for i in node_ids.iter() { let wait = self.wait(i, timeout).await?; wait.metrics( |x| { x.membership_config.get_configs().len() == 1 && x.membership_config.get_configs()[0].clone() == members }, msg, ) .await?; } Ok(()) } /// Wait for specified nodes until their state becomes `state`. #[tracing::instrument(level = "info", skip(self))] pub async fn wait_for_state( &self, node_ids: &BTreeSet<u64>, want_state: State, timeout: Option<Duration>, msg: &str, ) -> Result<()> { for i in node_ids.iter() { self.wait(i, timeout).await?.state(want_state, msg).await?; } Ok(()) } /// Wait for specified nodes until their snapshot becomes `want`. #[tracing::instrument(level = "info", skip(self))] pub async fn wait_for_snapshot( &self, node_ids: &BTreeSet<u64>, want: LogId, timeout: Option<Duration>, msg: &str, ) -> Result<()> { for i in node_ids.iter() { self.wait(i, timeout).await?.snapshot(want, msg).await?; } Ok(()) } /// Get the ID of the current leader. pub fn leader(&self) -> Option<NodeId> { let isolated = { let isolated = self.isolated_nodes.lock().unwrap(); isolated.clone() }; self.latest_metrics().into_iter().find_map(|node| { if node.current_leader == Some(node.id) { if isolated.contains(&node.id) { None } else { Some(node.id) } } else { None } }) } /// Restore the network of the specified node. #[tracing::instrument(level = "debug", skip(self))] pub async fn restore_node(&self, id: NodeId) { let mut nodes = self.isolated_nodes.lock().unwrap(); nodes.remove(&id); } pub async fn add_learner(&self, leader: NodeId, target: NodeId) -> Result<AddLearnerResponse, AddLearnerError> { let node = self.get_raft_handle(&leader).unwrap(); node.add_learner(target, None, true).await } pub async fn add_learner_with_blocking( &self, leader: NodeId, target: NodeId, blocking: bool, ) -> Result<AddLearnerResponse, AddLearnerError> { let node = { let rt = self.routing_table.lock().unwrap(); rt.get(&leader).unwrap_or_else(|| panic!("node with ID {} does not exist", leader)).clone() }; node.0.add_learner(target, None, blocking).await } /// Send a client read request to the target node. pub async fn client_read(&self, target: NodeId) -> Result<(), ClientReadError> { let node = { let rt = self.routing_table.lock().unwrap(); rt.get(&target).unwrap_or_else(|| panic!("node with ID {} does not exist", target)).clone() }; node.0.client_read().await } /// Send a client request to the target node, causing test failure on error. pub async fn client_request(&self, target: NodeId, client_id: &str, serial: u64) { let req = MemClientRequest { client: client_id.into(), serial, status: format!("request-{}", serial), }; if let Err(err) = self.send_client_request(target, req).await { tracing::error!({error=%err}, "error from client request"); panic!("{:?}", err) } } /// Request the current leader from the target node. pub async fn current_leader(&self, target: NodeId) -> Option<NodeId> { let node = self.get_raft_handle(&target).unwrap(); node.current_leader().await } /// Send multiple client requests to the target node, causing test failure on error. pub async fn client_request_many(&self, target: NodeId, client_id: &str, count: usize) { for idx in 0..count { self.client_request(target, client_id, idx as u64).await } } async fn send_client_request( &self, target: NodeId, req: MemClientRequest, ) -> std::result::Result<MemClientResponse, ClientWriteError> { let node = { let rt = self.routing_table.lock().unwrap(); rt.get(&target) .unwrap_or_else(|| panic!("node '{}' does not exist in routing table", target)) .clone() }; let payload = EntryPayload::Normal(req); node.0.client_write(ClientWriteRequest::new(payload)).await.map(|res| res.data) } /// Assert that the cluster is in a pristine state, with all nodes as learners. pub async fn assert_pristine_cluster(&self) { let nodes = self.latest_metrics(); for node in nodes.iter() { assert!( node.current_leader.is_none(), "node {} has a current leader: {:?}, expected none", node.id, node.current_leader, ); assert_eq!( node.state, State::Learner, "node is in state {:?}, expected Learner", node.state ); assert_eq!( node.current_term, 0, "node {} has term {}, expected 0", node.id, node.current_term ); assert_eq!( None, node.last_applied.index(), "node {} has last_applied {:?}, expected None", node.id, node.last_applied ); assert_eq!( None, node.last_log_index, "node {} has last_log_index {:?}, expected None", node.id, node.last_log_index ); let members = node.membership_config.get_configs()[0].clone(); assert_eq!( members.iter().cloned().collect::<Vec<_>>(), vec![node.id], "node {0} has membership {1:?}, expected [{0}]", node.id, members ); assert!( !node.membership_config.membership.is_in_joint_consensus(), "node {} is in joint consensus, expected uniform consensus", node.id ); } } /// Assert that the cluster has an elected leader, and is in a stable state with all nodes uniform. /// /// If `expected_term` is `Some`, then all nodes will be tested to ensure that they are in the /// given term. Else, the leader's current term will be used for the assertion. /// /// If `expected_last_log` is `Some`, then all nodes will be tested to ensure that their last /// log index and last applied log match the given value. Else, the leader's last_log_index /// will be used for the assertion. pub async fn assert_stable_cluster(&self, expected_term: Option<u64>, expected_last_log: Option<u64>) { let isolated = { let x = self.isolated_nodes.lock().unwrap(); x.clone() }; let nodes = self.latest_metrics(); let non_isolated_nodes: Vec<_> = nodes.iter().filter(|node| !isolated.contains(&node.id)).collect(); let leader = nodes .iter() .filter(|node| !isolated.contains(&node.id)) .find(|node| node.state == State::Leader) .expect("expected to find a cluster leader"); let followers: Vec<_> = nodes .iter() .filter(|node| !isolated.contains(&node.id)) .filter(|node| node.state == State::Follower) .collect(); assert_eq!( followers.len() + 1, non_isolated_nodes.len(), "expected all nodes to be followers with one leader, got 1 leader and {} followers, expected {} followers", followers.len(), non_isolated_nodes.len() - 1, ); let expected_term = match expected_term { Some(term) => term, None => leader.current_term, }; let expected_last_log = if expected_last_log.is_some() { expected_last_log } else { leader.last_log_index }; let all_nodes = nodes.iter().map(|node| node.id).collect::<Vec<_>>(); for node in non_isolated_nodes.iter() { assert_eq!( node.current_leader, Some(leader.id), "node {} has leader {:?}, expected {}", node.id, node.current_leader, leader.id ); assert_eq!( node.current_term, expected_term, "node {} has term {}, expected {}", node.id, node.current_term, expected_term ); assert_eq!( node.last_applied.index(), expected_last_log, "node {} has last_applied {:?}, expected {:?}", node.id, node.last_applied, expected_last_log ); assert_eq!( node.last_log_index, expected_last_log, "node {} has last_log_index {:?}, expected {:?}", node.id, node.last_log_index, expected_last_log ); let members = node.membership_config.get_configs()[0].clone(); let mut members = members.into_iter().collect::<Vec<_>>(); members.sort_unstable(); assert_eq!( members, all_nodes, "node {} has membership {:?}, expected {:?}", node.id, members, all_nodes ); assert!( !node.membership_config.membership.is_in_joint_consensus(), "node {} was not in uniform consensus state", node.id ); } } /// Assert against the state of the storage system one node in the cluster. pub async fn assert_storage_state_with_sto( &self, storage: &Arc<StoreWithDefensive>, id: &u64, expect_term: u64, expect_last_log: u64, expect_voted_for: Option<u64>, expect_sm_last_applied_log: LogId, expect_snapshot: &Option<(ValueTest<u64>, u64)>, ) -> anyhow::Result<()> { let last_log_id = storage.get_log_state().await?.last_log_id; assert_eq!( expect_last_log, last_log_id.index().unwrap(), "expected node {} to have last_log {}, got {:?}", id, expect_last_log, last_log_id ); let vote = storage.read_vote().await?.unwrap_or_else(|| panic!("no hard state found for node {}", id)); assert_eq!( vote.term, expect_term, "expected node {} to have term {}, got {:?}", id, expect_term, vote ); if let Some(voted_for) = &expect_voted_for { assert_eq!( vote.node_id, *voted_for, "expected node {} to have voted for {}, got {:?}", id, voted_for, vote ); } if let Some((index_test, term)) = &expect_snapshot { let snap = storage .get_current_snapshot() .await .map_err(|err| panic!("{}", err)) .unwrap() .unwrap_or_else(|| panic!("no snapshot present for node {}", id)); match index_test { ValueTest::Exact(index) => assert_eq!( &snap.meta.last_log_id.index, index, "expected node {} to have snapshot with index {}, got {}", id, index, snap.meta.last_log_id.index ), ValueTest::Range(range) => assert!( range.contains(&snap.meta.last_log_id.index), "expected node {} to have snapshot within range {:?}, got {}", id, range, snap.meta.last_log_id.index ), } assert_eq!( &snap.meta.last_log_id.leader_id.term, term, "expected node {} to have snapshot with term {}, got {}", id, term, snap.meta.last_log_id.leader_id.term ); } let (last_applied, _) = storage.last_applied_state().await?; assert_eq!( &last_applied, &Some(expect_sm_last_applied_log), "expected node {} to have state machine last_applied_log {}, got {:?}", id, expect_sm_last_applied_log, last_applied ); Ok(()) } /// Assert against the state of the storage system one node in the cluster. pub async fn assert_storage_state_in_node( &self, node_id: u64, expect_term: u64, expect_last_log: u64, expect_voted_for: Option<u64>, expect_sm_last_applied_log: LogId, expect_snapshot: Option<(ValueTest<u64>, u64)>, ) -> anyhow::Result<()> { let rt = self.routing_table.lock().unwrap(); for (id, (_node, storage)) in rt.iter() { if *id != node_id { continue; } self.assert_storage_state_with_sto( storage, id, expect_term, expect_last_log, expect_voted_for, expect_sm_last_applied_log, &expect_snapshot, ) .await?; break; } Ok(()) } /// Assert against the state of the storage system per node in the cluster. pub async fn assert_storage_state( &self, expect_term: u64, expect_last_log: u64, expect_voted_for: Option<u64>, expect_sm_last_applied_log: LogId, expect_snapshot: Option<(ValueTest<u64>, u64)>, ) -> anyhow::Result<()> { let rt = self.routing_table.lock().unwrap(); for (id, (_node, storage)) in rt.iter() { self.assert_storage_state_with_sto( storage, id, expect_term, expect_last_log, expect_voted_for, expect_sm_last_applied_log, &expect_snapshot, ) .await?; } Ok(()) } #[tracing::instrument(level = "debug", skip(self))] pub fn check_reachable(&self, id: NodeId, target: NodeId) -> std::result::Result<(), NetworkError> { let isolated = self.isolated_nodes.lock().unwrap(); if isolated.contains(&target) || isolated.contains(&id) { let network_err = NetworkError::new(&AnyError::error(format!("isolated:{} -> {}", id, target))); return Err(network_err); } Ok(()) } } #[async_trait] impl RaftNetwork<MemClientRequest> for RaftRouter { /// Send an AppendEntries RPC to the target Raft node (Β§5). async fn send_append_entries( &self, target: u64, _target_node: Option<&Node>, rpc: AppendEntriesRequest<MemClientRequest>, ) -> std::result::Result<AppendEntriesResponse, RPCError<AppendEntriesError>> { tracing::debug!("append_entries to id={} {:?}", target, rpc); self.rand_send_delay().await; self.check_reachable(rpc.vote.node_id, target)?; let node = self.get_raft_handle(&target)?; let resp = node.append_entries(rpc).await; tracing::debug!("append_entries: recv resp from id={} {:?}", target, resp); let resp = resp.map_err(|e| RemoteError::new(target, e))?; Ok(resp) } /// Send an InstallSnapshot RPC to the target Raft node (Β§7). async fn send_install_snapshot( &self, target: u64, _target_node: Option<&Node>, rpc: InstallSnapshotRequest, ) -> std::result::Result<InstallSnapshotResponse, RPCError<InstallSnapshotError>> { self.rand_send_delay().await; self.check_reachable(rpc.vote.node_id, target)?; let node = self.get_raft_handle(&target)?; let resp = node.install_snapshot(rpc).await; let resp = resp.map_err(|e| RemoteError::new(target, e))?; Ok(resp) } /// Send a RequestVote RPC to the target Raft node (Β§5). async fn send_vote( &self, target: u64, _target_node: Option<&Node>, rpc: VoteRequest, ) -> std::result::Result<VoteResponse, RPCError<VoteError>> { self.rand_send_delay().await; self.check_reachable(rpc.vote.node_id, target)?; let node = self.get_raft_handle(&target)?; let resp = node.vote(rpc).await; let resp = resp.map_err(|e| RemoteError::new(target, e))?; Ok(resp) } } pub enum ValueTest<T> { Exact(T), Range(std::ops::Range<T>), } impl<T> From<T> for ValueTest<T> { fn from(src: T) -> Self { Self::Exact(src) } } impl<T> From<std::ops::Range<T>> for ValueTest<T> { fn from(src: std::ops::Range<T>) -> Self { Self::Range(src) } } fn timeout() -> Option<Duration> { Some(Duration::from_millis(5000)) } /// Create a blank log entry for test. pub fn blank<T: AppData>(term: u64, index: u64) -> Entry<T> { Entry { log_id: LogId::new(LeaderId::new(term, 0), index), payload: EntryPayload::Blank, } }
32.795551
119
0.561355
89a0782732fa796cd714c6cd069bf89009c2d0d0
770
// Copyright 2019-2021 Parity Technologies (UK) Ltd. // This file is part of substrate-subxt. // // subxt is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // subxt is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see <http://www.gnu.org/licenses/>. pub mod chain_spec; pub mod service;
40.526316
75
0.748052
ef99425d2f054642b1561fa48c14d250b3a95f44
2,052
use crate::inspector::editors::PropertyEditorTranslationContext; use crate::{ color::{ColorFieldBuilder, ColorFieldMessage}, core::color::Color, inspector::{ editors::{ PropertyEditorBuildContext, PropertyEditorDefinition, PropertyEditorInstance, PropertyEditorMessageContext, }, FieldKind, InspectorError, PropertyChanged, }, message::{MessageDirection, UiMessage}, widget::WidgetBuilder, Thickness, }; use std::any::TypeId; #[derive(Debug)] pub struct ColorPropertyEditorDefinition; impl PropertyEditorDefinition for ColorPropertyEditorDefinition { fn value_type_id(&self) -> TypeId { TypeId::of::<Color>() } fn create_instance( &self, ctx: PropertyEditorBuildContext, ) -> Result<PropertyEditorInstance, InspectorError> { let value = ctx.property_info.cast_value::<Color>()?; Ok(PropertyEditorInstance::Simple { editor: ColorFieldBuilder::new( WidgetBuilder::new().with_margin(Thickness::uniform(1.0)), ) .with_color(*value) .build(ctx.build_context), }) } fn create_message( &self, ctx: PropertyEditorMessageContext, ) -> Result<Option<UiMessage>, InspectorError> { let value = ctx.property_info.cast_value::<Color>()?; Ok(Some(ColorFieldMessage::color( ctx.instance, MessageDirection::ToWidget, *value, ))) } fn translate_message(&self, ctx: PropertyEditorTranslationContext) -> Option<PropertyChanged> { if ctx.message.direction() == MessageDirection::FromWidget { if let Some(ColorFieldMessage::Color(value)) = ctx.message.data::<ColorFieldMessage>() { return Some(PropertyChanged { name: ctx.name.to_string(), owner_type_id: ctx.owner_type_id, value: FieldKind::object(*value), }); } } None } }
31.569231
100
0.609162
ac1d7edb80c1956c1db3fafa3bc16c47dd0b9333
8,846
use crate::commands::constants::BAT_LANGUAGES; use crate::prelude::*; use encoding_rs::{Encoding, UTF_8}; use log::debug; use nu_engine::StringOrBinary; use nu_engine::WholeStreamCommand; use nu_errors::ShellError; use nu_protocol::{CommandAction, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value}; use nu_source::{AnchorLocation, Span, Tagged}; use std::path::{Path, PathBuf}; pub struct Open; impl WholeStreamCommand for Open { fn name(&self) -> &str { "open" } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "path", SyntaxShape::FilePath, "the file path to load values from", ) .switch( "raw", "load content as a string instead of a table", Some('r'), ) .named( "encoding", SyntaxShape::String, "encoding to use to open file", Some('e'), ) } fn usage(&self) -> &str { "Load a file into a cell, convert to table if possible (avoid by appending '--raw')." } fn extra_usage(&self) -> &str { r#"Multiple encodings are supported for reading text files by using the '--encoding <encoding>' parameter. Here is an example of a few: big5, euc-jp, euc-kr, gbk, iso-8859-1, utf-16, cp1252, latin5 For a more complete list of encodings please refer to the encoding_rs documentation link at https://docs.rs/encoding_rs/0.8.28/encoding_rs/#statics"# } fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { open(args) } fn examples(&self) -> Vec<Example> { vec![ Example { description: "Opens \"users.csv\" and creates a table from the data", example: "open users.csv", result: None, }, Example { description: "Opens file with iso-8859-1 encoding", example: "open file.csv --encoding iso-8859-1 | from csv", result: None, }, Example { description: "Lists the contents of a directory (identical to `ls ../projectB`)", example: "open ../projectB", result: None, }, ] } } pub fn get_encoding(opt: Option<Tagged<String>>) -> Result<&'static Encoding, ShellError> { match opt { None => Ok(UTF_8), Some(label) => match Encoding::for_label((&label.item).as_bytes()) { None => Err(ShellError::labeled_error( format!( r#"{} is not a valid encoding, refer to https://docs.rs/encoding_rs/0.8.23/encoding_rs/#statics for a valid list of encodings"#, label.item ), "invalid encoding", label.span(), )), Some(encoding) => Ok(encoding), }, } } fn open(args: CommandArgs) -> Result<ActionStream, ShellError> { let scope = args.scope().clone(); let shell_manager = args.shell_manager(); let cwd = PathBuf::from(shell_manager.path()); let name = args.call_info.name_tag.clone(); let ctrl_c = args.ctrl_c(); let path: Tagged<PathBuf> = args.req(0)?; let raw = args.has_flag("raw"); let encoding: Option<Tagged<String>> = args.get_flag("encoding")?; if path.is_dir() { let args = nu_engine::shell::LsArgs { path: Some(path), all: false, long: false, short_names: false, du: false, }; return shell_manager.ls(args, name, ctrl_c); } // TODO: Remove once Streams are supported everywhere! // As a short term workaround for getting AutoConvert and Bat functionality (Those don't currently support Streams) // Check if the extension has a "from *" command OR "bat" supports syntax highlighting // AND the user doesn't want the raw output // In these cases, we will collect the Stream let ext = if raw { None } else { path.extension() .map(|name| name.to_string_lossy().to_string()) }; if let Some(ext) = ext { // Check if we have a conversion command if let Some(_command) = scope.get_command(&format!("from {}", ext)) { let (_, tagged_contents) = crate::commands::open::fetch( &cwd, &PathBuf::from(&path.item), path.tag.span, encoding, )?; return Ok(ActionStream::one(ReturnSuccess::action( CommandAction::AutoConvert(tagged_contents, ext), ))); } // Check if bat does syntax highlighting if BAT_LANGUAGES.contains(&ext.as_ref()) { let (_, tagged_contents) = crate::commands::open::fetch( &cwd, &PathBuf::from(&path.item), path.tag.span, encoding, )?; return Ok(ActionStream::one(ReturnSuccess::value(tagged_contents))); } } // Normal Streaming operation let with_encoding = if encoding.is_none() { None } else { Some(get_encoding(encoding)?) }; let sob_stream = shell_manager.open(&path.item, path.tag.span, with_encoding)?; let final_stream = sob_stream.map(move |x| { // The tag that will used when returning a Value let file_tag = Tag { span: path.tag.span, anchor: Some(AnchorLocation::File(path.to_string_lossy().to_string())), }; match x { Ok(StringOrBinary::String(s)) => { ReturnSuccess::value(UntaggedValue::string(s).into_value(file_tag)) } Ok(StringOrBinary::Binary(b)) => ReturnSuccess::value( UntaggedValue::binary(b.into_iter().collect()).into_value(file_tag), ), Err(se) => Err(se), } }); Ok(ActionStream::new(final_stream)) } // Note that we do not output a Stream in "fetch" since it is only used by "enter" command // Which we expect to use a concrete Value a not a Stream pub fn fetch( cwd: &Path, location: &Path, span: Span, encoding_choice: Option<Tagged<String>>, ) -> Result<(Option<String>, Value), ShellError> { // TODO: I don't understand the point of this? Maybe for better error reporting let mut cwd = PathBuf::from(cwd); cwd.push(location); let nice_location = dunce::canonicalize(&cwd).map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => ShellError::labeled_error( format!("Cannot find file {:?}", cwd), "cannot find file", span, ), std::io::ErrorKind::PermissionDenied => { ShellError::labeled_error("Permission denied", "permission denied", span) } _ => ShellError::labeled_error( format!("Cannot open file {:?} because {:?}", &cwd, e), "Cannot open", span, ), })?; // The extension may be used in AutoConvert later on let ext = location .extension() .map(|name| name.to_string_lossy().to_string()); // The tag that will used when returning a Value let file_tag = Tag { span, anchor: Some(AnchorLocation::File( nice_location.to_string_lossy().to_string(), )), }; let res = std::fs::read(location) .map_err(|_| ShellError::labeled_error("Can't open filename given", "can't open", span))?; // If no encoding is provided we try to guess the encoding to read the file with let encoding = if encoding_choice.is_none() { UTF_8 } else { get_encoding(encoding_choice.clone())? }; // If the user specified an encoding, then do not do BOM sniffing let decoded_res = if encoding_choice.is_some() { let (cow_res, _replacements) = encoding.decode_with_bom_removal(&res); cow_res } else { // Otherwise, use the default UTF-8 encoder with BOM sniffing let (cow_res, actual_encoding, replacements) = encoding.decode(&res); // If we had to use replacement characters then fallback to binary if replacements { return Ok((ext, UntaggedValue::binary(res).into_value(file_tag))); } debug!("Decoded using {:?}", actual_encoding); cow_res }; let v = UntaggedValue::string(decoded_res.to_string()).into_value(file_tag); Ok((ext, v)) } #[cfg(test)] mod tests { use super::Open; use super::ShellError; #[test] fn examples_work_as_expected() -> Result<(), ShellError> { use crate::examples::test as test_examples; test_examples(Open {}) } }
33.381132
148
0.571106
cc1b3118735f0b3bbc9d3144f4e6e67445104829
6,681
use num_bigint::Sign; use num_traits::Zero; use super::int::PyInt; use super::pystr::PyStrRef; use crate::builtins::PyTypeRef; use crate::function::OptionalArg; use crate::slots::SlotConstructor; use crate::vm::VirtualMachine; use crate::{ IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyResult, PyValue, TryFromBorrowedObject, TryFromObject, TypeProtocol, }; use std::fmt::{Debug, Formatter}; impl IntoPyObject for bool { fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_bool(self) } } impl TryFromBorrowedObject for bool { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<bool> { if obj.isinstance(&vm.ctx.types.int_type) { Ok(get_value(obj)) } else { Err(vm.new_type_error(format!("Expected type bool, not {}", obj.class().name()))) } } } /// Convert Python bool into Rust bool. pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> { if obj.is(&vm.ctx.true_value) { return Ok(true); } if obj.is(&vm.ctx.false_value) { return Ok(false); } let rs_bool = match vm.get_method(obj.clone(), "__bool__") { Some(method_or_err) => { // If descriptor returns Error, propagate it further let method = method_or_err?; let bool_obj = vm.invoke(&method, ())?; if !bool_obj.isinstance(&vm.ctx.types.bool_type) { return Err(vm.new_type_error(format!( "__bool__ should return bool, returned type {}", bool_obj.class().name() ))); } get_value(&bool_obj) } None => match vm.get_method(obj, "__len__") { Some(method_or_err) => { let method = method_or_err?; let bool_obj = vm.invoke(&method, ())?; let int_obj = bool_obj.payload::<PyInt>().ok_or_else(|| { vm.new_type_error(format!( "'{}' object cannot be interpreted as an integer", bool_obj.class().name() )) })?; let len_val = int_obj.as_bigint(); if len_val.sign() == Sign::Minus { return Err(vm.new_value_error("__len__() should return >= 0".to_owned())); } !len_val.is_zero() } None => true, }, }; Ok(rs_bool) } /// bool(x) -> bool /// /// Returns True when the argument x is true, False otherwise. /// The builtins True and False are the only two instances of the class bool. /// The class bool is a subclass of the class int, and cannot be subclassed. #[pyclass(name = "bool", module = false, base = "PyInt")] pub struct PyBool; impl PyValue for PyBool { fn class(vm: &VirtualMachine) -> &PyTypeRef { &vm.ctx.types.bool_type } } impl Debug for PyBool { fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result { todo!() } } impl SlotConstructor for PyBool { type Args = OptionalArg<PyObjectRef>; fn py_new(zelf: PyTypeRef, x: Self::Args, vm: &VirtualMachine) -> PyResult { if !zelf.isinstance(&vm.ctx.types.type_type) { let actual_type = &zelf.class().name(); return Err(vm.new_type_error(format!( "requires a 'type' object but received a '{}'", actual_type ))); } let val = match x { OptionalArg::Present(val) => boolval(vm, val)?, OptionalArg::Missing => false, }; Ok(vm.ctx.new_bool(val)) } } #[pyimpl(with(SlotConstructor))] impl PyBool { #[pymethod(magic)] fn repr(zelf: bool) -> String { if zelf { "True" } else { "False" }.to_owned() } #[pymethod(magic)] fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> { if format_spec.as_str().is_empty() { vm.to_str(&obj) } else { Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_owned())) } } #[pymethod(name = "__ror__")] #[pymethod(magic)] fn or(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.isinstance(&vm.ctx.types.bool_type) && rhs.isinstance(&vm.ctx.types.bool_type) { let lhs = get_value(&lhs); let rhs = get_value(&rhs); (lhs || rhs).into_pyobject(vm) } else { get_py_int(&lhs).or(rhs, vm).into_pyobject(vm) } } #[pymethod(name = "__rand__")] #[pymethod(magic)] fn and(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.isinstance(&vm.ctx.types.bool_type) && rhs.isinstance(&vm.ctx.types.bool_type) { let lhs = get_value(&lhs); let rhs = get_value(&rhs); (lhs && rhs).into_pyobject(vm) } else { get_py_int(&lhs).and(rhs, vm).into_pyobject(vm) } } #[pymethod(name = "__rxor__")] #[pymethod(magic)] fn xor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.isinstance(&vm.ctx.types.bool_type) && rhs.isinstance(&vm.ctx.types.bool_type) { let lhs = get_value(&lhs); let rhs = get_value(&rhs); (lhs ^ rhs).into_pyobject(vm) } else { get_py_int(&lhs).xor(rhs, vm).into_pyobject(vm) } } } pub(crate) fn init(context: &PyContext) { PyBool::extend_class(context, &context.types.bool_type); } // pub fn not(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<bool> { // if obj.isinstance(&vm.ctx.types.bool_type) { // let value = get_value(obj); // Ok(!value) // } else { // Err(vm.new_type_error(format!("Can only invert a bool, on {:?}", obj))) // } // } // Retrieve inner int value: pub(crate) fn get_value(obj: &PyObjectRef) -> bool { !obj.payload::<PyInt>().unwrap().as_bigint().is_zero() } fn get_py_int(obj: &PyObjectRef) -> &PyInt { obj.payload::<PyInt>().unwrap() } #[derive(Debug, Default, Copy, Clone, PartialEq)] pub struct IntoPyBool { value: bool, } impl IntoPyBool { pub const TRUE: IntoPyBool = IntoPyBool { value: true }; pub const FALSE: IntoPyBool = IntoPyBool { value: false }; pub fn to_bool(self) -> bool { self.value } } impl TryFromObject for IntoPyBool { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { Ok(IntoPyBool { value: boolval(vm, obj)?, }) } }
31.514151
100
0.574315
725a19b5b23b4314a06a68740018fed683441b45
169
use validator::Validate; #[derive(Validate)] #[validate(schema())] struct Test { s: i32, } fn hey(_: &Test) -> Option<(String, String)> { None } fn main() {}
12.071429
46
0.591716
fcabc33ba80d7e704b1d567c5baf001b84a0dda7
9,893
// Copyright (c) SimpleStaking and Tezedge Contributors // SPDX-License-Identifier: MIT use std::sync::Arc; use rocksdb::ColumnFamilyDescriptor; use serde::{Deserialize, Serialize}; use crypto::hash::{ChainId, HashType}; use tezos_messages::Head; use crate::persistent::{BincodeEncoded, Decoder, default_table_options, Encoder, KeyValueSchema, KeyValueStoreWithSchema, PersistentStorage, SchemaError}; use crate::StorageError; pub type ChainMetaStorageKv = dyn KeyValueStoreWithSchema<ChainMetaStorage> + Sync + Send; pub type DbVersion = i64; pub trait ChainMetaStorageReader: Sync + Send { /// Load current head from dedicated storage fn get_current_head(&self, chain_id: &ChainId) -> Result<Option<Head>, StorageError>; } /// Represents storage of the chain metadata (current_head, test_chain, ...). /// Metadata are related to concrete chain_id, which is used as a part of key. /// /// Reason for this storage is that, for example current head cannot be easily selected from block_meta_storage (lets say by level), /// because there are some computations (with fitness) that need to be done... /// /// This storage differs from the other in regard that it is not exposing key-value pair /// but instead it provides get_ and set_ methods for each property prefixed with chain_id. /// /// Maybe this properties split is not very nice but, we need to access properties separatly, /// if we stored metadata grouped to struct K-V: <chain_id> - MetadataStruct, /// we need to all the time deserialize whole sturct. /// /// e.g. storage key-value will looks like: /// (<main_chain_id>, 'current_head') - block_hash_xyz /// (<main_chain_id>, 'test_chain_id') - chain_id_xyz /// #[derive(Clone)] pub struct ChainMetaStorage { kv: Arc<ChainMetaStorageKv> } impl ChainMetaStorage { pub fn new(persistent_storage: &PersistentStorage) -> Self { Self { kv: persistent_storage.kv() } } #[inline] pub fn set_current_head(&self, chain_id: &ChainId, head: &Head) -> Result<(), StorageError> { self.kv .put( &MetaKey::key_current_head(chain_id.clone()), &MetadataValue::CurrentHead(head.clone()), ) .map_err(StorageError::from) } #[inline] pub fn get_test_chain_id(&self, chain_id: &ChainId) -> Result<Option<ChainId>, StorageError> { self.kv .get(&MetaKey::key_test_chain_id(chain_id.clone())) .map(|result| match result { Some(MetadataValue::TestChainId(value)) => Some(value), _ => None }) .map_err(StorageError::from) } #[inline] pub fn set_test_chain_id(&self, chain_id: &ChainId, test_chain_id: &ChainId) -> Result<(), StorageError> { self.kv .put( &MetaKey::key_test_chain_id(chain_id.clone()), &MetadataValue::TestChainId(test_chain_id.clone()), ) .map_err(StorageError::from) } #[inline] pub fn remove_test_chain_id(&self, chain_id: &ChainId) -> Result<(), StorageError> { self.kv .delete(&MetaKey::key_test_chain_id(chain_id.clone())) .map_err(StorageError::from) } } impl ChainMetaStorageReader for ChainMetaStorage { #[inline] fn get_current_head(&self, chain_id: &ChainId) -> Result<Option<Head>, StorageError> { self.kv .get(&MetaKey::key_current_head(chain_id.clone())) .map(|result| match result { Some(MetadataValue::CurrentHead(value)) => Some(value), _ => None }) .map_err(StorageError::from) } } impl KeyValueSchema for ChainMetaStorage { type Key = MetaKey; type Value = MetadataValue; fn descriptor() -> ColumnFamilyDescriptor { let mut cf_opts = default_table_options(); // 1 MB cf_opts.set_write_buffer_size(1024 * 1024); ColumnFamilyDescriptor::new(Self::name(), cf_opts) } #[inline] fn name() -> &'static str { "chain_meta_storage" } } #[derive(Serialize, Deserialize, Debug)] pub struct MetaKey { chain_id: ChainId, key: String, } impl MetaKey { const LEN_CHAIN_ID: usize = HashType::ChainId.size(); const IDX_CHAIN_ID: usize = 0; const IDX_KEY: usize = Self::IDX_CHAIN_ID + Self::LEN_CHAIN_ID; const KEY_CURRENT_HEAD: &'static str = "ch"; const KEY_TEST_CHAIN_ID: &'static str = "tcid"; fn key_current_head(chain_id: ChainId) -> MetaKey { MetaKey { chain_id, key: Self::KEY_CURRENT_HEAD.to_string(), } } fn key_test_chain_id(chain_id: ChainId) -> MetaKey { MetaKey { chain_id, key: Self::KEY_TEST_CHAIN_ID.to_string(), } } } impl Encoder for MetaKey { fn encode(&self) -> Result<Vec<u8>, SchemaError> { if self.chain_id.len() == Self::LEN_CHAIN_ID { let mut bytes = Vec::with_capacity(Self::LEN_CHAIN_ID); bytes.extend(&self.chain_id); bytes.extend(self.key.encode()?); Ok(bytes) } else { Err(SchemaError::EncodeError) } } } impl Decoder for MetaKey { fn decode(bytes: &[u8]) -> Result<Self, SchemaError> { if bytes.len() > Self::LEN_CHAIN_ID { let chain_id = bytes[Self::IDX_CHAIN_ID..Self::IDX_KEY].to_vec(); let key = String::decode(&bytes[Self::IDX_KEY..])?; Ok(MetaKey { chain_id, key }) } else { Err(SchemaError::DecodeError) } } } #[derive(Serialize, Deserialize)] pub enum MetadataValue { CurrentHead(Head), TestChainId(ChainId), } impl BincodeEncoded for MetadataValue {} impl BincodeEncoded for Head {} #[cfg(test)] mod tests { use failure::Error; use crypto::hash::HashType; use crate::tests_common::TmpStorage; use super::*; #[test] fn test_current_head() -> Result<(), Error> { let tmp_storage = TmpStorage::create("__test_current_head")?; let index = ChainMetaStorage::new(tmp_storage.storage()); let chain_id1 = HashType::ChainId.string_to_bytes("NetXgtSLGNJvNye")?; let block_1 = Head { hash: HashType::BlockHash.string_to_bytes("BLockGenesisGenesisGenesisGenesisGenesisb83baZgbyZe")?, level: 1, }; let chain_id2 = HashType::ChainId.string_to_bytes("NetXjD3HPJJjmcd")?; let block_2 = Head { hash: HashType::BlockHash.string_to_bytes("BLockGenesisGenesisGenesisGenesisGenesisd6f5afWyME7")?, level: 2, }; // no current heads assert!(index.get_current_head(&chain_id1)?.is_none()); assert!(index.get_current_head(&chain_id2)?.is_none()); // set for chain_id1 index.set_current_head(&chain_id1, &block_1)?; assert!(index.get_current_head(&chain_id1)?.is_some()); assert_eq!(index.get_current_head(&chain_id1)?.unwrap().hash, block_1.hash.clone()); assert!(index.get_current_head(&chain_id2)?.is_none()); // set for chain_id2 index.set_current_head(&chain_id2, &block_2)?; assert!(index.get_current_head(&chain_id1)?.is_some()); assert_eq!(index.get_current_head(&chain_id1)?.unwrap().hash, block_1.hash.clone()); assert!(index.get_current_head(&chain_id2)?.is_some()); assert_eq!(index.get_current_head(&chain_id2)?.unwrap().hash, block_2.hash.clone()); // update for chain_id1 index.set_current_head(&chain_id1, &block_2)?; assert!(index.get_current_head(&chain_id1)?.is_some()); assert_eq!(index.get_current_head(&chain_id1)?.unwrap().hash, block_2.hash.clone()); assert!(index.get_current_head(&chain_id2)?.is_some()); assert_eq!(index.get_current_head(&chain_id2)?.unwrap().hash, block_2.hash.clone()); Ok(()) } #[test] fn test_test_chain_id() -> Result<(), Error> { let tmp_storage = TmpStorage::create("__test_test_chain_id")?; let index = ChainMetaStorage::new(tmp_storage.storage()); let chain_id1 = HashType::ChainId.string_to_bytes("NetXgtSLGNJvNye")?; let chain_id2 = HashType::ChainId.string_to_bytes("NetXjD3HPJJjmcd")?; let chain_id3 = HashType::ChainId.string_to_bytes("NetXjD3HPJJjmcd")?; assert!(index.get_test_chain_id(&chain_id1)?.is_none()); assert!(index.get_test_chain_id(&chain_id2)?.is_none()); // update for chain_id1 index.set_test_chain_id(&chain_id1, &chain_id3)?; assert!(index.get_test_chain_id(&chain_id1)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id1)?.unwrap(), chain_id3.clone()); assert!(index.get_test_chain_id(&chain_id2)?.is_none()); // update for chain_id2 index.set_test_chain_id(&chain_id2, &chain_id3)?; assert!(index.get_test_chain_id(&chain_id1)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id1)?.unwrap(), chain_id3.clone()); assert!(index.get_test_chain_id(&chain_id2)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id2)?.unwrap(), chain_id3.clone()); // update for chain_id1 index.set_test_chain_id(&chain_id1, &chain_id2)?; assert!(index.get_test_chain_id(&chain_id1)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id1)?.unwrap(), chain_id2.clone()); assert!(index.get_test_chain_id(&chain_id2)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id2)?.unwrap(), chain_id3.clone()); // remove for chain_id1 index.remove_test_chain_id(&chain_id1)?; assert!(index.get_test_chain_id(&chain_id1)?.is_none()); assert!(index.get_test_chain_id(&chain_id2)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id2)?.unwrap(), chain_id3.clone()); Ok(()) } }
35.458781
154
0.645002
1d692ce15fc2511029c67eaf3008621bad9f8bbc
1,317
use crate::ModbusSerializationError; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] pub struct RegisterSlice<'a> { bytes: &'a [u8], } impl<'a> RegisterSlice<'a> { pub fn new(bytes: &'a [u8]) -> Result<Self, ModbusSerializationError> { if bytes.len() % 2 == 0 { Ok(Self { bytes }) } else { Err(ModbusSerializationError::Invalid) } } pub unsafe fn new_unchecked(bytes: &'a [u8]) -> Self { Self { bytes } } pub fn get(self, idx: usize) -> Option<u16> { (self.bytes.len() >= (idx + 1) * 2).then(|| unsafe { self.get_unchecked(idx) }) } pub unsafe fn get_unchecked(self, idx: usize) -> u16 { let bidx = idx * 2; let bytes = self.bytes.get_unchecked(bidx..=(bidx + 1)); u16::from_be_bytes([bytes[0], bytes[1]]) } pub fn len(self) -> usize { self.bytes.len() / 2 } pub fn bytes_len(self) -> usize { self.bytes.len() } pub fn bytes(self) -> &'a [u8] { self.bytes } } impl<'a> TryFrom<&'a [u8]> for RegisterSlice<'a> { //TODO this should be a different error type type Error = ModbusSerializationError; fn try_from(data: &'a [u8]) -> Result<Self, ModbusSerializationError> { Self::new(data) } }
25.823529
87
0.555809
ac13e0479ce1f21708b78fd2cd8e28206327c468
10,075
//! //! Experimental nbody approximate solver //! //! The user can choose the distance at which to fallback on approximate solutions. //! The algorithm works similar to a Barnes–Hut simulation, but uses a kdtree instead of a quad tree. //! //! The user defines some geometric functions and their ideal accuracy. //! use super::*; ///Helper enum indicating whether or not to gravitate a node as a whole, or as its individual parts. pub enum GravEnum<'a, T: Aabb, M> { Mass(&'a mut M), Bot(PMut<'a, [T]>), } ///User defined functions for nbody pub trait Nbody { type T: Aabb<Num = Self::N>; type N: Num; type Mass: Default + Copy + core::fmt::Debug; //return the position of the center of mass fn compute_center_of_mass(&mut self, a: &[Self::T]) -> Self::Mass; fn is_close(&mut self, a: &Self::Mass, line: Self::N, a: impl Axis) -> bool; fn is_close_half(&mut self, a: &Self::Mass, line: Self::N, a: impl Axis) -> bool; fn gravitate(&mut self, a: GravEnum<Self::T, Self::Mass>, b: GravEnum<Self::T, Self::Mass>); fn gravitate_self(&mut self, a: PMut<[Self::T]>); fn apply_a_mass(&mut self, mass: Self::Mass, i: PMut<[Self::T]>); fn combine_two_masses(&mut self, a: &Self::Mass, b: &Self::Mass) -> Self::Mass; } use compt::dfs_order::CompleteTreeContainer; use compt::dfs_order::PreOrder; use compt::dfs_order::VistrMut; struct NodeWrapper<'a, T: Aabb, M> { node: Node<'a, T>, mass: M, } ///Naive version simply visits every pair. pub fn naive_mut<T: Aabb>(bots: PMut<[T]>, func: impl FnMut(PMut<T>, PMut<T>)) { tools::for_every_pair(bots, func); } fn build_masses2<N: Nbody>( vistr: VistrMut<NodeWrapper<N::T, N::Mass>, PreOrder>, no: &mut N, ) -> N::Mass { let (nn, rest) = vistr.next(); let mass = no.compute_center_of_mass(&nn.node.range); let mass = if let Some([left, right]) = rest { let a = build_masses2(left, no); let b = build_masses2(right, no); let m = no.combine_two_masses(&a, &b); no.combine_two_masses(&m, &mass) } else { mass }; nn.mass = mass; mass } fn collect_masses<'a, 'b, N: Nbody>( root_div: N::N, root_axis: impl Axis, root: &N::Mass, vistr: VistrMut<'b, NodeWrapper<'a, N::T, N::Mass>, PreOrder>, no: &mut N, func1: &mut impl FnMut(&'b mut NodeWrapper<'a, N::T, N::Mass>, &mut N), func2: &mut impl FnMut(&'b mut PMut<'a, [N::T]>, &mut N), ) { let (nn, rest) = vistr.next(); if !no.is_close_half(&nn.mass, root_div, root_axis) { func1(nn, no); return; } func2(&mut nn.node.range, no); if let Some([left, right]) = rest { collect_masses(root_div, root_axis, root, left, no, func1, func2); collect_masses(root_div, root_axis, root, right, no, func1, func2); } } fn pre_recc<N: Nbody>( root_div: N::N, root_axis: impl Axis, root: &mut NodeWrapper<N::T, N::Mass>, vistr: VistrMut<NodeWrapper<N::T, N::Mass>, PreOrder>, no: &mut N, ) { let (nn, rest) = vistr.next(); if !no.is_close(&nn.mass, root_div, root_axis) { no.gravitate( GravEnum::Bot(root.node.range.borrow_mut()), GravEnum::Mass(&mut nn.mass), ); return; } no.gravitate( GravEnum::Bot(root.node.range.borrow_mut()), GravEnum::Bot(nn.node.range.borrow_mut()), ); if let Some([left, right]) = rest { pre_recc(root_div, root_axis, root, left, no); pre_recc(root_div, root_axis, root, right, no); } } fn recc_common<'a, 'b, N: Nbody>( axis: impl Axis, vistr: VistrMut<'a, NodeWrapper<'b, N::T, N::Mass>, PreOrder>, no: &mut N, ) -> Option<[VistrMut<'a, NodeWrapper<'b, N::T, N::Mass>, PreOrder>; 2]> { let (nn, rest) = vistr.next(); no.gravitate_self(nn.node.range.borrow_mut()); if let Some([mut left, mut right]) = rest { if let Some(div) = nn.node.div { pre_recc(div, axis, nn, left.borrow_mut(), no); pre_recc(div, axis, nn, right.borrow_mut(), no); let mut finished_masses = Vec::new(); let mut finished_bots = Vec::new(); collect_masses( div, axis, &nn.mass, left.borrow_mut(), no, &mut |a, _| finished_masses.push(a), &mut |a, _| finished_bots.push(a), ); let mut finished_masses2 = Vec::new(); let mut finished_bots2 = Vec::new(); collect_masses( div, axis, &nn.mass, right.borrow_mut(), no, &mut |a, _| finished_masses2.push(a), &mut |a, _| finished_bots2.push(a), ); //We have collected masses on both sides. //now gravitate all the ones on the left side with all the ones on the right side. for a in finished_masses.into_iter() { for b in finished_masses2.iter_mut() { no.gravitate(GravEnum::Mass(&mut a.mass), GravEnum::Mass(&mut b.mass)); } for b in finished_bots2.iter_mut() { no.gravitate(GravEnum::Mass(&mut a.mass), GravEnum::Bot(b.borrow_mut())); } } for a in finished_bots.into_iter() { for b in finished_masses2.iter_mut() { no.gravitate(GravEnum::Bot(a.borrow_mut()), GravEnum::Mass(&mut b.mass)); } for b in finished_bots2.iter_mut() { no.gravitate(GravEnum::Bot(a.borrow_mut()), GravEnum::Bot(b.borrow_mut())); } } //parallelize this Some([left, right]) } else { None } } else { None } } fn recc_par<N: Nbody, JJ: par::Joiner>( axis: impl Axis, par: JJ, vistr: VistrMut<NodeWrapper<N::T, N::Mass>, PreOrder>, no: &mut N, ) where N::T: Send, N::N: Send, N::Mass: Send, N: Splitter + Send + Sync, { let keep_going = recc_common(axis, vistr, no); if let Some([left, right]) = keep_going { match par.next() { par::ParResult::Parallel([dleft, dright]) => { let (mut no1, mut no2) = no.div(); rayon::join( || recc_par(axis.next(), dleft, left, &mut no1), || recc_par(axis.next(), dright, right, &mut no2), ); no.add(no1, no2); } par::ParResult::Sequential(_) => { recc(axis.next(), left, no); recc(axis.next(), right, no); } } } } fn recc<N: Nbody>( axis: impl Axis, vistr: VistrMut<NodeWrapper<N::T, N::Mass>, PreOrder>, no: &mut N, ) { let keep_going = recc_common(axis, vistr, no); if let Some([left, right]) = keep_going { recc(axis.next(), left, no); recc(axis.next(), right, no); } } fn get_bots_from_vistr<'a, T: Aabb, N>( vistr: VistrMut<'a, NodeWrapper<T, N>, PreOrder>, ) -> PMut<'a, [T]> { let mut new_slice = None; vistr.dfs_preorder(|a| { if let Some(s) = new_slice.take() { new_slice = Some(crate::pmut::combine_slice(s, a.node.range.borrow_mut())); } else { new_slice = Some(a.node.range.borrow_mut()); } }); new_slice.unwrap() } fn apply_tree<N: Nbody>(mut vistr: VistrMut<NodeWrapper<N::T, N::Mass>, PreOrder>, no: &mut N) { { let mass = vistr.borrow_mut().next().0.mass; let new_slice = get_bots_from_vistr(vistr.borrow_mut()); no.apply_a_mass(mass, new_slice); } let (_, rest) = vistr.next(); if let Some([left, right]) = rest { apply_tree(left, no); apply_tree(right, no); } } type TreeInner<T> = CompleteTreeContainer<T, PreOrder>; fn convert_tree_into_wrapper<T: Aabb, M: Default>( tree: TreeInner<Node<T>>, ) -> TreeInner<NodeWrapper<T, M>> { let k = tree .into_nodes() .into_vec() .into_iter() .map(|node| NodeWrapper { node, mass: Default::default(), }) .collect(); CompleteTreeContainer::from_preorder(k).unwrap() } fn convert_wrapper_into_tree<T: Aabb, M: Default>( tree: TreeInner<NodeWrapper<T, M>>, ) -> TreeInner<Node<T>> { let nt: Vec<_> = tree .into_nodes() .into_vec() .into_iter() .map(|node| node.node) .collect(); CompleteTreeContainer::from_preorder(nt).unwrap() } ///Perform nbody ///The tree is taken by value so that its nodes can be expended to include more data. pub fn nbody_mut_par<'a, N: Nbody>(tree: crate::Tree<'a, N::T>, no: &mut N) -> crate::Tree<'a, N::T> where N: Send + Sync + Splitter, N::T: Send + Sync, <N::T as Aabb>::Num: Send + Sync, N::Mass: Send + Sync, { let num_aabbs=tree.num_aabbs(); let mut newtree = convert_tree_into_wrapper(tree.into_inner()); //calculate node masses of each node. build_masses2(newtree.vistr_mut(), no); let par=par::ParallelBuilder::new().build_for_tree_of_height(newtree.get_height()); recc_par(default_axis(), par, newtree.vistr_mut(), no); apply_tree(newtree.vistr_mut(), no); unsafe{ crate::Tree::from_raw_parts(convert_wrapper_into_tree(newtree),num_aabbs) } } ///Perform nbody ///The tree is taken by value so that its nodes can be expended to include more data. pub fn nbody_mut<'a, N: Nbody>(tree: crate::Tree<'a, N::T>, no: &mut N) -> crate::Tree<'a, N::T> { let num_aabbs=tree.num_aabbs(); let mut newtree = convert_tree_into_wrapper(tree.into_inner()); //calculate node masses of each node. build_masses2(newtree.vistr_mut(), no); recc(default_axis(), newtree.vistr_mut(), no); apply_tree(newtree.vistr_mut(), no); unsafe{ crate::Tree::from_raw_parts(convert_wrapper_into_tree(newtree),num_aabbs) } }
29.287791
101
0.565062
f4db69b11fe7b8101683f093a45c52d82ed46fc2
1,825
use crate::commands::math::reducers::{reducer_for, Reduce}; use crate::commands::math::utils::run_with_function; use crate::commands::WholeStreamCommand; use crate::prelude::*; use nu_errors::ShellError; use nu_protocol::{Signature, UntaggedValue, Value}; pub struct SubCommand; #[async_trait] impl WholeStreamCommand for SubCommand { fn name(&self) -> &str { "math max" } fn signature(&self) -> Signature { Signature::build("math max") } fn usage(&self) -> &str { "Finds the maximum within a list of numbers or tables" } async fn run( &self, args: CommandArgs, registry: &CommandRegistry, ) -> Result<OutputStream, ShellError> { run_with_function( RunnableContext { input: args.input, registry: registry.clone(), shell_manager: args.shell_manager, host: args.host, ctrl_c: args.ctrl_c, current_errors: args.current_errors, name: args.call_info.name_tag, raw_input: args.raw_input, }, maximum, ) .await } fn examples(&self) -> Vec<Example> { vec![Example { description: "Find the maximum of list of numbers", example: "echo [-50 100 25] | math max", result: Some(vec![UntaggedValue::int(100).into()]), }] } } pub fn maximum(values: &[Value], _name: &Tag) -> Result<Value, ShellError> { let max_func = reducer_for(Reduce::Maximum); max_func(Value::nothing(), values.to_vec()) } #[cfg(test)] mod tests { use super::SubCommand; #[test] fn examples_work_as_expected() { use crate::examples::test as test_examples; test_examples(SubCommand {}) } }
26.071429
76
0.579726
9027422989259c5fa1306550928b128775b45e97
2,914
use clap::{Parser, Subcommand}; use std::path::PathBuf; use tama::error::Response; use tama::tomcat::{deploy, reload, start, stop, undeploy}; use tama::{ error::Result, host_config::{get_host_config, HostConfig}, tomcat::list, }; #[derive(Parser, Debug)] #[clap(bin_name = "tama")] #[clap(version, about)] struct Cli { #[clap(subcommand)] action: MainAction, } #[derive(Subcommand, Debug)] enum MainAction { /// Deploy a new application. Deploy { /// Context path. #[clap(long, short)] context_path: String, /// Path to war file. #[clap(long, short)] war_file: PathBuf, /// Parallel deploy. #[clap(name = "parallel", long, short)] is_parallel: bool, }, /// Undeploy an existing application. Undeploy { /// Context path. #[clap(long, short)] context_path: String, }, /// List currently deployed applications. List, /// Reload an existing application. Reload { /// Context path. #[clap(long, short)] context_path: String, }, /// Start an existing application. Start { /// Context path. #[clap(long, short)] context_path: String, }, /// Stop an existing application. Stop { /// Context path. #[clap(long, short)] context_path: String, }, } impl MainAction { fn handle(self, config: &HostConfig) -> Result<Response> { match self { MainAction::Deploy { context_path, war_file, is_parallel, } => deploy(config, &context_path, &war_file, is_parallel), MainAction::Undeploy { context_path } => undeploy(config, &context_path), MainAction::List => list(config), MainAction::Reload { context_path } => reload(config, &context_path), MainAction::Start { context_path } => start(config, &context_path), MainAction::Stop { context_path } => stop(config, &context_path), } } } fn handle_error<T>(r: Result<T>) -> T { match r { Ok(t) => t, Err(e) => { println!("{}", e); std::process::exit(1) } } } fn main() { let opt = Cli::parse(); let config = get_host_config(); let config = handle_error(config); let result: Result<Response> = opt.action.handle(&config); let response = handle_error(result); match response { tama::error::Response::Ok(Some(text)) => { println!("OK - {}", text); std::process::exit(0) } tama::error::Response::Ok(None) => std::process::exit(0), tama::error::Response::Fail(Some(text)) => { println!("FAIL - {}", text); std::process::exit(1) } tama::error::Response::Fail(None) => std::process::exit(1), } }
26.490909
85
0.54324
019b659a9ae0bc1017cf7d284918538cec7593ce
6,842
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. 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. ==============================================================================*/ //! Test helpers for writing event files. use std::io::Write; use crate::proto::tensorboard as pb; use crate::types::{Step, Tag, WallTime}; /// Extends [`Write`] with methods for writing summary event files. pub trait SummaryWriteExt: Write { /// Writes a TFRecord containing an `Event` proto into this writer. fn write_event(&mut self, event: &pb::Event) -> std::io::Result<()> { use prost::Message; let mut data = Vec::new(); event.encode(&mut data)?; crate::tf_record::TfRecord::from_data(data).write(self)?; Ok(()) } /// Writes a TFRecord containing a TF 1.x scalar event (`simple_value`) into this writer. fn write_scalar( &mut self, tag: &Tag, step: Step, wt: WallTime, value: f32, ) -> std::io::Result<()> { let event = pb::Event { step: step.0, wall_time: wt.into(), what: Some(pb::event::What::Summary(pb::Summary { value: vec![pb::summary::Value { tag: tag.0.clone(), value: Some(pb::summary::value::Value::SimpleValue(value)), ..Default::default() }], ..Default::default() })), ..Default::default() }; self.write_event(&event) } /// Writes a TFRecord containing a TF 1.x `graph_def` event. fn write_graph(&mut self, step: Step, wt: WallTime, bytes: Vec<u8>) -> std::io::Result<()> { let event = pb::Event { step: step.0, wall_time: wt.into(), what: Some(pb::event::What::GraphDef(bytes)), ..Default::default() }; self.write_event(&event) } /// Writes a TFRecord containing a TF 1.x `tagged_run_metadata` event. fn write_tagged_run_metadata( &mut self, tag: &Tag, step: Step, wt: WallTime, run_metadata: Vec<u8>, ) -> std::io::Result<()> { let event = pb::Event { step: step.0, wall_time: wt.into(), what: Some(pb::event::What::TaggedRunMetadata(pb::TaggedRunMetadata { tag: tag.0.clone(), run_metadata, ..Default::default() })), ..Default::default() }; self.write_event(&event) } } impl<W: Write> SummaryWriteExt for W {} #[cfg(test)] mod tests { use super::*; use std::io::{Cursor, Read}; use crate::event_file::{self, EventFileReader}; fn read_all_events<R: Read>(reader: R) -> Result<Vec<pb::Event>, event_file::ReadEventError> { let mut result = Vec::new(); use crate::event_file::ReadEventError::ReadRecordError; use crate::tf_record::ReadRecordError::Truncated; let mut reader = EventFileReader::new(reader); loop { match reader.read_event() { Ok(event) => result.push(event), Err(ReadRecordError(Truncated)) => return Ok(result), Err(e) => return Err(e), } } } #[test] fn test_event_roundtrip() { let mut event: pb::Event = Default::default(); event.step = 123; event.wall_time = 1234.5; event.what = Some(pb::event::What::FileVersion("hello!".to_string())); let mut cursor = Cursor::new(Vec::<u8>::new()); cursor.write_event(&event).unwrap(); cursor.set_position(0); assert_eq!(read_all_events(cursor).unwrap(), vec![event]); } #[test] fn test_scalar_roundtrip() { let mut cursor = Cursor::new(Vec::<u8>::new()); cursor .write_scalar( &Tag("accuracy".to_string()), Step(777), WallTime::new(1234.5).unwrap(), 0.875, ) .unwrap(); cursor.set_position(0); let events = read_all_events(cursor).unwrap(); assert_eq!(events.len(), 1); let event = &events[0]; let expected = pb::Event { step: 777, wall_time: 1234.5, what: Some(pb::event::What::Summary(pb::Summary { value: vec![pb::summary::Value { tag: "accuracy".to_string(), value: Some(pb::summary::value::Value::SimpleValue(0.875)), ..Default::default() }], ..Default::default() })), ..Default::default() }; assert_eq!(event, &expected); } #[test] fn test_graph_roundtrip() { let mut cursor = Cursor::new(Vec::<u8>::new()); cursor .write_graph( Step(777), WallTime::new(1234.5).unwrap(), b"my graph".to_vec(), ) .unwrap(); cursor.set_position(0); let events = read_all_events(cursor).unwrap(); assert_eq!(events.len(), 1); let event = &events[0]; let expected = pb::Event { step: 777, wall_time: 1234.5, what: Some(pb::event::What::GraphDef(b"my graph".to_vec())), ..Default::default() }; assert_eq!(event, &expected); } #[test] fn test_tagged_run_metadata_roundtrip() { let mut cursor = Cursor::new(Vec::<u8>::new()); cursor .write_tagged_run_metadata( &Tag("step0000".to_string()), Step(777), WallTime::new(1234.5).unwrap(), b"my run metadata".to_vec(), ) .unwrap(); cursor.set_position(0); let events = read_all_events(cursor).unwrap(); assert_eq!(events.len(), 1); let event = &events[0]; let expected = pb::Event { step: 777, wall_time: 1234.5, what: Some(pb::event::What::TaggedRunMetadata(pb::TaggedRunMetadata { tag: "step0000".to_string(), run_metadata: b"my run metadata".to_vec(), })), ..Default::default() }; assert_eq!(event, &expected); } }
32.42654
98
0.524262
2945b1ab912450c488bbcf85f8578c3a34c28a42
14,792
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use hir; use hir::def_id::{DefId, DefIndex}; use hir::map::DefPathHash; use hir::map::definitions::Definitions; use ich::{self, CachingCodemapView, Fingerprint}; use middle::cstore::CrateStore; use ty::{TyCtxt, fast_reject}; use session::Session; use std::cmp::Ord; use std::hash as std_hash; use std::cell::RefCell; use std::collections::HashMap; use syntax::ast; use syntax::codemap::CodeMap; use syntax::ext::hygiene::SyntaxContext; use syntax::symbol::Symbol; use syntax_pos::{Span, DUMMY_SP}; use syntax_pos::hygiene; use rustc_data_structures::stable_hasher::{HashStable, StableHashingContextProvider, StableHasher, StableHasherResult, ToStableHashKey}; use rustc_data_structures::accumulate_vec::AccumulateVec; use rustc_data_structures::fx::{FxHashSet, FxHashMap}; thread_local!(static IGNORED_ATTR_NAMES: RefCell<FxHashSet<Symbol>> = RefCell::new(FxHashSet())); /// This is the context state available during incr. comp. hashing. It contains /// enough information to transform DefIds and HirIds into stable DefPaths (i.e. /// a reference to the TyCtxt) and it holds a few caches for speeding up various /// things (e.g. each DefId/DefPath is only hashed once). #[derive(Clone)] pub struct StableHashingContext<'gcx> { sess: &'gcx Session, definitions: &'gcx Definitions, cstore: &'gcx CrateStore, body_resolver: BodyResolver<'gcx>, hash_spans: bool, hash_bodies: bool, node_id_hashing_mode: NodeIdHashingMode, // Very often, we are hashing something that does not need the // CachingCodemapView, so we initialize it lazily. raw_codemap: &'gcx CodeMap, caching_codemap: Option<CachingCodemapView<'gcx>>, } #[derive(PartialEq, Eq, Clone, Copy)] pub enum NodeIdHashingMode { Ignore, HashDefPath, } /// The BodyResolver allows to map a BodyId to the corresponding hir::Body. /// We could also just store a plain reference to the hir::Crate but we want /// to avoid that the crate is used to get untracked access to all of the HIR. #[derive(Clone, Copy)] struct BodyResolver<'gcx>(&'gcx hir::Crate); impl<'gcx> BodyResolver<'gcx> { // Return a reference to the hir::Body with the given BodyId. // DOES NOT DO ANY TRACKING, use carefully. fn body(self, id: hir::BodyId) -> &'gcx hir::Body { self.0.body(id) } } impl<'gcx> StableHashingContext<'gcx> { // The `krate` here is only used for mapping BodyIds to Bodies. // Don't use it for anything else or you'll run the risk of // leaking data out of the tracking system. pub fn new(sess: &'gcx Session, krate: &'gcx hir::Crate, definitions: &'gcx Definitions, cstore: &'gcx CrateStore) -> Self { let hash_spans_initial = !sess.opts.debugging_opts.incremental_ignore_spans; debug_assert!(ich::IGNORED_ATTRIBUTES.len() > 0); IGNORED_ATTR_NAMES.with(|names| { let mut names = names.borrow_mut(); if names.is_empty() { names.extend(ich::IGNORED_ATTRIBUTES.iter() .map(|&s| Symbol::intern(s))); } }); StableHashingContext { sess, body_resolver: BodyResolver(krate), definitions, cstore, caching_codemap: None, raw_codemap: sess.codemap(), hash_spans: hash_spans_initial, hash_bodies: true, node_id_hashing_mode: NodeIdHashingMode::HashDefPath, } } #[inline] pub fn sess(&self) -> &'gcx Session { self.sess } #[inline] pub fn while_hashing_hir_bodies<F: FnOnce(&mut Self)>(&mut self, hash_bodies: bool, f: F) { let prev_hash_bodies = self.hash_bodies; self.hash_bodies = hash_bodies; f(self); self.hash_bodies = prev_hash_bodies; } #[inline] pub fn while_hashing_spans<F: FnOnce(&mut Self)>(&mut self, hash_spans: bool, f: F) { let prev_hash_spans = self.hash_spans; self.hash_spans = hash_spans; f(self); self.hash_spans = prev_hash_spans; } #[inline] pub fn with_node_id_hashing_mode<F: FnOnce(&mut Self)>(&mut self, mode: NodeIdHashingMode, f: F) { let prev = self.node_id_hashing_mode; self.node_id_hashing_mode = mode; f(self); self.node_id_hashing_mode = prev; } #[inline] pub fn def_path_hash(&self, def_id: DefId) -> DefPathHash { if def_id.is_local() { self.definitions.def_path_hash(def_id.index) } else { self.cstore.def_path_hash(def_id) } } #[inline] pub fn local_def_path_hash(&self, def_index: DefIndex) -> DefPathHash { self.definitions.def_path_hash(def_index) } #[inline] pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId { self.definitions.node_to_hir_id(node_id) } #[inline] pub fn hash_bodies(&self) -> bool { self.hash_bodies } #[inline] pub fn codemap(&mut self) -> &mut CachingCodemapView<'gcx> { match self.caching_codemap { Some(ref mut cm) => { cm } ref mut none => { *none = Some(CachingCodemapView::new(self.raw_codemap)); none.as_mut().unwrap() } } } #[inline] pub fn is_ignored_attr(&self, name: Symbol) -> bool { IGNORED_ATTR_NAMES.with(|names| { names.borrow().contains(&name) }) } pub fn hash_hir_item_like<F: FnOnce(&mut Self)>(&mut self, f: F) { let prev_hash_node_ids = self.node_id_hashing_mode; self.node_id_hashing_mode = NodeIdHashingMode::Ignore; f(self); self.node_id_hashing_mode = prev_hash_node_ids; } } impl<'a, 'gcx, 'lcx> StableHashingContextProvider for TyCtxt<'a, 'gcx, 'lcx> { type ContextType = StableHashingContext<'gcx>; fn create_stable_hashing_context(&self) -> Self::ContextType { (*self).create_stable_hashing_context() } } impl<'gcx> StableHashingContextProvider for StableHashingContext<'gcx> { type ContextType = StableHashingContext<'gcx>; fn create_stable_hashing_context(&self) -> Self::ContextType { self.clone() } } impl<'gcx> ::dep_graph::DepGraphSafe for StableHashingContext<'gcx> { } impl<'gcx> HashStable<StableHashingContext<'gcx>> for hir::BodyId { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { if hcx.hash_bodies() { hcx.body_resolver.body(*self).hash_stable(hcx, hasher); } } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for hir::HirId { #[inline] fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { match hcx.node_id_hashing_mode { NodeIdHashingMode::Ignore => { // Don't do anything. } NodeIdHashingMode::HashDefPath => { let hir::HirId { owner, local_id, } = *self; hcx.local_def_path_hash(owner).hash_stable(hcx, hasher); local_id.hash_stable(hcx, hasher); } } } } impl<'gcx> ToStableHashKey<StableHashingContext<'gcx>> for hir::HirId { type KeyType = (DefPathHash, hir::ItemLocalId); #[inline] fn to_stable_hash_key(&self, hcx: &StableHashingContext<'gcx>) -> (DefPathHash, hir::ItemLocalId) { let def_path_hash = hcx.local_def_path_hash(self.owner); (def_path_hash, self.local_id) } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for ast::NodeId { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { match hcx.node_id_hashing_mode { NodeIdHashingMode::Ignore => { // Don't do anything. } NodeIdHashingMode::HashDefPath => { hcx.definitions.node_to_hir_id(*self).hash_stable(hcx, hasher); } } } } impl<'gcx> ToStableHashKey<StableHashingContext<'gcx>> for ast::NodeId { type KeyType = (DefPathHash, hir::ItemLocalId); #[inline] fn to_stable_hash_key(&self, hcx: &StableHashingContext<'gcx>) -> (DefPathHash, hir::ItemLocalId) { hcx.definitions.node_to_hir_id(*self).to_stable_hash_key(hcx) } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for Span { // Hash a span in a stable way. We can't directly hash the span's BytePos // fields (that would be similar to hashing pointers, since those are just // offsets into the CodeMap). Instead, we hash the (file name, line, column) // triple, which stays the same even if the containing FileMap has moved // within the CodeMap. // Also note that we are hashing byte offsets for the column, not unicode // codepoint offsets. For the purpose of the hash that's sufficient. // Also, hashing filenames is expensive so we avoid doing it twice when the // span starts and ends in the same file, which is almost always the case. fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { const TAG_VALID_SPAN: u8 = 0; const TAG_INVALID_SPAN: u8 = 1; const TAG_EXPANSION: u8 = 0; const TAG_NO_EXPANSION: u8 = 1; if !hcx.hash_spans { return } if *self == DUMMY_SP { return std_hash::Hash::hash(&TAG_INVALID_SPAN, hasher); } // If this is not an empty or invalid span, we want to hash the last // position that belongs to it, as opposed to hashing the first // position past it. let span = self.data(); if span.hi < span.lo { return std_hash::Hash::hash(&TAG_INVALID_SPAN, hasher); } let (file_lo, line_lo, col_lo) = match hcx.codemap() .byte_pos_to_line_and_col(span.lo) { Some(pos) => pos, None => { return std_hash::Hash::hash(&TAG_INVALID_SPAN, hasher); } }; if !file_lo.contains(span.hi) { return std_hash::Hash::hash(&TAG_INVALID_SPAN, hasher); } std_hash::Hash::hash(&TAG_VALID_SPAN, hasher); // We truncate the stable_id hash and line and col numbers. The chances // of causing a collision this way should be minimal. std_hash::Hash::hash(&(file_lo.name_hash as u64), hasher); let col = (col_lo.0 as u64) & 0xFF; let line = ((line_lo as u64) & 0xFF_FF_FF) << 8; let len = ((span.hi - span.lo).0 as u64) << 32; let line_col_len = col | line | len; std_hash::Hash::hash(&line_col_len, hasher); if span.ctxt == SyntaxContext::empty() { TAG_NO_EXPANSION.hash_stable(hcx, hasher); } else { TAG_EXPANSION.hash_stable(hcx, hasher); // Since the same expansion context is usually referenced many // times, we cache a stable hash of it and hash that instead of // recursing every time. thread_local! { static CACHE: RefCell<FxHashMap<hygiene::Mark, u64>> = RefCell::new(FxHashMap()); } let sub_hash: u64 = CACHE.with(|cache| { let mark = span.ctxt.outer(); if let Some(&sub_hash) = cache.borrow().get(&mark) { return sub_hash; } let mut hasher = StableHasher::new(); mark.expn_info().hash_stable(hcx, &mut hasher); let sub_hash: Fingerprint = hasher.finish(); let sub_hash = sub_hash.to_smaller_hash(); cache.borrow_mut().insert(mark, sub_hash); sub_hash }); sub_hash.hash_stable(hcx, hasher); } } } pub fn hash_stable_trait_impls<'gcx, W, R>( hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>, blanket_impls: &Vec<DefId>, non_blanket_impls: &HashMap<fast_reject::SimplifiedType, Vec<DefId>, R>) where W: StableHasherResult, R: std_hash::BuildHasher, { { let mut blanket_impls: AccumulateVec<[_; 8]> = blanket_impls .iter() .map(|&def_id| hcx.def_path_hash(def_id)) .collect(); if blanket_impls.len() > 1 { blanket_impls.sort_unstable(); } blanket_impls.hash_stable(hcx, hasher); } { let mut keys: AccumulateVec<[_; 8]> = non_blanket_impls.keys() .map(|k| (k, k.map_def(|d| hcx.def_path_hash(d)))) .collect(); keys.sort_unstable_by(|&(_, ref k1), &(_, ref k2)| k1.cmp(k2)); keys.len().hash_stable(hcx, hasher); for (key, ref stable_key) in keys { stable_key.hash_stable(hcx, hasher); let mut impls : AccumulateVec<[_; 8]> = non_blanket_impls[key] .iter() .map(|&impl_id| hcx.def_path_hash(impl_id)) .collect(); if impls.len() > 1 { impls.sort_unstable(); } impls.hash_stable(hcx, hasher); } } }
34.480186
86
0.574162
4a20615a47f29b00f0bc62567bfffb11da228a14
16,347
use std::os::raw::*; use std::mem; use std::ptr; use std::ffi::CStr; use std::fmt::{self, Debug, Formatter}; use super::{OsSharedContext, winapi_utils::*}; use error::Result; impl OsSharedContext { pub fn wgl(&self) -> Result<&Wgl> { self.wgl.as_ref().map_err(Clone::clone) } } // extern "C" fns implement Debug, but not extern "system" fns. Urgh. #[allow(non_snake_case)] #[derive(Copy, Clone, Default)] pub struct WglFns { pub wglGetExtensionsStringARB: Option<unsafe extern "system" fn(HDC) -> *const c_char>, pub wglCreateContextAttribsARB: Option<unsafe extern "system" fn(HDC, HGLRC, *const c_int) -> HGLRC>, pub wglChoosePixelFormatARB: Option<unsafe extern "system" fn(HDC, *const c_int, *const f32, UINT, *mut c_int, *mut UINT) -> BOOL>, pub wglSwapIntervalEXT: Option<unsafe extern "system" fn(c_int) -> BOOL>, pub wglGetSwapIntervalEXT: Option<unsafe extern "system" fn() -> c_int>, } impl Debug for WglFns { fn fmt(&self, f: &mut Formatter) -> fmt::Result { #[allow(non_snake_case)] let &Self { wglGetExtensionsStringARB, wglCreateContextAttribsARB, wglChoosePixelFormatARB, wglSwapIntervalEXT, wglGetSwapIntervalEXT, } = self; f.debug_struct("WglFns") .field("wglGetExtensionsStringARB", &wglGetExtensionsStringARB .map(|f| f as *const c_void)) .field("wglCreateContextAttribsARB", &wglCreateContextAttribsARB.map(|f| f as *const c_void)) .field("wglChoosePixelFormatARB", &wglChoosePixelFormatARB .map(|f| f as *const c_void)) .field("wglSwapIntervalEXT", &wglSwapIntervalEXT .map(|f| f as *const c_void)) .field("wglGetSwapIntervalEXT", &wglGetSwapIntervalEXT .map(|f| f as *const c_void)) .finish() } } #[allow(non_snake_case)] #[derive(Debug)] pub struct Wgl { pub opengl32_hmodule: HMODULE, pub fns: WglFns, pub WGL_ARB_create_context: bool, pub WGL_ARB_create_context_profile: bool, pub WGL_ARB_create_context_robustness: bool, pub WGL_EXT_create_context_es_profile: bool, pub WGL_EXT_create_context_es2_profile: bool, pub WGL_ARB_multisample: bool, pub WGL_EXT_multisample: bool, pub WGL_EXT_pixel_format: bool, pub WGL_ARB_pixel_format: bool, pub WGL_ARB_pixel_format_float: bool, pub WGL_ARB_robustness_application_isolation: bool, pub WGL_ARB_robustness_share_group_isolation: bool, pub WGL_EXT_swap_control: bool, pub WGL_EXT_swap_control_tear: bool, pub WGL_EXT_colorspace: bool, pub WGL_EXT_framebuffer_sRGB: bool, pub WGL_ARB_framebuffer_sRGB: bool, } impl Drop for Wgl { fn drop(&mut self) { unsafe { FreeLibrary(self.opengl32_hmodule); } } } impl Wgl { pub fn new() -> Result<Self> { // The plan: Create a legacy OpenGL context (needs a temporary window, etc), get the WGL function pointers, then get rid of everything. unsafe { let opengl32_hmodule = LoadLibraryA(b"opengl32.dll\0".as_ptr() as _); if opengl32_hmodule.is_null() { return winapi_fail("LoadLibraryA(\"opengl32.dll\") returned NULL"); } let hinstance = GetModuleHandleW(ptr::null()); let classname = to_wide_with_nul("DMC dummy OpenGL context window"); assert!(classname.len() < 256); let wclass = WNDCLASSEXW { cbSize: mem::size_of::<WNDCLASSEXW>() as _, hInstance: hinstance, lpfnWndProc: Some(DefWindowProcW), lpszClassName: classname.as_ptr(), style: CS_OWNDC, cbClsExtra: 0, cbWndExtra: 0, hIcon: ptr::null_mut(), hIconSm: ptr::null_mut(), hCursor: ptr::null_mut(), hbrBackground: ptr::null_mut(), lpszMenuName: ptr::null(), }; let class_atom = RegisterClassExW(&wclass); if class_atom == 0 { return winapi_fail("RegisterClassExW"); } let tmp_hwnd = CreateWindowExW( WS_EX_OVERLAPPEDWINDOW, MAKEINTATOM(class_atom), ptr::null_mut(), // No title WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, // x CW_USEDEFAULT, // y CW_USEDEFAULT, // w CW_USEDEFAULT, // h ptr::null_mut(), // No parent ptr::null_mut(), // No menu hinstance, ptr::null_mut(), // No custom data pointer ); assert!(!tmp_hwnd.is_null()); let tmp_window_hdc = GetDC(tmp_hwnd); assert!(!tmp_window_hdc.is_null()); let pfd = PIXELFORMATDESCRIPTOR { nSize: mem::size_of::<PIXELFORMATDESCRIPTOR>() as _, nVersion: 1, dwFlags: PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, iPixelType: PFD_TYPE_RGBA, cColorBits: 32, cRedBits: 0, cRedShift: 0, cGreenBits: 0, cGreenShift: 0, cBlueBits: 0, cBlueShift: 0, cAlphaBits: 0, cAlphaShift: 0, cAccumBits: 0, cAccumRedBits: 0, cAccumGreenBits: 0, cAccumBlueBits: 0, cAccumAlphaBits: 0, cDepthBits: 24, cStencilBits: 8, cAuxBuffers: 0, iLayerType: PFD_MAIN_PLANE, bReserved: 0, dwLayerMask: 0, dwVisibleMask: 0, dwDamageMask: 0, }; let i_pixel_format = ChoosePixelFormat(tmp_window_hdc, &pfd); assert_ne!(i_pixel_format, 0); let is_ok = SetPixelFormat(tmp_window_hdc, i_pixel_format, &pfd); assert_ne!(is_ok, FALSE); let tmp_hglrc = wglCreateContext(tmp_window_hdc); assert!(!tmp_hglrc.is_null()); let is_ok = wglMakeCurrent(tmp_window_hdc, tmp_hglrc); assert_ne!(is_ok, FALSE); unsafe fn get_fn(name: &[u8]) -> Option<&c_void> { assert_eq!(&0, name.last().unwrap()); match wglGetProcAddress(name.as_ptr() as _) as usize { 0 => None, f => Some(mem::transmute(f)), } }; let mut wgl = Wgl { opengl32_hmodule, fns: WglFns { wglGetExtensionsStringARB: mem::transmute(get_fn(b"wglGetExtensionsStringARB\0")), wglCreateContextAttribsARB: mem::transmute(get_fn(b"wglCreateContextAttribsARB\0")), wglChoosePixelFormatARB: mem::transmute(get_fn(b"wglChoosePixelFormatARB\0")), wglSwapIntervalEXT: mem::transmute(get_fn(b"wglSwapIntervalEXT\0")), wglGetSwapIntervalEXT: mem::transmute(get_fn(b"wglGetSwapIntervalEXT\0")), }, WGL_ARB_create_context: false, WGL_ARB_create_context_profile: false, WGL_ARB_create_context_robustness: false, WGL_EXT_create_context_es_profile: false, WGL_EXT_create_context_es2_profile: false, WGL_ARB_multisample: false, WGL_EXT_multisample: false, WGL_EXT_pixel_format: false, WGL_ARB_pixel_format: false, WGL_ARB_pixel_format_float: false, WGL_ARB_robustness_application_isolation: false, WGL_ARB_robustness_share_group_isolation: false, WGL_EXT_swap_control: false, WGL_EXT_swap_control_tear: false, WGL_EXT_colorspace: false, WGL_EXT_framebuffer_sRGB: false, WGL_ARB_framebuffer_sRGB: false, }; if let Some(f) = wgl.fns.wglGetExtensionsStringARB { let exts = f(tmp_window_hdc); assert!(!exts.is_null()); let exts = CStr::from_ptr(exts).to_string_lossy(); for ext in exts.split(' ') { match ext { "WGL_ARB_create_context" => wgl.WGL_ARB_create_context = true, "WGL_ARB_create_context_profile" => wgl.WGL_ARB_create_context_profile = true, "WGL_ARB_create_context_robustness" => wgl.WGL_ARB_create_context_robustness = true, "WGL_EXT_create_context_es_profile" => wgl.WGL_EXT_create_context_es_profile = true, "WGL_EXT_create_context_es2_profile" => wgl.WGL_EXT_create_context_es2_profile = true, "WGL_ARB_multisample" => wgl.WGL_ARB_multisample = true, "WGL_EXT_multisample" => wgl.WGL_EXT_multisample = true, "WGL_EXT_pixel_format" => wgl.WGL_EXT_pixel_format = true, "WGL_ARB_pixel_format" => wgl.WGL_ARB_pixel_format = true, "WGL_ARB_pixel_format_float" => wgl.WGL_ARB_pixel_format_float = true, "WGL_ARB_robustness_application_isolation" => wgl.WGL_ARB_robustness_application_isolation = true, "WGL_ARB_robustness_share_group_isolation" => wgl.WGL_ARB_robustness_share_group_isolation = true, "WGL_EXT_swap_control" => wgl.WGL_EXT_swap_control = true, "WGL_EXT_swap_control_tear" => wgl.WGL_EXT_swap_control_tear = true, "WGL_EXT_colorspace" => wgl.WGL_EXT_colorspace = true, "WGL_EXT_framebuffer_sRGB" => wgl.WGL_EXT_framebuffer_sRGB = true, "WGL_ARB_framebuffer_sRGB" => wgl.WGL_ARB_framebuffer_sRGB = true, _ => (), } } } if wgl.WGL_ARB_create_context { assert!(wgl.fns.wglCreateContextAttribsARB.is_some()); } if wgl.WGL_ARB_pixel_format { assert!(wgl.fns.wglChoosePixelFormatARB.is_some()); } if wgl.WGL_EXT_swap_control { assert!(wgl.fns.wglSwapIntervalEXT.is_some()); assert!(wgl.fns.wglGetSwapIntervalEXT.is_some()); } // Now we've got the function pointers, get rid of the tmp window and hdc let is_ok = wglMakeCurrent(tmp_window_hdc, ptr::null_mut()); assert_ne!(is_ok, FALSE); let is_ok = wglDeleteContext(tmp_hglrc); assert_ne!(is_ok, FALSE); // NOTE: Don't Release or Delete the HDC. Not needed and will fail because of CS_OWNDC. let is_ok = DestroyWindow(tmp_hwnd); assert_ne!(is_ok, FALSE); let is_ok = UnregisterClassW(MAKEINTATOM(class_atom), hinstance); assert_ne!(is_ok, FALSE); Ok(wgl) } } } #[allow(dead_code)] #[allow(non_upper_case_globals)] pub mod consts { use super::*; // NOTE: Not everything's in it. Additions welcome! pub const WGL_CONTEXT_DEBUG_BIT_ARB: c_int = 0x00000001; pub const WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB: c_int = 0x00000002; pub const WGL_CONTEXT_MAJOR_VERSION_ARB: c_int = 0x2091; pub const WGL_CONTEXT_MINOR_VERSION_ARB: c_int = 0x2092; pub const WGL_CONTEXT_LAYER_PLANE_ARB: c_int = 0x2093; pub const WGL_CONTEXT_FLAGS_ARB: c_int = 0x2094; pub const ERROR_INVALID_VERSION_ARB: c_int = 0x2095; pub const WGL_CONTEXT_OPENGL_NO_ERROR_ARB: c_int = 0x31B3; pub const WGL_CONTEXT_PROFILE_MASK_ARB: c_int = 0x9126; pub const WGL_CONTEXT_CORE_PROFILE_BIT_ARB: c_int = 0x00000001; pub const WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB: c_int = 0x00000002; pub const ERROR_INVALID_PROFILE_ARB: c_int = 0x2096; pub const WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB: c_int = 0x00000004; pub const WGL_LOSE_CONTEXT_ON_RESET_ARB: c_int = 0x8252; pub const WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB: c_int = 0x8256; pub const WGL_NO_RESET_NOTIFICATION_ARB: c_int = 0x8261; pub const WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB: c_int = 0x20A9; pub const WGL_SAMPLE_BUFFERS_ARB: c_int = 0x2041; pub const WGL_SAMPLES_ARB: c_int = 0x2042; pub const WGL_NUMBER_PIXEL_FORMATS_ARB: c_int = 0x2000; pub const WGL_DRAW_TO_WINDOW_ARB: c_int = 0x2001; pub const WGL_DRAW_TO_BITMAP_ARB: c_int = 0x2002; pub const WGL_ACCELERATION_ARB: c_int = 0x2003; pub const WGL_NEED_PALETTE_ARB: c_int = 0x2004; pub const WGL_NEED_SYSTEM_PALETTE_ARB: c_int = 0x2005; pub const WGL_SWAP_LAYER_BUFFERS_ARB: c_int = 0x2006; pub const WGL_SWAP_METHOD_ARB: c_int = 0x2007; pub const WGL_NUMBER_OVERLAYS_ARB: c_int = 0x2008; pub const WGL_NUMBER_UNDERLAYS_ARB: c_int = 0x2009; pub const WGL_TRANSPARENT_ARB: c_int = 0x200A; pub const WGL_TRANSPARENT_RED_VALUE_ARB: c_int = 0x2037; pub const WGL_TRANSPARENT_GREEN_VALUE_ARB: c_int = 0x2038; pub const WGL_TRANSPARENT_BLUE_VALUE_ARB: c_int = 0x2039; pub const WGL_TRANSPARENT_ALPHA_VALUE_ARB: c_int = 0x203A; pub const WGL_TRANSPARENT_INDEX_VALUE_ARB: c_int = 0x203B; pub const WGL_SHARE_DEPTH_ARB: c_int = 0x200C; pub const WGL_SHARE_STENCIL_ARB: c_int = 0x200D; pub const WGL_SHARE_ACCUM_ARB: c_int = 0x200E; pub const WGL_SUPPORT_GDI_ARB: c_int = 0x200F; pub const WGL_SUPPORT_OPENGL_ARB: c_int = 0x2010; pub const WGL_DOUBLE_BUFFER_ARB: c_int = 0x2011; pub const WGL_STEREO_ARB: c_int = 0x2012; pub const WGL_PIXEL_TYPE_ARB: c_int = 0x2013; pub const WGL_COLOR_BITS_ARB: c_int = 0x2014; pub const WGL_RED_BITS_ARB: c_int = 0x2015; pub const WGL_RED_SHIFT_ARB: c_int = 0x2016; pub const WGL_GREEN_BITS_ARB: c_int = 0x2017; pub const WGL_GREEN_SHIFT_ARB: c_int = 0x2018; pub const WGL_BLUE_BITS_ARB: c_int = 0x2019; pub const WGL_BLUE_SHIFT_ARB: c_int = 0x201A; pub const WGL_ALPHA_BITS_ARB: c_int = 0x201B; pub const WGL_ALPHA_SHIFT_ARB: c_int = 0x201C; pub const WGL_ACCUM_BITS_ARB: c_int = 0x201D; pub const WGL_ACCUM_RED_BITS_ARB: c_int = 0x201E; pub const WGL_ACCUM_GREEN_BITS_ARB: c_int = 0x201F; pub const WGL_ACCUM_BLUE_BITS_ARB: c_int = 0x2020; pub const WGL_ACCUM_ALPHA_BITS_ARB: c_int = 0x2021; pub const WGL_DEPTH_BITS_ARB: c_int = 0x2022; pub const WGL_STENCIL_BITS_ARB: c_int = 0x2023; pub const WGL_AUX_BUFFERS_ARB: c_int = 0x2024; pub const WGL_NO_ACCELERATION_ARB: c_int = 0x2025; pub const WGL_GENERIC_ACCELERATION_ARB: c_int = 0x2026; pub const WGL_FULL_ACCELERATION_ARB: c_int = 0x2027; pub const WGL_SWAP_EXCHANGE_ARB: c_int = 0x2028; pub const WGL_SWAP_COPY_ARB: c_int = 0x2029; pub const WGL_SWAP_UNDEFINED_ARB: c_int = 0x202A; pub const WGL_TYPE_RGBA_ARB: c_int = 0x202B; pub const WGL_TYPE_COLORINDEX_ARB: c_int = 0x202C; pub const WGL_TYPE_RGBA_FLOAT_ARB: c_int = 0x21A0; pub const WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT: c_int = 0x20A9; pub const WGL_DEPTH_FLOAT_EXT: c_int = 0x2040; pub const WGL_CONTEXT_ES_PROFILE_BIT_EXT: c_int = 0x00000004; pub const WGL_CONTEXT_ES2_PROFILE_BIT_EXT: c_int = 0x00000004; pub const WGL_COLORSPACE_EXT: c_int = 0x3087; pub const WGL_COLORSPACE_SRGB_EXT: c_int = 0x3089; pub const WGL_COLORSPACE_LINEAR_EXT: c_int = 0x308A; }
46.839542
143
0.600538
dd105e85b0b1f60dffb762dc8c36f6325bafd42e
21,735
//! SocketCAN support. //! //! The Linux kernel supports using CAN-devices through a network-like API //! (see https://www.kernel.org/doc/Documentation/networking/can.txt). This //! crate allows easy access to this functionality without having to wrestle //! libc calls. //! //! # An introduction to CAN //! //! The CAN bus was originally designed to allow microcontrollers inside a //! vehicle to communicate over a single shared bus. Messages called //! *frames* are multicast to all devices on the bus. //! //! Every frame consists of an ID and a payload of up to 8 bytes. If two //! devices attempt to send a frame at the same time, the device with the //! higher ID will notice the conflict, stop sending and reattempt to sent its //! frame in the next time slot. This means that the lower the ID, the higher //! the priority. Since most devices have a limited buffer for outgoing frames, //! a single device with a high priority (== low ID) can block communication //! on that bus by sending messages too fast. //! //! The Linux socketcan subsystem makes the CAN bus available as a regular //! networking device. Opening an network interface allows receiving all CAN //! messages received on it. A device CAN be opened multiple times, every //! client will receive all CAN frames simultaneously. //! //! Similarly, CAN frames can be sent to the bus by multiple client //! simultaneously as well. //! //! # Hardware and more information //! //! More information on CAN [can be found on Wikipedia](). When not running on //! an embedded platform with already integrated CAN components, //! [Thomas Fischl's USBtin](http://www.fischl.de/usbtin/) (see //! [section 2.4](http://www.fischl.de/usbtin/#socketcan)) is one of many ways //! to get started. //! //! # RawFd //! //! Raw access to the underlying file descriptor and construction through //! is available through the `AsRawFd`, `IntoRawFd` and `FromRawFd` //! implementations. // clippy: do not warn about things like "SocketCAN" inside the docs #![cfg_attr(feature = "cargo-clippy", allow(doc_markdown))] extern crate byte_conv; extern crate embedded_can; extern crate hex; extern crate itertools; extern crate libc; extern crate neli; extern crate nix; extern crate try_from; mod err; pub use embedded_can::{ExtendedId, Id, StandardId}; pub use err::{CanError, CanErrorDecodingFailure}; pub mod dump; mod nl; mod util; #[cfg(test)] mod tests; use libc::{c_int, c_short, c_void, c_uint, c_ulong, socket, SOCK_RAW, close, bind, sockaddr, read, write, SOL_SOCKET, SO_RCVTIMEO, timespec, timeval, EINPROGRESS, SO_SNDTIMEO, time_t, suseconds_t, fcntl, F_GETFL, F_SETFL, O_NONBLOCK}; use itertools::Itertools; use nix::net::if_::if_nametoindex; pub use nl::CanInterface; use std::{error, fmt, io, time}; use std::mem::{size_of, MaybeUninit}; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use util::{set_socket_option, set_socket_option_mult}; /// Check an error return value for timeouts. /// /// Due to the fact that timeouts are reported as errors, calling `read_frame` /// on a socket with a timeout that does not receive a frame in time will /// result in an error being returned. This trait adds a `should_retry` method /// to `Error` and `Result` to check for this condition. pub trait ShouldRetry { /// Check for timeout /// /// If `true`, the error is probably due to a timeout. fn should_retry(&self) -> bool; } impl ShouldRetry for io::Error { fn should_retry(&self) -> bool { match self.kind() { // EAGAIN, EINPROGRESS and EWOULDBLOCK are the three possible codes // returned when a timeout occurs. the stdlib already maps EAGAIN // and EWOULDBLOCK os WouldBlock io::ErrorKind::WouldBlock => true, // however, EINPROGRESS is also valid io::ErrorKind::Other => { if let Some(i) = self.raw_os_error() { i == EINPROGRESS } else { false } } _ => false, } } } impl<E: fmt::Debug> ShouldRetry for io::Result<E> { fn should_retry(&self) -> bool { if let Err(ref e) = *self { e.should_retry() } else { false } } } // constants stolen from C headers const AF_CAN: c_int = 29; const PF_CAN: c_int = 29; const CAN_RAW: c_int = 1; const SOL_CAN_BASE: c_int = 100; const SOL_CAN_RAW: c_int = SOL_CAN_BASE + CAN_RAW; const CAN_RAW_FILTER: c_int = 1; const CAN_RAW_ERR_FILTER: c_int = 2; const CAN_RAW_LOOPBACK: c_int = 3; const CAN_RAW_RECV_OWN_MSGS: c_int = 4; // unused: // const CAN_RAW_FD_FRAMES: c_int = 5; const CAN_RAW_JOIN_FILTERS: c_int = 6; // get timestamp in a struct timeval (us accuracy) // const SIOCGSTAMP: c_int = 0x8906; // get timestamp in a struct timespec (ns accuracy) const SIOCGSTAMPNS: c_int = 0x8907; /// if set, indicate 29 bit extended format pub const EFF_FLAG: u32 = 0x80000000; /// remote transmission request flag pub const RTR_FLAG: u32 = 0x40000000; /// error flag pub const ERR_FLAG: u32 = 0x20000000; /// valid bits in standard frame id pub const SFF_MASK: u32 = 0x000007ff; /// valid bits in extended frame id pub const EFF_MASK: u32 = 0x1fffffff; /// valid bits in error frame pub const ERR_MASK: u32 = 0x1fffffff; /// an error mask that will cause SocketCAN to report all errors pub const ERR_MASK_ALL: u32 = ERR_MASK; /// an error mask that will cause SocketCAN to silently drop all errors pub const ERR_MASK_NONE: u32 = 0; fn c_timeval_new(t: time::Duration) -> timeval { timeval { tv_sec: t.as_secs() as time_t, tv_usec: (t.subsec_nanos() / 1000) as suseconds_t, } } #[derive(Debug)] #[repr(C)] struct CanAddr { _af_can: c_short, if_index: c_int, // address familiy, rx_id: u32, tx_id: u32, } #[derive(Debug)] /// Errors opening socket pub enum CanSocketOpenError { /// Device could not be found LookupError(nix::Error), /// System error while trying to look up device name IOError(io::Error), } impl fmt::Display for CanSocketOpenError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { CanSocketOpenError::LookupError(ref e) => write!(f, "CAN Device not found: {}", e), CanSocketOpenError::IOError(ref e) => write!(f, "IO: {}", e), } } } impl error::Error for CanSocketOpenError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { CanSocketOpenError::LookupError(ref e) => Some(e), CanSocketOpenError::IOError(ref e) => Some(e), } } } #[derive(Debug, Copy, Clone)] /// Error that occurs when creating CAN packets pub enum ConstructionError { /// CAN ID was outside the range of valid IDs IDTooLarge, /// More than 8 Bytes of payload data were passed in TooMuchData, } impl fmt::Display for ConstructionError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConstructionError::IDTooLarge => write!(f, "CAN ID too large"), ConstructionError::TooMuchData => { write!(f, "Payload is larger than CAN maximum of 8 bytes") } } } } impl error::Error for ConstructionError { fn description(&self) -> &str { match *self { ConstructionError::IDTooLarge => "can id too large", ConstructionError::TooMuchData => "too much data", } } } impl From<nix::Error> for CanSocketOpenError { fn from(e: nix::Error) -> CanSocketOpenError { CanSocketOpenError::LookupError(e) } } impl From<io::Error> for CanSocketOpenError { fn from(e: io::Error) -> CanSocketOpenError { CanSocketOpenError::IOError(e) } } /// A socket for a CAN device. /// /// Will be closed upon deallocation. To close manually, use std::drop::Drop. /// Internally this is just a wrapped file-descriptor. #[derive(Debug)] pub struct CanSocket { fd: c_int, } impl CanSocket { /// Open a named CAN device. /// /// Usually the more common case, opens a socket can device by name, such /// as "vcan0" or "socan0". pub fn open(ifname: &str) -> Result<CanSocket, CanSocketOpenError> { let if_index = if_nametoindex(ifname)?; CanSocket::open_if(if_index) } /// Open CAN device by interface number. /// /// Opens a CAN device by kernel interface number. pub fn open_if(if_index: c_uint) -> Result<CanSocket, CanSocketOpenError> { let addr = CanAddr { _af_can: AF_CAN as c_short, if_index: if_index as c_int, rx_id: 0, // ? tx_id: 0, // ? }; // open socket let sock_fd; unsafe { sock_fd = socket(PF_CAN, SOCK_RAW, CAN_RAW); } if sock_fd == -1 { return Err(CanSocketOpenError::from(io::Error::last_os_error())); } // bind it let bind_rv; unsafe { let sockaddr_ptr = &addr as *const CanAddr; bind_rv = bind(sock_fd, sockaddr_ptr as *const sockaddr, size_of::<CanAddr>() as u32); } // FIXME: on fail, close socket (do not leak socketfds) if bind_rv == -1 { let e = io::Error::last_os_error(); unsafe { close(sock_fd); } return Err(CanSocketOpenError::from(e)); } Ok(CanSocket { fd: sock_fd }) } fn close(&mut self) -> io::Result<()> { unsafe { let rv = close(self.fd); if rv != -1 { return Err(io::Error::last_os_error()); } } Ok(()) } /// Change socket to non-blocking mode pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { // retrieve current flags let oldfl = unsafe { fcntl(self.fd, F_GETFL) }; if oldfl == -1 { return Err(io::Error::last_os_error()); } let newfl = if nonblocking { oldfl | O_NONBLOCK } else { oldfl & !O_NONBLOCK }; let rv = unsafe { fcntl(self.fd, F_SETFL, newfl) }; if rv != 0 { return Err(io::Error::last_os_error()); } Ok(()) } /// Sets the read timeout on the socket /// /// For convenience, the result value can be checked using /// `ShouldRetry::should_retry` when a timeout is set. pub fn set_read_timeout(&self, duration: time::Duration) -> io::Result<()> { set_socket_option(self.fd, SOL_SOCKET, SO_RCVTIMEO, &c_timeval_new(duration)) } /// Sets the write timeout on the socket pub fn set_write_timeout(&self, duration: time::Duration) -> io::Result<()> { set_socket_option(self.fd, SOL_SOCKET, SO_SNDTIMEO, &c_timeval_new(duration)) } /// Blocking read a single can frame. pub fn read_frame(&self) -> io::Result<CanFrame> { let mut frame = CanFrame { _id: 0, _data_len: 0, _pad: 0, _res0: 0, _res1: 0, _data: [0; 8], }; let read_rv = unsafe { let frame_ptr = &mut frame as *mut CanFrame; read(self.fd, frame_ptr as *mut c_void, size_of::<CanFrame>()) }; if read_rv as usize != size_of::<CanFrame>() { return Err(io::Error::last_os_error()); } Ok(frame) } /// Blocking read a single can frame with timestamp /// /// Note that reading a frame and retrieving the timestamp requires two /// consecutive syscalls. To avoid race conditions, exclusive access /// to the socket is enforce through requiring a `mut &self`. pub fn read_frame_with_timestamp(&mut self) -> io::Result<(CanFrame, time::SystemTime)> { let frame = self.read_frame()?; let mut ts: timespec; let rval = unsafe { // we initialize tv calling ioctl, passing this responsibility on ts = MaybeUninit::uninit().assume_init(); libc::ioctl(self.fd, SIOCGSTAMPNS as c_ulong, &mut ts as *mut timespec) }; if rval == -1 { return Err(io::Error::last_os_error()); } Ok((frame, util::system_time_from_timespec(ts))) } /// Write a single can frame. /// /// Note that this function can fail with an `EAGAIN` error or similar. /// Use `write_frame_insist` if you need to be sure that the message got /// sent or failed. pub fn write_frame(&self, frame: &CanFrame) -> io::Result<()> { // not a mutable reference needed (see std::net::UdpSocket) for // a comparison // debug!("Sending: {:?}", frame); let write_rv = unsafe { let frame_ptr = frame as *const CanFrame; write(self.fd, frame_ptr as *const c_void, size_of::<CanFrame>()) }; if write_rv as usize != size_of::<CanFrame>() { return Err(io::Error::last_os_error()); } Ok(()) } /// Blocking write a single can frame, retrying until it gets sent /// successfully. pub fn write_frame_insist(&self, frame: &CanFrame) -> io::Result<()> { loop { match self.write_frame(frame) { Ok(v) => return Ok(v), Err(e) => { if !e.should_retry() { return Err(e); } } } } } /// Sets filters on the socket. /// /// CAN packages received by SocketCAN are matched against these filters, /// only matching packets are returned by the interface. /// /// See `CanFilter` for details on how filtering works. By default, all /// single filter matching all incoming frames is installed. pub fn set_filters(&self, filters: &[CanFilter]) -> io::Result<()> { set_socket_option_mult(self.fd, SOL_CAN_RAW, CAN_RAW_FILTER, filters) } /// Sets the error mask on the socket. /// /// By default (`ERR_MASK_NONE`) no error conditions are reported as /// special error frames by the socket. Enabling error conditions by /// setting `ERR_MASK_ALL` or another non-empty error mask causes the /// socket to receive notification about the specified conditions. #[inline] pub fn set_error_mask(&self, mask: u32) -> io::Result<()> { set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &mask) } /// Enable or disable loopback. /// /// By default, loopback is enabled, causing other applications that open /// the same CAN bus to see frames emitted by different applications on /// the same system. #[inline] pub fn set_loopback(&self, enabled: bool) -> io::Result<()> { let loopback: c_int = if enabled { 1 } else { 0 }; set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback) } /// Enable or disable receiving of own frames. /// /// When loopback is enabled, this settings controls if CAN frames sent /// are received back immediately by sender. Default is off. pub fn set_recv_own_msgs(&self, enabled: bool) -> io::Result<()> { let recv_own_msgs: c_int = if enabled { 1 } else { 0 }; set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, &recv_own_msgs) } /// Enable or disable join filters. /// /// By default a frame is accepted if it matches any of the filters set /// with `set_filters`. If join filters is enabled, a frame has to match /// _all_ filters to be accepted. pub fn set_join_filters(&self, enabled: bool) -> io::Result<()> { let join_filters: c_int = if enabled { 1 } else { 0 }; set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS, &join_filters) } } impl AsRawFd for CanSocket { fn as_raw_fd(&self) -> RawFd { self.fd } } impl FromRawFd for CanSocket { unsafe fn from_raw_fd(fd: RawFd) -> CanSocket { CanSocket { fd: fd } } } impl IntoRawFd for CanSocket { fn into_raw_fd(self) -> RawFd { self.fd } } impl Drop for CanSocket { fn drop(&mut self) { self.close().ok(); // ignore result } } impl embedded_can::Can for CanSocket { type Frame = CanFrame; type Error = io::Error; fn try_transmit( &mut self, frame: &Self::Frame, ) -> Result<Option<Self::Frame>, nb::Error<Self::Error>> { self.write_frame(frame).map(|_| None).map_err(|io_err| { if io_err.kind() == io::ErrorKind::WouldBlock { nb::Error::WouldBlock } else { nb::Error::Other(io_err) } }) } fn try_receive(&mut self) -> nb::Result<Self::Frame, Self::Error> { self.read_frame().map_err(|io_err| { if io_err.kind() == io::ErrorKind::WouldBlock { nb::Error::WouldBlock } else { nb::Error::Other(io_err) } }) } } /// CanFrame /// /// Uses the same memory layout as the underlying kernel struct for performance /// reasons. #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct CanFrame { /// 32 bit CAN_ID + EFF/RTR/ERR flags _id: u32, /// data length. Bytes beyond are not valid _data_len: u8, /// padding _pad: u8, /// reserved _res0: u8, /// reserved _res1: u8, /// buffer for data _data: [u8; 8], } impl CanFrame { pub fn new(id: Id, data: &[u8], rtr: bool, err: bool) -> Result<CanFrame, ConstructionError> { if data.len() > 8 { return Err(ConstructionError::TooMuchData); } let mut _id = match id { Id::Standard(standard_id) => standard_id.as_raw() as u32, // set EFF_FLAG on large message Id::Extended(extended_id) => extended_id.as_raw() | EFF_FLAG, }; if rtr { _id |= RTR_FLAG; } if err { _id |= ERR_FLAG; } let mut full_data = [0; 8]; // not cool =/ for (n, c) in data.iter().enumerate() { full_data[n] = *c; } Ok(CanFrame { _id: _id, _data_len: data.len() as u8, _pad: 0, _res0: 0, _res1: 0, _data: full_data, }) } pub fn id(&self) -> Id { if self.is_extended() { let id = unsafe {ExtendedId::new_unchecked(self._id & EFF_MASK)}; Id::Extended(id) } else { let id = unsafe {StandardId::new_unchecked((self._id & SFF_MASK) as u16)}; Id::Standard(id) } } /// Return the actual CAN ID (without EFF/RTR/ERR flags) #[inline] pub fn id_raw(&self) -> u32 { if self.is_extended() { self._id & EFF_MASK } else { self._id & SFF_MASK } } /// Return the error message #[inline] pub fn err(&self) -> u32 { self._id & ERR_MASK } /// Check if frame uses 29 bit extended frame format #[inline] pub fn is_extended(&self) -> bool { self._id & EFF_FLAG != 0 } /// Check if frame is an error message #[inline] pub fn is_error(&self) -> bool { self._id & ERR_FLAG != 0 } /// Check if frame is a remote transmission request #[inline] pub fn is_rtr(&self) -> bool { self._id & RTR_FLAG != 0 } /// A slice into the actual data. Slice will always be <= 8 bytes in length #[inline] pub fn data(&self) -> &[u8] { &self._data[..(self._data_len as usize)] } /// Read error from message and transform it into a `CanError`. /// /// SocketCAN errors are indicated using the error bit and coded inside /// id and data payload. Call `error()` converts these into usable /// `CanError` instances. /// /// If the frame is malformed, this may fail with a /// `CanErrorDecodingFailure`. #[inline] pub fn error(&self) -> Result<CanError, CanErrorDecodingFailure> { CanError::from_frame(self) } } impl fmt::UpperHex for CanFrame { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{:X}#", self.id_raw())?; let mut parts = self.data().iter().map(|v| format!("{:02X}", v)); let sep = if f.alternate() { " " } else { "" }; write!(f, "{}", parts.join(sep)) } } impl embedded_can::Frame for CanFrame { fn new(id: impl Into<Id>, data: &[u8]) -> Result<Self, ()> { CanFrame::new(id.into(), data, false, false).map_err(|_err| ()) } fn new_remote(id: impl Into<Id>, _dlc: usize) -> Result<Self, ()> { CanFrame::new(id.into(), &[], true, false).map_err(|_err| ()) } fn is_extended(&self) -> bool { self.is_extended() } fn is_remote_frame(&self) -> bool { self.is_rtr() } fn dlc(&self) -> usize { self._data_len as usize } fn data(&self) -> &[u8] { self.data() } fn id(&self) -> embedded_can::Id { self.id() } } /// CanFilter /// /// Contains an internal id and mask. Packets are considered to be matched by /// a filter if `received_id & mask == filter_id & mask` holds true. #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct CanFilter { _id: u32, _mask: u32, } impl CanFilter { /// Construct a new CAN filter. pub fn new(id: u32, mask: u32) -> Result<CanFilter, ConstructionError> { Ok(CanFilter { _id: id, _mask: mask, }) } }
29.652115
98
0.594111
6787431a71d25d9453a261ff9ee27696bf9aef9f
1,572
use std::collections::HashSet; use std::io; use std::ops::AddAssign; #[derive(Clone, Copy, Hash, Eq, PartialEq, Debug)] struct Point { x: i32, y: i32, } impl AddAssign for Point { fn add_assign(&mut self, other: Self) { *self = Self { x: self.x + other.x, y: self.y + other.y, }; } } fn main() { let mut wire_a = HashSet::new(); let mut closest_intersection = std::i32::MAX; for i in 0..2 { let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let mut pos = Point { x: 0, y: 0 }; for j in input.trim().split(',') { let length: usize = j.chars().skip(1).collect::<String>().parse().unwrap(); let direction = match j.chars().nth(0).unwrap() { 'U' => Point { x: 0, y: 1 }, 'D' => Point { x: 0, y: -1 }, 'L' => Point { x: -1, y: 0 }, 'R' => Point { x: 1, y: 0 }, _ => panic!("Unknown token"), }; for _ in 0..length { pos += direction; if i == 0 { wire_a.insert(pos); } else { if wire_a.contains(&pos) { let distance = pos.x.abs() + pos.y.abs(); if distance < closest_intersection { closest_intersection = distance; } } } } } } println!("{}", closest_intersection); }
27.578947
87
0.420483
22699699ec743ea4762a6401d8dec30cd7b913b6
10,571
use std::collections::HashSet; use std::hash::Hash; use std::time::Duration; use crate::adapters::IntoAdapterVec; use crate::conn::{LdapConnAsync, LdapConnSettings}; use crate::controls_impl::IntoRawControlVec; use crate::exop::Exop; use crate::ldap::{Ldap, Mod}; use crate::result::{CompareResult, ExopResult, LdapResult, Result, SearchResult}; use crate::search::{ResultEntry, Scope, SearchOptions, SearchStream}; use crate::RequestId; use tokio::runtime::{self, Runtime}; use url::Url; /// Synchronous connection to an LDAP server. /// /// In this version of the interface, [`new()`](#method.new) will return /// a struct encapsulating a runtime, the connection, and an operation handle. All /// operations are performed through that struct, synchronously: the thread will /// wait until the result is available or the operation times out. /// /// The API is virtually identical to the asynchronous one. The chief difference is /// that `LdapConn` is not cloneable: if you need another handle, you must open a /// new connection. #[derive(Debug)] pub struct LdapConn { rt: Runtime, ldap: Ldap, } impl LdapConn { /// Open a connection to an LDAP server specified by `url`. /// /// See [LdapConnAsync::new()](struct.LdapConnAsync.html#method.new) for the /// details of the supported URL formats. pub fn new(url: &str) -> Result<Self> { Self::with_settings(LdapConnSettings::new(), url) } /// Open a connection to an LDAP server specified by `url`, using /// `settings` to specify additional parameters. pub fn with_settings(settings: LdapConnSettings, url: &str) -> Result<Self> { let url = Url::parse(url)?; Self::from_url_with_settings(settings, &url) } /// Open a connection to an LDAP server specified by an already parsed `Url`. pub fn from_url(url: &Url) -> Result<Self> { Self::from_url_with_settings(LdapConnSettings::new(), url) } /// Open a connection to an LDAP server specified by an already parsed `Url`, using /// `settings` to specify additional parameters. pub fn from_url_with_settings(settings: LdapConnSettings, url: &Url) -> Result<Self> { let rt = runtime::Builder::new_current_thread() .enable_all() .build()?; let ldap = rt.block_on(async move { let (conn, ldap) = match LdapConnAsync::from_url_with_settings(settings, url).await { Ok((conn, ldap)) => (conn, ldap), Err(e) => return Err(e), }; super::drive!(conn); Ok(ldap) })?; Ok(LdapConn { ldap, rt }) } /// See [`Ldap::with_search_options()`](struct.Ldap.html#method.with_search_options). pub fn with_search_options(&mut self, opts: SearchOptions) -> &mut Self { self.ldap.search_opts = Some(opts); self } /// See [`Ldap::with_controls()`](struct.Ldap.html#method.with_controls). pub fn with_controls<V: IntoRawControlVec>(&mut self, ctrls: V) -> &mut Self { self.ldap.controls = Some(ctrls.into()); self } /// See [`Ldap::with_timeout()`](struct.Ldap.html#method.with_timeout). pub fn with_timeout(&mut self, duration: Duration) -> &mut Self { self.ldap.timeout = Some(duration); self } /// See [`Ldap::is_closed()`](struct.Ldap.html#method.is_closed). pub fn is_closed(&mut self) -> bool { self.ldap.tx.is_closed() } /// See [`Ldap::simple_bind()`](struct.Ldap.html#method.simple_bind). pub fn simple_bind(&mut self, bind_dn: &str, bind_pw: &str) -> Result<LdapResult> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.simple_bind(bind_dn, bind_pw).await }) } /// See [`Ldap::sasl_external_bind()`](struct.Ldap.html#method.sasl_external_bind). pub fn sasl_external_bind(&mut self) -> Result<LdapResult> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.sasl_external_bind().await }) } /// See [`Ldap::search()`](struct.Ldap.html#method.search). pub fn search<'a, S: AsRef<str> + Send + Sync + 'a>( &mut self, base: &str, scope: Scope, filter: &str, attrs: Vec<S>, ) -> Result<SearchResult> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.search(base, scope, filter, attrs).await }) } /// Perform a Search, but unlike `search()`, which returns all results at once, return a handle which /// will be used for retrieving entries one by one. See [`EntryStream`](struct.EntryStream.html) /// for the explanation of the protocol which must be adhered to in this case. pub fn streaming_search<'a, 'b, S: AsRef<str> + Send + Sync + 'a>( &'b mut self, base: &str, scope: Scope, filter: &str, attrs: Vec<S>, ) -> Result<EntryStream<'a, 'b, S>> { let rt = &mut self.rt; let ldap = &mut self.ldap; let stream = rt.block_on(async move { ldap.streaming_search(base, scope, filter, attrs).await })?; Ok(EntryStream { stream, conn: self }) } /// Perform a streaming Search internally modified by a chain of [adapters](adapters/index.html). /// See [`Ldap::streaming_search_with()`](struct.Ldap.html#method.streaming_search_with). pub fn streaming_search_with< 'a, 'b, V: IntoAdapterVec<'a, S>, S: AsRef<str> + Send + Sync + 'a, >( &'b mut self, adapters: V, base: &str, scope: Scope, filter: &str, attrs: Vec<S>, ) -> Result<EntryStream<'a, 'b, S>> { let rt = &mut self.rt; let ldap = &mut self.ldap; let stream = rt.block_on(async move { ldap.streaming_search_with(adapters.into(), base, scope, filter, attrs) .await })?; Ok(EntryStream { stream, conn: self }) } /// See [`Ldap::add()`](struct.Ldap.html#method.add). pub fn add<S: AsRef<[u8]> + Eq + Hash>( &mut self, dn: &str, attrs: Vec<(S, HashSet<S>)>, ) -> Result<LdapResult> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.add(dn, attrs).await }) } /// See [`Ldap::compare()`](struct.Ldap.html#method.compare). pub fn compare<B: AsRef<[u8]>>( &mut self, dn: &str, attr: &str, val: B, ) -> Result<CompareResult> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.compare(dn, attr, val).await }) } /// See [`Ldap::delete()`](struct.Ldap.html#method.delete). pub fn delete(&mut self, dn: &str) -> Result<LdapResult> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.delete(dn).await }) } /// See [`Ldap::modify()`](struct.Ldap.html#method.modify). pub fn modify<S: AsRef<[u8]> + Eq + Hash>( &mut self, dn: &str, mods: Vec<Mod<S>>, ) -> Result<LdapResult> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.modify(dn, mods).await }) } /// See [`Ldap::modifydn()`](struct.Ldap.html#method.modifydn). pub fn modifydn( &mut self, dn: &str, rdn: &str, delete_old: bool, new_sup: Option<&str>, ) -> Result<LdapResult> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.modifydn(dn, rdn, delete_old, new_sup).await }) } /// See [`Ldap::unbind()`](struct.Ldap.html#method.unbind). pub fn unbind(&mut self) -> Result<()> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.unbind().await }) } /// See [`Ldap::extended()`](struct.Ldap.html#method.extended). pub fn extended<E>(&mut self, exop: E) -> Result<ExopResult> where E: Into<Exop>, { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.extended(exop).await }) } /// See [`Ldap::last_id()`](struct.Ldap.html#method.last_id). pub fn last_id(&mut self) -> RequestId { self.ldap.last_id() } /// See [`Ldap::abandon()`](struct.Ldap.html#method.abandon). pub fn abandon(&mut self, msgid: RequestId) -> Result<()> { let rt = &mut self.rt; let ldap = &mut self.ldap; rt.block_on(async move { ldap.abandon(msgid).await }) } } /// Handle for obtaining a stream of search results. /// /// User code can't construct a stream directly, but only by using /// [`streaming_search()`](struct.LdapConn.html#method.streaming_search) or /// [`streaming_search_with()`](struct.LdapConn.html#method.streaming_search_with) on /// an `LdapConn` handle. /// /// For compatibility, this struct's name is different from the async version /// which is [`SearchStream`](struct.SearchStream.html). The protocol and behavior /// are the same, with one important difference: an `EntryStream` shares the /// Tokio runtime with `LdapConn` from which it's obtained, but the two can't be /// used in parallel, which is enforced by capturing the reference to `LdapConn` /// during the lifetime of `EntryStream`. pub struct EntryStream<'a, 'b, S> { stream: SearchStream<'a, S>, conn: &'b mut LdapConn, } impl<'a, 'b, S> EntryStream<'a, 'b, S> where S: AsRef<str> + Send + Sync + 'a, { /// See [`SearchStream::next()`](struct.SearchStream.html#method.next). #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Result<Option<ResultEntry>> { let rt = &mut self.conn.rt; let stream = &mut self.stream; rt.block_on(async move { stream.next().await }) } /// See [`SearchStream::finish()`](struct.SearchStream.html#method.finish). /// /// The name `result()` was kept for backwards compatibility. pub fn result(mut self) -> LdapResult { let rt = &mut self.conn.rt; let stream = &mut self.stream; rt.block_on(async move { stream.finish().await }) } /// Returns the Message ID of the initial Search. /// /// This method calls [`Ldap::last_id()`](struct.Ldap.html#method.last_id) /// on the `Ldap` handle encapsulated by the underlying stream. pub fn last_id(&mut self) -> RequestId { self.stream.ldap_handle().last_id() } }
36.078498
105
0.605052
fbb71d4f806392c03860d4823da438fe9f992191
3,085
use syn::parse::{Error, ParseStream, Result}; use syn::{Ident, LitStr, Path, Token}; pub struct Attr { pub other_cli_commands: Option<Path>, pub pre_build: Option<Path>, pub post_build: Option<Path>, #[cfg(feature = "dev-server")] pub serve: Option<Path>, pub frontend_watch: Option<Path>, pub frontend_pkg_name: Option<LitStr>, #[cfg(not(feature = "dev-server"))] pub backend_watch: Option<Path>, pub backend_pkg_name: Option<LitStr>, pub default_build_path: Option<Path>, pub build_args: Option<Path>, pub serve_args: Option<Path>, } impl Attr { pub fn parse(input: ParseStream) -> Result<Self> { let frontend_pkg_name = input.parse().ok(); if frontend_pkg_name.is_some() && !input.is_empty() { input.parse::<Token![,]>()?; } let backend_pkg_name = input.parse().ok(); if backend_pkg_name.is_some() && !input.is_empty() { input.parse::<Token![,]>()?; } let mut other_cli_commands = None; let mut pre_build = None; let mut post_build = None; #[cfg(feature = "dev-server")] let mut serve = None; let mut frontend_watch = None; #[cfg(not(feature = "dev-server"))] let mut backend_watch = None; let mut default_build_path = None; let mut build_args = None; let mut serve_args = None; while !input.is_empty() { let ident: Ident = input.parse()?; let path: Path = if input.parse::<Token![=]>().is_ok() { input.parse()? } else { ident.clone().into() }; match ident.to_string().as_str() { "other_cli_commands" => other_cli_commands = Some(path), "pre_build" => pre_build = Some(path), "post_build" => post_build = Some(path), #[cfg(feature = "dev-server")] "serve" => serve = Some(path), #[cfg(not(feature = "dev-server"))] "backend_watch" => backend_watch = Some(path), "frontend_watch" => frontend_watch = Some(path), "default_build_path" => default_build_path = Some(path), "build_args" => build_args = Some(path), "serve_args" => serve_args = Some(path), _ => return Err(Error::new(ident.span(), "invalid argument")), } let _comma_token: Token![,] = match input.parse() { Ok(x) => x, Err(_) if input.is_empty() => break, Err(err) => return Err(err), }; } Ok(Self { other_cli_commands, pre_build, post_build, #[cfg(feature = "dev-server")] serve, frontend_watch, frontend_pkg_name, #[cfg(not(feature = "dev-server"))] backend_watch, backend_pkg_name, default_build_path, build_args, serve_args, }) } }
33.172043
78
0.523825
f92d97465335f30baec57471349286e204033d6e
1,021
/** * * https://doc.rust-lang.org/rust-by-example/fn/closures/capture.html */ fn main() { use std::mem; let color = String::from("green"); // borrow color let print = || println!("`color`: {}", color); print(); let _reborrow = &color; print(); let _color_moved = color; let mut count = 0; // mut borrow let mut inc = || { count += 1; println!("`count`: {}", count); }; inc(); //let _reborrow = &count; inc(); // 非 copy η±»εž‹ let movable = Box::new(3); // move θΏ›ι—­εŒ… let consume = || { println!("`movable`: {:?}", movable); mem::drop(movable); }; consume(); // movable 已经 drop δΊ†οΌŒε†θ―·ζ±‚δΌšζŠ₯ι”™ //consume(); let haystack = vec![1, 2, 3]; // 强刢 move // 不带 move 就是 borrow let contains = move |needle| haystack.contains(needle); println!("{}", contains(&1)); println!("{}", contains(&4)); // 已经 move δΊ† //println!("There're {} elements in vec", haystack.len()); }
17.305085
69
0.506366
5d425e1b741d600695e5c9039ec1253110826f36
4,812
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use config::config::NodeConfig; use failure::prelude::*; use futures::future::{err, ok, Future}; use scratchpad::SparseMerkleTree; use std::sync::Arc; use storage_client::{StorageRead, VerifiedStateView}; use types::{ account_address::{AccountAddress, ADDRESS_LENGTH}, account_config::get_account_resource_or_default, get_with_proof::{RequestItem, ResponseItem}, transaction::SignedTransaction, vm_error::VMStatus, }; use vm_runtime::{MoveVM, VMVerifier}; #[cfg(test)] #[path = "unit_tests/vm_validator_test.rs"] mod vm_validator_test; pub trait TransactionValidation: Send + Sync { type ValidationInstance: VMVerifier; /// Validate a txn from client fn validate_transaction( &self, _txn: SignedTransaction, ) -> Box<dyn Future<Item = Option<VMStatus>, Error = failure::Error> + Send>; } #[derive(Clone)] pub struct VMValidator { storage_read_client: Arc<dyn StorageRead>, vm: MoveVM, } impl VMValidator { pub fn new(config: &NodeConfig, storage_read_client: Arc<dyn StorageRead>) -> Self { VMValidator { storage_read_client, vm: MoveVM::new(&config.vm_config), } } } impl TransactionValidation for VMValidator { type ValidationInstance = MoveVM; fn validate_transaction( &self, txn: SignedTransaction, ) -> Box<dyn Future<Item = Option<VMStatus>, Error = failure::Error> + Send> { // TODO: For transaction validation, there are two options to go: // 1. Trust storage: there is no need to get root hash from storage here. We will // create another struct similar to `VerifiedStateView` that implements `StateView` // but does not do verification. // 2. Don't trust storage. This requires more work: // 1) AC must have validator set information // 2) Get state_root from transaction info which can be verified with signatures of // validator set. // 3) Create VerifiedStateView with verified state // root. // Just ask something from storage. It doesn't matter what it is -- we just need the // transaction info object in account state proof which contains the state root hash. let address = AccountAddress::new([0xff; ADDRESS_LENGTH]); let item = RequestItem::GetAccountState { address }; match self .storage_read_client .update_to_latest_ledger(/* client_known_version = */ 0, vec![item]) { Ok((mut items, ledger_info_with_sigs, _, _)) => { if items.len() != 1 { return Box::new(err(format_err!( "Unexpected number of items ({}).", items.len() ))); } match items.remove(0) { ResponseItem::GetAccountState { account_state_with_proof, } => { let transaction_info = account_state_with_proof.proof.transaction_info(); let state_root = transaction_info.state_root_hash(); let smt = SparseMerkleTree::new(state_root); let state_view = VerifiedStateView::new( Arc::clone(&self.storage_read_client), ( Some(ledger_info_with_sigs.ledger_info().version()), state_root, ), &smt, ); Box::new(ok(self.vm.validate_transaction(txn, &state_view))) } _ => panic!("Unexpected item in response."), } } Err(e) => Box::new(err(e)), } } } /// read account state /// returns account's current sequence number and balance pub async fn get_account_state( storage_read_client: Arc<dyn StorageRead>, address: AccountAddress, ) -> Result<(u64, u64)> { let req_item = RequestItem::GetAccountState { address }; let (response_items, _, _, _) = storage_read_client .update_to_latest_ledger_async(0 /* client_known_version */, vec![req_item]) .await?; let account_state = match &response_items[0] { ResponseItem::GetAccountState { account_state_with_proof, } => &account_state_with_proof.blob, _ => bail!("Not account state response."), }; let account_resource = get_account_resource_or_default(account_state)?; let sequence_number = account_resource.sequence_number(); let balance = account_resource.balance(); Ok((sequence_number, balance)) }
37.59375
97
0.598712
26db527dcd87fc903a92470aec27e3315a175fb3
17,981
//! //! Cargo compile currently does the following steps: //! //! All configurations are already injected as environment variables via the //! main cargo command //! //! 1. Read the manifest //! 2. Shell out to `cargo-resolve` with a list of dependencies and sources as //! stdin //! //! a. Shell out to `--do update` and `--do list` for each source //! b. Resolve dependencies and return a list of name/version/source //! //! 3. Shell out to `--do download` for each source //! 4. Shell out to `--do get` for each source, and build up the list of paths //! to pass to rustc -L //! 5. Call `cargo-rustc` with the results of the resolver zipped together with //! the results of the `get` //! //! a. Topologically sort the dependencies //! b. Compile each dependency in order, passing in the -L's pointing at each //! previously compiled dependency //! use std::collections::HashMap; use std::default::Default; use std::path::{Path, PathBuf}; use std::sync::Arc; use core::registry::PackageRegistry; use core::{Source, SourceId, PackageSet, Package, Target, PackageId}; use core::{Profile, TargetKind}; use core::resolver::Method; use ops::{self, BuildOutput, ExecEngine}; use sources::{PathSource}; use util::config::{ConfigValue, Config}; use util::{CargoResult, internal, human, ChainError, profile}; /// Contains informations about how a package should be compiled. pub struct CompileOptions<'a> { pub config: &'a Config, /// Number of concurrent jobs to use. pub jobs: Option<u32>, /// The target platform to compile for (example: `i686-unknown-linux-gnu`). pub target: Option<&'a str>, /// Extra features to build for the root package pub features: &'a [String], /// Flag if the default feature should be built for the root package pub no_default_features: bool, /// Root package to build (if None it's the current one) pub spec: Option<&'a str>, /// Filter to apply to the root package to select which targets will be /// built. pub filter: CompileFilter<'a>, /// Engine which drives compilation pub exec_engine: Option<Arc<Box<ExecEngine>>>, /// Whether this is a release build or not pub release: bool, /// Mode for this compile. pub mode: CompileMode, /// The specified target will be compiled with all the available arguments, /// note that this only accounts for the *final* invocation of rustc pub target_rustc_args: Option<&'a [String]>, } #[derive(Clone, Copy, PartialEq)] pub enum CompileMode { Test, Build, Bench, Doc { deps: bool }, } pub enum CompileFilter<'a> { Everything, Only { lib: bool, bins: &'a [String], examples: &'a [String], tests: &'a [String], benches: &'a [String], } } pub fn compile<'a>(manifest_path: &Path, options: &CompileOptions<'a>) -> CargoResult<ops::Compilation<'a>> { debug!("compile; manifest-path={}", manifest_path.display()); let mut source = try!(PathSource::for_path(manifest_path.parent().unwrap(), options.config)); try!(source.update()); // TODO: Move this into PathSource let package = try!(source.root_package()); debug!("loaded package; package={}", package); for key in package.manifest().warnings().iter() { try!(options.config.shell().warn(key)) } compile_pkg(&package, options) } pub fn compile_pkg<'a>(package: &Package, options: &CompileOptions<'a>) -> CargoResult<ops::Compilation<'a>> { let CompileOptions { config, jobs, target, spec, features, no_default_features, release, mode, ref filter, ref exec_engine, ref target_rustc_args } = *options; let target = target.map(|s| s.to_string()); let features = features.iter().flat_map(|s| { s.split(' ') }).map(|s| s.to_string()).collect::<Vec<String>>(); if spec.is_some() && (no_default_features || features.len() > 0) { return Err(human("features cannot be modified when the main package \ is not being built")) } if jobs == Some(0) { return Err(human("jobs must be at least 1")) } let override_ids = try!(source_ids_from_config(config, package.root())); let (packages, resolve_with_overrides, sources) = { let rustc_host = config.rustc_host().to_string(); let mut registry = PackageRegistry::new(config); // First, resolve the package's *listed* dependencies, as well as // downloading and updating all remotes and such. let resolve = try!(ops::resolve_pkg(&mut registry, package)); // Second, resolve with precisely what we're doing. Filter out // transitive dependencies if necessary, specify features, handle // overrides, etc. let _p = profile::start("resolving w/ overrides..."); try!(registry.add_overrides(override_ids)); let platform = target.as_ref().map(|e| &e[..]).or(Some(&rustc_host[..])); let method = Method::Required{ dev_deps: true, // TODO: remove this option? features: &features, uses_default_features: !no_default_features, target_platform: platform}; let resolved_with_overrides = try!(ops::resolve_with_previous(&mut registry, package, method, Some(&resolve), None)); let req: Vec<PackageId> = resolved_with_overrides.iter().map(|r| { r.clone() }).collect(); let packages = try!(registry.get(&req).chain_error(|| { human("Unable to get packages from source") })); (packages, resolved_with_overrides, registry.move_sources()) }; let pkgid = match spec { Some(spec) => try!(resolve_with_overrides.query(spec)), None => package.package_id(), }; let to_build = packages.iter().find(|p| p.package_id() == pkgid).unwrap(); let targets = try!(generate_targets(to_build, mode, filter, release)); let target_with_args = match *target_rustc_args { Some(args) if targets.len() == 1 => { let (target, profile) = targets[0]; let mut profile = profile.clone(); profile.rustc_args = Some(args.to_vec()); Some((target, profile)) } Some(_) => { return Err(human("extra arguments to `rustc` can only be passed to \ one target, consider filtering\nthe package by \ passing e.g. `--lib` or `--bin NAME` to specify \ a single target")) } None => None, }; let targets = target_with_args.as_ref().map(|&(t, ref p)| vec![(t, p)]) .unwrap_or(targets); let ret = { let _p = profile::start("compiling"); let mut build_config = try!(scrape_build_config(config, jobs, target)); build_config.exec_engine = exec_engine.clone(); build_config.release = release; if let CompileMode::Doc { deps } = mode { build_config.doc_all = deps; } try!(ops::compile_targets(&targets, to_build, &PackageSet::new(&packages), &resolve_with_overrides, &sources, config, build_config, to_build.manifest().profiles())) }; return Ok(ret); } impl<'a> CompileFilter<'a> { pub fn new(lib_only: bool, bins: &'a [String], tests: &'a [String], examples: &'a [String], benches: &'a [String]) -> CompileFilter<'a> { if lib_only || !bins.is_empty() || !tests.is_empty() || !examples.is_empty() || !benches.is_empty() { CompileFilter::Only { lib: lib_only, bins: bins, examples: examples, benches: benches, tests: tests, } } else { CompileFilter::Everything } } pub fn matches(&self, target: &Target) -> bool { match *self { CompileFilter::Everything => true, CompileFilter::Only { lib, bins, examples, tests, benches } => { let list = match *target.kind() { TargetKind::Bin => bins, TargetKind::Test => tests, TargetKind::Bench => benches, TargetKind::Example => examples, TargetKind::Lib(..) => return lib, TargetKind::CustomBuild => return false, }; list.iter().any(|x| *x == target.name()) } } } } /// Given the configuration for a build, this function will generate all /// target/profile combinations needed to be built. fn generate_targets<'a>(pkg: &'a Package, mode: CompileMode, filter: &CompileFilter, release: bool) -> CargoResult<Vec<(&'a Target, &'a Profile)>> { let profiles = pkg.manifest().profiles(); let build = if release {&profiles.release} else {&profiles.dev}; let test = if release {&profiles.bench} else {&profiles.test}; let profile = match mode { CompileMode::Test => test, CompileMode::Bench => &profiles.bench, CompileMode::Build => build, CompileMode::Doc { .. } => &profiles.doc, }; return match *filter { CompileFilter::Everything => { match mode { CompileMode::Bench => { Ok(pkg.targets().iter().filter(|t| t.benched()).map(|t| { (t, profile) }).collect::<Vec<_>>()) } CompileMode::Test => { let mut base = pkg.targets().iter().filter(|t| { t.tested() }).map(|t| { (t, if t.is_example() {build} else {profile}) }).collect::<Vec<_>>(); // Always compile the library if we're testing everything as // it'll be needed for doctests if let Some(t) = pkg.targets().iter().find(|t| t.is_lib()) { if t.doctested() { base.push((t, build)); } } Ok(base) } CompileMode::Build => { Ok(pkg.targets().iter().filter(|t| { t.is_bin() || t.is_lib() }).map(|t| (t, profile)).collect()) } CompileMode::Doc { .. } => { Ok(pkg.targets().iter().filter(|t| t.documented()) .map(|t| (t, profile)).collect()) } } } CompileFilter::Only { lib, bins, examples, tests, benches } => { let mut targets = Vec::new(); if lib { if let Some(t) = pkg.targets().iter().find(|t| t.is_lib()) { targets.push((t, profile)); } else { return Err(human(format!("no library targets found"))) } } { let mut find = |names: &[String], desc, kind, profile| { for name in names { let target = pkg.targets().iter().find(|t| { t.name() == *name && *t.kind() == kind }); let t = match target { Some(t) => t, None => return Err(human(format!("no {} target \ named `{}`", desc, name))), }; debug!("found {} `{}`", desc, name); targets.push((t, profile)); } Ok(()) }; try!(find(bins, "bin", TargetKind::Bin, profile)); try!(find(examples, "example", TargetKind::Example, build)); try!(find(tests, "test", TargetKind::Test, test)); try!(find(benches, "bench", TargetKind::Bench, &profiles.bench)); } Ok(targets) } }; } /// Read the `paths` configuration variable to discover all path overrides that /// have been configured. fn source_ids_from_config(config: &Config, cur_path: &Path) -> CargoResult<Vec<SourceId>> { let configs = try!(config.values()); debug!("loaded config; configs={:?}", configs); let config_paths = match configs.get("paths") { Some(cfg) => cfg, None => return Ok(Vec::new()) }; let paths = try!(config_paths.list().chain_error(|| { internal("invalid configuration for the key `paths`") })); paths.iter().map(|&(ref s, ref p)| { // The path listed next to the string is the config file in which the // key was located, so we want to pop off the `.cargo/config` component // to get the directory containing the `.cargo` folder. p.parent().unwrap().parent().unwrap().join(s) }).filter(|p| { // Make sure we don't override the local package, even if it's in the // list of override paths. cur_path != &**p }).map(|p| SourceId::for_path(&p)).collect() } /// Parse all config files to learn about build configuration. Currently /// configured options are: /// /// * build.jobs /// * target.$target.ar /// * target.$target.linker /// * target.$target.libfoo.metadata fn scrape_build_config(config: &Config, jobs: Option<u32>, target: Option<String>) -> CargoResult<ops::BuildConfig> { let cfg_jobs = match try!(config.get_i64("build.jobs")) { Some((n, p)) => { if n <= 0 { return Err(human(format!("build.jobs must be positive, \ but found {} in {:?}", n, p))); } else if n >= u32::max_value() as i64 { return Err(human(format!("build.jobs is too large: \ found {} in {:?}", n, p))); } else { Some(n as u32) } } None => None, }; let jobs = jobs.or(cfg_jobs).unwrap_or(::num_cpus::get() as u32); let mut base = ops::BuildConfig { jobs: jobs, requested_target: target.clone(), ..Default::default() }; base.host = try!(scrape_target_config(config, config.rustc_host())); base.target = match target.as_ref() { Some(triple) => try!(scrape_target_config(config, &triple)), None => base.host.clone(), }; Ok(base) } fn scrape_target_config(config: &Config, triple: &str) -> CargoResult<ops::TargetConfig> { let key = format!("target.{}", triple); let ar = try!(config.get_string(&format!("{}.ar", key))); let linker = try!(config.get_string(&format!("{}.linker", key))); let mut ret = ops::TargetConfig { ar: ar.map(|p| p.0), linker: linker.map(|p| p.0), overrides: HashMap::new(), }; let table = match try!(config.get_table(&key)) { Some((table, _)) => table, None => return Ok(ret), }; for (lib_name, _) in table.into_iter() { if lib_name == "ar" || lib_name == "linker" { continue } let mut output = BuildOutput { library_paths: Vec::new(), library_links: Vec::new(), cfgs: Vec::new(), metadata: Vec::new(), }; let key = format!("{}.{}", key, lib_name); let table = try!(config.get_table(&key)).unwrap().0; for (k, _) in table.into_iter() { let key = format!("{}.{}", key, k); match try!(config.get(&key)).unwrap() { ConfigValue::String(v, path) => { if k == "rustc-flags" { let whence = format!("in `{}` (in {})", key, path.display()); let (paths, links) = try!( BuildOutput::parse_rustc_flags(&v, &whence) ); output.library_paths.extend(paths.into_iter()); output.library_links.extend(links.into_iter()); } else { output.metadata.push((k, v)); } }, ConfigValue::List(a, p) => { if k == "rustc-link-lib" { output.library_links.extend(a.into_iter().map(|v| v.0)); } else if k == "rustc-link-search" { output.library_paths.extend(a.into_iter().map(|v| { PathBuf::from(&v.0) })); } else if k == "rustc-cfg" { output.cfgs.extend(a.into_iter().map(|v| v.0)); } else { try!(config.expected("string", &k, ConfigValue::List(a, p))); } }, // technically could be a list too, but that's the exception to // the rule... cv => { try!(config.expected("string", &k, cv)); } } } ret.overrides.insert(lib_name, output); } Ok(ret) }
38.42094
81
0.505923
8a0e4b5a1e40aeb8ad18ed3b9eb8aa99e32840ca
14,453
//! UDP relay proxy server use std::{ io::{self, Cursor}, net::{IpAddr, Ipv4Addr, SocketAddr}, sync::Arc, time::Duration, }; use bytes::BytesMut; use futures::{self, future, stream::FuturesUnordered, FutureExt, StreamExt}; use log::{debug, error, info, trace, warn}; use lru_time_cache::{Entry, LruCache}; use tokio::{ self, net::udp::{RecvHalf, SendHalf}, sync::{mpsc, oneshot, Mutex}, time, }; use crate::{ config::ServerConfig, context::{Context, SharedContext}, relay::{ flow::{SharedMultiServerFlowStatistic, SharedServerFlowStatistic}, socks5::Address, sys::create_udp_socket, utils::try_timeout, }, }; use super::{ crypto_io::{decrypt_payload, encrypt_payload}, DEFAULT_TIMEOUT, MAXIMUM_UDP_PAYLOAD_SIZE, }; struct UdpAssociationWatcher(oneshot::Sender<()>); // Represent a UDP association #[derive(Clone)] struct UdpAssociation { // local -> remote Queue // Drops tx, will close local -> remote task tx: mpsc::Sender<Vec<u8>>, // local <- remote task life watcher watcher: Arc<UdpAssociationWatcher>, } impl UdpAssociation { /// Create an association with addr async fn associate( context: SharedContext, svr_idx: usize, src_addr: SocketAddr, mut response_tx: mpsc::Sender<(SocketAddr, BytesMut)>, ) -> io::Result<UdpAssociation> { // Create a socket for receiving packets let local_addr = match context.config().local { None => { // Let system allocate an address for us SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0) } Some(ref addr) => { // Uses configured local address addr.bind_addr(&*context).await? } }; let remote_udp = create_udp_socket(&local_addr).await?; let local_addr = remote_udp.local_addr().expect("could not determine port bound to"); debug!("created UDP Association for {} from {}", src_addr, local_addr); // Create a channel for sending packets to remote // FIXME: Channel size 1024? let (tx, mut rx) = mpsc::channel::<Vec<u8>>(1024); // Create a watcher for local <- remote task let (watcher_tx, watcher_rx) = oneshot::channel::<()>(); let close_flag = Arc::new(UdpAssociationWatcher(watcher_tx)); // Splits socket into sender and receiver let (mut receiver, mut sender) = remote_udp.split(); let timeout = context.config().udp_timeout.unwrap_or(DEFAULT_TIMEOUT); // local -> remote { let context = context.clone(); tokio::spawn(async move { let svr_cfg = context.server_config(svr_idx); while let Some(pkt) = rx.recv().await { // pkt is already a raw packet, so just send it if let Err(err) = UdpAssociation::relay_l2r(&*context, src_addr, &mut sender, &pkt[..], timeout, svr_cfg).await { error!("failed to relay packet, {} -> ..., error: {}", src_addr, err); // FIXME: Ignore? Or how to deal with it? } } debug!("UDP ASSOCIATE {} -> .. finished", src_addr); }); } // local <- remote tokio::spawn(async move { let transfer_fut = async move { let svr_cfg = context.server_config(svr_idx); loop { // Read and send back to source match UdpAssociation::relay_r2l(&*context, src_addr, &mut receiver, &mut response_tx, svr_cfg).await { Ok(..) => {} Err(err) => { error!("failed to receive packet, {} <- .., error: {}", src_addr, err); // FIXME: Don't break, or if you can find a way to drop the UdpAssociation // break; } } } }; // Resolved only if watcher_rx resolved let _ = future::select(transfer_fut.boxed(), watcher_rx.boxed()).await; debug!("UDP ASSOCIATE {} <- .. finished", src_addr); }); Ok(UdpAssociation { tx, watcher: close_flag, }) } /// Relay packets from local to remote async fn relay_l2r( context: &Context, src: SocketAddr, remote_udp: &mut SendHalf, pkt: &[u8], timeout: Duration, svr_cfg: &ServerConfig, ) -> io::Result<()> { // First of all, decrypt payload CLIENT -> SERVER let decrypted_pkt = match decrypt_payload(context, svr_cfg.method(), svr_cfg.key(), pkt) { Ok(Some(pkt)) => pkt, Ok(None) => { error!("failed to decrypt pkt in UDP relay, packet too short"); let err = io::Error::new(io::ErrorKind::InvalidData, "packet too short"); return Err(err); } Err(err) => { error!("failed to decrypt pkt in UDP relay: {}", err); let err = io::Error::new(io::ErrorKind::InvalidData, "decrypt failed"); return Err(err); } }; // CLIENT -> SERVER protocol: ADDRESS + PAYLOAD let mut cur = Cursor::new(decrypted_pkt); let addr = Address::read_from(&mut cur).await?; debug!("UDP ASSOCIATE {} <-> {} establishing", src, addr); if context.check_outbound_blocked(&addr) { warn!("outbound {} is blocked by ACL rules", addr); return Ok(()); } // Take out internal buffer for optimizing one byte copy let header_len = cur.position() as usize; let decrypted_pkt = cur.into_inner(); let body = &decrypted_pkt[header_len..]; let send_len = match addr { Address::SocketAddress(ref remote_addr) => { debug!( "UDP ASSOCIATE {} -> {} ({}), payload length {} bytes", src, addr, remote_addr, body.len() ); try_timeout(remote_udp.send_to(body, remote_addr), Some(timeout)).await? } Address::DomainNameAddress(ref dname, port) => lookup_outbound_then!(context, dname, port, |remote_addr| { match try_timeout(remote_udp.send_to(body, &remote_addr), Some(timeout)).await { Ok(l) => { debug!( "UDP ASSOCIATE {} -> {} ({}), payload length {} bytes", src, addr, remote_addr, body.len() ); Ok(l) } Err(err) => { error!( "UDP ASSOCIATE {} -> {} ({}), payload length {} bytes", src, addr, remote_addr, body.len() ); Err(err) } } }) .map(|(_, l)| l)?, }; assert_eq!(body.len(), send_len); Ok(()) } /// Relay packets from remote to local async fn relay_r2l( context: &Context, src_addr: SocketAddr, remote_udp: &mut RecvHalf, response_tx: &mut mpsc::Sender<(SocketAddr, BytesMut)>, svr_cfg: &ServerConfig, ) -> io::Result<()> { // Waiting for response from server SERVER -> CLIENT // Packet length is limited by MAXIMUM_UDP_PAYLOAD_SIZE, excess bytes will be discarded. let mut remote_buf = [0u8; MAXIMUM_UDP_PAYLOAD_SIZE]; let (remote_recv_len, remote_addr) = remote_udp.recv_from(&mut remote_buf).await?; debug!( "UDP ASSOCIATE {} <- {}, payload length {} bytes", src_addr, remote_addr, remote_recv_len ); // FIXME: The Address should be the Address that client sent let addr = Address::SocketAddress(remote_addr); // CLIENT <- SERVER protocol: ADDRESS + PAYLOAD let mut send_buf = Vec::new(); addr.write_to_buf(&mut send_buf); send_buf.extend_from_slice(&remote_buf[..remote_recv_len]); let mut encrypt_buf = BytesMut::new(); encrypt_payload(context, svr_cfg.method(), svr_cfg.key(), &send_buf, &mut encrypt_buf)?; // Send back to src_addr if let Err(err) = response_tx.send((src_addr, encrypt_buf)).await { error!("failed to send packet into response channel, error: {}", err); // FIXME: What to do? Ignore? } Ok(()) } // Send packet to remote // // Return `Err` if receiver have been closed async fn send(&mut self, pkt: Vec<u8>) { if let Err(..) = self.tx.send(pkt).await { // SHOULDn't HAPPEN unreachable!("UDP Association local -> remote Queue closed unexpectly"); } } } async fn listen(context: SharedContext, flow_stat: SharedServerFlowStatistic, svr_idx: usize) -> io::Result<()> { let svr_cfg = context.server_config(svr_idx); let listen_addr = svr_cfg.addr().bind_addr(&*context).await?; let listener = create_udp_socket(&listen_addr).await?; let local_addr = listener.local_addr().expect("determine port bound to"); info!("shadowsocks UDP listening on {}", local_addr); let (mut r, mut w) = listener.split(); // NOTE: Associations are only eliminated by expire time // So it may exhaust all available file descriptors let timeout = context.config().udp_timeout.unwrap_or(DEFAULT_TIMEOUT); let assoc_map = Arc::new(Mutex::new(LruCache::with_expiry_duration(timeout))); // FIXME: Channel size 1024? let (tx, mut rx) = mpsc::channel::<(SocketAddr, BytesMut)>(1024); { // Tokio task for sending data back to clients let assoc_map = assoc_map.clone(); let flow_stat = flow_stat.clone(); tokio::spawn(async move { while let Some((src, pkt)) = rx.recv().await { let cache_key = src.to_string(); { let mut amap = assoc_map.lock().await; // Check or update expire time if amap.get(&cache_key).is_none() { debug!( "UDP association {} <-> ... is already expired, throwing away packet {} bytes", src, pkt.len() ); continue; } } if let Err(err) = w.send_to(&pkt, &src).await { error!("UDP packet send failed, err: {:?}", err); break; } flow_stat.udp().incr_tx(pkt.len() as u64); } // FIXME: How to stop the outer listener Future? }); } let mut pkt_buf = [0u8; MAXIMUM_UDP_PAYLOAD_SIZE]; loop { let (recv_len, src) = match time::timeout(timeout, r.recv_from(&mut pkt_buf)).await { Ok(r) => r?, Err(..) => { // Cleanup expired association // Do not consume this iterator, it will updates expire time of items that traversed let mut assoc_map = assoc_map.lock().await; let _ = assoc_map.iter(); continue; } }; // Packet length is limited by MAXIMUM_UDP_PAYLOAD_SIZE, excess bytes will be discarded. let pkt = &pkt_buf[..recv_len]; trace!("received UDP packet from {}, length {} bytes", src, recv_len); flow_stat.udp().incr_rx(pkt.len() as u64); if recv_len == 0 { // For windows, it will generate a ICMP Port Unreachable Message // https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recvfrom // Which will result in recv_from return 0. // // It cannot be solved here, because `WSAGetLastError` is already set. // // See `relay::udprelay::utils::create_socket` for more detail. continue; } // Check ACL if context.check_client_blocked(&src) { warn!("client {} is blocked by ACL rules", src); continue; } // Check or (re)create an association let mut assoc = { // Locks the whole association map let mut assoc_map = assoc_map.lock().await; // Get or create an association let assoc = match assoc_map.entry(src.to_string()) { Entry::Occupied(oc) => oc.into_mut(), Entry::Vacant(vc) => vc.insert( UdpAssociation::associate(context.clone(), svr_idx, src, tx.clone()) .await .expect("create udp association"), ), }; // Clone the handle and release the lock. // Make sure we keep the critical section small assoc.clone() }; // Send to local -> remote task assoc.send(pkt.to_vec()).await; } } /// Starts a UDP relay server pub async fn run(context: SharedContext, flow_stat: SharedMultiServerFlowStatistic) -> io::Result<()> { let vec_fut = FuturesUnordered::new(); for (svr_idx, svr_cfg) in context.config().server.iter().enumerate() { let context = context.clone(); let flow_stat = flow_stat .get(svr_cfg.addr().port()) .expect("port not existed in multi-server flow statistic") .clone(); let svr_fut = listen(context, flow_stat, svr_idx); vec_fut.push(svr_fut); } match vec_fut.into_future().await.0 { Some(res) => { error!("one of UDP servers exited unexpectly, result: {:?}", res); let err = io::Error::new(io::ErrorKind::Other, "server exited unexpectly"); Err(err) } None => unreachable!(), } }
34.826506
120
0.523006
fb03fbe065448b47a785c75aa7c792a215fca423
3,890
extern crate sdl2; extern crate vulkano; use sdl2::sys::{SDL_GetError, SDL_GetWindowWMInfo, SDL_SysWMinfo}; use sdl2::sys::{SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL}; use sdl2::sys::SDL_SYSWM_TYPE; use sdl2::sys::SDL_Window; use sdl2::sys::SDL_bool::SDL_FALSE; use sdl2::video::Window; use std::ffi::CString; use std::mem; use std::os::raw::c_char; use std::sync::Arc; use vulkano::instance::{Instance, InstanceExtensions}; use vulkano::swapchain::{Surface, SurfaceCreationError}; #[derive(Debug)] pub enum ErrorType { Unknown, PlatformNotSupported, OutOfMemory, MissingExtension(String), Generic(String), } pub fn required_extensions(window: &Window) -> Result<InstanceExtensions, ErrorType> { let wm_info = get_wminfo(window.raw())?; let mut extensions = InstanceExtensions { khr_surface: true, ..InstanceExtensions::none() }; match wm_info.subsystem { SDL_SYSWM_TYPE::SDL_SYSWM_X11 => extensions.khr_xlib_surface = true, SDL_SYSWM_TYPE::SDL_SYSWM_WAYLAND => extensions.khr_wayland_surface = true, SDL_SYSWM_TYPE::SDL_SYSWM_WINDOWS => extensions.khr_win32_surface = true, SDL_SYSWM_TYPE::SDL_SYSWM_ANDROID => extensions.khr_android_surface = true, _ => return Err(ErrorType::PlatformNotSupported), } Ok(extensions) } pub fn build_vk_surface(window: &Window, instance: Arc<Instance>) -> Result<Arc<Surface>, ErrorType> { let wm_info = get_wminfo(window.raw())?; unsafe { sdl2_to_surface(&wm_info, instance) } } #[cfg(target_os = "android")] unsafe fn sdl2_to_surface(wm_info: &SDL_SysWMinfo, instance: Arc<Instance>) -> Result<Arc<Surface>, ErrorType> { let window = wm_info.info.android.window; translate_vk_result(Surface::from_anativewindow(instance, window)) } #[cfg(all(unix, not(target_os = "android")))] unsafe fn sdl2_to_surface(wm_info: &SDL_SysWMinfo, instance: Arc<Instance>) -> Result<Arc<Surface>, ErrorType> { if wm_info.subsystem == SDL_SYSWM_TYPE::SDL_SYSWM_X11 { let display = wm_info.info.x11.display; let window = wm_info.info.x11.window; translate_vk_result(Surface::from_xlib(instance, display, window)) } else if wm_info.subsystem == SDL_SYSWM_TYPE::SDL_SYSWM_WAYLAND { let display = wm_info.info.wl.display; let surface = wm_info.info.wl.surface; translate_vk_result(Surface::from_wayland(instance, display, surface)) } else { unreachable!(); } } #[cfg(target_os = "windows")] unsafe fn sdl2_to_surface(wm_info: &SDL_SysWMinfo, instance: Arc<Instance>) -> Result<Arc<Surface>, ErrorType> { let hinstance = wm_info.info.win.hinstance; let hwnd = wm_info.info.win.window; translate_vk_result(Surface::from_hwnd(instance, hinstance, hwnd)) } fn translate_vk_result(obj: Result<Arc<Surface>, SurfaceCreationError>) -> Result<Arc<Surface>, ErrorType> { match obj { Ok(x) => Ok(x), Err(SurfaceCreationError::OomError(_)) => Err(ErrorType::OutOfMemory), Err(SurfaceCreationError::MissingExtension { name: x }) => Err(ErrorType::MissingExtension(String::from(x))), } } fn get_wminfo(window: *mut SDL_Window) -> Result<SDL_SysWMinfo, ErrorType> { let mut wm_info: SDL_SysWMinfo; unsafe { wm_info = mem::zeroed(); } wm_info.version.major = SDL_MAJOR_VERSION as u8; wm_info.version.minor = SDL_MINOR_VERSION as u8; wm_info.version.patch = SDL_PATCHLEVEL as u8; unsafe { if SDL_GetWindowWMInfo(window, &mut wm_info as *mut SDL_SysWMinfo) == SDL_FALSE { let error = CString::from_raw(SDL_GetError() as *mut c_char); match error.into_string() { Ok(x) => return Err(ErrorType::Generic(x)), Err(_) => return Err(ErrorType::Unknown), } } } Ok(wm_info) }
32.689076
117
0.683805
f9473d0a8752ee973a9b4edb0cc18ec785234a3f
482
// clippy1.rs // The Clippy tool is a collection of lints to analyze your code // so you can catch common mistakes and improve your Rust code. // // For these exercises the code will fail to compile when there are clippy warnings // check clippy's suggestions from the output to solve the exercise. // Execute `rustlings hint clippy1` for hints :) fn main() { let x = 1.2331f64; let y = 1.2332f64; if (y-x).abs() < f64::EPSILON { println!("Success!"); } }
28.352941
83
0.674274
1402e8d86963713249abdec1a3239d1551e064c5
5,586
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::ops::Drop; use std::sync::{Condvar, Mutex}; /// A counting, blocking, semaphore. /// /// Semaphores are a form of atomic counter where access is only granted if the /// counter is a positive value. Each acquisition will block the calling thread /// until the counter is positive, and each release will increment the counter /// and unblock any threads if necessary. /// /// # Examples /// /// ``` /// use std_semaphore::Semaphore; /// /// // Create a semaphore that represents 5 resources /// let sem = Semaphore::new(5); /// /// // Acquire one of the resources /// sem.acquire(); /// /// // Acquire one of the resources for a limited period of time /// { /// let _guard = sem.access(); /// // ... /// } // resources is released here /// /// // Release our initially acquired resource /// sem.release(); /// ``` pub struct Semaphore { lock: Mutex<isize>, cvar: Condvar, } /// An RAII guard which will release a resource acquired from a semaphore when /// dropped. pub struct SemaphoreGuard<'a> { sem: &'a Semaphore, } impl Semaphore { /// Creates a new semaphore with the initial count specified. /// /// The count specified can be thought of as a number of resources, and a /// call to `acquire` or `access` will block until at least one resource is /// available. It is valid to initialize a semaphore with a negative count. pub fn new(count: isize) -> Semaphore { Semaphore { lock: Mutex::new(count), cvar: Condvar::new(), } } /// Acquires a resource of this semaphore, blocking the current thread until /// it can do so. /// /// This method will block until the internal count of the semaphore is at /// least 1. pub fn acquire(&self) { let mut count = self.lock.lock().unwrap(); while *count <= 0 { count = self.cvar.wait(count).unwrap(); } *count -= 1; } /// Release a resource from this semaphore. /// /// This will increment the number of resources in this semaphore by 1 and /// will notify any pending waiters in `acquire` or `access` if necessary. pub fn release(&self) { *self.lock.lock().unwrap() += 1; self.cvar.notify_one(); } /// Acquires a resource of this semaphore, returning an RAII guard to /// release the semaphore when dropped. /// /// This function is semantically equivalent to an `acquire` followed by a /// `release` when the guard returned is dropped. pub fn access(&self) -> SemaphoreGuard { self.acquire(); SemaphoreGuard { sem: self } } } impl<'a> Drop for SemaphoreGuard<'a> { fn drop(&mut self) { self.sem.release(); } } #[cfg(test)] mod tests { use std::prelude::v1::*; use std::sync::Arc; use super::Semaphore; use std::sync::mpsc::channel; use std::thread; #[test] fn test_sem_acquire_release() { let s = Semaphore::new(1); s.acquire(); s.release(); s.acquire(); } #[test] fn test_sem_basic() { let s = Semaphore::new(1); let _g = s.access(); } #[test] fn test_sem_as_mutex() { let s = Arc::new(Semaphore::new(1)); let s2 = s.clone(); let _t = thread::spawn(move || { let _g = s2.access(); }); let _g = s.access(); } #[test] fn test_sem_as_cvar() { // Child waits and parent signals let (tx, rx) = channel(); let s = Arc::new(Semaphore::new(0)); let s2 = s.clone(); let _t = thread::spawn(move || { s2.acquire(); tx.send(()).unwrap(); }); s.release(); let _ = rx.recv(); // Parent waits and child signals let (tx, rx) = channel(); let s = Arc::new(Semaphore::new(0)); let s2 = s.clone(); let _t = thread::spawn(move || { s2.release(); let _ = rx.recv(); }); s.acquire(); tx.send(()).unwrap(); } #[test] fn test_sem_multi_resource() { // Parent and child both get in the critical section at the same // time, and shake hands. let s = Arc::new(Semaphore::new(2)); let s2 = s.clone(); let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); let _t = thread::spawn(move || { let _g = s2.access(); let _ = rx2.recv(); tx1.send(()).unwrap(); }); let _g = s.access(); tx2.send(()).unwrap(); rx1.recv().unwrap(); } #[test] fn test_sem_runtime_friendly_blocking() { let s = Arc::new(Semaphore::new(1)); let s2 = s.clone(); let (tx, rx) = channel(); { let _g = s.access(); thread::spawn(move || { tx.send(()).unwrap(); drop(s2.access()); tx.send(()).unwrap(); }); rx.recv().unwrap(); // wait for child to come alive } rx.recv().unwrap(); // wait for child to be done } }
28.35533
80
0.559434
e4790dff0661b53fc2360b12d5a69dd3e8bf08bf
8,618
//! Module for performing cross-validation of models. use std::prelude::v1::*; use std::cmp; use std::iter::Chain; use std::slice::Iter; use linalg::{BaseMatrix, Matrix}; use learning::{LearningResult, SupModel}; use learning::toolkit::rand_utils::in_place_fisher_yates; /// Randomly splits the inputs into k 'folds'. For each fold a model /// is trained using all inputs except for that fold, and tested on the /// data in the fold. Returns the scores for each fold. /// /// # Arguments /// * `model` - Used to train and predict for each fold. /// * `inputs` - All input samples. /// * `targets` - All targets. /// * `k` - Number of folds to use. /// * `score` - Used to compare the outputs for each fold to the targets. Higher scores are better. See the `analysis::score` module for examples. /// /// # Examples /// ``` /// use rusty_machine::analysis::cross_validation::k_fold_validate; /// use rusty_machine::analysis::score::row_accuracy; /// use rusty_machine::learning::naive_bayes::{NaiveBayes, Bernoulli}; /// use rusty_machine::linalg::{BaseMatrix, Matrix}; /// /// let inputs = Matrix::new(3, 2, vec![1.0, 1.1, /// 5.2, 4.3, /// 6.2, 7.3]); /// /// let targets = Matrix::new(3, 3, vec![1.0, 0.0, 0.0, /// 0.0, 0.0, 1.0, /// 0.0, 0.0, 1.0]); /// /// let mut model = NaiveBayes::<Bernoulli>::new(); /// /// let accuracy_per_fold: Vec<f64> = k_fold_validate( /// &mut model, /// &inputs, /// &targets, /// 3, /// // Score each fold by the fraction of test samples where /// // the model's prediction equals the target. /// row_accuracy /// ).unwrap(); /// ``` pub fn k_fold_validate<M, S>(model: &mut M, inputs: &Matrix<f64>, targets: &Matrix<f64>, k: usize, score: S) -> LearningResult<Vec<f64>> where S: Fn(&Matrix<f64>, &Matrix<f64>) -> f64, M: SupModel<Matrix<f64>, Matrix<f64>>, { assert_eq!(inputs.rows(), targets.rows()); let num_samples = inputs.rows(); let shuffled_indices = create_shuffled_indices(num_samples); let folds = Folds::new(&shuffled_indices, k); let mut costs: Vec<f64> = Vec::new(); for p in folds { // TODO: don't allocate fresh buffers for every fold let train_inputs = inputs.select_rows(p.train_indices_iter.clone()); let train_targets = targets.select_rows(p.train_indices_iter.clone()); let test_inputs = inputs.select_rows(p.test_indices_iter.clone()); let test_targets = targets.select_rows(p.test_indices_iter.clone()); model.train(&train_inputs, &train_targets)?; let outputs = model.predict(&test_inputs)?; costs.push(score(&outputs, &test_targets)); } Ok(costs) } /// A permutation of 0..n. struct ShuffledIndices(Vec<usize>); /// Permute the indices of the inputs samples. fn create_shuffled_indices(num_samples: usize) -> ShuffledIndices { let mut indices: Vec<usize> = (0..num_samples).collect(); in_place_fisher_yates(&mut indices); ShuffledIndices(indices) } /// A partition of indices of all available samples into /// a training set and a test set. struct Partition<'a> { train_indices_iter: TrainingIndices<'a>, test_indices_iter: TestIndices<'a> } #[derive(Clone)] struct TestIndices<'a>(Iter<'a, usize>); #[derive(Clone)] struct TrainingIndices<'a> { chain: Chain<Iter<'a, usize>, Iter<'a, usize>>, size: usize } impl<'a> TestIndices<'a> { fn new(indices: &'a [usize]) -> TestIndices<'a> { TestIndices(indices.iter()) } } impl<'a> Iterator for TestIndices<'a> { type Item = &'a usize; fn next(&mut self) -> Option<&'a usize> { self.0.next() } } impl <'a> ExactSizeIterator for TestIndices<'a> { fn len(&self) -> usize { self.0.len() } } impl<'a> TrainingIndices<'a> { fn new(left: &'a [usize], right: &'a [usize]) -> TrainingIndices<'a> { let chain = left.iter().chain(right.iter()); TrainingIndices { chain: chain, size: left.len() + right.len() } } } impl<'a> Iterator for TrainingIndices<'a> { type Item = &'a usize; fn next(&mut self) -> Option<&'a usize> { self.chain.next() } } impl <'a> ExactSizeIterator for TrainingIndices<'a> { fn len(&self) -> usize { self.size } } /// An iterator over the sets of indices required for k-fold cross validation. struct Folds<'a> { num_folds: usize, indices: &'a[usize], count: usize } impl<'a> Folds<'a> { /// Let n = indices.len(), and k = num_folds. /// The first n % k folds have size n / k + 1 and the /// rest have size n / k. (In particular, if n % k == 0 then all /// folds are the same size.) fn new(indices: &'a ShuffledIndices, num_folds: usize) -> Folds<'a> { let num_samples = indices.0.len(); assert!(num_folds > 1 && num_samples >= num_folds, "Require num_folds > 1 && num_samples >= num_folds"); Folds { num_folds: num_folds, indices: &indices.0, count: 0 } } } impl<'a> Iterator for Folds<'a> { type Item = Partition<'a>; fn next(&mut self) -> Option<Self::Item> { if self.count >= self.num_folds { return None; } let num_samples = self.indices.len(); let q = num_samples / self.num_folds; let r = num_samples % self.num_folds; let fold_start = self.count * q + cmp::min(self.count, r); let fold_size = if self.count >= r {q} else {q + 1}; let fold_end = fold_start + fold_size; self.count += 1; let prefix = &self.indices[..fold_start]; let suffix = &self.indices[fold_end..]; let infix = &self.indices[fold_start..fold_end]; Some(Partition { train_indices_iter: TrainingIndices::new(prefix, suffix), test_indices_iter: TestIndices::new(infix) }) } } #[cfg(test)] mod tests { use super::{ShuffledIndices, Folds}; // k % n == 0 #[test] fn test_folds_n6_k3() { let idxs = ShuffledIndices(vec![0, 1, 2, 3, 4, 5]); let folds = collect_folds(Folds::new(&idxs, 3)); assert_eq!(folds, vec![ (vec![2, 3, 4, 5], vec![0, 1]), (vec![0, 1, 4, 5], vec![2, 3]), (vec![0, 1, 2, 3], vec![4, 5]) ]); } // k % n == 1 #[test] fn test_folds_n5_k2() { let idxs = ShuffledIndices(vec![0, 1, 2, 3, 4]); let folds = collect_folds(Folds::new(&idxs, 2)); assert_eq!(folds, vec![ (vec![3, 4], vec![0, 1, 2]), (vec![0, 1, 2], vec![3, 4]) ]); } // k % n == 2 #[test] fn test_folds_n6_k4() { let idxs = ShuffledIndices(vec![0, 1, 2, 3, 4, 5]); let folds = collect_folds(Folds::new(&idxs, 4)); assert_eq!(folds, vec![ (vec![2, 3, 4, 5], vec![0, 1]), (vec![0, 1, 4, 5], vec![2, 3]), (vec![0, 1, 2, 3, 5], vec![4]), (vec![0, 1, 2, 3, 4], vec![5]) ]); } // k == n #[test] fn test_folds_n4_k4() { let idxs = ShuffledIndices(vec![0, 1, 2, 3]); let folds = collect_folds(Folds::new(&idxs, 4)); assert_eq!(folds, vec![ (vec![1, 2, 3], vec![0]), (vec![0, 2, 3], vec![1]), (vec![0, 1, 3], vec![2]), (vec![0, 1, 2], vec![3]) ]); } #[test] #[should_panic] fn test_folds_rejects_large_k() { let idxs = ShuffledIndices(vec![0, 1, 2]); let _ = collect_folds(Folds::new(&idxs, 4)); } // Check we're really returning iterators into the shuffled // indices rather than into (0..n). #[test] fn test_folds_unordered_indices() { let idxs = ShuffledIndices(vec![5, 4, 3, 2, 1, 0]); let folds = collect_folds(Folds::new(&idxs, 3)); assert_eq!(folds, vec![ (vec![3, 2, 1, 0], vec![5, 4]), (vec![5, 4, 1, 0], vec![3, 2]), (vec![5, 4, 3, 2], vec![1, 0]) ]); } fn collect_folds<'a>(folds: Folds<'a>) -> Vec<(Vec<usize>, Vec<usize>)> { folds .map(|p| (p.train_indices_iter.map(|x| *x).collect::<Vec<_>>(), p.test_indices_iter.map(|x| *x).collect::<Vec<_>>())) .collect::<Vec<(Vec<usize>, Vec<usize>)>>() } }
30.027875
146
0.54479
618ead00f24912253c3369b7ff2e158d1910f8dd
15,469
use crate::database::Connection; use crate::extractors::*; use crate::helpers::*; use crate::server::GetAppState; use crate::utils::logging::log_request; use actix_service::Service; use actix_web::error; use actix_web::http::header::*; use actix_web::http::{Method, StatusCode}; use actix_web::{dev, FromRequest, HttpRequest, HttpResponse}; use db::models::*; use futures::future::{ok, Ready}; use http::caching::*; use itertools::Itertools; use log::Level; use serde_json::Value; use std::collections::BTreeMap; use url::form_urlencoded; use uuid::Uuid; const CACHED_RESPONSE_HEADER: &'static str = "X-Cached-Response"; const CACHE_BYPASS_HEADER: &'static str = "Cache-Bypass"; #[derive(PartialEq, Clone)] pub enum OrganizationLoad { // /organizations/{id}/.. Path, } #[derive(PartialEq, Clone)] pub enum CacheUsersBy { // Logged in users and anonymous users receive cached results None, // Logged in users are not cached, anonymous users receive cached results AnonymousOnly, // Users are cached into groups according to the combination of roles on the users row // e.g. "Admin,Super", "Admin", "" is used for both logged in users with no roles and anon users // Organization access is not taken into account GlobalRoles, // Users are cached by their ID UserId, // Only public users (logged out or lacking organization_users) are cached PublicUsersOnly, // Users are cached by their associated organization roles (cannot be used for event specific role endpoints) OrganizationScopePresence(OrganizationLoad, Scopes), } enum Cache { Miss(CacheConfiguration), Hit(HttpResponse, CacheConfiguration), Skip, } #[derive(Clone)] pub struct CacheResource { pub cache_users_by: CacheUsersBy, } struct CacheConfiguration { cache_response: bool, served_cache: bool, error: bool, user_key: Option<String>, cache_data: BTreeMap<String, String>, } impl CacheConfiguration { fn new() -> CacheConfiguration { CacheConfiguration { cache_response: false, served_cache: false, error: false, user_key: None, cache_data: BTreeMap::new(), } } fn start_error(mut self, error: &str) -> Cache { self.error = true; error!("CacheResource Middleware start: {:?}", error); return Cache::Miss(self); } } impl CacheResource { pub fn new(cache_users_by: CacheUsersBy) -> Self { Self { cache_users_by } } // Identify caching action and data based on request // When resulting in Cache::Hit route handler will be skipped fn start(&self, request: &HttpRequest) -> Cache { let mut cache_configuration = CacheConfiguration::new(); if request.method() == Method::GET { if request .headers() .contains_key(CACHE_BYPASS_HEADER.parse::<HeaderName>().unwrap()) { return Cache::Miss(cache_configuration); } for (key, value) in form_urlencoded::parse(request.uri().query().unwrap_or("").as_bytes()) { cache_configuration .cache_data .insert(key.to_string(), value.to_string()); } let user_text = "x-user-role".to_string(); cache_configuration .cache_data .insert("path".to_string(), request.path().to_string()); cache_configuration .cache_data .insert("method".to_string(), request.method().to_string()); let state = request.state().clone(); let config = state.config.clone(); if self.cache_users_by != CacheUsersBy::None { let user = match OptionalUser::from_request(request, &mut dev::Payload::None).into_inner() { Ok(user) => user, Err(error) => { return cache_configuration.start_error(&format!("{:?}", error)); } }; if let Some(user) = user.0 { match &self.cache_users_by { CacheUsersBy::None => (), CacheUsersBy::AnonymousOnly => { // Do not cache return Cache::Skip; } CacheUsersBy::UserId => { cache_configuration.user_key = Some(user.id().to_string()); } CacheUsersBy::PublicUsersOnly => { if !user.is_public_user { return Cache::Miss(cache_configuration); } } CacheUsersBy::GlobalRoles => { cache_configuration.user_key = Some(user.user.role.iter().map(|r| r.to_string()).join(",")); } CacheUsersBy::OrganizationScopePresence(load_type, scope) => { if let Some(connection) = request.extensions().get::<Connection>() { let connection = connection.get(); match load_type { OrganizationLoad::Path => { // Assumes path element exists let organization_id: Uuid = request.match_info().get(&"id".to_string()).unwrap().parse().unwrap(); let organization = match Organization::find(organization_id, connection) { Ok(organization) => organization, Err(error) => { return cache_configuration.start_error(&format!("{:?}", error)); } }; let has_scope = match user.has_scope_for_organization(*scope, &organization, connection) { Ok(organization_scopes) => organization_scopes, Err(error) => { return cache_configuration.start_error(&format!("{:?}", error)); } }; cache_configuration.user_key = Some(format!("{}-{}", scope, if has_scope { "t" } else { "f" })); } } } else { return cache_configuration.start_error("unable to load connection"); } } } if let Some(ref user_key) = cache_configuration.user_key { cache_configuration.cache_data.insert(user_text, user_key.to_string()); } } } let cache_database = state.database.cache_database.clone(); // if there is a error in the cache, the value does not exist let cached_value = cache_database .clone() .inner .clone() .and_then(|conn| caching::get_cached_value(conn, &config, &cache_configuration.cache_data)); if let Some(response) = cached_value { // Insert self into extensions to let response know not to set the value cache_configuration.served_cache = true; return Cache::Hit(response, cache_configuration); } } cache_configuration.cache_response = true; Cache::Miss(cache_configuration) } // Updates cached data based on Cache result // This method will also issue unmodified when actual result did not change fn update(cache_configuration: CacheConfiguration, mut response: dev::ServiceResponse) -> dev::ServiceResponse { match *response.request().method() { Method::GET if response.status() == StatusCode::OK => { let state = response.request().state(); let cache_database = state.database.cache_database.clone(); let config = state.config.clone(); if cache_configuration.cache_response { cache_database.inner.clone().and_then(|conn| { caching::set_cached_value(conn, &config, response.response(), &cache_configuration.cache_data) .ok() }); } if cache_configuration.served_cache { response .headers_mut() .insert(CACHED_RESPONSE_HEADER.parse().unwrap(), HeaderValue::from_static("1")); } // If an error occurred fetching db data, do not send caching headers if !cache_configuration.error { // Cache headers for client if let Ok(cache_control_header_value) = HeaderValue::from_str(&format!( "{}, max-age={}", if cache_configuration.user_key.is_none() { "public" } else { "private" }, config.client_cache_period )) { response.headers_mut().insert(CACHE_CONTROL, cache_control_header_value); } if let Ok(response_str) = application::unwrap_body_to_string(response.response()) { if let Ok(payload) = serde_json::from_str::<Value>(&response_str) { let etag_hash = etag_hash(&payload.to_string()); if let Ok(new_header_value) = HeaderValue::from_str(&etag_hash) { response.headers_mut().insert(ETAG, new_header_value); let headers = response.request().headers(); if headers.contains_key(IF_NONE_MATCH) { let etag = ETag(EntityTag::weak(etag_hash.to_string())); let if_none_match = headers.get(IF_NONE_MATCH).map(|h| h.to_str().ok()); if let Some(Some(header_value)) = if_none_match { let etag_header = ETag(EntityTag::weak(header_value.to_string())); if etag.weak_eq(&etag_header) { return response.into_response(HttpResponse::NotModified().finish()); } } } } } } } } Method::PUT | Method::PATCH | Method::POST | Method::DELETE => { if response.response().error().is_none() { let path = response.request().path().to_owned(); let state = response.request().state(); let cache_database = state.database.cache_database.clone(); cache_database .inner .clone() .and_then(|conn| caching::delete_by_key_fragment(conn, path).ok()); } } _ => (), }; response } } impl<S> dev::Transform<S> for CacheResource where S: Service<Request = dev::ServiceRequest, Response = dev::ServiceResponse, Error = error::Error> + 'static, { type Request = S::Request; type Response = S::Response; type Error = S::Error; type InitError = (); type Transform = CacheResourceService<S>; type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { let cache_users_by = self.cache_users_by.clone(); let resource = CacheResource { cache_users_by }; ok(CacheResourceService::new(service, resource)) } } use std::cell::RefCell; use std::future::Future; use std::pin::Pin; use std::rc::Rc; use std::task::{Context, Poll}; pub struct CacheResourceService<S> { service: Rc<RefCell<S>>, resource: CacheResource, } impl<S> CacheResourceService<S> { fn new(service: S, resource: CacheResource) -> Self { Self { service: Rc::new(RefCell::new(service)), resource, } } } impl<S> Service for CacheResourceService<S> where S: Service<Request = dev::ServiceRequest, Response = dev::ServiceResponse, Error = error::Error> + 'static, { type Request = S::Request; type Response = dev::ServiceResponse; type Error = S::Error; type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.service.borrow_mut().poll_ready(cx).map_err(error::Error::from) } fn call(&mut self, request: Self::Request) -> Self::Future { let service = self.service.clone(); let resource = self.resource.clone(); let (http_req, payload) = request.into_parts(); let cache = resource.start(&http_req); match cache { Cache::Hit(response, status) => { log_request( Level::Debug, "api::cache_resource", "Cache hit", &http_req, json!({"cache_user_key": status.user_key, "cache_response": status.cache_response, "cache_hit": true}), ); let response = dev::ServiceResponse::new(http_req, response); Box::pin(async move { Ok(CacheResource::update(status, response)) }) } Cache::Miss(status) => { log_request( Level::Debug, "api::cache_resource", "Cache miss", &http_req, json!({"cache_user_key": status.user_key, "cache_response": status.cache_response, "cache_hit": false}), ); let request = dev::ServiceRequest::from_parts(http_req, payload) .unwrap_or_else(|_| unreachable!("Failed to recompose request in CacheResourceService::call")); let fut = service.borrow_mut().call(request); Box::pin(async move { let response = fut.await?; Ok(CacheResource::update(status, response)) }) } Cache::Skip => { let request = dev::ServiceRequest::from_parts(http_req, payload) .unwrap_or_else(|_| unreachable!("Failed to recompose request in CacheResourceService::call")); let fut = service.borrow_mut().call(request); Box::pin(fut) } } } }
41.921409
124
0.509729
e5a1351c6fb940ecbeda6819d2f39508d9d5067a
1,567
use crate::math::{Isometry, Point}; use na::RealField; use crate::pipeline::narrow_phase::{ProximityDetector, ProximityDispatcher}; use crate::query::proximity_internal; use crate::query::Proximity; use crate::shape::{Ball, Shape}; /// Proximity detector between two balls. pub struct BallBallProximityDetector { proximity: Proximity, } impl Clone for BallBallProximityDetector { fn clone(&self) -> BallBallProximityDetector { BallBallProximityDetector { proximity: self.proximity, } } } impl BallBallProximityDetector { /// Creates a new persistent collision detector between two balls. #[inline] pub fn new() -> BallBallProximityDetector { BallBallProximityDetector { proximity: Proximity::Disjoint, } } } impl<N: RealField> ProximityDetector<N> for BallBallProximityDetector { fn update( &mut self, _: &ProximityDispatcher<N>, ma: &Isometry<N>, a: &Shape<N>, mb: &Isometry<N>, b: &Shape<N>, margin: N, ) -> bool { if let (Some(a), Some(b)) = (a.as_shape::<Ball<N>>(), b.as_shape::<Ball<N>>()) { self.proximity = proximity_internal::ball_against_ball( &Point::from(ma.translation.vector), a, &Point::from(mb.translation.vector), b, margin, ); true } else { false } } #[inline] fn proximity(&self) -> Proximity { self.proximity } }
25.274194
88
0.579451
4b1feb4a07bb1a107ad16d93403bbafb282a9899
21,160
//! This provides the logic for the finalized and head chains. //! //! Each chain type is stored in it's own map. A variety of helper functions are given along with //! this struct to simplify the logic of the other layers of sync. use super::chain::{ChainId, ProcessingResult, RemoveChain, SyncingChain}; use super::sync_type::RangeSyncType; use crate::beacon_processor::WorkEvent as BeaconWorkEvent; use crate::metrics; use crate::sync::network_context::SyncNetworkContext; use beacon_chain::{BeaconChain, BeaconChainTypes}; use eth2_libp2p::PeerId; use eth2_libp2p::SyncInfo; use fnv::FnvHashMap; use slog::{crit, debug, error}; use smallvec::SmallVec; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::mpsc; use types::EthSpec; use types::{Epoch, Hash256, Slot}; /// The number of head syncing chains to sync at a time. const PARALLEL_HEAD_CHAINS: usize = 2; /// Minimum work we require a finalized chain to do before picking a chain with more peers. const MIN_FINALIZED_CHAIN_VALIDATED_EPOCHS: u64 = 10; /// The state of the long range/batch sync. #[derive(Clone)] pub enum RangeSyncState { /// A finalized chain is being synced. Finalized(u64), /// There are no finalized chains and we are syncing one more head chains. Head(SmallVec<[u64; PARALLEL_HEAD_CHAINS]>), /// There are no head or finalized chains and no long range sync is in progress. Idle, } /// A collection of finalized and head chains currently being processed. pub struct ChainCollection<T: BeaconChainTypes> { /// The beacon chain for processing. beacon_chain: Arc<BeaconChain<T>>, /// The set of finalized chains being synced. finalized_chains: FnvHashMap<ChainId, SyncingChain<T>>, /// The set of head chains being synced. head_chains: FnvHashMap<ChainId, SyncingChain<T>>, /// The current sync state of the process. state: RangeSyncState, /// Logger for the collection. log: slog::Logger, } impl<T: BeaconChainTypes> ChainCollection<T> { pub fn new(beacon_chain: Arc<BeaconChain<T>>, log: slog::Logger) -> Self { ChainCollection { beacon_chain, finalized_chains: FnvHashMap::default(), head_chains: FnvHashMap::default(), state: RangeSyncState::Idle, log, } } /// Updates the Syncing state of the collection after a chain is removed. fn on_chain_removed(&mut self, id: &ChainId, was_syncing: bool, sync_type: RangeSyncType) { let _ = metrics::get_int_gauge(&metrics::SYNCING_CHAINS_COUNT, &[sync_type.as_str()]) .map(|m| m.dec()); match self.state { RangeSyncState::Finalized(ref syncing_id) => { if syncing_id == id { // the finalized chain that was syncing was removed debug_assert!(was_syncing); let syncing_head_ids: SmallVec<[u64; PARALLEL_HEAD_CHAINS]> = self .head_chains .iter() .filter(|(_id, chain)| chain.is_syncing()) .map(|(id, _)| *id) .collect(); self.state = if syncing_head_ids.is_empty() { RangeSyncState::Idle } else { RangeSyncState::Head(syncing_head_ids) }; } else { debug_assert!(!was_syncing); } } RangeSyncState::Head(ref mut syncing_head_ids) => { if let Some(index) = syncing_head_ids .iter() .enumerate() .find(|(_, &chain_id)| &chain_id == id) .map(|(i, _)| i) { // a syncing head chain was removed debug_assert!(was_syncing); syncing_head_ids.swap_remove(index); if syncing_head_ids.is_empty() { self.state = RangeSyncState::Idle; } } else { debug_assert!(!was_syncing); } } RangeSyncState::Idle => { // the removed chain should not be syncing debug_assert!(!was_syncing) } } } /// Calls `func` on every chain of the collection. If the result is /// `ProcessingResult::RemoveChain`, the chain is removed and returned. /// NOTE: `func` must not change the syncing state of a chain. pub fn call_all<F>(&mut self, mut func: F) -> Vec<(SyncingChain<T>, RangeSyncType, RemoveChain)> where F: FnMut(&mut SyncingChain<T>) -> ProcessingResult, { let mut to_remove = Vec::new(); for (id, chain) in self.finalized_chains.iter_mut() { if let Err(remove_reason) = func(chain) { to_remove.push((*id, RangeSyncType::Finalized, remove_reason)); } } for (id, chain) in self.head_chains.iter_mut() { if let Err(remove_reason) = func(chain) { to_remove.push((*id, RangeSyncType::Head, remove_reason)); } } let mut results = Vec::with_capacity(to_remove.len()); for (id, sync_type, reason) in to_remove.into_iter() { let chain = match sync_type { RangeSyncType::Finalized => self.finalized_chains.remove(&id), RangeSyncType::Head => self.head_chains.remove(&id), }; let chain = chain.expect("Chain exists"); self.on_chain_removed(&id, chain.is_syncing(), sync_type); results.push((chain, sync_type, reason)); } results } /// Executes a function on the chain with the given id. /// /// If the function returns `ProcessingResult::RemoveChain`, the chain is removed and returned. /// If the chain is found, its syncing type is returned, or an error otherwise. /// NOTE: `func` should not change the sync state of a chain. #[allow(clippy::type_complexity)] pub fn call_by_id<F>( &mut self, id: ChainId, func: F, ) -> Result<(Option<(SyncingChain<T>, RemoveChain)>, RangeSyncType), ()> where F: FnOnce(&mut SyncingChain<T>) -> ProcessingResult, { if let Entry::Occupied(mut entry) = self.finalized_chains.entry(id) { // Search in our finalized chains first if let Err(remove_reason) = func(entry.get_mut()) { let chain = entry.remove(); self.on_chain_removed(&id, chain.is_syncing(), RangeSyncType::Finalized); Ok((Some((chain, remove_reason)), RangeSyncType::Finalized)) } else { Ok((None, RangeSyncType::Finalized)) } } else if let Entry::Occupied(mut entry) = self.head_chains.entry(id) { // Search in our head chains next if let Err(remove_reason) = func(entry.get_mut()) { let chain = entry.remove(); self.on_chain_removed(&id, chain.is_syncing(), RangeSyncType::Head); Ok((Some((chain, remove_reason)), RangeSyncType::Head)) } else { Ok((None, RangeSyncType::Head)) } } else { // Chain was not found in the finalized collection, nor the head collection Err(()) } } /// Updates the state of the chain collection. /// /// This removes any out-dated chains, swaps to any higher priority finalized chains and /// updates the state of the collection. This starts head chains syncing if any are required to /// do so. pub fn update( &mut self, network: &mut SyncNetworkContext<T::EthSpec>, local: &SyncInfo, awaiting_head_peers: &mut HashMap<PeerId, SyncInfo>, beacon_processor_send: &mpsc::Sender<BeaconWorkEvent<T::EthSpec>>, ) { // Remove any outdated finalized/head chains self.purge_outdated_chains(local, awaiting_head_peers); let local_head_epoch = local.head_slot.epoch(T::EthSpec::slots_per_epoch()); // Choose the best finalized chain if one needs to be selected. self.update_finalized_chains(network, local.finalized_epoch, local_head_epoch); if !matches!(self.state, RangeSyncState::Finalized(_)) { // Handle head syncing chains if there are no finalized chains left. self.update_head_chains( network, local.finalized_epoch, local_head_epoch, awaiting_head_peers, beacon_processor_send, ); } } pub fn state( &self, ) -> Result<Option<(RangeSyncType, Slot /* from */, Slot /* to */)>, &'static str> { match self.state { RangeSyncState::Finalized(ref syncing_id) => { let chain = self .finalized_chains .get(syncing_id) .ok_or("Finalized syncing chain not found")?; Ok(Some(( RangeSyncType::Finalized, chain.start_epoch.start_slot(T::EthSpec::slots_per_epoch()), chain.target_head_slot, ))) } RangeSyncState::Head(ref syncing_head_ids) => { let mut range: Option<(Slot, Slot)> = None; for id in syncing_head_ids { let chain = self .head_chains .get(id) .ok_or("Head syncing chain not found")?; let start = chain.start_epoch.start_slot(T::EthSpec::slots_per_epoch()); let target = chain.target_head_slot; range = range .map(|(min_start, max_slot)| (min_start.min(start), max_slot.max(target))) .or(Some((start, target))); } let (start_slot, target_slot) = range.ok_or("Syncing head with empty head ids")?; Ok(Some((RangeSyncType::Head, start_slot, target_slot))) } RangeSyncState::Idle => Ok(None), } } /// This looks at all current finalized chains and decides if a new chain should be prioritised /// or not. fn update_finalized_chains( &mut self, network: &mut SyncNetworkContext<T::EthSpec>, local_epoch: Epoch, local_head_epoch: Epoch, ) { // Find the chain with most peers and check if it is already syncing if let Some((mut new_id, max_peers)) = self .finalized_chains .iter() .max_by_key(|(_, chain)| chain.available_peers()) .map(|(id, chain)| (*id, chain.available_peers())) { let mut old_id = None; if let RangeSyncState::Finalized(syncing_id) = self.state { if syncing_id == new_id { // best chain is already syncing old_id = Some(None); } else { // chains are different, check that they don't have the same number of peers if let Some(syncing_chain) = self.finalized_chains.get_mut(&syncing_id) { if max_peers > syncing_chain.available_peers() && syncing_chain.validated_epochs() > MIN_FINALIZED_CHAIN_VALIDATED_EPOCHS { syncing_chain.stop_syncing(); old_id = Some(Some(syncing_id)); } else { // chains have the same number of peers, pick the currently syncing // chain to avoid unnecesary switchings and try to advance it new_id = syncing_id; old_id = Some(None); } } } } let chain = self .finalized_chains .get_mut(&new_id) .expect("Chain exists"); match old_id { Some(Some(old_id)) => debug!(self.log, "Switching finalized chains"; "old_id" => old_id, &chain), None => debug!(self.log, "Syncing new finalized chain"; &chain), Some(None) => { // this is the same chain. We try to advance it. } } // update the state to a new finalized state self.state = RangeSyncState::Finalized(new_id); if let Err(remove_reason) = chain.start_syncing(network, local_epoch, local_head_epoch) { if remove_reason.is_critical() { crit!(self.log, "Chain removed while switching chains"; "chain" => new_id, "reason" => ?remove_reason); } else { // this happens only if sending a batch over the `network` fails a lot error!(self.log, "Chain removed while switching chains"; "chain" => new_id, "reason" => ?remove_reason); } self.finalized_chains.remove(&new_id); self.on_chain_removed(&new_id, true, RangeSyncType::Finalized); } } } /// Start syncing any head chains if required. fn update_head_chains( &mut self, network: &mut SyncNetworkContext<T::EthSpec>, local_epoch: Epoch, local_head_epoch: Epoch, awaiting_head_peers: &mut HashMap<PeerId, SyncInfo>, beacon_processor_send: &mpsc::Sender<BeaconWorkEvent<T::EthSpec>>, ) { // Include the awaiting head peers for (peer_id, peer_sync_info) in awaiting_head_peers.drain() { debug!(self.log, "including head peer"); self.add_peer_or_create_chain( local_epoch, peer_sync_info.head_root, peer_sync_info.head_slot, peer_id, RangeSyncType::Head, beacon_processor_send, network, ); } if self.head_chains.is_empty() { // There are no head chains, update the state. self.state = RangeSyncState::Idle; return; } // Order chains by available peers, if two chains have the same number of peers, prefer one // that is already syncing let mut preferred_ids = self .head_chains .iter() .map(|(id, chain)| (chain.available_peers(), !chain.is_syncing(), *id)) .collect::<Vec<_>>(); preferred_ids.sort_unstable(); let mut syncing_chains = SmallVec::<[u64; PARALLEL_HEAD_CHAINS]>::new(); for (_, _, id) in preferred_ids { let chain = self.head_chains.get_mut(&id).expect("known chain"); if syncing_chains.len() < PARALLEL_HEAD_CHAINS { // start this chain if it's not already syncing if !chain.is_syncing() { debug!(self.log, "New head chain started syncing"; &chain); } if let Err(remove_reason) = chain.start_syncing(network, local_epoch, local_head_epoch) { self.head_chains.remove(&id); if remove_reason.is_critical() { crit!(self.log, "Chain removed while switching head chains"; "chain" => id, "reason" => ?remove_reason); } else { error!(self.log, "Chain removed while switching head chains"; "chain" => id, "reason" => ?remove_reason); } } else { syncing_chains.push(id); } } else { // stop any other chain chain.stop_syncing(); } } self.state = if syncing_chains.is_empty() { RangeSyncState::Idle } else { RangeSyncState::Head(syncing_chains) }; } /// Returns if `true` if any finalized chains exist, `false` otherwise. pub fn is_finalizing_sync(&self) -> bool { !self.finalized_chains.is_empty() } /// Removes any outdated finalized or head chains. /// This removes chains with no peers, or chains whose start block slot is less than our current /// finalized block slot. Peers that would create outdated chains are removed too. pub fn purge_outdated_chains( &mut self, local_info: &SyncInfo, awaiting_head_peers: &mut HashMap<PeerId, SyncInfo>, ) { let local_finalized_slot = local_info .finalized_epoch .start_slot(T::EthSpec::slots_per_epoch()); let beacon_chain = &self.beacon_chain; let log_ref = &self.log; let is_outdated = |target_slot: &Slot, target_root: &Hash256| { target_slot <= &local_finalized_slot || beacon_chain.fork_choice.read().contains_block(target_root) }; // Retain only head peers that remain relevant awaiting_head_peers.retain(|_peer_id, peer_sync_info| { !is_outdated(&peer_sync_info.head_slot, &peer_sync_info.head_root) }); // Remove chains that are out-dated let mut removed_chains = Vec::new(); self.finalized_chains.retain(|id, chain| { if is_outdated(&chain.target_head_slot, &chain.target_head_root) || chain.available_peers() == 0 { debug!(log_ref, "Purging out of finalized chain"; &chain); removed_chains.push((*id, chain.is_syncing(), RangeSyncType::Finalized)); false } else { true } }); self.head_chains.retain(|id, chain| { if is_outdated(&chain.target_head_slot, &chain.target_head_root) || chain.available_peers() == 0 { debug!(log_ref, "Purging out of date head chain"; &chain); removed_chains.push((*id, chain.is_syncing(), RangeSyncType::Head)); false } else { true } }); // update the state of the collection for (id, was_syncing, sync_type) in removed_chains { self.on_chain_removed(&id, was_syncing, sync_type); } } /// Adds a peer to a chain with the given target, or creates a new syncing chain if it doesn't /// exists. #[allow(clippy::too_many_arguments)] pub fn add_peer_or_create_chain( &mut self, start_epoch: Epoch, target_head_root: Hash256, target_head_slot: Slot, peer: PeerId, sync_type: RangeSyncType, beacon_processor_send: &mpsc::Sender<BeaconWorkEvent<T::EthSpec>>, network: &mut SyncNetworkContext<T::EthSpec>, ) { let id = SyncingChain::<T>::id(&target_head_root, &target_head_slot); let collection = if let RangeSyncType::Finalized = sync_type { &mut self.finalized_chains } else { &mut self.head_chains }; match collection.entry(id) { Entry::Occupied(mut entry) => { let chain = entry.get_mut(); debug!(self.log, "Adding peer to known chain"; "peer_id" => %peer, "sync_type" => ?sync_type, &chain); debug_assert_eq!(chain.target_head_root, target_head_root); debug_assert_eq!(chain.target_head_slot, target_head_slot); if let Err(remove_reason) = chain.add_peer(network, peer) { if remove_reason.is_critical() { error!(self.log, "Chain removed after adding peer"; "chain" => id, "reason" => ?remove_reason); } else { error!(self.log, "Chain removed after adding peer"; "chain" => id, "reason" => ?remove_reason); } let chain = entry.remove(); self.on_chain_removed(&id, chain.is_syncing(), sync_type); } } Entry::Vacant(entry) => { let peer_rpr = peer.to_string(); let new_chain = SyncingChain::new( start_epoch, target_head_slot, target_head_root, peer, beacon_processor_send.clone(), &self.log, ); debug_assert_eq!(new_chain.get_id(), id); debug!(self.log, "New chain added to sync"; "peer_id" => peer_rpr, "sync_type" => ?sync_type, &new_chain); entry.insert(new_chain); let _ = metrics::get_int_gauge(&metrics::SYNCING_CHAINS_COUNT, &[sync_type.as_str()]) .map(|m| m.inc()); } } } }
41.409002
129
0.550473
870d07b63c2757fe59461c3fdfeb938b0cdc3df5
3,233
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common_base::tokio; use common_exception::ErrorCode; use common_grpc::RpcClientTlsConfig; use common_meta_api::MetaApi; use common_meta_grpc::MetaGrpcClient; use pretty_assertions::assert_eq; use crate::init_meta_ut; use crate::tests::service::MetaSrvTestContext; use crate::tests::start_metasrv_with_context; use crate::tests::tls_constants::TEST_CA_CERT; use crate::tests::tls_constants::TEST_CN_NAME; use crate::tests::tls_constants::TEST_SERVER_CERT; use crate::tests::tls_constants::TEST_SERVER_KEY; #[tokio::test(flavor = "multi_thread", worker_threads = 3)] async fn test_tls_server() -> anyhow::Result<()> { let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let mut tc = MetaSrvTestContext::new(0); tc.config.grpc_tls_server_key = TEST_SERVER_KEY.to_owned(); tc.config.grpc_tls_server_cert = TEST_SERVER_CERT.to_owned(); let r = start_metasrv_with_context(&mut tc).await; assert!(r.is_ok()); let addr = tc.config.grpc_api_address.clone(); let tls_conf = RpcClientTlsConfig { rpc_tls_server_root_ca_cert: TEST_CA_CERT.to_string(), domain_name: TEST_CN_NAME.to_string(), }; let client = MetaGrpcClient::try_create(addr.as_str(), "root", "xxx", None, Some(tls_conf)).await?; let r = client .get_table(("do not care", "do not care", "do not care").into()) .await; assert!(r.is_err()); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 3)] async fn test_tls_server_config_failure() -> anyhow::Result<()> { let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let mut tc = MetaSrvTestContext::new(0); tc.config.grpc_tls_server_key = "../tests/data/certs/not_exist.key".to_owned(); tc.config.grpc_tls_server_cert = "../tests/data/certs/not_exist.pem".to_owned(); let r = start_metasrv_with_context(&mut tc).await; assert!(r.is_err()); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 3)] async fn test_tls_client_config_failure() -> anyhow::Result<()> { let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let tls_conf = RpcClientTlsConfig { rpc_tls_server_root_ca_cert: "../tests/data/certs/not_exist.pem".to_string(), domain_name: TEST_CN_NAME.to_string(), }; let r = MetaGrpcClient::try_create("addr", "root", "xxx", None, Some(tls_conf)) .await .unwrap(); let c = r.make_client().await; assert!(c.is_err()); if let Err(e) = c { assert_eq!(e.code(), ErrorCode::TLSConfigurationFailure("").code()); } Ok(()) }
33.329897
94
0.692855
38a225a082e70ee8fd1c4f5a48d18f8390f837e4
19,602
// WARNING: This file was autogenerated by jni-bindgen. Any changes to this file may be lost!!! #[cfg(any(feature = "all", feature = "java-util-jar-JarFile"))] __jni_bindgen! { /// public class [JarFile](https://developer.android.com/reference/java/util/jar/JarFile.html) /// /// Required feature: java-util-jar-JarFile public class JarFile ("java/util/jar/JarFile") extends crate::java::util::zip::ZipFile { /// [JarFile](https://developer.android.com/reference/java/util/jar/JarFile.html#JarFile(java.lang.String)) /// /// Required features: "java-lang-String" #[cfg(any(feature = "all", all(feature = "java-lang-String")))] pub fn new_String<'env>(__jni_env: &'env __jni_bindgen::Env, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::lang::String>>) -> __jni_bindgen::std::result::Result<__jni_bindgen::Local<'env, crate::java::util::jar::JarFile>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "<init>", .descriptor == "(Ljava/lang/String;)V" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0.into())]; let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "<init>\0", "(Ljava/lang/String;)V\0"); __jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } /// [JarFile](https://developer.android.com/reference/java/util/jar/JarFile.html#JarFile(java.lang.String,%20boolean)) /// /// Required features: "java-lang-String" #[cfg(any(feature = "all", all(feature = "java-lang-String")))] pub fn new_String_boolean<'env>(__jni_env: &'env __jni_bindgen::Env, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::lang::String>>, arg1: bool) -> __jni_bindgen::std::result::Result<__jni_bindgen::Local<'env, crate::java::util::jar::JarFile>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "<init>", .descriptor == "(Ljava/lang/String;Z)V" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0.into()), __jni_bindgen::AsJValue::as_jvalue(&arg1)]; let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "<init>\0", "(Ljava/lang/String;Z)V\0"); __jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } /// [JarFile](https://developer.android.com/reference/java/util/jar/JarFile.html#JarFile(java.io.File)) /// /// Required features: "java-io-File" #[cfg(any(feature = "all", all(feature = "java-io-File")))] pub fn new_File<'env>(__jni_env: &'env __jni_bindgen::Env, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::io::File>>) -> __jni_bindgen::std::result::Result<__jni_bindgen::Local<'env, crate::java::util::jar::JarFile>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "<init>", .descriptor == "(Ljava/io/File;)V" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0.into())]; let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "<init>\0", "(Ljava/io/File;)V\0"); __jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } /// [JarFile](https://developer.android.com/reference/java/util/jar/JarFile.html#JarFile(java.io.File,%20boolean)) /// /// Required features: "java-io-File" #[cfg(any(feature = "all", all(feature = "java-io-File")))] pub fn new_File_boolean<'env>(__jni_env: &'env __jni_bindgen::Env, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::io::File>>, arg1: bool) -> __jni_bindgen::std::result::Result<__jni_bindgen::Local<'env, crate::java::util::jar::JarFile>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "<init>", .descriptor == "(Ljava/io/File;Z)V" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0.into()), __jni_bindgen::AsJValue::as_jvalue(&arg1)]; let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "<init>\0", "(Ljava/io/File;Z)V\0"); __jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } /// [JarFile](https://developer.android.com/reference/java/util/jar/JarFile.html#JarFile(java.io.File,%20boolean,%20int)) /// /// Required features: "java-io-File" #[cfg(any(feature = "all", all(feature = "java-io-File")))] pub fn new_File_boolean_int<'env>(__jni_env: &'env __jni_bindgen::Env, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::io::File>>, arg1: bool, arg2: i32) -> __jni_bindgen::std::result::Result<__jni_bindgen::Local<'env, crate::java::util::jar::JarFile>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "<init>", .descriptor == "(Ljava/io/File;ZI)V" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0.into()), __jni_bindgen::AsJValue::as_jvalue(&arg1), __jni_bindgen::AsJValue::as_jvalue(&arg2)]; let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "<init>\0", "(Ljava/io/File;ZI)V\0"); __jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } /// [getManifest](https://developer.android.com/reference/java/util/jar/JarFile.html#getManifest()) /// /// Required features: "java-util-jar-Manifest" #[cfg(any(feature = "all", all(feature = "java-util-jar-Manifest")))] pub fn getManifest<'env>(&'env self) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::util::jar::Manifest>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "getManifest", .descriptor == "()Ljava/util/jar/Manifest;" unsafe { let __jni_args = []; let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env); let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "getManifest\0", "()Ljava/util/jar/Manifest;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } } /// [getJarEntry](https://developer.android.com/reference/java/util/jar/JarFile.html#getJarEntry(java.lang.String)) /// /// Required features: "java-lang-String", "java-util-jar-JarEntry" #[cfg(any(feature = "all", all(feature = "java-lang-String", feature = "java-util-jar-JarEntry")))] pub fn getJarEntry<'env>(&'env self, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::lang::String>>) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::util::jar::JarEntry>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "getJarEntry", .descriptor == "(Ljava/lang/String;)Ljava/util/jar/JarEntry;" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0.into())]; let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env); let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "getJarEntry\0", "(Ljava/lang/String;)Ljava/util/jar/JarEntry;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } } /// [getEntry](https://developer.android.com/reference/java/util/jar/JarFile.html#getEntry(java.lang.String)) /// /// Required features: "java-lang-String", "java-util-zip-ZipEntry" #[cfg(any(feature = "all", all(feature = "java-lang-String", feature = "java-util-zip-ZipEntry")))] pub fn getEntry<'env>(&'env self, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::lang::String>>) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::util::zip::ZipEntry>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "getEntry", .descriptor == "(Ljava/lang/String;)Ljava/util/zip/ZipEntry;" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0.into())]; let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env); let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "getEntry\0", "(Ljava/lang/String;)Ljava/util/zip/ZipEntry;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } } /// [entries](https://developer.android.com/reference/java/util/jar/JarFile.html#entries()) /// /// Required features: "java-util-Enumeration" #[cfg(any(feature = "all", all(feature = "java-util-Enumeration")))] pub fn entries<'env>(&'env self) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::util::Enumeration>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "entries", .descriptor == "()Ljava/util/Enumeration;" unsafe { let __jni_args = []; let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env); let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "entries\0", "()Ljava/util/Enumeration;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } } /// [stream](https://developer.android.com/reference/java/util/jar/JarFile.html#stream()) /// /// Required features: "java-util-stream-Stream" #[cfg(any(feature = "all", all(feature = "java-util-stream-Stream")))] pub fn stream<'env>(&'env self) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::util::stream::Stream>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC, .name == "stream", .descriptor == "()Ljava/util/stream/Stream;" unsafe { let __jni_args = []; let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env); let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "stream\0", "()Ljava/util/stream/Stream;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } } /// [getInputStream](https://developer.android.com/reference/java/util/jar/JarFile.html#getInputStream(java.util.zip.ZipEntry)) /// /// Required features: "java-io-InputStream", "java-util-zip-ZipEntry" #[cfg(any(feature = "all", all(feature = "java-io-InputStream", feature = "java-util-zip-ZipEntry")))] pub fn getInputStream<'env>(&'env self, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::util::zip::ZipEntry>>) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::io::InputStream>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "java/util/jar/JarFile", java.flags == PUBLIC | SYNCRONIZED, .name == "getInputStream", .descriptor == "(Ljava/util/zip/ZipEntry;)Ljava/io/InputStream;" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0.into())]; let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env); let (__jni_class, __jni_method) = __jni_env.require_class_method("java/util/jar/JarFile\0", "getInputStream\0", "(Ljava/util/zip/ZipEntry;)Ljava/io/InputStream;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } } /// public static final [CENATT](https://developer.android.com/reference/java/util/jar/JarFile.html#CENATT) pub const CENATT : i32 = 36; /// public static final [CENATX](https://developer.android.com/reference/java/util/jar/JarFile.html#CENATX) pub const CENATX : i32 = 38; /// public static final [CENCOM](https://developer.android.com/reference/java/util/jar/JarFile.html#CENCOM) pub const CENCOM : i32 = 32; /// public static final [CENCRC](https://developer.android.com/reference/java/util/jar/JarFile.html#CENCRC) pub const CENCRC : i32 = 16; /// public static final [CENDSK](https://developer.android.com/reference/java/util/jar/JarFile.html#CENDSK) pub const CENDSK : i32 = 34; /// public static final [CENEXT](https://developer.android.com/reference/java/util/jar/JarFile.html#CENEXT) pub const CENEXT : i32 = 30; /// public static final [CENFLG](https://developer.android.com/reference/java/util/jar/JarFile.html#CENFLG) pub const CENFLG : i32 = 8; /// public static final [CENHDR](https://developer.android.com/reference/java/util/jar/JarFile.html#CENHDR) pub const CENHDR : i32 = 46; /// public static final [CENHOW](https://developer.android.com/reference/java/util/jar/JarFile.html#CENHOW) pub const CENHOW : i32 = 10; /// public static final [CENLEN](https://developer.android.com/reference/java/util/jar/JarFile.html#CENLEN) pub const CENLEN : i32 = 24; /// public static final [CENNAM](https://developer.android.com/reference/java/util/jar/JarFile.html#CENNAM) pub const CENNAM : i32 = 28; /// public static final [CENOFF](https://developer.android.com/reference/java/util/jar/JarFile.html#CENOFF) pub const CENOFF : i32 = 42; /// public static final [CENSIG](https://developer.android.com/reference/java/util/jar/JarFile.html#CENSIG) pub const CENSIG : i64 = 33639248i64; /// public static final [CENSIZ](https://developer.android.com/reference/java/util/jar/JarFile.html#CENSIZ) pub const CENSIZ : i32 = 20; /// public static final [CENTIM](https://developer.android.com/reference/java/util/jar/JarFile.html#CENTIM) pub const CENTIM : i32 = 12; /// public static final [CENVEM](https://developer.android.com/reference/java/util/jar/JarFile.html#CENVEM) pub const CENVEM : i32 = 4; /// public static final [CENVER](https://developer.android.com/reference/java/util/jar/JarFile.html#CENVER) pub const CENVER : i32 = 6; /// public static final [ENDCOM](https://developer.android.com/reference/java/util/jar/JarFile.html#ENDCOM) pub const ENDCOM : i32 = 20; /// public static final [ENDHDR](https://developer.android.com/reference/java/util/jar/JarFile.html#ENDHDR) pub const ENDHDR : i32 = 22; /// public static final [ENDOFF](https://developer.android.com/reference/java/util/jar/JarFile.html#ENDOFF) pub const ENDOFF : i32 = 16; /// public static final [ENDSIG](https://developer.android.com/reference/java/util/jar/JarFile.html#ENDSIG) pub const ENDSIG : i64 = 101010256i64; /// public static final [ENDSIZ](https://developer.android.com/reference/java/util/jar/JarFile.html#ENDSIZ) pub const ENDSIZ : i32 = 12; /// public static final [ENDSUB](https://developer.android.com/reference/java/util/jar/JarFile.html#ENDSUB) pub const ENDSUB : i32 = 8; /// public static final [ENDTOT](https://developer.android.com/reference/java/util/jar/JarFile.html#ENDTOT) pub const ENDTOT : i32 = 10; /// public static final [EXTCRC](https://developer.android.com/reference/java/util/jar/JarFile.html#EXTCRC) pub const EXTCRC : i32 = 4; /// public static final [EXTHDR](https://developer.android.com/reference/java/util/jar/JarFile.html#EXTHDR) pub const EXTHDR : i32 = 16; /// public static final [EXTLEN](https://developer.android.com/reference/java/util/jar/JarFile.html#EXTLEN) pub const EXTLEN : i32 = 12; /// public static final [EXTSIG](https://developer.android.com/reference/java/util/jar/JarFile.html#EXTSIG) pub const EXTSIG : i64 = 134695760i64; /// public static final [EXTSIZ](https://developer.android.com/reference/java/util/jar/JarFile.html#EXTSIZ) pub const EXTSIZ : i32 = 8; /// public static final [LOCCRC](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCCRC) pub const LOCCRC : i32 = 14; /// public static final [LOCEXT](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCEXT) pub const LOCEXT : i32 = 28; /// public static final [LOCFLG](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCFLG) pub const LOCFLG : i32 = 6; /// public static final [LOCHDR](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCHDR) pub const LOCHDR : i32 = 30; /// public static final [LOCHOW](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCHOW) pub const LOCHOW : i32 = 8; /// public static final [LOCLEN](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCLEN) pub const LOCLEN : i32 = 22; /// public static final [LOCNAM](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCNAM) pub const LOCNAM : i32 = 26; /// public static final [LOCSIG](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCSIG) pub const LOCSIG : i64 = 67324752i64; /// public static final [LOCSIZ](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCSIZ) pub const LOCSIZ : i32 = 18; /// public static final [LOCTIM](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCTIM) pub const LOCTIM : i32 = 10; /// public static final [LOCVER](https://developer.android.com/reference/java/util/jar/JarFile.html#LOCVER) pub const LOCVER : i32 = 4; /// public static final [MANIFEST_NAME](https://developer.android.com/reference/java/util/jar/JarFile.html#MANIFEST_NAME) pub const MANIFEST_NAME : &'static str = "META-INF/MANIFEST.MF"; } }
69.021127
371
0.647791
1eaf353eef500307f3609d73eef8643f77845734
60
pub mod error; pub mod item_service; pub mod stock_service;
15
22
0.8
f9eee8023b05a19774cdee252535afc39f59123e
3,480
use async_tungstenite::tungstenite::handshake::server::{ErrorResponse, Request, Response}; use async_tungstenite::tungstenite::Message; use crossbeam_utils::atomic::AtomicCell; use futures::sink::SinkExt; use futures::StreamExt; use smol::net::{SocketAddr, TcpListener, TcpStream}; use crate::protocol::h264::Nalu; use crate::rtmp_server::{eventbus_map, video_header_map, meta_data_map}; use crate::protocol::fmp4::{Fmp4Encoder, Track}; #[allow(unused)] pub async fn run_server(addr: String) -> anyhow::Result<()> { // Create the event loop and TCP listener we'll accept connections on. let try_socket = TcpListener::bind(&addr).await; let listener = try_socket.expect("Failed to bind"); log::info!("Websocket Listening on: {}", addr); // Let's spawn the handling of each connection in a separate task. while let Ok((stream, addr)) = listener.accept().await { smol::spawn(handle_connection(stream, addr)).detach(); } Ok(()) } async fn handle_connection(raw_stream: TcpStream, addr: SocketAddr) -> anyhow::Result<()> { log::info!("Incoming TCP connection from: {}", addr); let uri = AtomicCell::default(); let callback = |req: &Request, res: Response| -> Result<Response, ErrorResponse>{ uri.store(req.uri().clone()); Ok(res) }; let ws_stream = async_tungstenite::accept_hdr_async(raw_stream, callback).await?; let (mut outgoing, _incoming) = ws_stream.split(); let uri = uri.take(); let stream_name = uri.path().strip_prefix("/websocket/") .ok_or(anyhow::anyhow!("invalid uri path"))?; log::info!("WebSocket connection established: {}, stream_name={}", addr, stream_name); let meta_data = meta_data_map() .get(stream_name) .map(|it| it.value().clone()) .ok_or_else(|| anyhow::anyhow!(format!("not found meta_data, stream={}", stream_name)))?; let video_header = video_header_map() .get(stream_name) .map(|it| it.value().clone()) .ok_or_else(|| anyhow::anyhow!(format!("not found meta_data, stream={}", stream_name)))?; let mut sps_list = vec![]; let mut pps_list = vec![]; let pioneer_nalus = Nalu::from_rtmp_message(&video_header); for nalu in pioneer_nalus { match nalu.get_nal_unit_type() { Nalu::UNIT_TYPE_SPS => sps_list.push(nalu.as_ref().to_vec()), Nalu::UNIT_TYPE_PPS => pps_list.push(nalu.as_ref().to_vec()), _ => {} } } let rx = eventbus_map() .get(stream_name) .map(|it| it.register_receiver()) .ok_or_else(|| anyhow::anyhow!(format!("not found eventbus, stream={}", stream_name)))?; let mut fmp4_encoder = Fmp4Encoder::new(Track { duration: meta_data.duration as u32, timescale: (meta_data.duration * meta_data.frame_rate) as u32, width: meta_data.width as _, height: meta_data.height as _, sps_list, pps_list, ..Default::default() }); // send video header let header = fmp4_encoder.init_segment(); outgoing.send(Message::binary(header)).await?; while let Ok(msg) = rx.recv().await { let nalus = Nalu::from_rtmp_message(&msg); for nalu in nalus { let bytes = fmp4_encoder.wrap_frame(nalu.as_ref(), nalu.is_key_frame); outgoing.send(Message::binary(bytes)).await?; } } log::info!("WebSocket disconnected: {}, stream_name={}", addr, stream_name); Ok(()) }
35.876289
97
0.641954
713108f649ab89ea349e536925db902272951c54
12,435
//! # APIs bridging OSTree and container images //! //! This module contains APIs to bidirectionally map between a single OSTree commit and a container image wrapping it. //! Because container images are just layers of tarballs, this builds on the [`crate::tar`] module. //! //! To emphasize this, the current high level model is that this is a one-to-one mapping - an ostree commit //! can be exported (wrapped) into a container image, which will have exactly one layer. Upon import //! back into an ostree repository, all container metadata except for its digested checksum will be discarded. //! //! ## Signatures //! //! OSTree supports GPG and ed25519 signatures natively, and it's expected by default that //! when booting from a fetched container image, one verifies ostree-level signatures. //! For ostree, a signing configuration is specified via an ostree remote. In order to //! pair this configuration together, this library defines a "URL-like" string schema: //! //! `ostree-remote-registry:<remotename>:<containerimage>` //! //! A concrete instantiation might be e.g.: `ostree-remote-registry:fedora:quay.io/coreos/fedora-coreos:stable` //! //! To parse and generate these strings, see [`OstreeImageReference`]. //! //! ## Layering //! //! A key feature of container images is support for layering. At the moment, support //! for this is [planned but not implemented](https://github.com/ostreedev/ostree-rs-ext/issues/12). use anyhow::anyhow; use std::borrow::Cow; use std::convert::{TryFrom, TryInto}; use std::ops::Deref; /// The label injected into a container image that contains the ostree commit SHA-256. pub const OSTREE_COMMIT_LABEL: &str = "ostree.commit"; /// Our generic catchall fatal error, expected to be converted /// to a string to output to a terminal or logs. type Result<T> = anyhow::Result<T>; /// A backend/transport for OCI/Docker images. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Transport { /// A remote Docker/OCI registry (`registry:` or `docker://`) Registry, /// A local OCI directory (`oci:`) OciDir, /// A local OCI archive tarball (`oci-archive:`) OciArchive, /// Local container storage (`containers-storage:`) ContainerStorage, } /// Combination of a remote image reference and transport. /// /// For example, #[derive(Debug, Clone, PartialEq, Eq)] pub struct ImageReference { /// The storage and transport for the image pub transport: Transport, /// The image name (e.g. `quay.io/somerepo/someimage:latest`) pub name: String, } /// Policy for signature verification. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SignatureSource { /// Fetches will use the named ostree remote for signature verification of the ostree commit. OstreeRemote(String), /// Fetches will defer to the `containers-policy.json`, but we make a best effort to reject `default: insecureAcceptAnything` policy. ContainerPolicy, /// NOT RECOMMENDED. Fetches will defer to the `containers-policy.json` default which is usually `insecureAcceptAnything`. ContainerPolicyAllowInsecure, } /// Combination of a signature verification mechanism, and a standard container image reference. /// #[derive(Debug, Clone, PartialEq, Eq)] pub struct OstreeImageReference { /// The signature verification mechanism. pub sigverify: SignatureSource, /// The container image reference. pub imgref: ImageReference, } impl TryFrom<&str> for Transport { type Error = anyhow::Error; fn try_from(value: &str) -> Result<Self> { Ok(match value { "registry" | "docker" => Self::Registry, "oci" => Self::OciDir, "oci-archive" => Self::OciArchive, "containers-storage" => Self::ContainerStorage, o => return Err(anyhow!("Unknown transport '{}'", o)), }) } } impl TryFrom<&str> for ImageReference { type Error = anyhow::Error; fn try_from(value: &str) -> Result<Self> { let (transport_name, mut name) = value .split_once(':') .ok_or_else(|| anyhow!("Missing ':' in {}", value))?; let transport: Transport = transport_name.try_into()?; if name.is_empty() { return Err(anyhow!("Invalid empty name in {}", value)); } if transport_name == "docker" { name = name .strip_prefix("//") .ok_or_else(|| anyhow!("Missing // in docker:// in {}", value))?; } Ok(Self { transport, name: name.to_string(), }) } } impl TryFrom<&str> for SignatureSource { type Error = anyhow::Error; fn try_from(value: &str) -> Result<Self> { match value { "ostree-image-signed" => Ok(Self::ContainerPolicy), "ostree-unverified-image" => Ok(Self::ContainerPolicyAllowInsecure), o => match o.strip_prefix("ostree-remote-image:") { Some(rest) => Ok(Self::OstreeRemote(rest.to_string())), _ => Err(anyhow!("Invalid signature source: {}", o)), }, } } } impl TryFrom<&str> for OstreeImageReference { type Error = anyhow::Error; fn try_from(value: &str) -> Result<Self> { let (first, second) = value .split_once(':') .ok_or_else(|| anyhow!("Missing ':' in {}", value))?; let (sigverify, rest) = match first { "ostree-image-signed" => (SignatureSource::ContainerPolicy, Cow::Borrowed(second)), "ostree-unverified-image" => ( SignatureSource::ContainerPolicyAllowInsecure, Cow::Borrowed(second), ), // Shorthand for ostree-unverified-image:registry: "ostree-unverified-registry" => ( SignatureSource::ContainerPolicyAllowInsecure, Cow::Owned(format!("registry:{}", second)), ), // This is a shorthand for ostree-remote-image with registry: "ostree-remote-registry" => { let (remote, rest) = second .split_once(':') .ok_or_else(|| anyhow!("Missing second ':' in {}", value))?; ( SignatureSource::OstreeRemote(remote.to_string()), Cow::Owned(format!("registry:{}", rest)), ) } "ostree-remote-image" => { let (remote, rest) = second .split_once(':') .ok_or_else(|| anyhow!("Missing second ':' in {}", value))?; ( SignatureSource::OstreeRemote(remote.to_string()), Cow::Borrowed(rest), ) } o => { return Err(anyhow!("Invalid ostree image reference scheme: {}", o)); } }; let imgref = rest.deref().try_into()?; Ok(Self { sigverify, imgref }) } } impl std::fmt::Display for Transport { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = match self { // TODO once skopeo supports this, canonicalize as registry: Self::Registry => "docker://", Self::OciArchive => "oci-archive:", Self::OciDir => "oci:", Self::ContainerStorage => "containers-storage:", }; f.write_str(s) } } impl std::fmt::Display for ImageReference { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.transport, self.name) } } impl std::fmt::Display for OstreeImageReference { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.sigverify { SignatureSource::OstreeRemote(r) => { write!(f, "ostree-remote-image:{}:{}", r, self.imgref) } SignatureSource::ContainerPolicy => write!(f, "ostree-image-signed:{}", self.imgref), SignatureSource::ContainerPolicyAllowInsecure => { write!(f, "ostree-unverified-image:{}", self.imgref) } } } } /// Apply default configuration for container image pulls to an existing configuration. /// For example, if `authfile` is not set, and `auth_anonymous` is `false`, and a global configuration file exists, it will be used. pub fn merge_default_container_proxy_opts( config: &mut containers_image_proxy::ImageProxyConfig, ) -> Result<()> { if !config.auth_anonymous && config.authfile.is_none() { config.authfile = crate::globals::get_global_authfile_path()?; } Ok(()) } pub mod deploy; mod encapsulate; pub use encapsulate::*; mod unencapsulate; pub use unencapsulate::*; // We have this trick of compiling ourself with integration testing // enabled, which uses a lot of the code here. See the // `ostree-ext = { path = ".", features = ["internal-testing-api"] }` // bit in Cargo.toml. // // But that isn't turned on for other crates that use this, and correctly gating all // of it is a little tedious. So let's just use the big hammer for now to // quiet the dead code warnings. #[allow(dead_code)] pub(crate) mod ocidir; mod skopeo; pub mod store; #[cfg(test)] mod tests { use super::*; const INVALID_IRS: &[&str] = &["", "foo://", "docker:blah", "registry:", "foo:bar"]; const VALID_IRS: &[&str] = &[ "containers-storage:localhost/someimage", "docker://quay.io/exampleos/blah:sometag", ]; #[test] fn test_imagereference() { let ir: ImageReference = "registry:quay.io/exampleos/blah".try_into().unwrap(); assert_eq!(ir.transport, Transport::Registry); assert_eq!(ir.name, "quay.io/exampleos/blah"); assert_eq!(ir.to_string(), "docker://quay.io/exampleos/blah"); for &v in VALID_IRS { ImageReference::try_from(v).unwrap(); } for &v in INVALID_IRS { if ImageReference::try_from(v).is_ok() { panic!("Should fail to parse: {}", v) } } let ir: ImageReference = "oci:somedir".try_into().unwrap(); assert_eq!(ir.transport, Transport::OciDir); assert_eq!(ir.name, "somedir"); } #[test] fn test_ostreeimagereference() { // Test both long form `ostree-remote-image:$myremote:registry` and the // shorthand `ostree-remote-registry:$myremote`. let ir_s = "ostree-remote-image:myremote:registry:quay.io/exampleos/blah"; let ir_registry = "ostree-remote-registry:myremote:quay.io/exampleos/blah"; for &ir_s in &[ir_s, ir_registry] { let ir: OstreeImageReference = ir_s.try_into().unwrap(); assert_eq!( ir.sigverify, SignatureSource::OstreeRemote("myremote".to_string()) ); assert_eq!(ir.imgref.transport, Transport::Registry); assert_eq!(ir.imgref.name, "quay.io/exampleos/blah"); assert_eq!( ir.to_string(), "ostree-remote-image:myremote:docker://quay.io/exampleos/blah" ); } let ir: OstreeImageReference = ir_s.try_into().unwrap(); // test our Eq implementation assert_eq!(&ir, &OstreeImageReference::try_from(ir_registry).unwrap()); let ir_s = "ostree-image-signed:docker://quay.io/exampleos/blah"; let ir: OstreeImageReference = ir_s.try_into().unwrap(); assert_eq!(ir.sigverify, SignatureSource::ContainerPolicy); assert_eq!(ir.imgref.transport, Transport::Registry); assert_eq!(ir.imgref.name, "quay.io/exampleos/blah"); assert_eq!( ir.to_string(), "ostree-image-signed:docker://quay.io/exampleos/blah" ); let ir_s = "ostree-unverified-image:docker://quay.io/exampleos/blah"; let ir: OstreeImageReference = ir_s.try_into().unwrap(); assert_eq!(ir.sigverify, SignatureSource::ContainerPolicyAllowInsecure); assert_eq!(ir.imgref.transport, Transport::Registry); assert_eq!(ir.imgref.name, "quay.io/exampleos/blah"); assert_eq!( ir.to_string(), "ostree-unverified-image:docker://quay.io/exampleos/blah" ); let ir_shorthand = OstreeImageReference::try_from("ostree-unverified-registry:quay.io/exampleos/blah") .unwrap(); assert_eq!(&ir_shorthand, &ir); } }
38.261538
137
0.609891
18ac1d2ea183446e9ed8cac68ad4aad1fe016023
855
// traits1.rs // Time to implement some traits! // // Your task is to implement the trait // `AppendBar' for the type `String'. // // The trait AppendBar has only one function, // which appends "Bar" to any object // implementing this trait. trait AppendBar { fn append_bar(self) -> Self; } impl AppendBar for String { //Add your code here fn append_bar(self) -> String { return self + "Bar"; } } fn main() { let s = String::from("Foo"); let s = s.append_bar(); println!("s: {}", s); } #[cfg(test)] mod tests { use super::*; #[test] fn is_FooBar() { assert_eq!(String::from("Foo").append_bar(), String::from("FooBar")); } #[test] fn is_BarBar() { assert_eq!( String::from("").append_bar().append_bar(), String::from("BarBar") ); } }
18.586957
77
0.560234
db17a12baf1bb86839e9cd51ae8ce13d23ab6b58
151
use axum_debug::debug_handler; use axum::response::IntoResponse; #[debug_handler] async fn handler() -> impl IntoResponse { "hi!" } fn main() {}
15.1
41
0.688742
9cddba949d29423f287e8c301871bcb5ac4c5b96
1,170
use anyhow::Result; use crate::{ common::{ error::{Error, Errors}, pos::Pos, types::Type, }, frontend::{ast::Module, pass::error::PassError}, }; pub fn apply(module: &Module) -> Result<()> { let mut pass = SemaCheck::new(); pass.apply(module); match pass.issues.0.len() { 0 => Ok(()), _ => Err(pass.issues.into()), } } #[derive(Debug)] struct SemaCheck { issues: Errors, } impl SemaCheck { fn new() -> Self { Self { issues: Errors::default(), } } fn apply(&mut self, module: &Module) { let mut main_exists = false; for function in &module.functions { if function.name != "main" { continue; } main_exists = true; if function.ret_typ != Type::Int { self.issue(function.pos.clone(), PassError::MainShouldReturnInt); } } if !main_exists { self.issue(Pos::default(), PassError::MainNotFound); } } fn issue(&mut self, pos: Pos, err: PassError) { self.issues.0.push(Error::new(pos, err)); } }
21.272727
81
0.505128
d77c3ed5641ee9111b36d960a841235bc054e49b
1,195
// Lang item required to make the normal `main` work in applications // // This is how the `start` lang item works: // When `rustc` compiles a binary crate, it creates a `main` function that looks // like this: // // ``` // #[export_name = "main"] // pub extern "C" fn rustc_main(argc: isize, argv: *const *const u8) -> isize { // start(main, argc, argv) // } // ``` // // Where `start` is this function and `main` is the binary crate's `main` // function. // // The final piece is that the entry point of our program, the reset handler, // has to call `rustc_main`. That's covered by the `reset_handler` function in // root of this crate. #[cfg(has_termination_lang)] #[lang = "start"] extern "C" fn start<T>(main: fn() -> T, _argc: isize, _argv: *const *const u8) -> isize where T: Termination, { main(); 0 } #[cfg(not(has_termination_lang))] #[lang = "start"] extern "C" fn start(main: fn(), _argc: isize, _argv: *const *const u8) -> isize { main(); 0 } #[lang = "termination"] #[cfg(has_termination_lang)] pub trait Termination { fn report(self) -> i32; } #[cfg(has_termination_lang)] impl Termination for () { fn report(self) -> i32 { 0 } }
23.431373
87
0.633473
dd82e626b6940cbde5cb3fd47cdcfc2daf5bd563
3,777
use regex::Regex; use std::collections::{HashMap, HashSet}; use std::env; use std::fs; const COLOR_RE_STR: &str = r"^#[0-9a-f]{6}$"; const DATA_RE_STR: &str = r"(\w+):(\S+)"; const HEIGHT_RE_STR: &str = r"^(\d+)(cm|in)$"; const PASSPORT_RE_STR: &str = r"^\d{9}$"; const SPLIT_RE_STR: &str = r"\n\n"; type Profiles<'a> = Vec<HashMap<&'a str, &'a str>>; /// From a traveler database String, create a vector of profiles (HashMaps) fn get_profiles<'a>(database: &'a String) -> Profiles<'a> { let split_re = Regex::new(SPLIT_RE_STR).unwrap(); let data_re = Regex::new(DATA_RE_STR).unwrap(); split_re.split(&database[..]).map(|profile_str| { let mut profile: HashMap<&str, &str> = HashMap::new(); for attr in data_re.captures_iter(profile_str) { profile.insert( attr.get(1).unwrap().as_str(), attr.get(2).unwrap().as_str(), ); } profile }).collect() } /// Count valid passports in the profile list fn part1(profiles: &Profiles) -> usize { let required_fields = vec!["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; profiles.iter().filter(|profile| required_fields.iter().all(|key| profile.contains_key(key)) ).count() } fn opt_parse(num_s: &&str) -> Option<usize> { num_s.parse().map_or(None, |num| Some(num)) } fn part2(profiles: &Profiles) -> usize { let height_re = Regex::new(HEIGHT_RE_STR).unwrap(); let color_re = Regex::new(COLOR_RE_STR).unwrap(); let passport_re = Regex::new(PASSPORT_RE_STR).unwrap(); let mut valid_eye_colors: HashSet<&str> = HashSet::new(); for color in vec![ "amb", "blu", "brn", "gry", "grn", "hzl", "oth", ].into_iter() { valid_eye_colors.insert(color); } profiles.iter().filter(|profile| { profile.get("byr") .and_then(opt_parse) .map_or(false, |val| val >= 1920 && val <= 2002) && profile.get("iyr") .and_then(opt_parse) .map_or(false, |val| val >= 2010 && val <= 2020) && profile.get("eyr") .and_then(opt_parse) .map_or(false, |val| val >= 2020 && val <= 2030) && profile.get("hgt") .and_then(|sval| height_re.captures(sval)) .and_then(|captures| captures.get(2).zip(captures.get(1))) .and_then(|(unit, num_s)| opt_parse(&num_s.as_str()) .map(|num| match unit.as_str() { "cm" => num >= 150 && num <= 193, "in" => num >= 59 && num <= 76, _ => panic!("Regex should have missed"), }) ).unwrap_or(false) && profile.get("hcl") .map_or(false, |hcl| color_re.is_match(hcl)) && profile.get("ecl") .map_or(false, |sval| valid_eye_colors.contains(sval)) && profile.get("pid") .map_or(false, |pid| passport_re.is_match(pid)) }).count() } fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let contents = fs::read_to_string(filename).expect("Error opening file"); let profiles = get_profiles(&contents); println!("Part 1: {}", part1(&profiles)); println!("Part 2: {}", part2(&profiles)); } #[cfg(test)] mod tests { use super::*; #[test] fn part1_example() { let database = include_str!("sample").to_string(); let profiles = get_profiles(&database); assert_eq!(part1(&profiles), 2); } #[test] fn part2_example() { let database = include_str!("sample2").to_string(); let profiles = get_profiles(&database); assert_eq!(part2(&profiles), 4); } }
30.959016
80
0.54726
d9ebea162f86e27756b89d50c2da3be8fe821445
977
#[doc = "Reader of register CSE"] pub type R = crate::R<u32, super::CSE>; #[doc = "Writer for register CSE"] pub type W = crate::W<u32, super::CSE>; #[doc = "Register CSE `reset()`'s with value 0"] impl crate::ResetValue for super::CSE { #[inline(always)] fn reset_value() -> Self::Ux { 0 } } #[doc = "Reader of field `CSE`"] pub type CSE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CSE`"] pub struct CSE_W<'a> { w: &'a mut W } impl<'a> CSE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } impl R { #[doc = "Bits 0:7 - Carrier Sense Errors"] #[inline(always)] pub fn cse(&self) -> CSE_R { CSE_R::new((self.bits & 0xff) as u8) } } impl W { #[doc = "Bits 0:7 - Carrier Sense Errors"] #[inline(always)] pub fn cse(&mut self) -> CSE_W { CSE_W { w: self } } }
26.405405
71
0.567042
4a958c0a9bc9b69bc39b2c995dea72035058c51a
224
! version = 2.0 + knock knock - Who's there? + * % who is there - <star> who? + * % * who - LOL! <star>! That's funny! + i have a dog - What color is it? + (@colors) % what color is it - That's a silly color for a dog!
11.2
33
0.575893
9bff4116c37d0532bb6ac1ad292786683ca82f2d
3,669
use nu_engine::CallExt; use nu_protocol::ast::Call; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{ Category, Example, PipelineData, ShellError, Signature, Spanned, SyntaxShape, Value, }; #[derive(Clone)] pub struct OverlayRemove; impl Command for OverlayRemove { fn name(&self) -> &str { "overlay remove" } fn usage(&self) -> &str { "Remove an active overlay" } fn signature(&self) -> nu_protocol::Signature { Signature::build("overlay remove") .optional("name", SyntaxShape::String, "Overlay to remove") .switch( "keep-custom", "Keep newly added symbols within the next activated overlay", Some('k'), ) .category(Category::Core) } fn extra_usage(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nushell.html"# } fn is_parser_keyword(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { let overlay_name: Spanned<String> = if let Some(name) = call.opt(engine_state, stack, 0)? { name } else { Spanned { item: stack.last_overlay_name()?, span: call.head, } }; if !stack.is_overlay_active(&overlay_name.item) { return Err(ShellError::OverlayNotFoundAtRuntime( overlay_name.item, overlay_name.span, )); } if call.has_flag("keep-custom") { if let Some(overlay_id) = engine_state.find_overlay(overlay_name.item.as_bytes()) { let overlay_frame = engine_state.get_overlay(overlay_id); let origin_module = engine_state.get_module(overlay_frame.origin); let env_vars_to_keep: Vec<(String, Value)> = stack .get_overlay_env_vars(engine_state, &overlay_name.item) .into_iter() .filter(|(name, _)| !origin_module.has_env_var(name.as_bytes())) .collect(); stack.remove_overlay(&overlay_name.item); for (name, val) in env_vars_to_keep { stack.add_env_var(name, val); } } else { return Err(ShellError::OverlayNotFoundAtRuntime( overlay_name.item, overlay_name.span, )); } } else { stack.remove_overlay(&overlay_name.item); } Ok(PipelineData::new(call.head)) } fn examples(&self) -> Vec<Example> { vec![ Example { description: "Remove an overlay created from a module", example: r#"module spam { export def foo [] { "foo" } } overlay add spam overlay remove spam"#, result: None, }, Example { description: "Remove an overlay created from a file", example: r#"echo 'export alias f = "foo"' | save spam.nu overlay add spam.nu overlay remove spam"#, result: None, }, Example { description: "Remove the last activated overlay", example: r#"module spam { export env FOO { "foo" } } overlay add spam overlay remove"#, result: None, }, ] } }
31.09322
99
0.53148
08d41a539b4a8c9a13e5b6c3189f178928bbd491
1,184
/// A lookup implementation returning the `AccountId` from a `MultiAddress`. pub struct AccountIdLookup<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>); impl<AccountId, AccountIndex> StaticLookup for AccountIdLookup<AccountId, AccountIndex> where AccountId: Codec + Clone + PartialEq + Debug, AccountIndex: Codec + Clone + PartialEq + Debug, crate::MultiAddress<AccountId, AccountIndex>: Codec, { type Source = crate::MultiAddress<AccountId, AccountIndex>; type Target = AccountId; fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> { match x { crate::MultiAddress::Id(i) => Ok(i), _ => Err(LookupError), } } fn unlookup(x: Self::Target) -> Self::Source { crate::MultiAddress::Id(x) } } /// Perform a StaticLookup where there are multiple lookup sources of the same type. impl<A, B> StaticLookup for (A, B) where A: StaticLookup, B: StaticLookup<Source = A::Source, Target = A::Target>, { type Source = A::Source; type Target = A::Target; fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> { A::lookup(x.clone()).or_else(|_| B::lookup(x)) } fn unlookup(x: Self::Target) -> Self::Source { A::unlookup(x) } }
32
92
0.704392
7aa82532560a66851d3a9003cbcd2dc2e1985cc0
45,052
#![macro_use] mod trivial; pub use trivial::*; mod from_iter; pub use from_iter::{from_iter, repeat}; pub mod of; pub use of::{of, of_fn, of_option, of_result}; pub(crate) mod from_future; pub use from_future::{from_future, from_future_result}; pub mod interval; pub use interval::{interval, interval_at}; pub(crate) mod connectable_observable; pub use connectable_observable::{Connect, ConnectableObservable}; mod observable_block_all; #[cfg(test)] pub use observable_block_all::*; mod observable_block; #[cfg(test)] pub use observable_block::*; pub mod from_fn; pub use from_fn::*; pub mod timer; pub use timer::{timer, timer_at}; pub mod start; pub use start::start; mod observable_all; pub use observable_all::*; mod observable_err; pub use observable_err::*; mod observable_next; pub use observable_next::*; mod defer; mod observable_comp; pub use defer::*; use crate::prelude::*; pub use observable_comp::*; use crate::ops::default_if_empty::DefaultIfEmptyOp; use crate::ops::distinct::{DistinctKeyOp, DistinctUntilKeyChangedOp}; use crate::ops::pairwise::PairwiseOp; use crate::ops::tap::TapOp; use ops::{ box_it::{BoxOp, IntoBox}, buffer::{BufferWithCountOp, BufferWithCountOrTimerOp, BufferWithTimeOp}, combine_latest::CombineLatestOp, contains::ContainsOp, debounce::DebounceOp, delay::DelayOp, distinct::DistinctOp, distinct::DistinctUntilChangedOp, filter::FilterOp, filter_map::FilterMapOp, finalize::FinalizeOp, flatten::FlattenOp, group_by::GroupByOp, last::LastOp, map::MapOp, map_to::MapToOp, merge::MergeOp, merge_all::MergeAllOp, observe_on::ObserveOnOp, sample::SampleOp, scan::ScanOp, skip::SkipOp, skip_last::SkipLastOp, skip_until::SkipUntilOp, skip_while::SkipWhileOp, start_with::StartWithOp, subscribe_on::SubscribeOnOP, take::TakeOp, take_last::TakeLastOp, take_until::TakeUntilOp, take_while::TakeWhileOp, throttle_time::{ThrottleEdge, ThrottleTimeOp}, with_latest_from::WithLatestFromOp, zip::ZipOp, Accum, AverageOp, CountOp, FlatMapOp, MinMaxOp, ReduceOp, SumOp, }; use std::ops::{Add, Mul}; use std::time::{Duration, Instant}; type ALLOp<O, F> = DefaultIfEmptyOp<TakeOp<FilterOp<MapOp<O, F>, fn(&bool) -> bool>>>; pub trait Observable: Sized { type Item; type Err; /// emit only the first item emitted by an Observable #[inline] fn first(self) -> TakeOp<Self> { self.take(1) } /// emit only the first item emitted by an Observable #[inline] fn first_or(self, default: Self::Item) -> DefaultIfEmptyOp<TakeOp<Self>> { self.first().default_if_empty(default) } /// Emit only the last final item emitted by a source observable or a /// default item given. /// /// Completes right after emitting the single item. Emits error when /// source observable emits it. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::empty() /// .last_or(1234) /// .subscribe(|v| println!("{}", v)); /// /// // print log: /// // 1234 /// ``` #[inline] fn last_or( self, default: Self::Item, ) -> DefaultIfEmptyOp<LastOp<Self, Self::Item>> { self.last().default_if_empty(default) } /// Emit only item n (0-indexed) emitted by an Observable #[inline] fn element_at(self, nth: u32) -> TakeOp<SkipOp<Self>> { self.skip(nth).first() } /// Do not emit any items from an Observable but mirror its termination /// notification #[inline] fn ignore_elements(self) -> FilterOp<Self, fn(&Self::Item) -> bool> { fn always_false<Item>(_: &Item) -> bool { false } self.filter(always_false as fn(&Self::Item) -> bool) } /// Determine whether all items emitted by an Observable meet some criteria #[inline] fn all<F>(self, pred: F) -> ALLOp<Self, F> where F: Fn(Self::Item) -> bool, { fn not(b: &bool) -> bool { !b } self .map(pred) .filter(not as fn(&bool) -> bool) .first_or(true) } /// Determine whether an Observable emits a particular item or not fn contains(self, target: Self::Item) -> ContainsOp<Self, Self::Item> { ContainsOp { source: self, target, } } /// Emits only last final item emitted by a source observable. /// /// Completes right after emitting the single last item, or when source /// observable completed, being an empty one. Emits error when source /// observable emits it. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(0..100) /// .last() /// .subscribe(|v| println!("{}", v)); /// /// // print log: /// // 99 /// ``` #[inline] fn last(self) -> LastOp<Self, Self::Item> { LastOp { source: self, last: None, } } /// Call a function when observable completes, errors or is unsubscribed from. #[inline] fn finalize<F>(self, f: F) -> FinalizeOp<Self, F> where F: FnMut(), { FinalizeOp { source: self, func: f, } } /// Creates an Observable that combines all the emissions from Observables /// that get emitted from an Observable. /// /// # Example /// /// ``` /// # use rxrust::prelude::*; /// let mut source = LocalSubject::new(); /// let numbers = LocalSubject::new(); /// // create a even stream by filter /// let even = numbers.clone().filter((|v| *v % 2 == 0) as fn(&i32) -> bool); /// // create an odd stream by filter /// let odd = numbers.clone().filter((|v| *v % 2 != 0) as fn(&i32) -> bool); /// /// // merge odd and even stream again /// let out = source.clone().flatten(); /// /// source.next(even); /// source.next(odd); /// /// // attach observers /// out.subscribe(|v: i32| println!("{} ", v)); /// ``` #[inline] fn flatten<Inner, A>(self) -> FlattenOp<Self, Inner> where Inner: Observable<Item = A, Err = Self::Err>, { FlattenOp { source: self, marker: std::marker::PhantomData::<Inner>, } } /// Applies given function to each item emitted by this Observable, where /// that function returns an Observable that itself emits items. It then /// merges the emissions of these resulting Observables, emitting these /// merged results as its own sequence. #[inline] fn flat_map<Inner, B, F>(self, f: F) -> FlatMapOp<Self, Inner, F> where Inner: Observable<Item = B, Err = Self::Err>, F: Fn(Self::Item) -> Inner, { FlattenOp { source: MapOp { source: self, func: f, }, marker: std::marker::PhantomData::<Inner>, } } /// Groups items emitted by the source Observable into Observables. /// Each emitted Observable emits items matching the key returned /// by the discriminator function. /// /// # Example /// /// ``` /// use rxrust::prelude::*; /// /// #[derive(Clone)] /// struct Person { /// name: String, /// age: u32, /// } /// /// observable::from_iter([ /// Person{ name: String::from("John"), age: 26 }, /// Person{ name: String::from("Anne"), age: 28 }, /// Person{ name: String::from("Gregory"), age: 24 }, /// Person{ name: String::from("Alice"), age: 28 }, /// ]) /// .group_by(|person: &Person| person.age) /// .subscribe(|group| { /// group /// .reduce(|acc, person| format!("{} {}", acc, person.name)) /// .subscribe(|result| println!("{}", result)); /// }); /// /// // Prints: /// // John /// // Anne Alice /// // Gregory /// ``` #[inline] fn group_by<D, Item, Key>(self, discr: D) -> GroupByOp<Self, D> where D: FnMut(&Item) -> Key, { GroupByOp { source: self, discr, } } /// Creates a new stream which calls a closure on each element and uses /// its return as the value. #[inline] fn map<B, F>(self, f: F) -> MapOp<Self, F> where F: FnMut(Self::Item) -> B, { MapOp { source: self, func: f, } } /// Maps emissions to a constant value. #[inline] fn map_to<B>(self, value: B) -> MapToOp<Self, B> { MapToOp { source: self, value, } } /// combine two Observables into one by merging their emissions /// /// # Example /// /// ``` /// # use rxrust::prelude::*; /// let numbers = LocalSubject::new(); /// // create a even stream by filter /// let even = numbers.clone().filter(|v| *v % 2 == 0); /// // create an odd stream by filter /// let odd = numbers.clone().filter(|v| *v % 2 != 0); /// /// // merge odd and even stream again /// let merged = even.merge(odd); /// /// // attach observers /// merged.subscribe(|v: &i32| println!("{} ", v)); /// ``` #[inline] fn merge<S>(self, o: S) -> MergeOp<Self, S> where S: Observable<Item = Self::Item, Err = Self::Err>, { MergeOp { source1: self, source2: o, } } /// Converts a higher-order Observable into a first-order Observable which /// concurrently delivers all values that are emitted on the inner /// Observables. /// /// # Example /// /// ``` /// # use rxrust::prelude::*; /// # use futures::executor::LocalPool; /// # use std::time::Duration; /// let mut local = LocalPool::new(); /// observable::from_iter( /// (0..3) /// .map(|_| interval(Duration::from_millis(1), local.spawner()).take(5)), /// ) /// .merge_all(2) /// .subscribe(move |i| println!("{}", i)); /// local.run(); /// ``` #[inline] fn merge_all(self, concurrent: usize) -> MergeAllOp<Self> { MergeAllOp { source: self, concurrent, } } /// Emit only those items from an Observable that pass a predicate test /// # Example /// /// ``` /// use rxrust:: prelude::*; /// /// let mut coll = vec![]; /// let coll_clone = coll.clone(); /// /// observable::from_iter(0..10) /// .filter(|v| *v % 2 == 0) /// .subscribe(|v| { coll.push(v); }); /// /// // only even numbers received. /// assert_eq!(coll, vec![0, 2, 4, 6, 8]); /// ``` #[inline] fn filter<F>(self, filter: F) -> FilterOp<Self, F> where F: Fn(&Self::Item) -> bool, { FilterOp { source: self, filter, } } /// The closure must return an Option<T>. filter_map creates an iterator which /// calls this closure on each element. If the closure returns Some(element), /// then that element is returned. If the closure returns None, it will try /// again, and call the closure on the next element, seeing if it will return /// Some. /// /// Why filter_map and not just filter and map? The key is in this part: /// /// If the closure returns Some(element), then that element is returned. /// /// In other words, it removes the Option<T> layer automatically. If your /// mapping is already returning an Option<T> and you want to skip over Nones, /// then filter_map is much, much nicer to use. /// /// # Examples /// /// ``` /// # use rxrust::prelude::*; /// let mut res: Vec<i32> = vec![]; /// observable::from_iter(["1", "lol", "3", "NaN", "5"].iter()) /// .filter_map(|s: &&str| s.parse().ok()) /// .subscribe(|v| res.push(v)); /// /// assert_eq!(res, [1, 3, 5]); /// ``` #[inline] fn filter_map<F, SourceItem, Item>(self, f: F) -> FilterMapOp<Self, F> where F: FnMut(SourceItem) -> Option<Item>, { FilterMapOp { source: self, f } } /// box an observable to a safety object and convert it to a simple type /// `BoxOp`, which only care `Item` and `Err` Observable emitted. /// /// # Example /// ``` /// use rxrust::prelude::*; /// use ops::box_it::LocalBoxOp; /// /// let mut boxed: LocalBoxOp<'_, i32, ()> = observable::of(1) /// .map(|v| v).box_it(); /// /// // BoxOp can box any observable type /// boxed = observable::empty().box_it(); /// /// boxed.subscribe(|_| {}); /// ``` #[inline] fn box_it<O: IntoBox<Self>>(self) -> BoxOp<O> where BoxOp<O>: Observable<Item = Self::Item, Err = Self::Err>, { O::box_it(self) } /// Ignore the first `count` values emitted by the source Observable. /// /// `skip` returns an Observable that ignore the first `count` values /// emitted by the source Observable. If the source emits fewer than `count` /// values then 0 of its values are emitted. After that, it completes, /// regardless if the source completes. /// /// # Example /// Ignore the first 5 seconds of an infinite 1-second interval Observable /// /// ``` /// # use rxrust::prelude::*; /// /// observable::from_iter(0..10).skip(5).subscribe(|v| println!("{}", v)); /// // print logs: /// // 6 /// // 7 /// // 8 /// // 9 /// // 10 /// ``` #[inline] fn skip(self, count: u32) -> SkipOp<Self> { SkipOp { source: self, count, } } /// Ignore the values emitted by the source Observable until the `predicate` /// returns true for the value. /// /// `skip_until` returns an Observable that skips values emitted by the source /// Observable until the result of the predicate is true for the value. The /// resulting Observable will include and emit the matching value. /// /// # Example /// Ignore the numbers in the 0-10 range until the Observer emits 5. /// /// ``` /// # use rxrust::prelude::*; /// /// let mut items = vec![]; /// observable::from_iter(0..10) /// .skip_until(|v| v == &5) /// .subscribe(|v| items.push(v)); /// /// assert_eq!((5..10).collect::<Vec<i32>>(), items); /// ``` #[inline] fn skip_until<F>(self, predicate: F) -> SkipUntilOp<Self, F> where F: FnMut(&Self::Item) -> bool, { SkipUntilOp { source: self, predicate, } } /// Ignore values while result of a callback is true. /// /// `skip_while` returns an Observable that ignores values while result of an /// callback is true emitted by the source Observable. /// /// # Example /// Suppress the first 5 items of an infinite 1-second interval Observable /// /// ``` /// # use rxrust::prelude::*; /// /// observable::from_iter(0..10) /// .skip_while(|v| v < &5) /// .subscribe(|v| println!("{}", v)); /// /// // print logs: /// // 5 /// // 6 /// // 7 /// // 8 /// // 9 /// ``` #[inline] fn skip_while<F>(self, callback: F) -> SkipWhileOp<Self, F> where F: FnMut(&Self::Item) -> bool, { SkipWhileOp { source: self, callback, } } /// Ignore the last `count` values emitted by the source Observable. /// /// `skip_last` returns an Observable that ignore the last `count` values /// emitted by the source Observable. If the source emits fewer than `count` /// values then 0 of its values are emitted. /// It will not emit values until source Observable complete. /// /// # Example /// Skip the last 5 seconds of an infinite 1-second interval Observable /// /// ``` /// # use rxrust::prelude::*; /// /// observable::from_iter(0..10) /// .skip_last(5) /// .subscribe(|v| println!("{}", v)); /// /// // print logs: /// // 0 /// // 1 /// // 2 /// // 3 /// // 4 /// ``` #[inline] fn skip_last(self, count: usize) -> SkipLastOp<Self> { SkipLastOp { source: self, count, } } /// Emits only the first `count` values emitted by the source Observable. /// /// `take` returns an Observable that emits only the first `count` values /// emitted by the source Observable. If the source emits fewer than `count` /// values then all of its values are emitted. After that, it completes, /// regardless if the source completes. /// /// # Example /// Take the first 5 seconds of an infinite 1-second interval Observable /// /// ``` /// # use rxrust::prelude::*; /// /// observable::from_iter(0..10).take(5).subscribe(|v| println!("{}", v)); /// // print logs: /// // 0 /// // 1 /// // 2 /// // 3 /// // 4 /// ``` /// #[inline] fn take(self, count: u32) -> TakeOp<Self> { TakeOp { source: self, count, } } /// Emits the values emitted by the source Observable until a `notifier` /// Observable emits a value. /// /// `take_until` subscribes and begins mirroring the source Observable. It /// also monitors a second Observable, `notifier` that you provide. If the /// `notifier` emits a value, the output Observable stops mirroring the source /// Observable and completes. If the `notifier` doesn't emit any value and /// completes then `take_until` will pass all values. #[inline] fn take_until<T>(self, notifier: T) -> TakeUntilOp<Self, T> { TakeUntilOp { source: self, notifier, } } /// Emits values while result of an callback is true. /// /// `take_while` returns an Observable that emits values while result of an /// callback is true emitted by the source Observable. /// It will not emit values until source Observable complete. /// /// # Example /// Take the first 5 seconds of an infinite 1-second interval Observable /// /// ``` /// # use rxrust::prelude::*; /// /// observable::from_iter(0..10) /// .take_while(|v| v < &5) /// .subscribe(|v| println!("{}", v)); /// // print logs: /// // 0 /// // 1 /// // 2 /// // 3 /// // 4 /// ``` /// #[inline] fn take_while<F>(self, callback: F) -> TakeWhileOp<Self, F> where F: FnMut(&Self::Item) -> bool, { TakeWhileOp { source: self, callback, inclusive: false, } } /// Emits values while result of an callback is true and the last one that /// causes the callback to return false. /// /// # Example /// Take the first 5 seconds of an infinite 1-second interval Observable /// /// ``` /// # use rxrust::prelude::*; /// /// observable::from_iter(0..10) /// .take_while_inclusive(|v| v < &4) /// .subscribe(|v| println!("{}", v)); /// // print logs: /// // 0 /// // 1 /// // 2 /// // 3 /// // 4 /// ``` /// #[inline] fn take_while_inclusive<F>(self, callback: F) -> TakeWhileOp<Self, F> where F: FnMut(&Self::Item) -> bool, { TakeWhileOp { source: self, callback, inclusive: true, } } /// Emits only the last `count` values emitted by the source Observable. /// /// `take_last` returns an Observable that emits only the last `count` values /// emitted by the source Observable. If the source emits fewer than `count` /// values then all of its values are emitted. /// It will not emit values until source Observable complete. /// /// # Example /// Take the last 5 seconds of an infinite 1-second interval Observable /// /// ``` /// # use rxrust::prelude::*; /// /// observable::from_iter(0..10) /// .take_last(5) /// .subscribe(|v| println!("{}", v)); /// // print logs: /// // 5 /// // 6 /// // 7 /// // 8 /// // 9 /// ``` /// #[inline] fn take_last(self, count: usize) -> TakeLastOp<Self> { TakeLastOp { source: self, count, } } /// Emits item it has most recently emitted since the previous sampling /// /// /// It will emit values when sampling observable complete. /// /// #Example /// Sampling every 5ms of an infinite 1ms interval Observable /// ``` /// use rxrust::prelude::*; /// use std::time::Duration; /// use futures::executor::LocalPool; /// /// let mut local_scheduler = LocalPool::new(); /// let spawner = local_scheduler.spawner(); /// observable::interval(Duration::from_millis(2), spawner.clone()) /// .sample(observable::interval(Duration::from_millis(5), spawner)) /// .take(5) /// .subscribe(move |v| println!("{}", v)); /// /// local_scheduler.run(); /// // print logs: /// // 1 /// // 4 /// // 6 /// // 9 /// // ... /// ``` #[inline] fn sample<O>(self, sampling: O) -> SampleOp<Self, O> where O: Observable, { SampleOp { source: self, sampling, } } /// The Scan operator applies a function to the first item emitted by the /// source observable and then emits the result of that function as its /// own first emission. It also feeds the result of the function back into /// the function along with the second item emitted by the source observable /// in order to generate its second emission. It continues to feed back its /// own subsequent emissions along with the subsequent emissions from the /// source Observable in order to create the rest of its sequence. /// /// Applies a binary operator closure to each item emitted from source /// observable and emits successive values. /// /// Completes when source observable completes. /// Emits error when source observable emits it. /// /// This version starts with an user-specified initial value for when the /// binary operator is called with the first item processed. /// /// # Arguments /// /// * `initial_value` - An initial value to start the successive accumulations /// from. /// * `binary_op` - A closure or function acting as a binary operator. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(vec![1, 1, 1, 1, 1]) /// .scan_initial(100, |acc, v| acc + v) /// .subscribe(|v| println!("{}", v)); /// /// // print log: /// // 101 /// // 102 /// // 103 /// // 104 /// // 105 /// ``` #[inline] fn scan_initial<OutputItem, BinaryOp>( self, initial_value: OutputItem, binary_op: BinaryOp, ) -> ScanOp<Self, BinaryOp, OutputItem> where BinaryOp: Fn(OutputItem, Self::Item) -> OutputItem, OutputItem: Clone, { ScanOp { source_observable: self, binary_op, initial_value, } } /// Works like [`scan_initial`](Observable::scan_initial) but starts with a /// value defined by a [`Default`] trait for the first argument `binary_op` /// operator operates on. /// /// # Arguments /// /// * `binary_op` - A closure or function acting as a binary operator. #[inline] fn scan<OutputItem, BinaryOp>( self, binary_op: BinaryOp, ) -> ScanOp<Self, BinaryOp, OutputItem> where BinaryOp: Fn(OutputItem, Self::Item) -> OutputItem, OutputItem: Default + Clone, { self.scan_initial(OutputItem::default(), binary_op) } /// Apply a function to each item emitted by an observable, sequentially, /// and emit the final value, after source observable completes. /// /// Emits error when source observable emits it. /// /// # Arguments /// /// * `initial` - An initial value to start the successive reduction from. /// * `binary_op` - A closure acting as a binary (folding) operator. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(vec![1, 1, 1, 1, 1]) /// .reduce_initial(100, |acc, v| acc + v) /// .subscribe(|v| println!("{}", v)); /// /// // print log: /// // 105 /// ``` #[inline] fn reduce_initial<OutputItem, BinaryOp>( self, initial: OutputItem, binary_op: BinaryOp, ) -> ReduceOp<Self, BinaryOp, OutputItem> where BinaryOp: Fn(OutputItem, Self::Item) -> OutputItem, OutputItem: Clone, { // realised as a composition of `scan`, and `last` self .scan_initial(initial.clone(), binary_op) .last_or(initial) } /// Works like [`reduce_initial`](Observable::reduce_initial) but starts with /// a value defined by a [`Default`] trait for the first argument `f` /// operator operates on. /// /// # Arguments /// /// * `binary_op` - A closure acting as a binary operator. #[inline] fn reduce<OutputItem, BinaryOp>( self, binary_op: BinaryOp, ) -> DefaultIfEmptyOp<LastOp<ScanOp<Self, BinaryOp, OutputItem>, OutputItem>> where BinaryOp: Fn(OutputItem, Self::Item) -> OutputItem, OutputItem: Default + Clone, { self.reduce_initial(OutputItem::default(), binary_op) } /// Emits the item from the source observable that had the maximum value. /// /// Emits error when source observable emits it. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(vec![3., 4., 7., 5., 6.]) /// .max() /// .subscribe(|v| println!("{}", v)); /// /// // print log: /// // 7 /// ``` #[inline] fn max(self) -> MinMaxOp<Self, Self::Item> where Self::Item: Clone + Send + PartialOrd<Self::Item>, { fn get_greater<Item>(i: Option<Item>, v: Item) -> Option<Item> where Item: Clone + PartialOrd<Item>, { i.map(|vv| if vv < v { v.clone() } else { vv }).or(Some(v)) } let get_greater_func = get_greater as fn(Option<Self::Item>, Self::Item) -> Option<Self::Item>; self .scan_initial(None, get_greater_func) .last() // we can safely unwrap, because we will ever get this item // once a max value exists and is there. .map(|v| v.unwrap()) } /// Emits the item from the source observable that had the minimum value. /// /// Emits error when source observable emits it. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(vec![3., 4., 7., 5., 6.]) /// .min() /// .subscribe(|v| println!("{}", v)); /// /// // print log: /// // 3 /// ``` #[inline] fn min(self) -> MinMaxOp<Self, Self::Item> where Self::Item: Clone + Send + PartialOrd<Self::Item>, { fn get_lesser<Item>(i: Option<Item>, v: Item) -> Option<Item> where Item: Clone + PartialOrd<Item>, { i.map(|vv| if vv > v { v.clone() } else { vv }).or(Some(v)) } let get_lesser_func = get_lesser as fn(Option<Self::Item>, Self::Item) -> Option<Self::Item>; self .scan_initial(None, get_lesser_func) .last() // we can safely unwrap, because we will ever get this item // once a max value exists and is there. .map(|v| v.unwrap()) } /// Calculates the sum of numbers emitted by an source observable and emits /// this sum when source completes. /// /// Emits zero when source completed as an and empty sequence. /// Emits error when source observable emits it. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(vec![1, 1, 1, 1, 1]) /// .sum() /// .subscribe(|v| println!("{}", v)); /// /// // p rint log: /// // 5 /// ``` #[inline] fn sum(self) -> SumOp<Self, Self::Item> where Self::Item: Clone + Default + Add<Self::Item, Output = Self::Item>, { self.reduce(|acc, v| acc + v) } /// Emits the number of items emitted by a source observable when this source /// completes. /// /// The output type of this operator is fixed to [`usize`]. /// /// Emits zero when source completed as an and empty sequence. /// Emits error when source observable emits it. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(vec!['1', '7', '3', '0', '4']) /// .count() /// .subscribe(|v| println!("{}", v)); /// /// // print log: /// // 5 /// ``` #[inline] fn count(self) -> CountOp<Self, Self::Item> { self.reduce(|acc, _v| acc + 1) } /// Calculates the sum of numbers emitted by an source observable and emits /// this sum when source completes. /// /// Emits zero when source completed as an and empty sequence. /// Emits error when source observable emits it. /// /// # Examples /// /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(vec![3., 4., 5., 6., 7.]) /// .average() /// .subscribe(|v| println!("{}", v)); /// /// // print log: /// // 5 /// ``` #[inline] fn average(self) -> AverageOp<Self, Self::Item> where Self::Item: Clone + Send + Default + Add<Self::Item, Output = Self::Item> + Mul<f64, Output = Self::Item>, { /// Computing an average by multiplying accumulated nominator by a /// reciprocal of accumulated denominator. In this way some generic /// types that support linear scaling over floats values could be /// averaged (e.g. vectors) fn average_floats<T>(acc: Accum<T>) -> T where T: Default + Clone + Send + Mul<f64, Output = T>, { // Note: we will never be dividing by zero here, as // the acc.1 will be always >= 1. // It would have be zero if we've would have received an element // when the source observable is empty but because of how // `scan` works, we will transparently not receive anything in // such case. acc.0 * (1.0 / (acc.1 as f64)) } fn accumulate_item<T>(acc: Accum<T>, v: T) -> Accum<T> where T: Clone + Add<T, Output = T>, { let newacc = acc.0 + v; let newcount = acc.1 + 1; (newacc, newcount) } // our starting point let start = (Self::Item::default(), 0); let acc = accumulate_item as fn(Accum<Self::Item>, Self::Item) -> Accum<Self::Item>; let avg = average_floats as fn(Accum<Self::Item>) -> Self::Item; self.scan_initial(start, acc).last().map(avg) } /// Returns a ConnectableObservable. A ConnectableObservable Observable /// resembles an ordinary Observable, except that it does not begin emitting /// items when it is subscribed to, but only when the Connect operator is /// applied to it. In this way you can wait for all intended observers to /// subscribe to the Observable before the Observable begins emitting items. #[inline] fn publish<Subject: Default>(self) -> ConnectableObservable<Self, Subject> { ConnectableObservable::new(self) } /// Returns a new Observable that multicast (shares) the original /// Observable. As long as there is at least one Subscriber this /// Observable will be subscribed and emitting data. When all subscribers /// have unsubscribed it will unsubscribe from the source Observable. /// Because the Observable is multicasting it makes the stream `hot`. /// This is an alias for `publish().ref_count()` #[inline] fn share<Subject>( self, ) -> <ConnectableObservable<Self, Subject> as Connect>::R where Subject: Default, ConnectableObservable<Self, Subject>: Connect, { self.publish::<Subject>().into_ref_count() } /// Delays the emission of items from the source Observable by a given timeout /// or until a given `Instant`. #[inline] fn delay<SD>(self, dur: Duration, scheduler: SD) -> DelayOp<Self, SD> { DelayOp { source: self, delay: dur, scheduler, } } #[inline] fn delay_at<SD>(self, at: Instant, scheduler: SD) -> DelayOp<Self, SD> { DelayOp { source: self, delay: at.elapsed(), scheduler, } } /// Specify the Scheduler on which an Observable will operate /// /// With `SubscribeON` you can decide what type of scheduler a specific /// Observable will be using when it is subscribed to. /// /// Schedulers control the speed and order of emissions to observers from an /// Observable stream. /// /// # Example /// Given the following code: /// ```rust /// use rxrust::prelude::*; /// /// let a = observable::from_iter(1..5); /// let b = observable::from_iter(5..10); /// a.merge(b).subscribe(|v| print!("{} ", v)); /// ``` /// /// Both Observable `a` and `b` will emit their values directly and /// synchronously once they are subscribed to. /// This will result in the output of `1 2 3 4 5 6 7 8 9`. /// /// But if we instead use the `subscribe_on` operator declaring that we want /// to use the new thread scheduler for values emitted by Observable `a`: /// ```rust /// use rxrust::prelude::*; /// use std::thread; /// use futures::executor::ThreadPool; /// /// let pool = ThreadPool::new().unwrap(); /// let a = observable::from_iter(1..5).subscribe_on(pool); /// let b = observable::from_iter(5..10); /// a.merge(b).into_shared().subscribe(|v|{ /// let handle = thread::current(); /// print!("{}({:?}) ", v, handle.id()) /// }); /// ``` /// /// The output will instead by `1(thread 1) 2(thread 1) 3(thread 1) 4(thread /// 1) 5(thread 2) 6(thread 2) 7(thread 2) 8(thread 2) 9(thread id2)`. /// The reason for this is that Observable `b` emits its values directly like /// before, but the emissions from `a` are scheduled on a new thread because /// we are now using the `NewThread` Scheduler for that specific Observable. #[inline] fn subscribe_on<SD>(self, scheduler: SD) -> SubscribeOnOP<Self, SD> { SubscribeOnOP { source: self, scheduler, } } /// Re-emits all notifications from source Observable with specified /// scheduler. /// /// `ObserveOn` is an operator that accepts a scheduler as the parameter, /// which will be used to reschedule notifications emitted by the source /// Observable. #[inline] fn observe_on<SD>(self, scheduler: SD) -> ObserveOnOp<Self, SD> { ObserveOnOp { source: self, scheduler, } } /// Emits a value from the source Observable only after a particular time span /// has passed without another source emission. #[inline] fn debounce<SD>( self, duration: Duration, scheduler: SD, ) -> DebounceOp<Self, SD> { DebounceOp { source: self, duration, scheduler, } } /// Emits a value from the source Observable, then ignores subsequent source /// values for duration milliseconds, then repeats this process. /// /// #Example /// ``` /// use rxrust::{ prelude::*, ops::throttle_time::ThrottleEdge }; /// use std::time::Duration; /// use futures::executor::LocalPool; /// /// let mut local_scheduler = LocalPool::new(); /// let spawner = local_scheduler.spawner(); /// observable::interval(Duration::from_millis(1), spawner.clone()) /// .throttle_time(Duration::from_millis(9), ThrottleEdge::Leading, spawner) /// .take(5) /// .subscribe(move |v| println!("{}", v)); /// /// local_scheduler.run(); /// ``` #[inline] fn throttle_time<SD>( self, duration: Duration, edge: ThrottleEdge, scheduler: SD, ) -> ThrottleTimeOp<Self, SD> { ThrottleTimeOp { source: self, duration, edge, scheduler, } } /// Returns an Observable that emits all items emitted by the source /// Observable that are distinct by comparison from previous items. #[inline] fn distinct(self) -> DistinctOp<Self> { DistinctOp { source: self } } /// Variant of distinct that takes a key selector. #[inline] fn distinct_key<F>(self, key: F) -> DistinctKeyOp<Self, F> { DistinctKeyOp { source: self, key } } /// Only emit when the current value is different than the last #[inline] fn distinct_until_changed(self) -> DistinctUntilChangedOp<Self> { DistinctUntilChangedOp { source: self } } /// Variant of distinct_until_changed that takes a key selector. #[inline] fn distinct_until_key_changed<F>( self, key: F, ) -> DistinctUntilKeyChangedOp<Self, F> { DistinctUntilKeyChangedOp { source: self, key } } /// 'Zips up' two observable into a single observable of pairs. /// /// zip() returns a new observable that will emit over two other /// observables, returning a tuple where the first element comes from the /// first observable, and the second element comes from the second /// observable. /// /// In other words, it zips two observables together, into a single one. #[inline] fn zip<U>(self, other: U) -> ZipOp<Self, U> where U: Observable, { ZipOp { a: self, b: other } } /// Combines the source Observable with other Observables to create an /// Observable whose values are calculated from the latest values of each, /// only when the source emits. /// /// Whenever the source Observable emits a value, it computes a formula /// using that value plus the latest values from other input Observables, /// then emits the output of that formula. #[inline] fn with_latest_from<U>(self, other: U) -> WithLatestFromOp<Self, U> where U: Observable, { WithLatestFromOp { a: self, b: other } } /// Emits default value if Observable completed with empty result /// /// #Example /// ``` /// use rxrust::prelude::*; /// /// observable::empty() /// .default_if_empty(5) /// .subscribe(|v| println!("{}", v)); /// /// // Prints: /// // 5 /// ``` #[inline] fn default_if_empty( self, default_value: Self::Item, ) -> DefaultIfEmptyOp<Self> { DefaultIfEmptyOp { source: self, is_empty: true, default_value, } } /// Buffers emitted values of type T in a Vec<T> and /// emits that Vec<T> as soon as the buffer's size equals /// the given count. /// On complete, if the buffer is not empty, /// it will be emitted. /// On error, the buffer will be discarded. /// /// The operator never returns an empty buffer. /// /// #Example /// ``` /// use rxrust::prelude::*; /// /// observable::from_iter(0..6) /// .buffer_with_count(3) /// .subscribe(|vec| println!("{:?}", vec)); /// /// // Prints: /// // [0, 1, 2] /// // [3, 4, 5] /// ``` #[inline] fn buffer_with_count(self, count: usize) -> BufferWithCountOp<Self> { BufferWithCountOp { source: self, count, } } /// Buffers emitted values of type T in a Vec<T> and /// emits that Vec<T> periodically. /// /// On complete, if the buffer is not empty, /// it will be emitted. /// On error, the buffer will be discarded. /// /// The operator never returns an empty buffer. /// /// #Example /// ``` /// use rxrust::prelude::*; /// use std::time::Duration; /// use futures::executor::ThreadPool; /// /// let pool = ThreadPool::new().unwrap(); /// /// observable::create(|mut subscriber| { /// subscriber.next(0); /// subscriber.next(1); /// std::thread::sleep(Duration::from_millis(100)); /// subscriber.next(2); /// subscriber.next(3); /// subscriber.complete(); /// }) /// .buffer_with_time(Duration::from_millis(50), pool) /// .into_shared() /// .subscribe(|vec| println!("{:?}", vec)); /// /// // Prints: /// // [0, 1] /// // [2, 3] /// ``` #[inline] fn buffer_with_time<S>( self, time: Duration, scheduler: S, ) -> BufferWithTimeOp<Self, S> { BufferWithTimeOp { source: self, time, scheduler, } } /// Buffers emitted values of type T in a Vec<T> and /// emits that Vec<T> either if the buffer's size equals count, or /// periodically. This operator combines the functionality of /// buffer_with_count and buffer_with_time. /// /// #Example /// ``` /// use rxrust::prelude::*; /// use std::time::Duration; /// use futures::executor::ThreadPool; /// /// let pool = ThreadPool::new().unwrap(); /// /// observable::create(|mut subscriber| { /// subscriber.next(0); /// subscriber.next(1); /// subscriber.next(2); /// std::thread::sleep(Duration::from_millis(100)); /// subscriber.next(3); /// subscriber.next(4); /// subscriber.complete(); /// }) /// .buffer_with_count_and_time(2, Duration::from_millis(50), pool) /// .into_shared() /// .subscribe(|vec| println!("{:?}", vec)); /// /// // Prints: /// // [0, 1] /// // [2] /// // [3, 4] /// ``` #[inline] fn buffer_with_count_and_time<S>( self, count: usize, time: Duration, scheduler: S, ) -> BufferWithCountOrTimerOp<Self, S> { BufferWithCountOrTimerOp { source: self, count, time, scheduler, } } /// Emits item which is combining latest items from two observables. /// /// combine_latest() merges two observables into one observable /// by applying a binary operator on the latest item of two observable /// whenever each of observables produces an element. /// /// #Example /// ``` /// use rxrust::prelude::*; /// use std::time::Duration; /// use futures::executor::LocalPool; /// /// let mut local_scheduler = LocalPool::new(); /// let spawner = local_scheduler.spawner(); /// observable::interval(Duration::from_millis(2), spawner.clone()) /// .combine_latest( /// observable::interval(Duration::from_millis(3), spawner), /// |a, b| (a, b), /// ) /// .take(5) /// .subscribe(move |v| println!("{}, {}", v.0, v.1)); /// /// local_scheduler.run(); /// // print logs: /// // 0, 0 /// // 1, 0 /// // 2, 0 /// // 2, 1 /// // 3, 1 /// ``` fn combine_latest<O, BinaryOp, OutputItem>( self, other: O, binary_op: BinaryOp, ) -> CombineLatestOp<Self, O, BinaryOp> where O: Observable<Err = Self::Err>, BinaryOp: FnMut(Self::Item, O::Item) -> OutputItem, { CombineLatestOp { a: self, b: other, binary_op, } } /// Returns an observable that, at the moment of subscription, will /// synchronously emit all values provided to this operator, then subscribe /// to the source and mirror all of its emissions to subscribers. fn start_with<B>(self, values: Vec<B>) -> StartWithOp<Self, B> { StartWithOp { source: self, values, } } /// Groups pairs of consecutive emissions together and emits them as an pair /// of two values. fn pairwise(self) -> PairwiseOp<Self> { PairwiseOp { source: self } } /// Used to perform side-effects for notifications from the source observable #[inline] fn tap<F>(self, f: F) -> TapOp<Self, F> where F: FnMut(&Self::Item), { TapOp { source: self, func: f, } } } pub trait LocalObservable<'a>: Observable { type Unsub: SubscriptionLike; fn actual_subscribe<O>(self, observer: O) -> Self::Unsub where O: Observer<Item = Self::Item, Err = Self::Err> + 'a; } #[cfg(test)] mod tests { use super::*; #[test] fn smoke_element_at() { let s = observable::from_iter(0..20); s.clone().element_at(0).subscribe(|v| assert_eq!(v, 0)); s.clone().element_at(5).subscribe(|v| assert_eq!(v, 5)); s.clone().element_at(20).subscribe(|v| assert_eq!(v, 20)); s.element_at(21).subscribe(|_| panic!()); } #[test] fn bench_element_at() { do_bench_element_at(); } benchmark_group!(do_bench_element_at, element_at_bench); fn element_at_bench(b: &mut bencher::Bencher) { b.iter(smoke_element_at); } #[test] fn first() { let mut completed = 0; let mut next_count = 0; observable::from_iter(0..2) .first() .subscribe_complete(|_| next_count += 1, || completed += 1); assert_eq!(completed, 1); assert_eq!(next_count, 1); } #[test] fn bench_first() { do_bench_first(); } benchmark_group!(do_bench_first, first_bench); fn first_bench(b: &mut bencher::Bencher) { b.iter(first); } #[test] fn first_or() { let mut completed = false; let mut next_count = 0; observable::from_iter(0..2) .first_or(100) .subscribe_complete(|_| next_count += 1, || completed = true); assert_eq!(next_count, 1); assert!(completed); completed = false; let mut v = 0; observable::empty() .first_or(100) .subscribe_complete(|value| v = value, || completed = true); assert!(completed); assert_eq!(v, 100); } #[test] fn bench_first_or() { do_bench_first_or(); } benchmark_group!(do_bench_first_or, first_or_bench); fn first_or_bench(b: &mut bencher::Bencher) { b.iter(first_or); } #[test] fn first_support_fork() { let mut value = 0; let mut value2 = 0; { let o = observable::from_iter(1..100).first(); let o1 = o.clone().first(); let o2 = o.first(); o1.subscribe(|v| value = v); o2.subscribe(|v| value2 = v); } assert_eq!(value, 1); assert_eq!(value2, 1); } #[test] fn first_or_support_fork() { let mut default = 0; let mut default2 = 0; let o = observable::create(|subscriber| { subscriber.complete(); }) .first_or(100); let o1 = o.clone().first_or(0); let o2 = o.clone().first_or(0); o1.subscribe(|v| default = v); o2.subscribe(|v| default2 = v); assert_eq!(default, 100); assert_eq!(default, 100); } #[test] fn smoke_ignore_elements() { observable::from_iter(0..20) .ignore_elements() .subscribe(move |_| panic!()); } #[test] fn bench_ignore() { do_bench_ignore(); } benchmark_group!(do_bench_ignore, ignore_emements_bench); fn ignore_emements_bench(b: &mut bencher::Bencher) { b.iter(smoke_ignore_elements); } #[cfg(not(target_arch = "wasm32"))] #[test] fn shared_ignore_elements() { observable::from_iter(0..20) .ignore_elements() .into_shared() .subscribe(|_| panic!()); } #[test] fn smoke_all() { observable::from_iter(0..10) .all(|v| v < 10) .subscribe(|b| assert!(b)); observable::from_iter(0..10) .all(|v| v < 5) .subscribe(|b| assert!(!b)); } #[test] fn bench_all() { do_bench_all(); } benchmark_group!(do_bench_all, all_bench); fn all_bench(b: &mut bencher::Bencher) { b.iter(smoke_all); } }
26.689573
80
0.596866
1edb52c52ec98e3225011a212e89d122f36cd281
11,247
// Copyright 2020 Contributors to the Parsec project. // SPDX-License-Identifier: Apache-2.0 use super::generated_ops::list_keys::{ KeyInfo as KeyInfoProto, Operation as OperationProto, Result as ResultProto, }; use crate::operations::list_keys::{KeyInfo, Operation, Result}; use crate::requests::{ProviderId, ResponseStatus}; use log::error; use num::FromPrimitive; use std::convert::{TryFrom, TryInto}; impl TryFrom<OperationProto> for Operation { type Error = ResponseStatus; fn try_from(_proto_op: OperationProto) -> std::result::Result<Self, Self::Error> { Ok(Operation {}) } } impl TryFrom<Operation> for OperationProto { type Error = ResponseStatus; fn try_from(_op: Operation) -> std::result::Result<Self, Self::Error> { Ok(Default::default()) } } impl TryFrom<KeyInfoProto> for KeyInfo { type Error = ResponseStatus; fn try_from(proto_info: KeyInfoProto) -> std::result::Result<Self, Self::Error> { let id: ProviderId = match FromPrimitive::from_u32(proto_info.provider_id) { Some(id) => id, None => return Err(ResponseStatus::ProviderDoesNotExist), }; let attributes = proto_info .attributes .ok_or_else(|| { error!("The attributes field of KeyInfo protobuf message is not set (mandatory field)."); ResponseStatus::InvalidEncoding })? .try_into()?; Ok(KeyInfo { provider_id: id, name: proto_info.name, attributes, }) } } impl TryFrom<KeyInfo> for KeyInfoProto { type Error = ResponseStatus; fn try_from(info: KeyInfo) -> std::result::Result<Self, Self::Error> { Ok(KeyInfoProto { provider_id: info.provider_id as u32, name: info.name, attributes: Some(info.attributes.try_into()?), }) } } impl TryFrom<ResultProto> for Result { type Error = ResponseStatus; fn try_from(proto_op: ResultProto) -> std::result::Result<Self, Self::Error> { let mut keys: Vec<KeyInfo> = Vec::new(); for key in proto_op.keys { keys.push(key.try_into()?); } Ok(Result { keys }) } } impl TryFrom<Result> for ResultProto { type Error = ResponseStatus; fn try_from(op: Result) -> std::result::Result<Self, Self::Error> { let mut keys: Vec<KeyInfoProto> = Vec::new(); for key in op.keys { keys.push(key.try_into()?); } Ok(ResultProto { keys }) } } #[cfg(test)] mod test { // Operation <-> Proto conversions are not tested since they're too simple use super::super::generated_ops::list_keys::{KeyInfo as KeyInfoProto, Result as ResultProto}; use super::super::generated_ops::psa_key_attributes::KeyAttributes as KeyAttributesProto; use super::super::{Convert, ProtobufConverter}; use crate::operations::list_keys::{KeyInfo, Operation, Result}; use crate::operations::psa_algorithm::{Algorithm, AsymmetricSignature, Hash}; use crate::operations::psa_key_attributes::{self, Attributes, Lifetime, Policy, UsageFlags}; use crate::operations::{NativeOperation, NativeResult}; use crate::requests::{request::RequestBody, response::ResponseBody, Opcode, ProviderId}; use std::convert::TryInto; static CONVERTER: ProtobufConverter = ProtobufConverter {}; #[test] fn proto_to_resp() { let mut proto: ResultProto = Default::default(); let mut usage_flags = UsageFlags::default(); let _ = usage_flags .set_decrypt() .set_export() .set_copy() .set_cache() .set_encrypt() .set_decrypt() .set_sign_message() .set_verify_message() .set_sign_hash() .set_verify_hash() .set_derive(); let key_attrs = Attributes { lifetime: Lifetime::Persistent, key_type: psa_key_attributes::Type::RsaKeyPair, bits: 1024, policy: Policy { usage_flags, permitted_algorithms: Algorithm::AsymmetricSignature( AsymmetricSignature::RsaPkcs1v15Sign { hash_alg: Hash::Sha1.into(), }, ), }, }; let key_attrs_proto: KeyAttributesProto = key_attrs.try_into().unwrap(); let key_info = KeyInfoProto { provider_id: ProviderId::MbedCrypto as u32, name: String::from("Some Key Name"), attributes: Some(key_attrs_proto), }; proto.keys.push(key_info); let resp: Result = proto.try_into().unwrap(); assert_eq!(resp.keys.len(), 1); assert_eq!(resp.keys[0].name, "Some Key Name"); assert_eq!(resp.keys[0].provider_id, ProviderId::MbedCrypto); assert_eq!(resp.keys[0].attributes, key_attrs); } #[test] fn resp_to_proto() { let mut resp: Result = Result { keys: Vec::new() }; let mut usage_flags = UsageFlags::default(); let _ = usage_flags .set_decrypt() .set_export() .set_copy() .set_cache() .set_encrypt() .set_decrypt() .set_sign_message() .set_verify_message() .set_sign_hash() .set_verify_hash() .set_derive(); let key_attributes = Attributes { lifetime: Lifetime::Persistent, key_type: psa_key_attributes::Type::RsaKeyPair, bits: 1024, policy: Policy { usage_flags, permitted_algorithms: Algorithm::AsymmetricSignature( AsymmetricSignature::RsaPkcs1v15Sign { hash_alg: Hash::Sha1.into(), }, ), }, }; let key_info = KeyInfo { provider_id: ProviderId::MbedCrypto, name: String::from("Foo"), attributes: key_attributes, }; resp.keys.push(key_info); let proto: ResultProto = resp.try_into().unwrap(); let key_attributes_proto: KeyAttributesProto = key_attributes.try_into().unwrap(); assert_eq!(proto.keys.len(), 1); assert_eq!(proto.keys[0].provider_id, ProviderId::MbedCrypto as u32); assert_eq!(proto.keys[0].name, "Foo"); assert_eq!(proto.keys[0].attributes, Some(key_attributes_proto)); } #[test] fn list_keys_req_to_native() { let req_body = RequestBody::from_bytes(Vec::new()); assert!(CONVERTER .body_to_operation(req_body, Opcode::ListKeys) .is_ok()); } #[test] fn op_list_keys_from_native() { let list_keys = Operation {}; let body = CONVERTER .operation_to_body(NativeOperation::ListKeys(list_keys)) .expect("Failed to convert request"); assert!(body.is_empty()); } #[test] fn op_list_keys_e2e() { let list_keys = Operation {}; let req_body = CONVERTER .operation_to_body(NativeOperation::ListKeys(list_keys)) .expect("Failed to convert request"); assert!(CONVERTER .body_to_operation(req_body, Opcode::ListKeys) .is_ok()); } #[test] fn req_from_native_mangled_body() { let req_body = RequestBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]); assert!(CONVERTER .body_to_operation(req_body, Opcode::ListKeys) .is_err()); } #[test] fn list_keys_body_to_native() { let resp_body = ResponseBody::from_bytes(Vec::new()); assert!(CONVERTER .body_to_result(resp_body, Opcode::ListKeys) .is_ok()); } #[test] fn result_list_keys_from_native() { let mut list_keys = Result { keys: Vec::new() }; let mut usage_flags = UsageFlags::default(); let _ = usage_flags .set_decrypt() .set_export() .set_copy() .set_cache() .set_encrypt() .set_decrypt() .set_sign_message() .set_verify_message() .set_sign_hash() .set_verify_hash() .set_derive(); let key_info = KeyInfo { provider_id: ProviderId::MbedCrypto, name: String::from("Bar"), attributes: Attributes { lifetime: Lifetime::Persistent, key_type: psa_key_attributes::Type::RsaKeyPair, bits: 1024, policy: Policy { usage_flags, permitted_algorithms: Algorithm::AsymmetricSignature( AsymmetricSignature::RsaPkcs1v15Sign { hash_alg: Hash::Sha1.into(), }, ), }, }, }; list_keys.keys.push(key_info); let body = CONVERTER .result_to_body(NativeResult::ListKeys(list_keys)) .expect("Failed to convert response"); assert!(!body.is_empty()); } #[test] fn list_keys_result_e2e() { let mut usage_flags = UsageFlags::default(); let _ = usage_flags .set_decrypt() .set_export() .set_copy() .set_cache() .set_encrypt() .set_decrypt() .set_sign_message() .set_verify_message() .set_sign_hash() .set_verify_hash() .set_derive(); let mut list_keys = Result { keys: Vec::new() }; let key_info = KeyInfo { provider_id: ProviderId::MbedCrypto, name: String::from("Baz"), attributes: Attributes { lifetime: Lifetime::Persistent, key_type: psa_key_attributes::Type::RsaKeyPair, bits: 1024, policy: Policy { usage_flags, permitted_algorithms: Algorithm::AsymmetricSignature( AsymmetricSignature::RsaPkcs1v15Sign { hash_alg: Hash::Sha1.into(), }, ), }, }, }; list_keys.keys.push(key_info); let body = CONVERTER .result_to_body(NativeResult::ListKeys(list_keys)) .expect("Failed to convert response"); assert!(!body.is_empty()); let result = CONVERTER .body_to_result(body, Opcode::ListKeys) .expect("Failed to convert back to result"); match result { NativeResult::ListKeys(result) => { assert_eq!(result.keys.len(), 1); } _ => panic!("Expected list_keys"), } } #[test] fn resp_from_native_mangled_body() { let resp_body = ResponseBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]); assert!(CONVERTER .body_to_result(resp_body, Opcode::ListKeys) .is_err()); } }
32.412104
105
0.557571
56dd6691abbe52a246a062cc73b757fe1165204f
712
// Copyright 2018 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. // run-pass #![allow(warnings)] #![feature(impl_header_lifetime_elision)] // This works for functions... fn foo<'a>(x: &str, y: &'a str) {} // ...so this should work for impls impl<'a> Foo<&str> for &'a str {} trait Foo<T> {} fn main() { }
27.384615
68
0.696629
1c06ed0bbeec1a90f39f59617a400b195315b38a
1,463
use std::collections::HashMap; use std::fs::File; use std::io::Read; pub struct Group { num_members: usize, yes_map: HashMap<char, usize>, } impl Group { fn new() -> Group { Group { num_members: 0, yes_map: HashMap::new(), } } } fn parse_data(input_data: &str) -> Vec<Group> { let mut output: Vec<Group> = Vec::new(); output.push(Group::new()); for l in input_data.lines() { if l.is_empty() { output.push(Group::new()); continue; } let cur_group = output.last_mut().unwrap(); cur_group.num_members += 1; l.chars().for_each(|c| { let entry = cur_group.yes_map.entry(c).or_insert(0); *entry += 1; }); } output } pub fn parse_input() -> Result<Vec<Group>, std::io::Error> { let mut file = File::open("input_06.txt")?; let mut buf_file = String::new(); file.read_to_string(&mut buf_file)?; Ok(parse_data(&buf_file)) } pub fn run_a(input: &Vec<Group>) -> Result<i64, std::io::Error> { let res: i64 = input.iter().map(|g| g.yes_map.len() as i64).sum(); Ok(res) } pub fn run_b(input: &Vec<Group>) -> Result<i64, std::io::Error> { let res: i64 = input .iter() .map(|g| g.yes_map.values().filter(|c| **c == g.num_members).count()) .sum::<usize>() as i64; Ok(res) } #[test] fn test_aoc06() { let sample_input = "abc\n\na\nb\nc\n\nab\nac\n\na\na\na\na\n\nb"; let sample_res = parse_data(&sample_input); assert_eq!(run_a(&sample_res).ok(), Some(11)); assert_eq!(run_b(&sample_res).ok(), Some(6)); }
20.319444
71
0.626794
7acb03659884ccca5f75cd4f2340e6ec06842f27
2,047
use super::{super::user::UserEntity, MessageEntity}; use crate::{ repository::{GetEntityFuture, Repository}, utils, Backend, Entity, }; use twilight_model::{ channel::{ChannelType, PrivateChannel}, id::{ChannelId, MessageId, UserId}, }; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[derive(Clone, Debug, Eq, PartialEq)] pub struct PrivateChannelEntity { pub id: ChannelId, pub last_message_id: Option<MessageId>, pub last_pin_timestamp: Option<String>, pub kind: ChannelType, pub recipient_id: Option<UserId>, } impl From<PrivateChannel> for PrivateChannelEntity { fn from(channel: PrivateChannel) -> Self { let recipient_id = channel.recipients.first().map(|user| user.id); Self { id: channel.id, last_message_id: channel.last_message_id, last_pin_timestamp: channel.last_pin_timestamp, kind: channel.kind, recipient_id, } } } impl Entity for PrivateChannelEntity { type Id = ChannelId; /// Return the private channel's ID. fn id(&self) -> Self::Id { self.id } } /// Repository to work with guild channels and their associated entities. pub trait PrivateChannelRepository<B: Backend>: Repository<PrivateChannelEntity, B> { /// Retrieve the last message of a private channel. fn last_message(&self, channel_id: ChannelId) -> GetEntityFuture<'_, MessageEntity, B::Error> { utils::relation_and_then( self.backend().private_channels(), self.backend().messages(), channel_id, |channel| channel.last_message_id, ) } /// Retrieve the recipient user associated with a private channel. fn recipient(&self, channel_id: ChannelId) -> GetEntityFuture<'_, UserEntity, B::Error> { utils::relation_and_then( self.backend().private_channels(), self.backend().users(), channel_id, |channel| channel.recipient_id, ) } }
31.015152
99
0.646312
71299b05ed44be76669f8bc5a4d58c58d298a1ed
926
use super::super::error::Result; use super::super::traits::AsyncBufRead; use core::pin::Pin; use futures::future::Future; use futures::ready; use futures::task::{Context, Poll}; pub struct ReadBuf<'a, R: ?Sized> { reader: Option<&'a mut R>, } impl<R: ?Sized + Unpin> Unpin for ReadBuf<'_, R> {} impl<'a, R: AsyncBufRead + ?Sized + Unpin> ReadBuf<'a, R> { pub(super) fn new(reader: &'a mut R) -> Self { ReadBuf { reader: Some(reader), } } } impl<'a, R: AsyncBufRead + ?Sized + Unpin> Future for ReadBuf<'a, R> { type Output = Result<&'a [u8]>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; let buf = ready!(Pin::new(this.reader.as_mut().unwrap()).poll_fill_buf(cx))?; let buf: &'a [u8] = unsafe { core::mem::transmute(buf) }; this.reader = None; Poll::Ready(Ok(buf)) } }
26.457143
85
0.577754
09519104174b592cbf2f1745e6a5d395f004a4d7
2,026
/* origin: FreeBSD /usr/src/lib/msun/src/e_logf.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ const LN2_HI: f32 = 6.9313812256e-01; /* 0x3f317180 */ const LN2_LO: f32 = 9.0580006145e-06; /* 0x3717f7d1 */ /* |(log(1+s)-log(1-s))/s - Lg(s)| < 2**-34.24 (~[-4.95e-11, 4.97e-11]). */ const LG1: f32 = 0.66666662693; /* 0xaaaaaa.0p-24*/ const LG2: f32 = 0.40000972152; /* 0xccce13.0p-25 */ const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */ const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */ #[inline] pub fn logf(mut x: f32) -> f32 { let x1p25 = f32::from_bits(0x4c000000); // 0x1p25f === 2 ^ 25 let mut ix = x.to_bits(); let mut k = 0i32; if (ix < 0x00800000) || ((ix >> 31) != 0) { /* x < 2**-126 */ if ix << 1 == 0 { return -1. / (x * x); /* log(+-0)=-inf */ } if (ix >> 31) != 0 { return (x - x) / 0.; /* log(-#) = NaN */ } /* subnormal number, scale up x */ k -= 25; x *= x1p25; ix = x.to_bits(); } else if ix >= 0x7f800000 { return x; } else if ix == 0x3f800000 { return 0.; } /* reduce x into [sqrt(2)/2, sqrt(2)] */ ix += 0x3f800000 - 0x3f3504f3; k += ((ix >> 23) as i32) - 0x7f; ix = (ix & 0x007fffff) + 0x3f3504f3; x = f32::from_bits(ix); let f = x - 1.; let s = f / (2. + f); let z = s * s; let w = z * z; let t1 = w * (LG2 + w * LG4); let t2 = z * (LG1 + w * LG3); let r = t2 + t1; let hfsq = 0.5 * f * f; let dk = k as f32; s * (hfsq + r) + dk * LN2_LO - hfsq + f + dk * LN2_HI }
30.69697
75
0.489141
f58ce9a035931697523c8773fb5c15b467af6a17
6,763
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::define_storage; use crate::storage::{CodecKVStore, StorageInstance, ValueCodec}; use crate::{ BLOCK_BODY_PREFIX_NAME, BLOCK_HEADER_PREFIX_NAME, BLOCK_PREFIX_NAME, BLOCK_TRANSACTIONS_PREFIX_NAME, BLOCK_TRANSACTION_INFOS_PREFIX_NAME, FAILED_BLOCK_PREFIX_NAME, }; use anyhow::{bail, Result}; use bcs_ext::BCSCodec; use crypto::HashValue; use logger::prelude::*; use serde::{Deserialize, Serialize}; use starcoin_types::block::{Block, BlockBody, BlockHeader}; use starcoin_types::peer_info::PeerId; #[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)] pub struct FailedBlock { block: Block, peer_id: Option<PeerId>, failed: String, } #[allow(clippy::from_over_into)] impl Into<(Block, Option<PeerId>, String)> for FailedBlock { fn into(self) -> (Block, Option<PeerId>, String) { (self.block, self.peer_id, self.failed) } } impl From<(Block, Option<PeerId>, String)> for FailedBlock { fn from(block: (Block, Option<PeerId>, String)) -> Self { Self { block: block.0, peer_id: block.1, failed: block.2, } } } define_storage!(BlockInnerStorage, HashValue, Block, BLOCK_PREFIX_NAME); define_storage!( BlockHeaderStorage, HashValue, BlockHeader, BLOCK_HEADER_PREFIX_NAME ); define_storage!( BlockBodyStorage, HashValue, BlockBody, BLOCK_BODY_PREFIX_NAME ); define_storage!( BlockTransactionsStorage, HashValue, Vec<HashValue>, BLOCK_TRANSACTIONS_PREFIX_NAME ); define_storage!( BlockTransactionInfosStorage, HashValue, Vec<HashValue>, BLOCK_TRANSACTION_INFOS_PREFIX_NAME ); define_storage!( FailedBlockStorage, HashValue, FailedBlock, FAILED_BLOCK_PREFIX_NAME ); #[derive(Clone)] pub struct BlockStorage { block_store: BlockInnerStorage, header_store: BlockHeaderStorage, body_store: BlockBodyStorage, block_txns_store: BlockTransactionsStorage, block_txn_infos_store: BlockTransactionInfosStorage, failed_block_storage: FailedBlockStorage, } impl ValueCodec for Block { fn encode_value(&self) -> Result<Vec<u8>> { self.encode() } fn decode_value(data: &[u8]) -> Result<Self> { Self::decode(data) } } impl ValueCodec for BlockHeader { fn encode_value(&self) -> Result<Vec<u8>> { self.encode() } fn decode_value(data: &[u8]) -> Result<Self> { Self::decode(data) } } impl ValueCodec for BlockBody { fn encode_value(&self) -> Result<Vec<u8>> { self.encode() } fn decode_value(data: &[u8]) -> Result<Self> { Self::decode(data) } } impl ValueCodec for FailedBlock { fn encode_value(&self) -> Result<Vec<u8>> { self.encode() } fn decode_value(data: &[u8]) -> Result<Self> { Self::decode(data) } } impl BlockStorage { pub fn new(instance: StorageInstance) -> Self { BlockStorage { block_store: BlockInnerStorage::new(instance.clone()), header_store: BlockHeaderStorage::new(instance.clone()), body_store: BlockBodyStorage::new(instance.clone()), block_txns_store: BlockTransactionsStorage::new(instance.clone()), block_txn_infos_store: BlockTransactionInfosStorage::new(instance.clone()), failed_block_storage: FailedBlockStorage::new(instance), } } pub fn save(&self, block: Block) -> Result<()> { debug!( "insert block:{}, parent:{}", block.header().id(), block.header().parent_hash() ); let block_id = block.header().id(); self.block_store.put(block_id, block) } pub fn save_header(&self, header: BlockHeader) -> Result<()> { self.header_store.put(header.id(), header) } pub fn get_headers(&self) -> Result<Vec<HashValue>> { let mut key_hashes = vec![]; for hash in self.header_store.keys()? { key_hashes.push(hash) } Ok(key_hashes) } pub fn save_body(&self, block_id: HashValue, body: BlockBody) -> Result<()> { self.body_store.put(block_id, body) } pub fn get(&self, block_id: HashValue) -> Result<Option<Block>> { self.block_store.get(block_id) } pub fn get_blocks(&self, ids: Vec<HashValue>) -> Result<Vec<Option<Block>>> { Ok(self.block_store.multiple_get(ids)?.into_iter().collect()) } pub fn get_body(&self, block_id: HashValue) -> Result<Option<BlockBody>> { self.body_store.get(block_id) } pub fn commit_block(&self, block: Block) -> Result<()> { let (header, body) = block.clone().into_inner(); //save header let block_id = header.id(); self.save_header(header)?; //save body self.save_body(block_id, body)?; //save block cache self.save(block) } pub fn get_block_header_by_hash(&self, block_id: HashValue) -> Result<Option<BlockHeader>> { self.header_store.get(block_id) } pub fn get_block_by_hash(&self, block_id: HashValue) -> Result<Option<Block>> { self.get(block_id) } pub fn get_transactions(&self, block_id: HashValue) -> Result<Vec<HashValue>> { match self.block_txns_store.get(block_id) { Ok(Some(transactions)) => Ok(transactions), _ => bail!("can't find block's transaction: {:?}", block_id), } } /// get txn info ids for `block_id`. /// return None, if block_id not exists. pub fn get_transaction_info_ids(&self, block_id: HashValue) -> Result<Option<Vec<HashValue>>> { self.block_txn_infos_store.get(block_id) } pub fn put_transaction_ids( &self, block_id: HashValue, transactions: Vec<HashValue>, ) -> Result<()> { self.block_txns_store.put(block_id, transactions) } pub fn put_transaction_infos( &self, block_id: HashValue, txn_info_ids: Vec<HashValue>, ) -> Result<()> { self.block_txn_infos_store.put(block_id, txn_info_ids) } pub fn save_failed_block( &self, block_id: HashValue, block: Block, peer_id: Option<PeerId>, failed: String, ) -> Result<()> { self.failed_block_storage .put(block_id, (block, peer_id, failed).into()) } pub fn get_failed_block_by_id( &self, block_id: HashValue, ) -> Result<Option<(Block, Option<PeerId>, String)>> { match self.failed_block_storage.get(block_id)? { Some(failed_block) => Ok(Some(failed_block.into())), None => Ok(None), } } }
28.062241
99
0.632264
ccd66a03e167e1dc74c3b6c9b3f7a8d50ddfbf27
5,650
//! This crate provides salsa's macros and attributes. #![recursion_limit = "256"] extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate quote; use proc_macro::TokenStream; mod database_storage; mod parenthesized; mod query_group; /// The decorator that defines a salsa "query group" trait. This is a /// trait that defines everything that a block of queries need to /// execute, as well as defining the queries themselves that are /// exported for others to use. /// /// This macro declares the "prototype" for a group of queries. It will /// expand into a trait and a set of structs, one per query. /// /// For each query, you give the name of the accessor method to invoke /// the query (e.g., `my_query`, below), as well as its parameter /// types and the output type. You also give the name for a query type /// (e.g., `MyQuery`, below) that represents the query, and optionally /// other details, such as its storage. /// /// # Examples /// /// The simplest example is something like this: /// /// ```ignore /// #[salsa::query_group] /// trait TypeckDatabase { /// #[salsa::input] // see below for other legal attributes /// fn my_query(&self, input: u32) -> u64; /// /// /// Queries can have any number of inputs (including zero); if there /// /// is not exactly one input, then the key type will be /// /// a tuple of the input types, so in this case `(u32, f32)`. /// fn other_query(&self, input1: u32, input2: f32) -> u64; /// } /// ``` /// /// Here is a list of legal `salsa::XXX` attributes: /// /// - Storage attributes: control how the query data is stored and set. These /// are described in detail in the section below. /// - `#[salsa::input]` /// - `#[salsa::memoized]` /// - `#[salsa::volatile]` /// - `#[salsa::dependencies]` /// - Query execution: /// - `#[salsa::invoke(path::to::my_fn)]` -- for a non-input, this /// indicates the function to call when a query must be /// recomputed. The default is to call a function in the same /// module with the same name as the query. /// - `#[query_type(MyQueryTypeName)]` specifies the name of the /// dummy struct created fo the query. Default is the name of the /// query, in camel case, plus the word "Query" (e.g., /// `MyQueryQuery` and `OtherQueryQuery` in the examples above). /// /// # Storage attributes /// /// Here are the possible storage values for each query. The default /// is `storage memoized`. /// /// ## Input queries /// /// Specifying `storage input` will give you an **input /// query**. Unlike derived queries, whose value is given by a /// function, input queries are explicitly set by doing /// `db.query(QueryType).set(key, value)` (where `QueryType` is the /// `type` specified for the query). Accessing a value that has not /// yet been set will panic. Each time you invoke `set`, we assume the /// value has changed, and so we will potentially re-execute derived /// queries that read (transitively) from this input. /// /// ## Derived queries /// /// Derived queries are specified by a function. /// /// - `#[salsa::memoized]` (the default) -- The result is memoized /// between calls. If the inputs have changed, we will recompute /// the value, but then compare against the old memoized value, /// which can significantly reduce the amount of recomputation /// required in new revisions. This does require that the value /// implements `Eq`. /// - `#[salsa::volatile]` -- indicates that the inputs are not fully /// captured by salsa. The result will be recomputed once per revision. /// - `#[salsa::dependencies]` -- does not cache the value, so it will /// be recomputed every time it is needed. We do track the inputs, however, /// so if they have not changed, then things that rely on this query /// may be known not to have changed. /// /// ## Attribute combinations /// /// Some attributes are mutually exclusive. For example, it is an error to add /// multiple storage specifiers: /// /// ```compile_fail /// # use salsa_macros as salsa; /// #[salsa::query_group] /// trait CodegenDatabase { /// #[salsa::input] /// #[salsa::memoized] /// fn my_query(&self, input: u32) -> u64; /// } /// ``` /// /// It is also an error to annotate a function to `invoke` on an `input` query: /// /// ```compile_fail /// # use salsa_macros as salsa; /// #[salsa::query_group] /// trait CodegenDatabase { /// #[salsa::input] /// #[salsa::invoke(typeck::my_query)] /// fn my_query(&self, input: u32) -> u64; /// } /// ``` #[proc_macro_attribute] pub fn query_group(args: TokenStream, input: TokenStream) -> TokenStream { query_group::query_group(args, input) } /// This attribute is placed on your database struct. It takes a list of the /// query groups that your database supports. The format looks like so: /// /// ```rust,ignore /// #[salsa::database(MyQueryGroup1, MyQueryGroup2)] /// struct MyDatabase { /// runtime: salsa::Runtime<MyDatabase>, // <-- your database will need this field, too /// } /// ``` /// /// Here, the struct `MyDatabase` would support the two query groups /// `MyQueryGroup1` and `MyQueryGroup2`. In addition to the `database` /// attribute, the struct needs to have a `runtime` field (of type /// [`salsa::Runtime`]) and to implement the `salsa::Database` trait. /// /// See [the `hello_world` example][hw] for more details. /// /// [`salsa::Runtime`]: struct.Runtime.html /// [hw]: https://github.com/salsa-rs/salsa/tree/master/examples/hello_world #[proc_macro_attribute] pub fn database(args: TokenStream, input: TokenStream) -> TokenStream { database_storage::database(args, input) }
37.171053
91
0.669912
e61fa2a5f3bf841aeac19b10c2d2e6861da7ff24
1,980
/// Internal namespace. pub( crate ) mod private { use crate::prelude::*; // macro_rules! NODE_ID // { // () => { < Node as HasId >::Id }; // } /// /// Canonical implementation of edge. /// #[ derive( Debug, Copy, Clone ) ] pub struct Edge< EdgeId = crate::IdentityWithInt, NodeId = crate::IdentityWithInt, Kind = crate::EdgeKindless > where EdgeId : IdentityInterface, NodeId : IdentityInterface, Kind : EdgeKindInterface, { /// Input node. pub in_node : NodeId, /// Output node. pub out_node : NodeId, /// Kind of the edge. pub kind : Kind, /// Identifier. pub id : EdgeId, } // impl< EdgeId, NodeId, Kind > HasId for Edge< EdgeId, NodeId, Kind > where EdgeId : IdentityInterface, NodeId : IdentityInterface, Kind : EdgeKindInterface, { type Id = EdgeId; fn id( &self ) -> Self::Id { self.id } } // impl< EdgeId, NodeId, Kind > EdgeBasicInterface for Edge< EdgeId, NodeId, Kind > where EdgeId : IdentityInterface, NodeId : IdentityInterface, Kind : EdgeKindInterface, { } // impl< EdgeId, NodeId, Kind > PartialEq for Edge< EdgeId, NodeId, Kind > where EdgeId : IdentityInterface, NodeId : IdentityInterface, Kind : EdgeKindInterface, { fn eq( &self, other : &Self ) -> bool { self.id() == other.id() } } impl< EdgeId, NodeId, Kind > Eq for Edge< EdgeId, NodeId, Kind > where EdgeId : IdentityInterface, NodeId : IdentityInterface, Kind : EdgeKindInterface, {} } /// Protected namespace of the module. pub mod protected { pub use super::orphan::*; } pub use protected::*; /// Parented namespace of the module. pub mod orphan { pub use super::exposed::*; pub use super::private::Edge; } /// Exposed namespace of the module. pub mod exposed { pub use super::prelude::*; } /// Prelude to use essentials: `use my_module::prelude::*`. pub mod prelude { }
18.165138
113
0.612626
141eb1def15cead194faad80905d10ab653200f5
11,148
use super::op_code::OpCode; use std::io::{self, Read}; use super::state::State; use std::iter::Iterator; use super::error::Error; use crate::bfi::op_code::OpCode::{OpRightBracket, OpLeftBracket}; pub struct BrainFuckInterpreter { op_codes: Vec<OpCode>, op_code_pointer: usize, memory: [u8; 30_000], memory_pointer: usize, state: State } impl BrainFuckInterpreter { pub fn new() -> BrainFuckInterpreter { BrainFuckInterpreter { op_codes: Vec::new(), op_code_pointer: 0, memory: [0; 30_000], memory_pointer: 0, state: State::Ready } } pub fn run(&mut self) -> Result<(), Error> { if self.state != State::Ready { return Err(Error::NotReady) } self.state = State::Running; loop { match self.step() { Ok(_) => (), Err(e) => match e { Error::LastInstructionReached => { self.state = State::Ended; return Ok(()) }, _ => { self.state = State::Error; return Err(e) } } } } } pub fn step(&mut self) -> Result<(), Error> { if self.op_codes.len() == 0 { return Ok(()) } match self.op_codes[self.op_code_pointer] { OpCode::OpPlus(value) => { self.memory[self.memory_pointer] = self.memory[self.memory_pointer].wrapping_add(value); }, OpCode::OpMinus(value) => { self.memory[self.memory_pointer] = self.memory[self.memory_pointer].wrapping_sub(value); }, OpCode::OpLeftShift(offset) => { self.memory_pointer = self.memory_pointer.wrapping_sub(offset as usize); if self.memory_pointer > 29_999 { self.memory_pointer = 29_999 } }, OpCode::OpRightShift(offset) => { self.memory_pointer += offset as usize; if self.memory_pointer == 30_000 { self.memory_pointer = 0; } }, OpCode::OpLeftBracket(address) => { if self.memory[self.memory_pointer] == 0 { match address { Some(jump_to_address) => match self.jump_to(jump_to_address) { Err(_e) => return Err(Error::MissingRightBracket), _ => () }, None => { let mut left_counter = 0; while self.op_code_pointer < self.op_codes.len() { assert!(left_counter >= 0); match self.next_instruction() { Err(_e) => return Err(Error::MissingRightBracket), _ => () } match self.op_codes[self.op_code_pointer] { OpCode::OpRightBracket(_) => { if left_counter == 0 { break; } else { left_counter -= 1; } }, OpCode::OpLeftBracket(_) => left_counter += 1, _ => () } } } } } }, OpCode::OpRightBracket(address) => { if self.memory[self.memory_pointer] != 0 { match address { Some(jump_to_address) => match self.jump_to(jump_to_address) { Err(_e) => return Err(Error::MissingRightBracket), _ => () }, None => { let mut right_counter = 0; while self.op_code_pointer > 0 { assert!(right_counter >= 0); self.previous_instruction()?; match self.op_codes[self.op_code_pointer] { OpCode::OpLeftBracket(_) => { if right_counter == 0 { break; } else { right_counter -= 1; } }, OpCode::OpRightBracket(_) => right_counter += 1, _ => () } } } } } }, OpCode::OpDot => { print!("{}", self.memory[self.memory_pointer] as char) }, OpCode::OpComa => { let r = io::stdin().bytes().next().and_then(|result| result.ok()); self.memory[self.memory_pointer] = r.unwrap(); } } return self.next_instruction() } pub fn load(&mut self, data: Vec<u8> ) { let mut or_code = OpCode::OpDot; for op in data { let op_char = op as char; match op_char { '+' => { match self.op_codes.last_mut().unwrap_or(&mut or_code) { OpCode::OpPlus(value) => *value = value.wrapping_add(1), _ => self.op_codes.push(OpCode::OpPlus(1)) } }, '-' => { match self.op_codes.last_mut().unwrap_or(&mut or_code) { OpCode::OpMinus(value) => *value = value.wrapping_add(1), _ => self.op_codes.push(OpCode::OpMinus(1)) } }, '<' => { match self.op_codes.last_mut().unwrap_or(&mut or_code) { OpCode::OpLeftShift(value) => *value = value.wrapping_add(1), _ => self.op_codes.push(OpCode::OpLeftShift(1)) } }, '>' => { match self.op_codes.last_mut().unwrap_or(&mut or_code) { OpCode::OpRightShift(value) => *value = value.wrapping_add(1), _ => self.op_codes.push(OpCode::OpRightShift(1)) } }, '[' => self.op_codes.push(OpCode::OpLeftBracket(None)), ']' => self.op_codes.push(OpCode::OpRightBracket(None)), '.' => self.op_codes.push(OpCode::OpDot), ',' => self.op_codes.push(OpCode::OpComa), _ => () } } self.reset(); } pub fn optimize_jumps(&mut self) { let mut new_op_codes = Vec::new(); for i in 0..self.op_codes.len() { match self.op_codes[i] { OpCode::OpLeftBracket(address) => { match address { None => { let mut left_counter = 0; let mut instruction_counter = i; while instruction_counter < self.op_codes.len() { assert!(left_counter >= 0); instruction_counter += 1; match self.op_codes[instruction_counter] { OpCode::OpRightBracket(_) => { if left_counter == 0 { break; } else { left_counter -= 1; } }, OpCode::OpLeftBracket(_) => left_counter += 1, _ => () } } new_op_codes.push(OpLeftBracket(Some(instruction_counter))); }, _ => () } }, OpCode::OpRightBracket(address) => { match address { None => { let mut right_counter = 0; let mut instruction_counter = i; while instruction_counter > 0 { assert!(right_counter >= 0); instruction_counter -= 1; match self.op_codes[instruction_counter] { OpCode::OpLeftBracket(_) => { if right_counter == 0 { break; } else { right_counter -= 1; } }, OpCode::OpRightBracket(_) => right_counter += 1, _ => () } } new_op_codes.push(OpRightBracket(Some(instruction_counter))); }, _ => () } }, _ => new_op_codes.push(self.op_codes[i].clone()) } } self.op_codes = new_op_codes; } fn reset_memory(&mut self) { if self.state == State::Ready { return } for cell in self.memory.iter_mut() { *cell = 0; } self.memory_pointer = 0 } pub fn reset(&mut self) { self.reset_memory(); self.op_code_pointer = 0; self.state = State::Ready; } fn next_instruction(&mut self) -> Result<(), Error> { if self.op_code_pointer == self.op_codes.len() - 1 { return Err(Error::LastInstructionReached) } self.op_code_pointer += 1; Ok(()) } fn jump_to(&mut self, address: usize) -> Result<(), Error> { if address >= self.op_codes.len() { return Err(Error::LastInstructionReached) } self.op_code_pointer = address; Ok(()) } fn previous_instruction(&mut self) -> Result<(), Error> { if self.op_code_pointer == 0 { return Err(Error::MissingLeftBracket) } self.op_code_pointer -= 1; Ok(()) } }
36.194805
104
0.374596
e5befb10fc542b456eb345dcd450db845085116b
4,202
mod array; mod audio_dropdown; mod boolean; mod choice; mod dictionary; mod help; mod higher_order; mod notice; mod numeric; mod optional; mod reset; mod section; mod switch; mod text; mod vector; use std::collections::HashMap; pub use array::*; pub use audio_dropdown::*; pub use boolean::*; pub use choice::*; pub use dictionary::*; pub use help::*; pub use higher_order::*; pub use notice::*; pub use numeric::*; pub use optional::*; pub use reset::*; pub use section::*; pub use switch::*; pub use text::*; pub use vector::*; use crate::dashboard::RequestHandler; use iced::Element; use serde_json as json; use settings_schema::SchemaNode; enum ShowMode { Basic, Advanced, Always, } #[derive(Clone, Debug)] pub enum SettingEvent { SettingsUpdated(json::Value), Section(Box<SectionEvent>), Choice(Box<ChoiceEvent>), } pub enum SettingControl { Section(Box<SectionControl>), Choice(Box<ChoiceControl>), Optional(Box<OptionalControl>), Switch(Box<SwitchControl>), Boolean(BooleanControl), Integer(IntegerControl), Float(FloatControl), Text(TextControl), Array(Box<ArrayControl>), Vector(Box<VectorControl>), Dictionary(Box<DictionaryControl>), HigherOrder(HigherOrderControl), AudioDropdown(AudioDropdownControl), } impl SettingControl { pub fn new( path: String, schema: SchemaNode, session: json::Value, request_handler: &mut RequestHandler, ) -> Self { match schema { SchemaNode::Section { entries } => SettingControl::Section(Box::new( SectionControl::new(path, entries, session, request_handler), )), SchemaNode::Choice { default, variants } => SettingControl::Choice(Box::new( ChoiceControl::new(path, default, variants, session, request_handler), )), SchemaNode::Optional { default_set, content, } => SettingControl::Optional(Box::new(OptionalControl {})), SchemaNode::Switch { default_enabled, content_advanced, content, } => SettingControl::Switch(Box::new(SwitchControl {})), SchemaNode::Boolean { default } => { SettingControl::Boolean(BooleanControl::new(path, default, session)) } SchemaNode::Integer { default, min, max, step, gui, } => SettingControl::Integer(IntegerControl::new( path, default, min, max, step, gui, session, )), SchemaNode::Float { default, min, max, step, gui, } => SettingControl::Float(FloatControl::new( path, default, min, max, step, gui, session, )), SchemaNode::Text { default } => SettingControl::Text(TextControl {}), SchemaNode::Array(_) => SettingControl::Array(Box::new(ArrayControl {})), SchemaNode::Vector { default_element, default, } => SettingControl::Vector(Box::new(VectorControl {})), SchemaNode::Dictionary { default_key, default_value, default, } => SettingControl::Dictionary(Box::new(DictionaryControl {})), } } pub fn update(&mut self, event: SettingEvent, request_handler: &mut RequestHandler) { match (self, event) { (SettingControl::Section(control), SettingEvent::Section(event)) => { control.update(*event, request_handler) } _ => unreachable!(), } } // List of labels or left-side controls. If no controls are required, spaces must be inserted pub fn label_elements(&mut self, advanced: bool) -> Vec<Element<SettingEvent>> { todo!() } // List of right-side controls. The first one is to the right of the entry label pub fn control_elements(&mut self, advanced: bool) -> Vec<Element<SettingEvent>> { todo!() } }
28.780822
97
0.57782
72a6ea3d8a1091216f7d18f40cfcc7df64b1cf34
1,134
/* * Metal API * * This is the API for Equinix Metal Product. Interact with your devices, user account, and projects. * * The version of the OpenAPI document: 1.0.0 * Contact: [email protected] * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VolumeSnapshot { #[serde(rename = "id", skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "status", skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "timestamp", skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, #[serde(rename = "volume", skip_serializing_if = "Option::is_none")] pub volume: Option<crate::models::Href>, } impl VolumeSnapshot { pub fn new() -> VolumeSnapshot { VolumeSnapshot { id: None, status: None, created_at: None, timestamp: None, volume: None, } } }
27.658537
101
0.63933
91a76c73b31d0ec1dd4a65cf5c4dd07446f02e76
26,293
#[doc = "Register `CIR` reader"] pub struct R(crate::R<CIR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CIR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CIR_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CIR_SPEC>) -> Self { R(reader) } } #[doc = "Register `CIR` writer"] pub struct W(crate::W<CIR_SPEC>); impl core::ops::Deref for W { type Target = crate::W<CIR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<CIR_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<CIR_SPEC>) -> Self { W(writer) } } #[doc = "Clock security system interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CSSC_AW { #[doc = "1: Clear CSSF flag"] CLEAR = 1, } impl From<CSSC_AW> for bool { #[inline(always)] fn from(variant: CSSC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `CSSC` writer - Clock security system interrupt clear"] pub struct CSSC_W<'a> { w: &'a mut W, } impl<'a> CSSC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CSSC_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "Clear CSSF flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(CSSC_AW::CLEAR) } #[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 << 23)) | ((value as u32 & 0x01) << 23); self.w } } #[doc = "PLLI2S ready interrupt clear"] pub type PLLI2SRDYC_AW = LSIRDYC_AW; #[doc = "Field `PLLI2SRDYC` writer - PLLI2S ready interrupt clear"] pub struct PLLI2SRDYC_W<'a> { w: &'a mut W, } impl<'a> PLLI2SRDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLLI2SRDYC_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(PLLI2SRDYC_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | ((value as u32 & 0x01) << 21); self.w } } #[doc = "Main PLL(PLL) ready interrupt clear"] pub type PLLRDYC_AW = LSIRDYC_AW; #[doc = "Field `PLLRDYC` writer - Main PLL(PLL) ready interrupt clear"] pub struct PLLRDYC_W<'a> { w: &'a mut W, } impl<'a> PLLRDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLLRDYC_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(PLLRDYC_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | ((value as u32 & 0x01) << 20); self.w } } #[doc = "HSE ready interrupt clear"] pub type HSERDYC_AW = LSIRDYC_AW; #[doc = "Field `HSERDYC` writer - HSE ready interrupt clear"] pub struct HSERDYC_W<'a> { w: &'a mut W, } impl<'a> HSERDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSERDYC_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(HSERDYC_AW::CLEAR) } #[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 << 19)) | ((value as u32 & 0x01) << 19); self.w } } #[doc = "HSI ready interrupt clear"] pub type HSIRDYC_AW = LSIRDYC_AW; #[doc = "Field `HSIRDYC` writer - HSI ready interrupt clear"] pub struct HSIRDYC_W<'a> { w: &'a mut W, } impl<'a> HSIRDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIRDYC_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(HSIRDYC_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | ((value as u32 & 0x01) << 18); self.w } } #[doc = "LSE ready interrupt clear"] pub type LSERDYC_AW = LSIRDYC_AW; #[doc = "Field `LSERDYC` writer - LSE ready interrupt clear"] pub struct LSERDYC_W<'a> { w: &'a mut W, } impl<'a> LSERDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSERDYC_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(LSERDYC_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | ((value as u32 & 0x01) << 17); self.w } } #[doc = "LSI ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LSIRDYC_AW { #[doc = "1: Clear interrupt flag"] CLEAR = 1, } impl From<LSIRDYC_AW> for bool { #[inline(always)] fn from(variant: LSIRDYC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `LSIRDYC` writer - LSI ready interrupt clear"] pub struct LSIRDYC_W<'a> { w: &'a mut W, } impl<'a> LSIRDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSIRDYC_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(LSIRDYC_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | ((value as u32 & 0x01) << 16); self.w } } #[doc = "PLLI2S ready interrupt enable"] pub type PLLI2SRDYIE_A = LSIRDYIE_A; #[doc = "Field `PLLI2SRDYIE` reader - PLLI2S ready interrupt enable"] pub type PLLI2SRDYIE_R = LSIRDYIE_R; #[doc = "Field `PLLI2SRDYIE` writer - PLLI2S ready interrupt enable"] pub struct PLLI2SRDYIE_W<'a> { w: &'a mut W, } impl<'a> PLLI2SRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLLI2SRDYIE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(PLLI2SRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(PLLI2SRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | ((value as u32 & 0x01) << 13); self.w } } #[doc = "Main PLL (PLL) ready interrupt enable"] pub type PLLRDYIE_A = LSIRDYIE_A; #[doc = "Field `PLLRDYIE` reader - Main PLL (PLL) ready interrupt enable"] pub type PLLRDYIE_R = LSIRDYIE_R; #[doc = "Field `PLLRDYIE` writer - Main PLL (PLL) ready interrupt enable"] pub struct PLLRDYIE_W<'a> { w: &'a mut W, } impl<'a> PLLRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLLRDYIE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(PLLRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(PLLRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | ((value as u32 & 0x01) << 12); self.w } } #[doc = "HSE ready interrupt enable"] pub type HSERDYIE_A = LSIRDYIE_A; #[doc = "Field `HSERDYIE` reader - HSE ready interrupt enable"] pub type HSERDYIE_R = LSIRDYIE_R; #[doc = "Field `HSERDYIE` writer - HSE ready interrupt enable"] pub struct HSERDYIE_W<'a> { w: &'a mut W, } impl<'a> HSERDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSERDYIE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(HSERDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(HSERDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | ((value as u32 & 0x01) << 11); self.w } } #[doc = "HSI ready interrupt enable"] pub type HSIRDYIE_A = LSIRDYIE_A; #[doc = "Field `HSIRDYIE` reader - HSI ready interrupt enable"] pub type HSIRDYIE_R = LSIRDYIE_R; #[doc = "Field `HSIRDYIE` writer - HSI ready interrupt enable"] pub struct HSIRDYIE_W<'a> { w: &'a mut W, } impl<'a> HSIRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIRDYIE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(HSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(HSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | ((value as u32 & 0x01) << 10); self.w } } #[doc = "LSE ready interrupt enable"] pub type LSERDYIE_A = LSIRDYIE_A; #[doc = "Field `LSERDYIE` reader - LSE ready interrupt enable"] pub type LSERDYIE_R = LSIRDYIE_R; #[doc = "Field `LSERDYIE` writer - LSE ready interrupt enable"] pub struct LSERDYIE_W<'a> { w: &'a mut W, } impl<'a> LSERDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSERDYIE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSERDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSERDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | ((value as u32 & 0x01) << 9); self.w } } #[doc = "LSI ready interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LSIRDYIE_A { #[doc = "0: Interrupt disabled"] DISABLED = 0, #[doc = "1: Interrupt enabled"] ENABLED = 1, } impl From<LSIRDYIE_A> for bool { #[inline(always)] fn from(variant: LSIRDYIE_A) -> Self { variant as u8 != 0 } } #[doc = "Field `LSIRDYIE` reader - LSI ready interrupt enable"] pub struct LSIRDYIE_R(crate::FieldReader<bool, LSIRDYIE_A>); impl LSIRDYIE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { LSIRDYIE_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LSIRDYIE_A { match self.bits { false => LSIRDYIE_A::DISABLED, true => LSIRDYIE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { **self == LSIRDYIE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { **self == LSIRDYIE_A::ENABLED } } impl core::ops::Deref for LSIRDYIE_R { type Target = crate::FieldReader<bool, LSIRDYIE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `LSIRDYIE` writer - LSI ready interrupt enable"] pub struct LSIRDYIE_W<'a> { w: &'a mut W, } impl<'a> LSIRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSIRDYIE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u32 & 0x01) << 8); self.w } } #[doc = "Clock security system interrupt flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CSSF_A { #[doc = "0: No clock security interrupt caused by HSE clock failure"] NOTINTERRUPTED = 0, #[doc = "1: Clock security interrupt caused by HSE clock failure"] INTERRUPTED = 1, } impl From<CSSF_A> for bool { #[inline(always)] fn from(variant: CSSF_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CSSF` reader - Clock security system interrupt flag"] pub struct CSSF_R(crate::FieldReader<bool, CSSF_A>); impl CSSF_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { CSSF_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CSSF_A { match self.bits { false => CSSF_A::NOTINTERRUPTED, true => CSSF_A::INTERRUPTED, } } #[doc = "Checks if the value of the field is `NOTINTERRUPTED`"] #[inline(always)] pub fn is_not_interrupted(&self) -> bool { **self == CSSF_A::NOTINTERRUPTED } #[doc = "Checks if the value of the field is `INTERRUPTED`"] #[inline(always)] pub fn is_interrupted(&self) -> bool { **self == CSSF_A::INTERRUPTED } } impl core::ops::Deref for CSSF_R { type Target = crate::FieldReader<bool, CSSF_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "PLLI2S ready interrupt flag"] pub type PLLI2SRDYF_A = LSIRDYF_A; #[doc = "Field `PLLI2SRDYF` reader - PLLI2S ready interrupt flag"] pub type PLLI2SRDYF_R = LSIRDYF_R; #[doc = "Main PLL (PLL) ready interrupt flag"] pub type PLLRDYF_A = LSIRDYF_A; #[doc = "Field `PLLRDYF` reader - Main PLL (PLL) ready interrupt flag"] pub type PLLRDYF_R = LSIRDYF_R; #[doc = "HSE ready interrupt flag"] pub type HSERDYF_A = LSIRDYF_A; #[doc = "Field `HSERDYF` reader - HSE ready interrupt flag"] pub type HSERDYF_R = LSIRDYF_R; #[doc = "HSI ready interrupt flag"] pub type HSIRDYF_A = LSIRDYF_A; #[doc = "Field `HSIRDYF` reader - HSI ready interrupt flag"] pub type HSIRDYF_R = LSIRDYF_R; #[doc = "LSE ready interrupt flag"] pub type LSERDYF_A = LSIRDYF_A; #[doc = "Field `LSERDYF` reader - LSE ready interrupt flag"] pub type LSERDYF_R = LSIRDYF_R; #[doc = "LSI ready interrupt flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LSIRDYF_A { #[doc = "0: No clock ready interrupt"] NOTINTERRUPTED = 0, #[doc = "1: Clock ready interrupt"] INTERRUPTED = 1, } impl From<LSIRDYF_A> for bool { #[inline(always)] fn from(variant: LSIRDYF_A) -> Self { variant as u8 != 0 } } #[doc = "Field `LSIRDYF` reader - LSI ready interrupt flag"] pub struct LSIRDYF_R(crate::FieldReader<bool, LSIRDYF_A>); impl LSIRDYF_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { LSIRDYF_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LSIRDYF_A { match self.bits { false => LSIRDYF_A::NOTINTERRUPTED, true => LSIRDYF_A::INTERRUPTED, } } #[doc = "Checks if the value of the field is `NOTINTERRUPTED`"] #[inline(always)] pub fn is_not_interrupted(&self) -> bool { **self == LSIRDYF_A::NOTINTERRUPTED } #[doc = "Checks if the value of the field is `INTERRUPTED`"] #[inline(always)] pub fn is_interrupted(&self) -> bool { **self == LSIRDYF_A::INTERRUPTED } } impl core::ops::Deref for LSIRDYF_R { type Target = crate::FieldReader<bool, LSIRDYF_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bit 13 - PLLI2S ready interrupt enable"] #[inline(always)] pub fn plli2srdyie(&self) -> PLLI2SRDYIE_R { PLLI2SRDYIE_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 12 - Main PLL (PLL) ready interrupt enable"] #[inline(always)] pub fn pllrdyie(&self) -> PLLRDYIE_R { PLLRDYIE_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 11 - HSE ready interrupt enable"] #[inline(always)] pub fn hserdyie(&self) -> HSERDYIE_R { HSERDYIE_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - HSI ready interrupt enable"] #[inline(always)] pub fn hsirdyie(&self) -> HSIRDYIE_R { HSIRDYIE_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - LSE ready interrupt enable"] #[inline(always)] pub fn lserdyie(&self) -> LSERDYIE_R { LSERDYIE_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - LSI ready interrupt enable"] #[inline(always)] pub fn lsirdyie(&self) -> LSIRDYIE_R { LSIRDYIE_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - Clock security system interrupt flag"] #[inline(always)] pub fn cssf(&self) -> CSSF_R { CSSF_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 5 - PLLI2S ready interrupt flag"] #[inline(always)] pub fn plli2srdyf(&self) -> PLLI2SRDYF_R { PLLI2SRDYF_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - Main PLL (PLL) ready interrupt flag"] #[inline(always)] pub fn pllrdyf(&self) -> PLLRDYF_R { PLLRDYF_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - HSE ready interrupt flag"] #[inline(always)] pub fn hserdyf(&self) -> HSERDYF_R { HSERDYF_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - HSI ready interrupt flag"] #[inline(always)] pub fn hsirdyf(&self) -> HSIRDYF_R { HSIRDYF_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - LSE ready interrupt flag"] #[inline(always)] pub fn lserdyf(&self) -> LSERDYF_R { LSERDYF_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - LSI ready interrupt flag"] #[inline(always)] pub fn lsirdyf(&self) -> LSIRDYF_R { LSIRDYF_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 23 - Clock security system interrupt clear"] #[inline(always)] pub fn cssc(&mut self) -> CSSC_W { CSSC_W { w: self } } #[doc = "Bit 21 - PLLI2S ready interrupt clear"] #[inline(always)] pub fn plli2srdyc(&mut self) -> PLLI2SRDYC_W { PLLI2SRDYC_W { w: self } } #[doc = "Bit 20 - Main PLL(PLL) ready interrupt clear"] #[inline(always)] pub fn pllrdyc(&mut self) -> PLLRDYC_W { PLLRDYC_W { w: self } } #[doc = "Bit 19 - HSE ready interrupt clear"] #[inline(always)] pub fn hserdyc(&mut self) -> HSERDYC_W { HSERDYC_W { w: self } } #[doc = "Bit 18 - HSI ready interrupt clear"] #[inline(always)] pub fn hsirdyc(&mut self) -> HSIRDYC_W { HSIRDYC_W { w: self } } #[doc = "Bit 17 - LSE ready interrupt clear"] #[inline(always)] pub fn lserdyc(&mut self) -> LSERDYC_W { LSERDYC_W { w: self } } #[doc = "Bit 16 - LSI ready interrupt clear"] #[inline(always)] pub fn lsirdyc(&mut self) -> LSIRDYC_W { LSIRDYC_W { w: self } } #[doc = "Bit 13 - PLLI2S ready interrupt enable"] #[inline(always)] pub fn plli2srdyie(&mut self) -> PLLI2SRDYIE_W { PLLI2SRDYIE_W { w: self } } #[doc = "Bit 12 - Main PLL (PLL) ready interrupt enable"] #[inline(always)] pub fn pllrdyie(&mut self) -> PLLRDYIE_W { PLLRDYIE_W { w: self } } #[doc = "Bit 11 - HSE ready interrupt enable"] #[inline(always)] pub fn hserdyie(&mut self) -> HSERDYIE_W { HSERDYIE_W { w: self } } #[doc = "Bit 10 - HSI ready interrupt enable"] #[inline(always)] pub fn hsirdyie(&mut self) -> HSIRDYIE_W { HSIRDYIE_W { w: self } } #[doc = "Bit 9 - LSE ready interrupt enable"] #[inline(always)] pub fn lserdyie(&mut self) -> LSERDYIE_W { LSERDYIE_W { w: self } } #[doc = "Bit 8 - LSI ready interrupt enable"] #[inline(always)] pub fn lsirdyie(&mut self) -> LSIRDYIE_W { LSIRDYIE_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "clock interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cir](index.html) module"] pub struct CIR_SPEC; impl crate::RegisterSpec for CIR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [cir::R](R) reader structure"] impl crate::Readable for CIR_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [cir::W](W) writer structure"] impl crate::Writable for CIR_SPEC { type Writer = W; } #[doc = "`reset()` method sets CIR to value 0"] impl crate::Resettable for CIR_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
30.644522
408
0.574754
e8ec504ee74e1b62c3ea13c0a2679f8c1f7848e1
14,175
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)] // This doesn't seem to cause any issues and nobody I know can read \u{1234} by heart. #![allow(clippy::non_ascii_literal)] mod error; mod tarsum; mod types; use anyhow::{bail, Context, Result}; use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use std::collections::BTreeMap; use std::ffi; use std::fs::File; use std::io::{self, BufReader, BufWriter, Write}; use std::path; use types::{HashSum, PackMode, PackType, Platform}; const DEFAULT_PACKLIST: &str = include_str!("packlist.yaml"); // This is to ensure that all progress bar prefixes are aligned. const PROGRESS_PREFIX_LEN: usize = 24; fn expand_tilde_path(path: &ffi::OsStr) -> Result<path::PathBuf> { Ok(path::PathBuf::from( shellexpand::tilde( &path .to_str() .ok_or_else(|| anyhow::anyhow!("Not a valid path: {:?}", path))?, ) .to_string(), )) } #[derive(clap::Parser, Debug)] #[clap(author, version, about)] struct Args { /// Directory to write output files to. #[clap(short, long, parse(from_os_str), default_value = ".")] output: path::PathBuf, /// Flipper dist directory to read from. #[clap( short, long, parse(try_from_os_str = expand_tilde_path), default_value = "~/fbsource/xplat/sonar/dist" )] dist: path::PathBuf, /// Custom list of files to pack. #[clap(short, long, parse(from_os_str))] packlist: Option<path::PathBuf>, /// Skip compressing the archives (for debugging) #[clap(long)] no_compression: bool, /// Platform to build for #[clap(value_name = "PLATFORM")] platform: Platform, } type PackListPlatform = BTreeMap<PackType, Vec<String>>; #[derive(Debug, serde::Deserialize)] struct PackListSpec { mode: PackMode, basedir: path::PathBuf, files: PackListPlatform, } #[derive(Debug, serde::Deserialize)] struct PackList(pub BTreeMap<Platform, PackListSpec>); #[derive(Debug, serde::Serialize)] struct PackFile { file_name: String, intrinsic_checksum: HashSum, extrinsic_checksum: HashSum, file_bytes: u64, } #[derive(Debug, serde::Serialize)] struct PackManifest { files: BTreeMap<PackType, PackFile>, } fn default_progress_bar(len: u64) -> indicatif::ProgressBar { let pb = indicatif::ProgressBar::new(len as u64 * 2); pb.set_style( indicatif::ProgressStyle::default_bar() .template("{prefix:.bold}β–•{bar:.magenta}▏{msg}") .progress_chars("β–ˆβ–“β–’β–‘ "), ); pb } fn pack( platform: &Platform, dist_dir: &std::path::Path, pack_list: &PackList, output_directory: &std::path::Path, ) -> Result<Vec<(PackType, path::PathBuf)>> { let pb = default_progress_bar(pack_list.0.len() as u64 * 2 - 1); pb.set_prefix(format!( "{:width$}", "Packing archives", width = PROGRESS_PREFIX_LEN )); let packlist_spec = pack_list .0 .get(platform) .ok_or_else(|| error::Error::MissingPlatformDefinition(platform.clone()))?; let base_dir = path::Path::new(dist_dir).join(&packlist_spec.basedir); let files = &packlist_spec.files; let res = files .into_par_iter() .map(|(&pack_type, pack_files)| { let output_path = path::Path::new(output_directory).join(format!("{}.tar", pack_type)); let mut tar = tar::Builder::new(File::create(&output_path).with_context(|| { format!( "Couldn't open file for writing: {}", &output_path.to_string_lossy() ) })?); // MacOS uses symlinks for bundling multiple framework versions and pointing // to the "Current" one. tar.follow_symlinks(false); let pack_platform_fn = match packlist_spec.mode { types::PackMode::Exact => pack_platform_exact, types::PackMode::Glob => pack_platform_glob, }; pack_platform_fn(platform, &base_dir, pack_files, pack_type, &mut tar)?; pb.inc(1); tar.finish()?; pb.inc(1); Ok((pack_type, output_path)) }) .collect(); pb.finish(); res } fn pack_platform_glob( platform: &Platform, base_dir: &path::Path, pack_files: &[String], pack_type: PackType, tar_builder: &mut tar::Builder<File>, ) -> Result<()> { let mut ov = ignore::overrides::OverrideBuilder::new(base_dir); for f in pack_files { ov.add(f.as_ref())?; } let walker = ignore::WalkBuilder::new(base_dir) // Otherwise we'll include .ignore files, etc. .standard_filters(false) // This is a big restriction. We won't traverse directories at all. // If we did, we could no longer make use of tar's `append_dir_all` // method which does a lot of clever stuff about symlinks, etc. .max_depth(Some(1)) .overrides(ov.build()?) .build(); // The first entry is the root dir, which we don't care about. for f in walker.into_iter().skip(1) { let dir_entry = f?; let path = dir_entry.file_name(); let full_path = path::Path::new(&base_dir).join(&path); if !full_path.exists() { bail!(error::Error::MissingPackFile( platform.clone(), pack_type, full_path, )); } if full_path.is_file() { tar_builder.append_path_with_name(full_path, &path)?; } else if full_path.is_dir() { tar_builder.append_dir_all(path, full_path)?; } } Ok(()) } fn pack_platform_exact( platform: &Platform, base_dir: &path::Path, pack_files: &[String], pack_type: PackType, tar_builder: &mut tar::Builder<File>, ) -> Result<()> { for f in pack_files { let full_path = path::Path::new(&base_dir).join(f); if !full_path.exists() { bail!(error::Error::MissingPackFile( platform.clone(), pack_type, full_path, )); } if full_path.is_file() { tar_builder.append_path_with_name(full_path, f)?; } else if full_path.is_dir() { tar_builder.append_dir_all(f, full_path)?; } } Ok(()) } /// Calculate the sha256 checksum of a file represented by a Reader. fn sha256_digest<R: io::Read>(mut reader: &mut R) -> Result<HashSum> { use sha2::{Digest, Sha256}; let mut sha256 = Sha256::new(); std::io::copy(&mut reader, &mut sha256)?; let hash = sha256.finalize(); Ok(HashSum(data_encoding::HEXLOWER.encode(&hash))) } fn main() -> Result<(), anyhow::Error> { use clap::Parser; let args = Args::parse(); let pack_list_str = args.packlist.as_ref().map_or_else( || DEFAULT_PACKLIST.to_string(), |f| { std::fs::read_to_string(&f) .unwrap_or_else(|e| panic!("Failed to open packfile {:?}: {}", &f, e)) }, ); let pack_list: PackList = serde_yaml::from_str(&pack_list_str).expect("Failed to deserialize YAML packlist."); std::fs::create_dir_all(&args.output) .with_context(|| format!("Failed to create output directory '{:?}'.", &args.output))?; let archive_paths = pack(&args.platform, &args.dist, &pack_list, &args.output)?; let compressed_archive_paths = if args.no_compression { None } else { Some(compress_paths(&archive_paths)?) }; manifest(&archive_paths, &compressed_archive_paths, &args.output)?; Ok(()) } /// Takes a list of archive paths, compresses them with LZMA and returns /// the updated paths. /// TODO: Remove compressed artifacts. fn compress_paths( archive_paths: &[(PackType, path::PathBuf)], ) -> Result<Vec<(PackType, path::PathBuf)>> { let pb = default_progress_bar(archive_paths.len() as u64 - 1); pb.set_prefix(format!( "{:width$}", "Compressing archives", width = PROGRESS_PREFIX_LEN )); let res = archive_paths .into_par_iter() .map(|(pack_type, path)| { let input_file = File::open(&path).with_context(|| { format!("Failed to open archive '{}'.", &path.to_string_lossy()) })?; let mut reader = BufReader::new(input_file); let mut output_path = path::PathBuf::from(path); output_path.set_extension("tar.xz"); let output_file: File = File::create(&output_path).with_context(|| { format!( "Failed opening compressed archive '{}' for writing.", &output_path.to_string_lossy() ) })?; let writer = BufWriter::new(output_file); let mut encoder = xz2::write::XzEncoder::new(writer, 9); std::io::copy(&mut reader, &mut encoder)?; pb.inc(1); Ok((*pack_type, output_path)) }) .collect::<Result<Vec<(PackType, path::PathBuf)>>>()?; pb.finish(); Ok(res) } fn manifest( archive_paths: &[(PackType, path::PathBuf)], compressed_archive_paths: &Option<Vec<(PackType, path::PathBuf)>>, output_directory: &path::Path, ) -> Result<path::PathBuf> { let archive_manifest = gen_manifest(archive_paths, compressed_archive_paths)?; write_manifest(output_directory, &archive_manifest) } fn write_manifest( output_directory: &path::Path, archive_manifest: &PackManifest, ) -> Result<path::PathBuf> { let path = path::PathBuf::from(output_directory).join("manifest.json"); let mut file = File::create(&path) .with_context(|| format!("Failed to write manifest to {}", &path.to_string_lossy()))?; file.write_all(serde_json::to_string_pretty(archive_manifest)?.as_bytes())?; Ok(path) } fn gen_manifest( archive_paths: &[(PackType, path::PathBuf)], compressed_archive_paths: &Option<Vec<(PackType, path::PathBuf)>>, ) -> Result<PackManifest> { Ok(PackManifest { files: gen_manifest_files(archive_paths, compressed_archive_paths)?, }) } fn gen_manifest_files( archive_paths: &[(PackType, path::PathBuf)], compressed_archive_paths: &Option<Vec<(PackType, path::PathBuf)>>, ) -> Result<BTreeMap<PackType, PackFile>> { use std::iter; let pb = default_progress_bar((archive_paths.len() as u64 - 1) * 2); pb.set_prefix(format!( "{:width$}", "Computing manifest", width = PROGRESS_PREFIX_LEN )); // This looks like a lot but we're just creating an iterator that either returns the // values of `compressed_archive_paths` if it is `Some(_)` or an infinite repetition // of `None`. This allows us to zip it below and avoid having to rely on index // arithmetic. The `as _` is necessary to tell rustc to perform the casts from // something like a `std::iter::Map` to the `Iterator` trait. let compressed_iter: Box<dyn Iterator<Item = Option<&(PackType, path::PathBuf)>>> = compressed_archive_paths.as_ref().map_or_else( || Box::new(iter::repeat(None)) as _, |inner| Box::new(inner.iter().map(Some)) as _, ); let res = archive_paths .iter() .zip(compressed_iter) .collect::<Vec<_>>() .into_par_iter() .map(|((pack_type, uncompressed_path), compressed)| { // If we have a compressed path, use that one, otherwise fall back to uncompressed. let path = compressed.map_or(uncompressed_path, |(_, p)| p); let file_bytes = File::open(path)?.metadata()?.len(); let uncompressed_reader = BufReader::new(File::open(uncompressed_path)?); let intrinsic_checksum = tarsum::tarsum(uncompressed_reader)?; pb.inc(1); let extrinsic_checksum = sha256_digest(&mut BufReader::new(File::open(path)?))?; pb.inc(1); Ok(( *pack_type, PackFile { file_name: path .file_name() // The file name is only indicative and must serialize well, so the lossy approximation is fine. .map_or_else(|| "".to_string(), |v| v.to_string_lossy().to_string()), intrinsic_checksum, extrinsic_checksum, file_bytes, }, )) }) .collect::<Result<Vec<_>>>()? .into_iter() .fold( BTreeMap::new(), |mut acc: BTreeMap<_, _>, (pack_type, pack_file)| { acc.insert(pack_type, pack_file); acc }, ); pb.finish(); Ok(res) } #[cfg(test)] mod test { use super::*; #[test] fn test_included_packlist_parses() { let res: PackList = serde_yaml::from_str(DEFAULT_PACKLIST).expect("Default packlist doesn't deserialize"); assert_eq!(res.0.len(), 4); } #[test] fn test_manifest() -> anyhow::Result<()> { let artifact_path = path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("src") .join("__fixtures__") .join("archive_a.tar"); let tmp_dir = tempdir::TempDir::new("manifest_test")?; let archive_paths = &[(PackType::Core, artifact_path)]; let path = manifest(archive_paths, &None, tmp_dir.path())?; let manifest_content = std::fs::read_to_string(&path)?; assert_eq!( manifest_content, "{\n \"files\": {\n \"core\": {\n \"file_name\": \"archive_a.tar\",\n \"intrinsic_checksum\": \"f360fae5e433bd5c0ac0e00dbdad22ec51691139b9ec1e6d0dbbe16e0bb4c568\",\n \"extrinsic_checksum\": \"8de80c3904d85115d1595d48c215022e5db225c920811d4d2eee80586e6390c8\",\n \"file_bytes\": 3072\n }\n }\n}" ); Ok(()) } }
33.75
334
0.595838
67d42967722a169684443d866a3e7c14e6225364
1,226
use mun_syntax::{ast, SmolStr}; use std::fmt; /// `Name` is a wrapper around string, which is used in hir for both references /// and declarations. #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Name { text: SmolStr, } impl fmt::Display for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.text, f) } } impl fmt::Debug for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.text, f) } } impl Name { const fn new(text: SmolStr) -> Name { Name { text } } pub(crate) fn missing() -> Name { Name::new("[missing name]".into()) } } pub(crate) trait AsName { fn as_name(&self) -> Name; } impl AsName for ast::NameRef { fn as_name(&self) -> Name { Name::new(self.text().clone()) } } impl AsName for ast::Name { fn as_name(&self) -> Name { Name::new(self.text().clone()) } } pub(crate) const FLOAT: Name = Name::new(SmolStr::new_inline_from_ascii(5, b"float")); pub(crate) const INT: Name = Name::new(SmolStr::new_inline_from_ascii(3, b"int")); pub(crate) const BOOLEAN: Name = Name::new(SmolStr::new_inline_from_ascii(4, b"bool"));
23.576923
87
0.607667
216cd3c95c0642e35b18564c9de9ee0053b824b3
2,414
use std::num::FpCategory; use iced::widget::pane_grid::Line; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use crate::common::debug_str; use crate::format_to_py; use crate::wrapped::color::ColorFormat; use crate::wrapped::WrappedColor; pub(crate) fn init_mod(_py: Python, m: &PyModule) -> PyResult<()> { m.add_class::<WrappedLine>()?; Ok(()) } /// Line(color, width) /// -- /// /// A line. /// /// It is normally used to define the highlight of something, like a split. /// /// Parameters /// ---------- /// color : Color /// The color of the line. /// width : float /// The width of the line. /// /// See also /// -------- /// `iced::widget::pane_grid::Line <https://docs.rs/iced/0.3.0/iced/widget/pane_grid/struct.Line.html>`_ #[pyclass(name = "Line", module = "pyiced")] #[derive(Debug, Clone)] pub(crate) struct WrappedLine(pub Line); #[pymethods] impl WrappedLine { #[new] fn new(color: &WrappedColor, width: f32) -> PyResult<Self> { let width = match width.classify() { FpCategory::Nan | FpCategory::Infinite => { return Err(PyErr::new::<PyValueError, _>("The width must be finite")); }, FpCategory::Zero | FpCategory::Subnormal => 0.0f32, FpCategory::Normal => { if width < 0.0 { return Err(PyErr::new::<PyValueError, _>("The width must be >= 0")); } width }, }; Ok(Self(Line { color: color.0, width, })) } /// The color of the line. /// /// Returns /// ------- /// Color /// The "color" parameter given when constructing this line. #[getter] fn color(&self) -> WrappedColor { WrappedColor(self.0.color) } /// The width of the line. /// /// Returns /// ------- /// float /// The "width" parameter given when constructing this line. #[getter] fn width(&self) -> f32 { self.0.width } #[classattr] #[allow(non_snake_case)] fn __match_args__() -> (&'static str, &'static str) { ("color", "width") } fn __str__(&self) -> PyResult<String> { debug_str(&self.0) } fn __repr__(&self) -> PyResult<String> { let Line { ref color, width } = self.0; format_to_py!("Line({}, {}", ColorFormat(color), width) } }
24.886598
104
0.539354
ab33a7988a6589f5dac643d4b43032a2e388720e
5,828
use bitcoind::bitcoincore_rpc::Client; use bitcoind::BitcoinD; use std::ffi::OsStr; use std::fmt; pub use bitcoind; pub use bitcoind::bitcoincore_rpc; mod versions; pub struct ElementsD(BitcoinD); #[non_exhaustive] pub struct Conf<'a>(bitcoind::Conf<'a>); /// All the possible error in this crate pub enum Error { /// Wrapper of bitcoind Error BitcoinD(bitcoind::Error), /// Returned when calling methods requiring a feature to be activated, but it's not NoFeature, /// Returned when calling methods requiring a env var to exist, but it's not NoEnvVar, /// Returned when calling methods requiring either a feature or env var, but both are absent NeitherFeatureNorEnvVar, /// Returned when calling methods requiring either a feature or anv var, but both are present BothFeatureAndEnvVar, } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::BitcoinD(e) => write!(f, "{:?}", e), Error::NoFeature => write!(f, "Called a method requiring a feature to be set, but it's not"), Error::NoEnvVar => write!(f, "Called a method requiring env var `ELEMENTSD_EXE` to be set, but it's not"), Error::NeitherFeatureNorEnvVar => write!(f, "Called a method requiring env var `ELEMENTSD_EXE` or a feature to be set, but neither are set"), Error::BothFeatureAndEnvVar => write!(f, "Called a method requiring env var `ELEMENTSD_EXE` or a feature to be set, but both are set"), } } } impl Conf<'_> { pub fn new(validate_pegin: Option<&BitcoinD>) -> Self { let mut bitcoind_conf = bitcoind::Conf::default(); let mut args = vec![ "-fallbackfee=0.0001", "-dustrelayfee=0.00000001", "-chain=liquidregtest", "-initialfreecoins=2100000000", ]; match validate_pegin.as_ref() { Some(bitcoind) => { args.push("-validatepegin=1"); args.push(string_to_static_str(format!( "-mainchainrpccookiefile={}", bitcoind.params.cookie_file.display() ))); args.push(string_to_static_str(format!( "-mainchainrpchost={}", bitcoind.params.rpc_socket.ip() ))); args.push(string_to_static_str(format!( "-mainchainrpcport={}", bitcoind.params.rpc_socket.port() ))); } None => { args.push("-validatepegin=0"); } } bitcoind_conf.args = args; bitcoind_conf.network = "liquidregtest"; Conf(bitcoind_conf) } } impl Default for Conf<'_> { fn default() -> Self { Self::new(None) } } impl ElementsD { /// Launch the elementsd process from the given `exe` executable with default args. /// /// Waits for the node to be ready to accept connections before returning pub fn new<S: AsRef<OsStr>>(exe: S) -> Result<ElementsD, Error> { ElementsD::with_conf(exe, &Conf::default()) } /// Launch the elementsd process from the given `exe` executable with given [Conf] param pub fn with_conf<S: AsRef<OsStr>>(exe: S, conf: &Conf) -> Result<ElementsD, Error> { Ok(ElementsD(BitcoinD::with_conf(exe, &conf.0)?)) } pub fn client(&self) -> &Client { &self.0.client } } /// Returns the daemons executable path, if it's provided as a feature or as `ELEMENTSD_EXE` env var /// If both are set, the one provided by the feature is returned pub fn exe_path() -> Result<String, Error> { match (downloaded_exe_path(), std::env::var("ELEMENTSD_EXE")) { (Ok(_), Ok(_)) => Err(Error::BothFeatureAndEnvVar), (Ok(path), Err(_)) => Ok(path), (Err(_), Ok(path)) => Ok(path), (Err(_), Err(_)) => Err(Error::NeitherFeatureNorEnvVar), } } /// Provide the bitcoind executable path if a version feature has been specified pub fn downloaded_exe_path() -> Result<String, Error> { if versions::HAS_FEATURE { Ok(format!( "{}/elements/elements-{}/bin/elementsd", env!("OUT_DIR"), versions::VERSION )) } else { Err(Error::NoFeature) } } impl From<bitcoind::Error> for Error { fn from(e: bitcoind::Error) -> Self { Error::BitcoinD(e) } } //TODO remove this bad code once Conf::args is not Vec<&str> fn string_to_static_str(s: String) -> &'static str { Box::leak(s.into_boxed_str()) } #[cfg(test)] mod tests { use crate::{exe_path, Conf, ElementsD}; use bitcoind::bitcoincore_rpc::jsonrpc::serde_json::Value; use bitcoind::bitcoincore_rpc::RpcApi; use bitcoind::BitcoinD; #[test] fn test_elementsd() { let exe = init(); let elementsd = ElementsD::new(exe).unwrap(); let info = elementsd .client() .call::<Value>("getblockchaininfo", &[]) .unwrap(); assert_eq!(info.get("chain").unwrap(), "liquidregtest"); } #[test] fn test_elementsd_with_validatepegin() { let bitcoind_exe = bitcoind::exe_path().unwrap(); let bitcoind_conf = bitcoind::Conf::default(); let bitcoind = BitcoinD::with_conf(&bitcoind_exe, &bitcoind_conf).unwrap(); let conf = Conf::new(Some(&bitcoind)); let exe = init(); let elementsd = ElementsD::with_conf(exe, &conf).unwrap(); let info = elementsd .client() .call::<Value>("getblockchaininfo", &[]) .unwrap(); assert_eq!(info.get("chain").unwrap(), "liquidregtest"); } fn init() -> String { let _ = env_logger::try_init(); exe_path().unwrap() } }
32.926554
154
0.59197
2ff6df27fb4373ac49fbb15d8f9e491306baf26d
7,733
// // // //! Generic directional scrollbar use geom::Rect; use surface::Colour; trait Theme { fn control_detail(&self) -> Colour; fn control_background(&self) -> Colour; } struct FixedTheme; impl Theme for FixedTheme { fn control_detail(&self) -> Colour { Colour::from_argb32(0xFF_909090) } //fn control_detail_disabled(&self) -> Colour { // Colour::from_argb32(0xFF_C0C0C0) //} fn control_background(&self) -> Colour { Colour::from_argb32(0xFF_F0F0F0) } } pub struct Widget<D> { dir: D, state: ::std::cell::RefCell<State>, } #[derive(Default)] struct State { dirty: bool, /// Current scrollbar mid position (in value-space) value_cur: usize, /// Size of the scrollbar value_size: usize, /// Maximum value for `value_cur` (sum of value_cur and value_size shouldn't exceed this) value_limit: usize, /// Total number of pixels available in the bar region bar_cap: u32, // (calculated) bar_start: u32, bar_size: u32, } const MIN_HANDLE_LENGTH: u32 = 11; // 3 lines, padding*4, border*2 const ARROW_SIZE: u32 = 5; // 5px high/wide arrow pub trait Direction: Default { /// Turn cartesian into short/long coords fn to_sl(&self, w: u32, h: u32) -> (u32,u32); /// Turn short/long into cartesian fn from_sl(&self, short: u32, long: u32) -> (u32,u32); fn draw_arrow(&self, suraface: ::surface::SurfaceView, side_is_low: bool); fn draw_grip(&self, suraface: ::surface::SurfaceView); fn name(&self) -> &'static str; } #[derive(Default)] pub struct Vertical; impl Direction for Vertical { fn to_sl(&self, w: u32, h: u32) -> (u32,u32) { (w, h) } fn from_sl(&self, short: u32, long: u32) -> (u32,u32) { (short, long) } fn draw_arrow(&self, surface: ::surface::SurfaceView, side_is_low: bool) { let midpt_x = surface.width() / 2; let midpt_y = surface.height() / 2; let surface = surface.slice(Rect::new(midpt_x - ARROW_SIZE, midpt_y - ARROW_SIZE/2, ARROW_SIZE*2,ARROW_SIZE*2)); for row in 0 .. ARROW_SIZE { let npx = if side_is_low { (row + 1) * 2 } else { ARROW_SIZE*2 - row * 2 }; surface.fill_rect( Rect::new(ARROW_SIZE - npx/2, row, npx, 1), FixedTheme.control_detail() ); } } fn draw_grip(&self, surface: ::surface::SurfaceView) { const SIZE: u32 = 7; const MARGIN: u32 = 2; let surface = surface.slice(Rect::new(0, surface.height()/2 - SIZE/2, !0,SIZE)); // Three lines at +1, +3, +5 surface.fill_rect( Rect::new(MARGIN,1, surface.width()-MARGIN*2,1), FixedTheme.control_detail() ); surface.fill_rect( Rect::new(MARGIN,3, surface.width()-MARGIN*2,1), FixedTheme.control_detail() ); surface.fill_rect( Rect::new(MARGIN,5, surface.width()-MARGIN*2,1), FixedTheme.control_detail() ); } fn name(&self) -> &'static str { "vert" } } #[derive(Default)] pub struct Horizontal; impl Direction for Horizontal { fn to_sl(&self, w: u32, h: u32) -> (u32,u32) { (h, w) } fn from_sl(&self, short: u32, long: u32) -> (u32,u32) { (long, short) } fn draw_arrow(&self, surface: ::surface::SurfaceView, side_is_low: bool) { let midpt_x = surface.width() / 2; let midpt_y = surface.height() / 2; let surface = surface.slice(Rect::new(midpt_x - ARROW_SIZE/2, midpt_y - ARROW_SIZE, ARROW_SIZE*2,ARROW_SIZE*2)); for row in 0 .. ARROW_SIZE { let npx = row; let startx = if side_is_low { ARROW_SIZE - row } else { 0 }; surface.fill_rect( Rect::new(startx, row, npx, 1), FixedTheme.control_detail() ); surface.fill_rect( Rect::new(startx, ARROW_SIZE*2 - row, npx, 1), FixedTheme.control_detail() ); } surface.fill_rect( Rect::new(0, ARROW_SIZE, ARROW_SIZE, 1), FixedTheme.control_detail() ); } fn draw_grip(&self, surface: ::surface::SurfaceView) { const SIZE: u32 = 7; const MARGIN: u32 = 2; let surface = surface.slice(Rect::new(surface.width()/2 - SIZE/2,0, SIZE,!0)); // Three lines at +2, +4, +6 surface.fill_rect( Rect::new(1,MARGIN, 1, surface.height()-MARGIN*2), FixedTheme.control_detail() ); surface.fill_rect( Rect::new(3,MARGIN, 1, surface.height()-MARGIN*2), FixedTheme.control_detail() ); surface.fill_rect( Rect::new(5,MARGIN, 1, surface.height()-MARGIN*2), FixedTheme.control_detail() ); } fn name(&self) -> &'static str { "horiz" } } impl<D> Widget<D> where D: Direction { fn new_() -> Widget<D> { Widget { state: Default::default(), dir: D::default(), } } /// Set (capacity, handke_size) /// NOTE: The size must be <= the capacity pub fn set_bar(&self, bar: Option<(usize, usize)>) { let mut s = self.state.borrow_mut(); if let Some( (cap, size) ) = bar { assert!( size <= cap ); s.value_limit = cap; s.value_size = size; } else { s.value_limit = 0; s.value_size = 1; } s.recalculate(); } pub fn set_pos(&self, cap: usize) { let mut st = self.state.borrow_mut(); st.value_cur = cap; st.recalculate(); } pub fn get_pos(&self) -> usize { self.state.borrow().value_cur } } impl Widget<Vertical> { pub fn new() -> Widget<Vertical> { Self::new_() } } impl Widget<Horizontal> { pub fn new() -> Widget<Horizontal> { Self::new_() } } impl<D> ::Element for Widget<D> where D: Direction { fn resize(&self, w: u32, h: u32) { let (sd, ld) = self.dir.to_sl(w, h); let mut state = self.state.borrow_mut(); state.dirty = true; state.bar_cap = ld - 2*sd; state.recalculate(); } fn render(&self, surface: ::surface::SurfaceView, force: bool) { if force { surface.fill_rect(Rect::new(0,0,!0,!0), FixedTheme.control_background()); } let (short_d, long_d) = self.dir.to_sl(surface.width(), surface.height()); if force { let r = Rect::new(0,0, short_d,short_d); kernel_log!("{} start r={:?}", self.dir.name(), r); surface.draw_rect(r, ::geom::Px(1), FixedTheme.control_detail()); self.dir.draw_arrow(surface.slice(r), true); } let mut state = self.state.borrow_mut(); if force || ::std::mem::replace(&mut state.dirty, false) { // Background let (x,y) = self.dir.from_sl(0, short_d); let (w,h) = self.dir.from_sl(short_d, long_d - 2*short_d); surface.fill_rect(Rect::new(x,y, w,h), FixedTheme.control_background()); // Indicator outline let (x,y) = self.dir.from_sl(0, short_d + state.bar_start); let (w,h) = self.dir.from_sl(short_d, state.bar_size); let r = Rect::new(x,y, w,h); kernel_log!("{} bar r={:?}", self.dir.name(), r); surface.draw_rect(r, ::geom::Px(1), FixedTheme.control_detail()); // Indicator grip self.dir.draw_grip( surface.slice(r) ); } if force { let (x,y) = self.dir.from_sl(0, long_d - short_d); let r = Rect::new(x,y, short_d,short_d); kernel_log!("{} end r={:?}", self.dir.name(), r); surface.draw_rect(r, ::geom::Px(1), FixedTheme.control_detail()); self.dir.draw_arrow(surface.slice(r), false); } } fn with_element_at_pos(&self, pos: ::geom::PxPos, _dims: ::geom::PxDims, f: ::WithEleAtPosCb) -> bool { f(self, pos) } } impl State { fn recalculate(&mut self) { fn div_round(n: u64, d: u64) -> u64 { (n + d/2) / d } if self.value_limit == 0 || self.value_size > self.value_limit { self.bar_start = 0; self.bar_size = self.bar_cap; } else { let start = div_round(self.value_cur as u64 * self.bar_cap as u64, self.value_limit as u64) as u32; let size = div_round(self.value_size as u64 * self.bar_cap as u64, self.value_limit as u64) as u32; if size < MIN_HANDLE_LENGTH { let midpt = start + size / 2; if midpt < MIN_HANDLE_LENGTH/2 { self.bar_start = 0; } else { self.bar_start = midpt - MIN_HANDLE_LENGTH/2; } self.bar_size = MIN_HANDLE_LENGTH; } else { self.bar_start = start; self.bar_size = size; } } kernel_log!("State = {{ bar_start: {}, bar_size: {}, bar_cap: {} }}", self.bar_start, self.bar_size, self.bar_cap); } }
27.816547
114
0.64839
1e0d4fa38e17d3f148625b11513433655f498e1f
1,980
pub struct IconTungsten { props: crate::Props, } impl yew::Component for IconTungsten { type Properties = crate::Props; type Message = (); fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender { true } fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender { false } fn view(&self) -> yew::prelude::Html { yew::prelude::html! { <svg class=self.props.class.unwrap_or("") width=self.props.size.unwrap_or(24).to_string() height=self.props.size.unwrap_or(24).to_string() viewBox="0 0 24 24" fill=self.props.fill.unwrap_or("none") stroke=self.props.color.unwrap_or("currentColor") stroke-width=self.props.stroke_width.unwrap_or(2).to_string() stroke-linecap=self.props.stroke_linecap.unwrap_or("round") stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round") > <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><path d="M0,0h24v24H0V0z" fill="none"/></g><g><g><rect height="3" width="2" x="11" y="19"/><rect height="2" width="3" x="2" y="11"/><rect height="2" width="3" x="19" y="11"/><rect height="3" transform="matrix(0.7071 -0.7071 0.7071 0.7071 -7.6665 17.8014)" width="1.99" x="16.66" y="16.66"/><rect height="1.99" transform="matrix(0.7071 -0.7071 0.7071 0.7071 -10.9791 9.8041)" width="3" x="4.85" y="17.16"/><path d="M15,8.02V3H9v5.02C7.79,8.94,7,10.37,7,12c0,2.76,2.24,5,5,5s5-2.24,5-5C17,10.37,16.21,8.94,15,8.02z M11,5h2v2.1 C12.68,7.04,12.34,7,12,7s-0.68,0.04-1,0.1V5z M12,15c-1.65,0-3-1.35-3-3s1.35-3,3-3c1.65,0,3,1.35,3,3S13.65,15,12,15z"/></g></g></svg> </svg> } } }
43.043478
789
0.583333
7a1d43140cd391c553f20fc88b13de8fff27c54e
1,934
//! This crate provides agda language support for the [tree-sitter][] parsing library. //! //! Typically, you will use the [language][language func] function to add this language to a //! tree-sitter [Parser][], and then use the parser to parse some code: //! //! ``` //! let code = ""; //! let mut parser = tree_sitter::Parser::new(); //! parser.set_language(tree_sitter_agda::language()).expect("Error loading agda grammar"); //! let tree = parser.parse(code, None).unwrap(); //! ``` //! //! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html //! [language func]: fn.language.html //! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html //! [tree-sitter]: https://tree-sitter.github.io/ use tree_sitter::Language; extern "C" { fn tree_sitter_agda() -> Language; } /// Get the tree-sitter [Language][] for this grammar. /// /// [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html pub fn language() -> Language { unsafe { tree_sitter_agda() } } /// The content of the [`node-types.json`][] file for this grammar. /// /// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types pub const NODE_TYPES: &'static str = include_str!("../../src/node-types.json"); // Uncomment these to include any queries that this grammar contains pub const HIGHLIGHTS_QUERY: &'static str = include_str!("../../queries/highlights.scm"); // pub const INJECTIONS_QUERY: &'static str = include_str!("../../queries/injections.scm"); // pub const LOCALS_QUERY: &'static str = include_str!("../../queries/locals.scm"); // pub const TAGS_QUERY: &'static str = include_str!("../../queries/tags.scm"); #[cfg(test)] mod tests { #[test] fn test_can_load_grammar() { let mut parser = tree_sitter::Parser::new(); parser .set_language(super::language()) .expect("Error loading agda language"); } }
36.490566
98
0.668563
ffef8fb824f77ebaace7732006e29fb3774cce28
5,979
use crate::errors::prelude::*; use crate::keys::prelude::*; use crate::messages::*; use crate::pok_sig::prelude::*; use crate::pok_vc::prelude::*; use crate::signature::prelude::*; /// The prover of a signature or credential receives it from an /// issuer and later proves to a verifier. /// The prover can either have the issuer sign all messages /// or can have some (0 to all) messages blindly signed by the issuer. use crate::{ BlindSignatureContext, CommitmentBuilder, HashElem, ProofChallenge, ProofNonce, ProofRequest, RandomElem, SignatureBlinding, SignatureMessage, SignatureProof, }; use std::collections::BTreeMap; /// This struct represents a Prover who receives signatures or proves with them. /// Provided are methods for 2PC where some are only known to the prover and a blind signature /// is created, unblinding signatures, verifying signatures, and creating signature proofs of knowledge /// with selective disclosure proofs pub struct Prover {} impl Prover { /// Generate a unique message that will be used across multiple signatures. /// This `link_secret` is the same in all signatures and allows a prover to demonstrate /// that signatures were issued to the same identity. This value should be a blinded /// message in all signatures and never revealed to anyone. pub fn new_link_secret() -> SignatureMessage { SignatureMessage::random() } /// Create the structures need to send to an issuer to complete a blinded signature pub fn new_blind_signature_context( verkey: &PublicKey, messages: &BTreeMap<usize, SignatureMessage>, nonce: &ProofNonce, ) -> Result<(BlindSignatureContext, SignatureBlinding), BBSError> { let blinding_factor = Signature::generate_blinding(); let mut builder = CommitmentBuilder::new(); // h0^blinding_factor*hi^mi..... builder.add(&verkey.h0, &blinding_factor); let mut committing = ProverCommittingG1::new(); committing.commit(&verkey.h0); let mut secrets = Vec::new(); secrets.push(SignatureMessage(blinding_factor.0)); for (i, m) in messages { if *i > verkey.h.len() { return Err(BBSErrorKind::PublicKeyGeneratorMessageCountMismatch( *i, verkey.h.len(), ) .into()); } secrets.push(m.clone()); builder.add(&verkey.h[*i], &m); committing.commit(&verkey.h[*i]); } // Create a random commitment, compute challenges and response. // The proof of knowledge consists of a commitment and responses // Prover and issuer engage in a proof of knowledge for `commitment` let commitment = builder.finalize(); let committed = committing.finish(); let mut extra = Vec::new(); extra.extend_from_slice(&commitment.to_bytes_uncompressed_form()[..]); extra.extend_from_slice(&nonce.to_bytes_uncompressed_form()[..]); let challenge_hash = committed.gen_challenge(extra); let proof_of_hidden_messages = committed .gen_proof(&challenge_hash, secrets.as_slice()) .unwrap(); Ok(( BlindSignatureContext { challenge_hash, commitment, proof_of_hidden_messages, }, blinding_factor, )) } /// Unblinds and verifies a signature received from an issuer pub fn complete_signature( verkey: &PublicKey, messages: &[SignatureMessage], blind_signature: &BlindSignature, blinding_factor: &SignatureBlinding, ) -> Result<Signature, BBSError> { let signature = blind_signature.to_unblinded(blinding_factor); if signature.verify(messages, verkey)? { Ok(signature) } else { Err(BBSErrorKind::GeneralError { msg: format!("Invalid signature."), } .into()) } } /// Create a new signature proof of knowledge and selective disclosure proof /// from a verifier's request /// /// # Arguments /// * `request` - Proof request from verifier /// * `proof_messages` - /// If blinding_factor is Some(Nonce) then it will use that. /// If None, a blinding factor will be generated at random. pub fn commit_signature_pok( request: &ProofRequest, proof_messages: &[ProofMessage], signature: &Signature, ) -> Result<PoKOfSignature, BBSError> { PoKOfSignature::init(&signature, &request.verification_key, proof_messages) } /// Create the challenge hash for a set of proofs /// /// # Arguments /// * `poks` - a vec of PoKOfSignature objects /// * `nonce` - a SignatureNonce /// * `claims` - an optional slice of bytes the prover wishes to include in the challenge pub fn create_challenge_hash( pok_sigs: &[PoKOfSignature], claims: Option<&[&[u8]]>, nonce: &ProofNonce, ) -> Result<ProofChallenge, BBSError> { let mut bytes = Vec::new(); for p in pok_sigs { bytes.extend_from_slice(p.to_bytes().as_slice()); } bytes.extend_from_slice(&nonce.to_bytes_uncompressed_form()[..]); if let Some(add_claims) = claims { for c in add_claims { bytes.extend_from_slice(c); } } let challenge = ProofChallenge::hash(&bytes); Ok(challenge) } /// Convert the a committed proof of signature knowledge to the proof pub fn generate_signature_pok( pok_sig: PoKOfSignature, challenge: &ProofChallenge, ) -> Result<SignatureProof, BBSError> { let revealed_messages = (&pok_sig.revealed_messages).clone(); let proof = pok_sig.gen_proof(challenge)?; Ok(SignatureProof { revealed_messages, proof, }) } }
37.36875
103
0.629202
0180d77d65972ce200e4f0694c199e34b9fc4192
1,170
use super::*; mod registered; #[test] fn unregistered_sends_nothing_when_timer_expires() { run!( |arc_process| { ( Just(arc_process.clone()), milliseconds(), strategy::term(arc_process), ) }, |(arc_process, milliseconds, message)| { let time = arc_process.integer(milliseconds).unwrap(); let destination = registered_name(); let result = erlang::start_timer_3::native(arc_process.clone(), time, destination, message); prop_assert!( result.is_ok(), "Timer reference not returned. Got {:?}", result ); let timer_reference = result.unwrap(); prop_assert!(timer_reference.is_boxed_local_reference()); let timeout_message = timeout_message(timer_reference, message, &arc_process); prop_assert!(!has_message(&arc_process, timeout_message)); timeout_after(milliseconds); prop_assert!(!has_message(&arc_process, timeout_message)); Ok(()) }, ); }
26.590909
95
0.547009
ed008f2f7d7b30523e6c87ccc73688d6331dc12b
1,568
use serde::{Deserialize, Serialize}; #[repr(transparent)] #[derive(Debug, Serialize, Deserialize, Default, Clone)] pub struct Hook(pub Vec<String>); pub struct Grabber<'a> { pub handle: &'a str, pub index: usize, } impl<'a> Grabber<'a> { pub fn from_str(handle: &'a str) -> Self { let num = match handle.find('.') { Some(n) => n, None => return Self { handle, index: 0 }, }; match &handle[0..num] { "all" => todo!(), s => match s.parse::<usize>() { Ok(n) if n > 0 => Self { handle: &handle[num + 1..], index: n - 1, }, _ => Self { handle: &handle[num + 1..], index: 0, }, }, } } } impl<'a> From<&'a str> for Grabber<'a> { fn from(s: &'a str) -> Self { Grabber::from_str(s) } } impl PartialEq<&str> for Hook { fn eq(&self, other: &&str) -> bool { self.inner().iter().any(|h| h == other) } } impl PartialEq<Hook> for &str { fn eq(&self, other: &Hook) -> bool { other.eq(self) } } impl PartialEq<&str> for &Hook { fn eq(&self, other: &&str) -> bool { self.inner().iter().any(|h| h == other) } } impl PartialEq<&Hook> for &str { fn eq(&self, other: &&Hook) -> bool { other.eq(self) } } impl Hook { pub fn push(&mut self, s: String) { self.0.push(s); } fn inner(&self) -> &Vec<String> { &self.0 } }
21.479452
56
0.452806
18ec55e10bb9a0410c1b54f6568687281275b0a6
584
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn f(a: isize, a: isize) {} //~^ ERROR identifier `a` is bound more than once in this parameter list fn main() { }
34.352941
72
0.724315
093cd7fd04afaa3f10c53cd9785a32acfe73c66b
1,095
#![warn(clippy::all)] #![allow(clippy::blacklisted_name, clippy::no_effect, redundant_semicolon, unused_assignments)] struct Foo(u32); #[derive(Clone)] struct Bar { a: u32, b: u32, } fn field() { let mut bar = Bar { a: 1, b: 2 }; let temp = bar.a; bar.a = bar.b; bar.b = temp; let mut baz = vec![bar.clone(), bar.clone()]; let temp = baz[0].a; baz[0].a = baz[1].a; baz[1].a = temp; } fn array() { let mut foo = [1, 2]; let temp = foo[0]; foo[0] = foo[1]; foo[1] = temp; foo.swap(0, 1); } fn slice() { let foo = &mut [1, 2]; let temp = foo[0]; foo[0] = foo[1]; foo[1] = temp; foo.swap(0, 1); } fn vec() { let mut foo = vec![1, 2]; let temp = foo[0]; foo[0] = foo[1]; foo[1] = temp; foo.swap(0, 1); } #[rustfmt::skip] fn main() { field(); array(); slice(); vec(); let mut a = 42; let mut b = 1337; a = b; b = a; ; let t = a; a = b; b = t; let mut c = Foo(42); c.0 = a; a = c.0; ; let t = c.0; c.0 = a; a = t; }
14.038462
95
0.457534