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
3aa06982ac1f841eca2efa6a87776a1af616f780
4,374
use std::io::Cursor; use crate::error; use crate::frame::frame_auth_challenge::*; use crate::frame::frame_auth_success::BodyReqAuthSuccess; use crate::frame::frame_authenticate::BodyResAuthenticate; use crate::frame::frame_error::CdrsError; use crate::frame::frame_event::BodyResEvent; use crate::frame::frame_result::{ BodyResResultPrepared, BodyResResultRows, BodyResResultSetKeyspace, BodyResResultVoid, ResResultBody, RowsMetadata, }; use crate::frame::frame_supported::*; use crate::frame::FromCursor; use crate::frame::Opcode; use crate::types::rows::Row; #[derive(Debug)] pub enum ResponseBody { Error(CdrsError), Startup, Ready(BodyResResultVoid), Authenticate(BodyResAuthenticate), Options, Supported(BodyResSupported), Query, Result(ResResultBody), Prepare, Execute, Register, Event(BodyResEvent), Batch, AuthChallenge(BodyResAuthChallenge), AuthResponse, AuthSuccess(BodyReqAuthSuccess), } impl ResponseBody { pub fn from(bytes: &[u8], response_type: &Opcode) -> error::Result<ResponseBody> { let mut cursor: Cursor<&[u8]> = Cursor::new(bytes); Ok(match *response_type { // request frames Opcode::Startup => unreachable!(), Opcode::Options => unreachable!(), Opcode::Query => unreachable!(), Opcode::Prepare => unreachable!(), Opcode::Execute => unreachable!(), Opcode::Register => unreachable!(), Opcode::Batch => unreachable!(), Opcode::AuthResponse => unreachable!(), // response frames Opcode::Error => ResponseBody::Error(CdrsError::from_cursor(&mut cursor)?), Opcode::Ready => ResponseBody::Ready(BodyResResultVoid::from_cursor(&mut cursor)?), Opcode::Authenticate => { ResponseBody::Authenticate(BodyResAuthenticate::from_cursor(&mut cursor)?) } Opcode::Supported => { ResponseBody::Supported(BodyResSupported::from_cursor(&mut cursor)?) } Opcode::Result => ResponseBody::Result(ResResultBody::from_cursor(&mut cursor)?), Opcode::Event => ResponseBody::Event(BodyResEvent::from_cursor(&mut cursor)?), Opcode::AuthChallenge => { ResponseBody::AuthChallenge(BodyResAuthChallenge::from_cursor(&mut cursor)?) } Opcode::AuthSuccess => { ResponseBody::AuthSuccess(BodyReqAuthSuccess::from_cursor(&mut cursor)?) } }) } pub fn into_rows(self) -> Option<Vec<Row>> { match self { ResponseBody::Result(res) => res.into_rows(), _ => None, } } pub fn as_rows_metadata(&self) -> Option<RowsMetadata> { match *self { ResponseBody::Result(ref res) => res.as_rows_metadata(), _ => None, } } pub fn as_cols(&self) -> Option<&BodyResResultRows> { match *self { ResponseBody::Result(ResResultBody::Rows(ref rows)) => Some(rows), _ => None, } } /// It unwraps body and returns BodyResResultPrepared which contains an exact result of /// PREPARE query. If frame body is not of type `Result` this method returns `None`. pub fn into_prepared(self) -> Option<BodyResResultPrepared> { match self { ResponseBody::Result(res) => res.into_prepared(), _ => None, } } /// It unwraps body and returns BodyResResultPrepared which contains an exact result of /// use keyspace query. If frame body is not of type `Result` this method returns `None`. pub fn into_set_keyspace(self) -> Option<BodyResResultSetKeyspace> { match self { ResponseBody::Result(res) => res.into_set_keyspace(), _ => None, } } /// It unwraps body and returns BodyResEvent. /// If frame body is not of type `Result` this method returns `None`. pub fn into_server_event(self) -> Option<BodyResEvent> { match self { ResponseBody::Event(event) => Some(event), _ => None, } } pub fn authenticator(&self) -> Option<&str> { match *self { ResponseBody::Authenticate(ref auth) => Some(auth.data.as_str()), _ => None, } } }
34.440945
95
0.608596
18c46e04807ac73a33c2ffc44394fd87facee080
609
use noise_fns::NoiseFn; /// Noise function that outputs the product of the two output values from two source /// functions. pub struct Multiply<'a, T: 'a> { /// Outputs a value. pub source1: &'a dyn NoiseFn<T>, /// Outputs a value. pub source2: &'a dyn NoiseFn<T>, } impl<'a, T> Multiply<'a, T> { pub fn new(source1: &'a dyn NoiseFn<T>, source2: &'a dyn NoiseFn<T>) -> Self { Self { source1, source2 } } } impl<'a, T> NoiseFn<T> for Multiply<'a, T> where T: Copy, { fn get(&self, point: T) -> f64 { self.source1.get(point) * self.source2.get(point) } }
22.555556
84
0.594417
260ef72ec59e71fdb4588053a284811733f5d2a0
4,506
use crate::handler::UpdateHandler; use bytes::buf::BufExt; use futures_util::future::{ok, ready, FutureExt, Ready}; use http::Error as HttpError; use hyper::{body, service::Service, Body, Error as HyperError, Method, Request, Response, Server, StatusCode}; use log::error; use std::{ convert::Infallible, error::Error as StdError, future::Future, net::SocketAddr, pin::Pin, sync::Arc, task::{Context, Poll}, }; use tokio::sync::Mutex; #[doc(hidden)] pub struct WebhookServiceFactory<H> { path: String, handler: Arc<Mutex<H>>, } impl<H> WebhookServiceFactory<H> { #[doc(hidden)] pub fn new<P>(path: P, update_handler: H) -> Self where P: Into<String>, { WebhookServiceFactory { path: path.into(), handler: Arc::new(Mutex::new(update_handler)), } } } impl<H, T> Service<T> for WebhookServiceFactory<H> { type Response = WebhookService<H>; type Error = Infallible; type Future = Ready<Result<Self::Response, Self::Error>>; fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { Ok(()).into() } fn call(&mut self, _: T) -> Self::Future { let path = self.path.clone(); ok(WebhookService { path, handler: self.handler.clone(), }) } } #[doc(hidden)] pub struct WebhookService<H> { path: String, handler: Arc<Mutex<H>>, } async fn handle_request<H>( handler: Arc<Mutex<H>>, path: String, request: Request<Body>, ) -> Result<Response<Body>, WebhookError> where H: UpdateHandler + Send, { Ok(if let Method::POST = *request.method() { if request.uri().path() == path { let data = body::aggregate(request).await?; match serde_json::from_reader(data.reader()) { Ok(update) => { let mut handler = handler.lock().await; handler.handle(update).await; Response::new(Body::empty()) } Err(err) => Response::builder() .header("Content-Type", "text/plain") .status(StatusCode::BAD_REQUEST) .body(Body::from(format!("Failed to parse update: {}\n", err)))?, } } else { Response::builder().status(StatusCode::NOT_FOUND).body(Body::empty())? } } else { Response::builder() .status(StatusCode::METHOD_NOT_ALLOWED) .header("Allow", "POST") .body(Body::empty())? }) } type ServiceFuture = Pin<Box<dyn Future<Output = Result<Response<Body>, WebhookError>> + Send>>; impl<H> Service<Request<Body>> for WebhookService<H> where H: UpdateHandler + Send + 'static, { type Response = Response<Body>; type Error = WebhookError; type Future = ServiceFuture; fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { Ok(()).into() } fn call(&mut self, request: Request<Body>) -> Self::Future { Box::pin( handle_request(self.handler.clone(), self.path.clone(), request).then(|result| match result { Ok(rep) => ok(rep), Err(err) => { error!("Webhook error: {}", err); ready( Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .body(Body::empty()) .map_err(WebhookError::from), ) } }), ) } } #[doc(hidden)] #[derive(Debug, derive_more::Display, derive_more::From)] pub enum WebhookError { Hyper(HyperError), Http(HttpError), } impl StdError for WebhookError { fn source(&self) -> Option<&(dyn StdError + 'static)> { use self::WebhookError::*; Some(match self { Hyper(err) => err, Http(err) => err, }) } } /// Starts a server for webhook /// /// # Arguments /// /// * address - Bind address /// * path - URL path for webhook /// * handler - Updates handler pub async fn run_server<A, P, H>(address: A, path: P, handler: H) -> Result<(), HyperError> where A: Into<SocketAddr>, P: Into<String>, H: UpdateHandler + Send + 'static, { let address = address.into(); let path = path.into(); let server = Server::bind(&address).serve(WebhookServiceFactory::new(path, handler)); server.await }
27.987578
110
0.551265
d5a021190d8d7cd8f6cbb42ccf41caabf4a18fa6
7,842
#![cfg(feature = "conform")] #![allow(non_snake_case)] extern crate env_logger; #[macro_use] extern crate log; #[macro_use] extern crate proptest; extern crate protobuf; extern crate tract_core; extern crate tract_tensorflow; mod utils; use crate::utils::*; use proptest::prelude::*; use protobuf::Message; use tract_core::ndarray::prelude::*; use tract_core::prelude::*; use tract_tensorflow::conform::*; use tract_tensorflow::tfpb; use tract_tensorflow::tfpb::types::DataType::DT_INT32; fn strided_slice_strat( ) -> BoxedStrategy<(Tensor, Tensor, Tensor, Tensor, (i32, i32, i32, i32, i32))> { ::proptest::collection::vec( (1..5).prop_flat_map(|n| { // each dim max ( Just(n), // input size 0..n, // begin 0..n, // end 1..2.max(n), // stride, abs any::<bool>(), // make begin negative any::<bool>(), // make end negative ) }), 1..4, // rank ) .prop_filter("Negatives stride are not typable yet", |dims| dims.iter().all(|d| d.1 <= d.2)) .prop_flat_map(|dims| { let rank = dims.iter().len(); (Just(dims), (0..(1 << rank), 0..(1 << rank), Just(0), Just(0), 0..(1 << rank))) }) .prop_map(|(dims, masks)| { let shape = dims.iter().map(|d| d.0 as usize).collect::<Vec<_>>(); let size: i32 = shape.iter().map(|d| *d as i32).product(); ( Tensor::from(Array::from_shape_vec(shape, (0..size).collect()).unwrap()), Array::from(dims.iter().map(|d| if d.4 { d.1 - d.0 } else { d.1 }).collect::<Vec<_>>()) .into(), Array::from(dims.iter().map(|d| if d.5 { d.2 - d.0 } else { d.2 }).collect::<Vec<_>>()) .into(), Array::from( dims.iter() .enumerate() .map(|(ix, d)| { if d.2 == d.1 || masks.4 & (1 << ix) != 0 { 1 } else { d.3 as i32 * (d.2 as i32 - d.1 as i32).signum() } }) .collect::<Vec<_>>(), ) .into(), masks, ) }) .boxed() } proptest! { #[test] fn strided_slice((ref i, ref b, ref e, ref s, ref masks) in strided_slice_strat()) { let graph = tfpb::graph() .node(placeholder_i32("input")) .node(const_i32("begin", b)) .node(const_i32("end", e)) .node(const_i32("stride", s)) .node(tfpb::node().name("op") .attr("T", DT_INT32) .attr("Index", DT_INT32) .attr("begin_mask", masks.0 as i64) .attr("end_mask", masks.1 as i64) .attr("shrink_axis_mask", masks.4 as i64) .input("input").input("begin") .input("end").input("stride") .op("StridedSlice") ).write_to_bytes().unwrap(); let inputs = vec!(("input", i.clone())); let res = compare(&graph, inputs, "op")?; res } } #[test] fn strided_slice_1() { let graph = tfpb::graph() .node(placeholder_i32("input")) .node(const_i32("begin", &tensor1(&[0]))) .node(const_i32("end", &tensor1(&[2]))) .node(const_i32("stride", &tensor1(&[1]))) .node( tfpb::node() .name("op") .attr("T", DT_INT32) .attr("Index", DT_INT32) .input("input") .input("begin") .input("end") .input("stride") .op("StridedSlice"), ) .write_to_bytes() .unwrap(); let inputs = vec![("input", tensor2(&[[0, 6], [0, 0]]))]; compare(&graph, inputs, "op").unwrap() } #[test] fn strided_slice_2() { let graph = tfpb::graph() .node(placeholder_i32("input")) .node(const_i32("begin", &tensor1(&[0]))) .node(const_i32("end", &tensor1(&[0]))) .node(const_i32("stride", &tensor1(&[1]))) .node( tfpb::node() .name("op") .attr("T", DT_INT32) .attr("Index", DT_INT32) .attr("shrink_axis_mask", 1 as i64) .input("input") .input("begin") .input("end") .input("stride") .op("StridedSlice"), ) .write_to_bytes() .unwrap(); let inputs = vec![("input", tensor1(&[0]))]; compare(&graph, inputs, "op").unwrap() } #[test] fn strided_slice_3() { let graph = tfpb::graph() .node(placeholder_i32("input")) .node(const_i32("begin", &tensor1(&[0]))) .node(const_i32("end", &tensor1(&[0]))) .node(const_i32("stride", &tensor1(&[1]))) .node( tfpb::node() .name("op") .attr("T", DT_INT32) .attr("Index", DT_INT32) .attr("shrink_axis_mask", 1 as i64) .input("input") .input("begin") .input("end") .input("stride") .op("StridedSlice"), ); let graph = graph.write_to_bytes().unwrap(); let inputs = vec![("input", tensor1(&[0, 1]))]; compare(&graph, inputs, "op").unwrap() } #[ignore] // negative stride #[test] fn strided_slice_4() { let graph = tfpb::graph() .node(placeholder_i32("input")) .node(const_i32("begin", &tensor1(&[1]))) .node(const_i32("end", &tensor1(&[0]))) .node(const_i32("stride", &tensor1(&[-1]))) .node( tfpb::node() .name("op") .attr("T", DT_INT32) .attr("Index", DT_INT32) .input("input") .input("begin") .input("end") .input("stride") .op("StridedSlice"), ); let graph = graph.write_to_bytes().unwrap(); let inputs = vec![("input", tensor1(&[0, 1]))]; compare(&graph, inputs, "op").unwrap() } #[test] fn strided_slice_5() { let graph = tfpb::graph() .node(placeholder_i32("input")) .node(const_i32("begin", &tensor1(&[0, 0]))) .node(const_i32("end", &tensor1(&[0, 0]))) .node(const_i32("stride", &tensor1(&[1, 1]))) .node( tfpb::node() .name("op") .attr("T", DT_INT32) .attr("Index", DT_INT32) .attr("end_mask", 2 as i64) .input("input") .input("begin") .input("end") .input("stride") .op("StridedSlice"), ); let graph = graph.write_to_bytes().unwrap(); let inputs = vec![("input", tensor2(&[[0, 1]]))]; compare(&graph, inputs, "op").unwrap() } #[test] fn strided_slice_shrink_override_begin_mask() { let graph = tfpb::graph() .node(placeholder_i32("input")) .node(const_i32("begin", &tensor1(&[1]))) .node(const_i32("end", &tensor1(&[1]))) .node(const_i32("stride", &tensor1(&[1]))) .node( tfpb::node() .name("op") .attr("T", DT_INT32) .attr("Index", DT_INT32) .attr("begin_mask", 1 as i64) .attr("shrink_axis_mask", 1 as i64) .input("input") .input("begin") .input("end") .input("stride") .op("StridedSlice"), ); let graph = graph.write_to_bytes().unwrap(); let inputs = vec![("input", tensor1(&[0, 1]))]; compare(&graph, inputs, "op").unwrap() }
32.139344
99
0.456261
69135d733a59edc434ad0028ca13bdca34a05839
4,861
use crate::prelude::*; /// The `ScrollIndicatorState` handles the `ScrollIndicator` widget. #[derive(Default, AsAny)] pub struct ScrollIndicatorState; impl State for ScrollIndicatorState { fn update_post_layout(&mut self, _: &mut Registry, ctx: &mut Context<'_>) { let padding = *ctx.widget().get::<Thickness>("padding"); let scroll_offset = *ctx.widget().get::<Point>("scroll_offset"); let content_id = *ctx.widget().get::<u32>("content_id"); let content_bounds = *ctx .get_widget(Entity::from(content_id)) .get::<Rectangle>("bounds"); let bounds = *ctx.widget().get::<Rectangle>("bounds"); let horizontal_p = bounds.width / content_bounds.width; let vertical_p = bounds.height / content_bounds.height; // calculate vertical scroll bar height and position. if let Some(mut vertical_scroll_bar) = ctx.try_child("vertical-scroll-bar") { if vertical_p < 1.0 { vertical_scroll_bar.set("visibility", Visibility::from("visible")); let scroll_bar_margin_bottom = vertical_scroll_bar.get::<Thickness>("margin").bottom(); let vertical_min_height = vertical_scroll_bar .get::<Constraint>("constraint") .min_height(); let height = ((bounds.height - padding.top - padding.bottom - scroll_bar_margin_bottom) * vertical_p) .max(vertical_min_height); let scroll_bar_bounds = vertical_scroll_bar.get_mut::<Rectangle>("bounds"); scroll_bar_bounds.height = height; scroll_bar_bounds.y = -(scroll_offset.y as f64 * vertical_p); } else { vertical_scroll_bar.set("visibility", Visibility::from("collapsed")); } } // calculate horizontal scroll bar width and position. if let Some(mut horizontal_scroll_bar) = ctx.try_child("horizontal-scroll-bar") { if horizontal_p < 1.0 { horizontal_scroll_bar.set("visibility", Visibility::from("visible")); let scroll_bar_margin_right = horizontal_scroll_bar.get::<Thickness>("margin").right(); let horizontal_min_width = horizontal_scroll_bar .get::<Constraint>("constraint") .min_width(); let width = ((bounds.width - padding.left - padding.right - scroll_bar_margin_right) * horizontal_p) .max(horizontal_min_width); let scroll_bar_bounds = horizontal_scroll_bar.get_mut::<Rectangle>("bounds"); scroll_bar_bounds.width = width; scroll_bar_bounds.x = -(scroll_offset.x as f64 * horizontal_p); } else { horizontal_scroll_bar.set("visibility", Visibility::from("collapsed")); } } } } widget!( /// The `ScrollIndicator` widget contains two scroll bars. /// /// **CSS element:** `scroll-indicator` ScrollIndicator<ScrollIndicatorState> { /// Sets or shares the scroll offset property. scroll_offset: Point, /// Sets or shares the padding property. padding: Thickness, /// Sets or shares the content id property. content_id: u32 } ); impl Template for ScrollIndicator { fn template(self, id: Entity, ctx: &mut BuildContext) -> Self { self.name("ScrollIndicator") .element("scroll-indicator") .vertical_alignment("stretch") .horizontal_alignment("stretch") .padding(0.0) .child( Grid::create() .child( ScrollBar::create() .element("scroll-bar") .id("vertical-scroll-bar") .min_height(8.0) .margin((0.0, 0.0, 0.0, 6.0)) .horizontal_alignment("end") .opacity(id) .build(ctx), ) .child( ScrollBar::create() .element("scroll-bar") .id("horizontal-scroll-bar") .min_width(8.0) .margin((0.0, 0.0, 6.0, 0.0)) .height(4.0) .vertical_alignment("end") .opacity(id) .build(ctx), ) .build(ctx), ) } fn layout(&self) -> Box<dyn Layout> { Box::new(PaddingLayout::new()) } }
40.508333
94
0.515326
1d308adef9af3f70ed922e6577c179f867fdbab9
2,085
//! A module to compute the binary size of data once encoded //! //! This module is used primilarly when implementing the `MessageWrite::get_size` /// Computes the binary size of the varint encoded u64 /// /// https://developers.google.com/protocol-buffers/docs/encoding pub fn sizeof_varint(v: u64) -> usize { match v { 0x0..=0x7F => 1, 0x80..=0x3FFF => 2, 0x4000..=0x1FF_FFF => 3, 0x200_000..=0xF_FFF_FFF => 4, 0x10_000_000..=0x7FF_FFF_FFF => 5, 0x0_800_000_000..=0x3F_FFF_FFF_FFF => 6, 0x040_000_000_000..=0x1_FFF_FFF_FFF_FFF => 7, 0x02_000_000_000_000..=0xFF_FFF_FFF_FFF_FFF => 8, 0x0_100_000_000_000_000..=0x7_FFF_FFF_FFF_FFF_FFF => 9, _ => 10, } } /// Computes the binary size of a variable length chunk of data (wire type 2) /// /// The total size is the varint encoded length size plus the length itself /// https://developers.google.com/protocol-buffers/docs/encoding pub fn sizeof_len(len: usize) -> usize { sizeof_varint(len as u64) + len } /// Computes the binary size of the varint encoded i32 pub fn sizeof_int32(v: i32) -> usize { sizeof_varint(v as u64) } /// Computes the binary size of the varint encoded i64 pub fn sizeof_int64(v: i64) -> usize { sizeof_varint(v as u64) } /// Computes the binary size of the varint encoded uint32 pub fn sizeof_uint32(v: u32) -> usize { sizeof_varint(u64::from(v)) } /// Computes the binary size of the varint encoded uint64 pub fn sizeof_uint64(v: u64) -> usize { sizeof_varint(v) } /// Computes the binary size of the varint encoded sint32 pub fn sizeof_sint32(v: i32) -> usize { sizeof_varint(((v << 1) ^ (v >> 31)) as u64) } /// Computes the binary size of the varint encoded sint64 pub fn sizeof_sint64(v: i64) -> usize { sizeof_varint(((v << 1) ^ (v >> 63)) as u64) } /// Computes the binary size of the varint encoded bool (always = 1) pub fn sizeof_bool(_: bool) -> usize { 1 } /// Computes the binary size of the varint encoded enum pub fn sizeof_enum(v: i32) -> usize { sizeof_int32(v) }
29.785714
81
0.671463
672d475ccd38b44cbeccb1a1f394f9ddae0b1c79
67
FieldFoo(<u32 as ::configure_me::parse_arg::ParseArg>::Error),
33.5
66
0.701493
23a32044200317b4b3b70fc2c199db8dfa444ce7
5,661
use std::io::BufRead; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use std::{fs, io, thread}; use crc32fast::Hasher; use crate::directory::{WatchCallback, WatchCallbackList, WatchHandle}; pub const POLLING_INTERVAL: Duration = Duration::from_millis(if cfg!(test) { 1 } else { 500 }); // Watches a file and executes registered callbacks when the file is modified. pub struct FileWatcher { path: Arc<Path>, callbacks: Arc<WatchCallbackList>, state: Arc<AtomicUsize>, // 0: new, 1: runnable, 2: terminated } impl FileWatcher { pub fn new(path: &Path) -> FileWatcher { FileWatcher { path: Arc::from(path), callbacks: Default::default(), state: Default::default(), } } pub fn spawn(&self) { if self .state .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) .is_err() { return; } let path = self.path.clone(); let callbacks = self.callbacks.clone(); let state = self.state.clone(); thread::Builder::new() .name("thread-tantivy-meta-file-watcher".to_string()) .spawn(move || { let mut current_checksum_opt = None; while state.load(Ordering::SeqCst) == 1 { if let Ok(checksum) = FileWatcher::compute_checksum(&path) { let metafile_has_changed = current_checksum_opt .map(|current_checksum| current_checksum != checksum) .unwrap_or(true); if metafile_has_changed { info!("Meta file {:?} was modified", path); current_checksum_opt = Some(checksum); // We actually ignore callbacks failing here. // We just wait for the end of their execution. let _ = callbacks.broadcast().wait(); } } thread::sleep(POLLING_INTERVAL); } }) .expect("Failed to spawn meta file watcher thread"); } pub fn watch(&self, callback: WatchCallback) -> WatchHandle { let handle = self.callbacks.subscribe(callback); self.spawn(); handle } fn compute_checksum(path: &Path) -> Result<u32, io::Error> { let reader = match fs::File::open(path) { Ok(f) => io::BufReader::new(f), Err(e) => { warn!("Failed to open meta file {:?}: {:?}", path, e); return Err(e); } }; let mut hasher = Hasher::new(); for line in reader.lines() { hasher.update(line?.as_bytes()) } Ok(hasher.finalize()) } } impl Drop for FileWatcher { fn drop(&mut self) { self.state.store(2, Ordering::SeqCst); } } #[cfg(test)] mod tests { use std::mem; use super::*; use crate::directory::mmap_directory::atomic_write; #[test] fn test_file_watcher_drop_watcher() -> crate::Result<()> { let tmp_dir = tempfile::TempDir::new()?; let tmp_file = tmp_dir.path().join("watched.txt"); let counter: Arc<AtomicUsize> = Default::default(); let (tx, rx) = crossbeam::channel::unbounded(); let timeout = Duration::from_millis(100); let watcher = FileWatcher::new(&tmp_file); let state = watcher.state.clone(); assert_eq!(state.load(Ordering::SeqCst), 0); let counter_clone = counter.clone(); let _handle = watcher.watch(WatchCallback::new(move || { let val = counter_clone.fetch_add(1, Ordering::SeqCst); tx.send(val + 1).unwrap(); })); assert_eq!(counter.load(Ordering::SeqCst), 0); assert_eq!(state.load(Ordering::SeqCst), 1); atomic_write(&tmp_file, b"foo")?; assert_eq!(rx.recv_timeout(timeout), Ok(1)); atomic_write(&tmp_file, b"foo")?; assert!(rx.recv_timeout(timeout).is_err()); atomic_write(&tmp_file, b"bar")?; assert_eq!(rx.recv_timeout(timeout), Ok(2)); mem::drop(watcher); atomic_write(&tmp_file, b"qux")?; thread::sleep(Duration::from_millis(10)); assert_eq!(counter.load(Ordering::SeqCst), 2); assert_eq!(state.load(Ordering::SeqCst), 2); Ok(()) } #[test] fn test_file_watcher_drop_handle() -> crate::Result<()> { let tmp_dir = tempfile::TempDir::new()?; let tmp_file = tmp_dir.path().join("watched.txt"); let counter: Arc<AtomicUsize> = Default::default(); let (tx, rx) = crossbeam::channel::unbounded(); let timeout = Duration::from_millis(100); let watcher = FileWatcher::new(&tmp_file); let state = watcher.state.clone(); assert_eq!(state.load(Ordering::SeqCst), 0); let counter_clone = counter.clone(); let handle = watcher.watch(WatchCallback::new(move || { let val = counter_clone.fetch_add(1, Ordering::SeqCst); tx.send(val + 1).unwrap(); })); assert_eq!(counter.load(Ordering::SeqCst), 0); assert_eq!(state.load(Ordering::SeqCst), 1); atomic_write(&tmp_file, b"foo")?; assert_eq!(rx.recv_timeout(timeout), Ok(1)); mem::drop(handle); atomic_write(&tmp_file, b"qux")?; assert_eq!(counter.load(Ordering::SeqCst), 1); assert_eq!(state.load(Ordering::SeqCst), 1); Ok(()) } }
30.435484
95
0.552023
1d15bb257e7d90818811bc1b4c2fff89dc99c072
759
use ark_curve_benches::*; use ark_std::ops::{AddAssign, MulAssign, SubAssign}; use ark_ec::{PairingEngine, ProjectiveCurve}; use ark_ff::{ biginteger::BigInteger768 as FqRepr, BigInteger, Field, PrimeField, SquareRootField, UniformRand, }; use ark_mnt4_753::{ fq::Fq, fq2::Fq2, fr::Fr, Fq4, G1Affine, G1Projective as G1, G2Affine, G2Projective as G2, MNT4_753, }; mod g1 { use super::*; ec_bench!(G1, G1Affine); } mod g2 { use super::*; ec_bench!(G2, G2Affine); } f_bench!(extension, Fq2, Fq2, fq2); f_bench!(target, Fq4, Fq4, fq4); f_bench!(Fq, Fq, FqRepr, FqRepr, fq); f_bench!(Fr, Fr, FqRepr, FqRepr, fr); pairing_bench!(MNT4_753, Fq4); bencher::benchmark_main!(fq, fr, fq2, fq4, g1::group_ops, g2::group_ops, pairing);
25.3
94
0.683794
eb138ef86e52d42bda37d4bf3f3c4e3c79cf0a46
5,217
use crate::{column_metadata, error::*, AliasedCondition, ColumnMetadata, SqlRow, ToSqlRow}; use async_trait::async_trait; use connector_interface::{filter::Filter, RecordFilter}; use futures::future::FutureExt; use prisma_models::*; use quaint::{ ast::*, connector::{self, Queryable}, pooled::PooledConnection, }; use tracing_futures::Instrument; use serde_json::{Map, Value}; use std::panic::AssertUnwindSafe; impl<'t> QueryExt for connector::Transaction<'t> {} impl QueryExt for PooledConnection {} /// An extension trait for Quaint's `Queryable`, offering certain Prisma-centric /// database operations on top of `Queryable`. #[async_trait] pub trait QueryExt: Queryable + Send + Sync { /// Filter and map the resulting types with the given identifiers. #[tracing::instrument(skip(self, q, idents))] async fn filter(&self, q: Query<'_>, idents: &[ColumnMetadata<'_>]) -> crate::Result<Vec<SqlRow>> { let result_set = self .query(q) .instrument(tracing::info_span!("Filter read query")) .await?; let mut sql_rows = Vec::new(); for row in result_set { sql_rows.push(row.to_sql_row(idents)?); } Ok(sql_rows) } /// Execute a singular SQL query in the database, returning an arbitrary /// JSON `Value` as a result. #[tracing::instrument(skip(self, q, params))] async fn raw_json<'a>( &'a self, q: String, params: Vec<PrismaValue>, ) -> std::result::Result<Value, crate::error::RawError> { let params: Vec<_> = params.into_iter().map(convert_lossy).collect(); let result_set = AssertUnwindSafe(self.query_raw(&q, &params)).catch_unwind().await??; let columns: Vec<String> = result_set.columns().iter().map(ToString::to_string).collect(); let mut result = Vec::new(); for row in result_set.into_iter() { let mut object = Map::new(); for (idx, p_value) in row.into_iter().enumerate() { let column_name: String = columns[idx].clone(); object.insert(column_name, Value::from(p_value)); } result.push(Value::Object(object)); } Ok(Value::Array(result)) } /// Execute a singular SQL query in the database, returning the number of /// affected rows. #[tracing::instrument(skip(self, q, params))] async fn raw_count<'a>( &'a self, q: String, params: Vec<PrismaValue>, ) -> std::result::Result<usize, crate::error::RawError> { let params: Vec<_> = params.into_iter().map(convert_lossy).collect(); let changes = AssertUnwindSafe(self.execute_raw(&q, &params)).catch_unwind().await??; Ok(changes as usize) } /// Select one row from the database. #[tracing::instrument(skip(self, q, meta))] async fn find(&self, q: Select<'_>, meta: &[ColumnMetadata<'_>]) -> crate::Result<SqlRow> { self.filter(q.limit(1).into(), meta) .await? .into_iter() .next() .ok_or(SqlError::RecordDoesNotExist) } /// Process the record filter and either return directly with precomputed values, /// or fetch IDs from the database. #[tracing::instrument(skip(self, model, record_filter))] async fn filter_selectors( &self, model: &ModelRef, record_filter: RecordFilter, ) -> crate::Result<Vec<RecordProjection>> { if let Some(selectors) = record_filter.selectors { Ok(selectors) } else { self.filter_ids(model, record_filter.filter).await } } /// Read the all columns as a (primary) identifier. #[tracing::instrument(skip(self, model, filter))] async fn filter_ids(&self, model: &ModelRef, filter: Filter) -> crate::Result<Vec<RecordProjection>> { let model_id = model.primary_identifier(); let id_cols: Vec<Column<'static>> = model_id.as_columns().collect(); let select = Select::from_table(model.as_table()) .columns(id_cols) .so_that(filter.aliased_cond(None)); self.select_ids(select, model_id).await } #[tracing::instrument(skip(self, select, model_id))] async fn select_ids(&self, select: Select<'_>, model_id: ModelProjection) -> crate::Result<Vec<RecordProjection>> { let idents: Vec<_> = model_id .fields() .flat_map(|f| match f { Field::Scalar(sf) => vec![sf.type_identifier_with_arity()], Field::Relation(rf) => rf.type_identifiers_with_arities(), }) .collect(); let field_names: Vec<_> = model_id.fields().map(|field| field.name()).collect(); let meta = column_metadata::create(field_names.as_slice(), &idents); let mut rows = self.filter(select.into(), &meta).await?; let mut result = Vec::new(); for row in rows.drain(0..) { let tuples: Vec<_> = model_id.scalar_fields().zip(row.values.into_iter()).collect(); let record_id: RecordProjection = RecordProjection::new(tuples); result.push(record_id); } Ok(result) } }
35.732877
119
0.611846
d5b80d75fef37557ee63e78ce86e2652054b81f6
18,285
//! This module defines the [Sorting] options. To set it up from [ArgMatches], a [Yaml] //! and its [Default] value, use the [configure_from](Sorting::configure_from) method. use super::Configurable; use crate::config_file::Config; use clap::ArgMatches; use yaml_rust::Yaml; /// A collection of flags on how to sort the output. #[derive(Clone, Debug, Copy, PartialEq, Eq, Default)] pub struct Sorting { pub column: SortColumn, pub order: SortOrder, pub dir_grouping: DirGrouping, } impl Sorting { /// Get a `Sorting` struct from [ArgMatches], a [Config] or the [Default] values. /// /// The [SortColumn], [SortOrder] and [DirGrouping] are configured with their respective /// [Configurable] implementation. pub fn configure_from(matches: &ArgMatches, config: &Config) -> Self { let column = SortColumn::configure_from(matches, config); let order = SortOrder::configure_from(matches, config); let dir_grouping = DirGrouping::configure_from(matches, config); Self { column, order, dir_grouping, } } } /// The flag showing which column to use for sorting. #[derive(Clone, Debug, Copy, PartialEq, Eq)] pub enum SortColumn { Extension, Name, Time, Size, Version, } impl Configurable<Self> for SortColumn { /// Get a potential `SortColumn` variant from [ArgMatches]. /// /// If either the "timesort" or "sizesort" arguments are passed, this returns the corresponding /// `SortColumn` variant in a [Some]. Otherwise this returns [None]. fn from_arg_matches(matches: &ArgMatches) -> Option<Self> { let sort = matches.value_of("sort"); if matches.is_present("timesort") || sort == Some("time") { Some(Self::Time) } else if matches.is_present("sizesort") || sort == Some("size") { Some(Self::Size) } else if matches.is_present("extensionsort") || sort == Some("extension") { Some(Self::Extension) } else if matches.is_present("versionsort") || sort == Some("version") { Some(Self::Version) } else { None } } /// Get a potential `SortColumn` variant from a [Config]. /// /// If the Config's [Yaml] contains a [String](Yaml::String) value pointed to by "sorting" -> /// "column" and it is one of "time", "size" or "name", this returns the corresponding variant /// in a [Some]. Otherwise this returns [None]. fn from_config(config: &Config) -> Option<Self> { if let Some(yaml) = &config.yaml { match &yaml["sorting"]["column"] { Yaml::BadValue => None, Yaml::String(value) => match value.as_ref() { "extension" => Some(Self::Extension), "name" => Some(Self::Name), "time" => Some(Self::Time), "size" => Some(Self::Size), "version" => Some(Self::Version), _ => { config.print_invalid_value_warning("sorting->column", &value); None } }, _ => { config.print_wrong_type_warning("sorting->column", "string"); None } } } else { None } } } /// The default value for `SortColumn` is [SortColumn::Name]. impl Default for SortColumn { fn default() -> Self { Self::Name } } /// The flag showing which sort order to use. #[derive(Clone, Debug, Copy, PartialEq, Eq)] pub enum SortOrder { Default, Reverse, } impl Configurable<Self> for SortOrder { /// Get a potential `SortOrder` variant from [ArgMatches]. /// /// If the "reverse" argument is passed, this returns [SortOrder::Reverse] in a [Some]. /// Otherwise this returns [None]. fn from_arg_matches(matches: &ArgMatches) -> Option<Self> { if matches.is_present("reverse") { Some(Self::Reverse) } else { None } } /// Get a potential `SortOrder` variant from a [Config]. /// /// If the Config's [Yaml] contains a [Boolean](Yaml::Boolean) value pointed to by "sorting" -> /// "reverse", this returns a mapped variant in a [Some]. Otherwise [None] is returned. A /// `true` maps to [SortOrder::Reverse] and a `false` maps to [SortOrder::Default]. fn from_config(config: &Config) -> Option<Self> { if let Some(yaml) = &config.yaml { match &yaml["sorting"]["reverse"] { Yaml::BadValue => None, Yaml::Boolean(value) => { if *value { Some(Self::Reverse) } else { Some(Self::Default) } } _ => { config.print_wrong_type_warning("sorting->reverse", "boolean"); None } } } else { None } } } /// The default value for `SortOrder` is [SortOrder::Default]. impl Default for SortOrder { fn default() -> Self { Self::Default } } /// The flag showing where to place directories. #[derive(Clone, Debug, Copy, PartialEq, Eq)] pub enum DirGrouping { None, First, Last, } impl Configurable<Self> for DirGrouping { /// Get a potential `DirGrouping` variant from [ArgMatches]. /// /// If the "classic" argument is passed, then this returns the [DirGrouping::None] variant in a /// [Some]. Otherwise if the argument is passed, this returns the variant corresponding to its /// parameter in a [Some]. Otherwise this returns [None]. fn from_arg_matches(matches: &ArgMatches) -> Option<Self> { if matches.is_present("classic") { Some(Self::None) } else if matches.occurrences_of("group-dirs") > 0 { match matches.value_of("group-dirs") { Some("first") => Some(Self::First), Some("last") => Some(Self::Last), Some("none") => Some(Self::None), _ => panic!("This should not be reachable!"), } } else { None } } /// Get a potential `DirGrouping` variant from a [Config]. /// /// If the Config's [Yaml] contains a [Boolean](Yaml::Boolean) value pointed to by "classic" /// and its value is `true`, then this returns the the [DirGrouping::None] variant in a [Some]. /// Otherwise if the Yaml contains a [String](Yaml::String) value pointed to by "sorting" -> /// "dir-grouping" and it is one of "first", "last" or "none", this returns its corresponding /// variant in a [Some]. Otherwise this returns [None]. fn from_config(config: &Config) -> Option<Self> { if let Some(yaml) = &config.yaml { if let Yaml::Boolean(true) = &yaml["classic"] { Some(Self::None) } else { match &yaml["sorting"]["dir-grouping"] { Yaml::BadValue => None, Yaml::String(value) => match value.as_ref() { "first" => Some(Self::First), "last" => Some(Self::Last), "none" => Some(Self::None), _ => { config.print_invalid_value_warning("sorting->dir-grouping", &value); None } }, _ => { config.print_wrong_type_warning("sorting->dir-grouping", "string"); None } } } } else { None } } } /// The default value for `DirGrouping` is [DirGrouping::None]. impl Default for DirGrouping { fn default() -> Self { Self::None } } #[cfg(test)] mod test_sort_column { use super::SortColumn; use crate::app; use crate::config_file::Config; use crate::flags::Configurable; use yaml_rust::YamlLoader; #[test] fn test_from_arg_matches_none() { let argv = vec!["lsd"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!(None, SortColumn::from_arg_matches(&matches)); } #[test] fn test_from_arg_matches_extension() { let argv = vec!["lsd", "--extensionsort"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Extension), SortColumn::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_time() { let argv = vec!["lsd", "--timesort"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Time), SortColumn::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_size() { let argv = vec!["lsd", "--sizesort"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Size), SortColumn::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_version() { let argv = vec!["lsd", "--versionsort"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Version), SortColumn::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_sort() { let argv = vec!["lsd", "--sort", "time"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Time), SortColumn::from_arg_matches(&matches) ); let argv = vec!["lsd", "--sort", "size"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Size), SortColumn::from_arg_matches(&matches) ); let argv = vec!["lsd", "--sort", "extension"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Extension), SortColumn::from_arg_matches(&matches) ); let argv = vec!["lsd", "--sort", "version"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Version), SortColumn::from_arg_matches(&matches) ); } #[test] fn test_multi_sort_use_last() { let argv = vec!["lsd", "--sort", "size", "-t", "-S", "-X", "--sort", "time"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortColumn::Time), SortColumn::from_arg_matches(&matches) ); } #[test] fn test_from_config_none() { assert_eq!(None, SortColumn::from_config(&Config::with_none())); } #[test] fn test_from_config_empty() { let yaml_string = "---"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!(None, SortColumn::from_config(&Config::with_yaml(yaml))); } #[test] fn test_from_config_invalid() { let yaml_string = "sorting:\n column: foo"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!(None, SortColumn::from_config(&Config::with_yaml(yaml))); } #[test] fn test_from_config_extension() { let yaml_string = "sorting:\n column: extension"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(SortColumn::Extension), SortColumn::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_name() { let yaml_string = "sorting:\n column: name"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(SortColumn::Name), SortColumn::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_time() { let yaml_string = "sorting:\n column: time"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(SortColumn::Time), SortColumn::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_size() { let yaml_string = "sorting:\n column: size"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(SortColumn::Size), SortColumn::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_version() { let yaml_string = "sorting:\n column: version"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(SortColumn::Version), SortColumn::from_config(&Config::with_yaml(yaml)) ); } } #[cfg(test)] mod test_sort_order { use super::SortOrder; use crate::app; use crate::config_file::Config; use crate::flags::Configurable; use yaml_rust::YamlLoader; #[test] fn test_from_arg_matches_none() { let argv = vec!["lsd"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!(None, SortOrder::from_arg_matches(&matches)); } #[test] fn test_from_arg_matches_reverse() { let argv = vec!["lsd", "--reverse"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SortOrder::Reverse), SortOrder::from_arg_matches(&matches) ); } #[test] fn test_from_config_none() { assert_eq!(None, SortOrder::from_config(&Config::with_none())); } #[test] fn test_from_config_empty() { let yaml_string = "---"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!(None, SortOrder::from_config(&Config::with_yaml(yaml))); } #[test] fn test_from_config_default() { let yaml_string = "sorting:\n reverse: false"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(SortOrder::Default), SortOrder::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_reverse() { let yaml_string = "sorting:\n reverse: true"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(SortOrder::Reverse), SortOrder::from_config(&Config::with_yaml(yaml)) ); } } #[cfg(test)] mod test_dir_grouping { use super::DirGrouping; use crate::app; use crate::config_file::Config; use crate::flags::Configurable; use yaml_rust::YamlLoader; #[test] fn test_from_arg_matches_none() { let argv = vec!["lsd"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!(None, DirGrouping::from_arg_matches(&matches)); } #[test] fn test_from_arg_matches_first() { let argv = vec!["lsd", "--group-dirs", "first"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(DirGrouping::First), DirGrouping::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_last() { let argv = vec!["lsd", "--group-dirs", "last"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(DirGrouping::Last), DirGrouping::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_explicit_none() { let argv = vec!["lsd", "--group-dirs", "none"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(DirGrouping::None), DirGrouping::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_classic_mode() { let argv = vec!["lsd", "--group-dirs", "first", "--classic"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(DirGrouping::None), DirGrouping::from_arg_matches(&matches) ); } #[test] fn test_from_config_none() { assert_eq!(None, DirGrouping::from_config(&Config::with_none())); } #[test] fn test_from_config_empty() { let yaml_string = "---"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!(None, DirGrouping::from_config(&Config::with_yaml(yaml))); } #[test] fn test_from_config_first() { let yaml_string = "sorting:\n dir-grouping: first"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(DirGrouping::First), DirGrouping::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_last() { let yaml_string = "sorting:\n dir-grouping: last"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(DirGrouping::Last), DirGrouping::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_explicit_none() { let yaml_string = "sorting:\n dir-grouping: none"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(DirGrouping::None), DirGrouping::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_classic_mode() { let yaml_string = "classic: true\nsorting:\n dir-grouping: first"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(DirGrouping::None), DirGrouping::from_config(&Config::with_yaml(yaml)) ); } }
32.305654
99
0.562319
873650719e3f8c84901fc7a1773889a76e0f5830
2,962
use image::ImageFormat; use pdfium_render::bitmap::PdfBitmapRotation; use pdfium_render::bitmap_config::PdfBitmapConfig; use pdfium_render::pdfium::Pdfium; pub fn main() { // Attempt to bind to a pdfium library in the current working directory; failing that, // attempt to bind to the system-provided library. // The library name will differ depending on the current platform. On Linux, // the library will be named libpdfium.so by default; on Windows, pdfium.dll; and on // MacOS, libpdfium.dylib. We can use the Pdfium::pdfium_platform_library_name_at_path() // function to append the correct library name for the current platform to a path we specify. let bindings = Pdfium::bind_to_library( // Attempt to bind to a pdfium library in the current working directory... Pdfium::pdfium_platform_library_name_at_path("./"), ) .or_else( // ... and fall back to binding to a system-provided pdfium library. |_| Pdfium::bind_to_system_library(), ); match bindings { Ok(bindings) => { // The code below simply unwraps every Result<> returned from Pdfium. // In production code, you would actually want to check the results, rather // than just unwrapping them :) // First, create a set of shared settings that we'll apply to each page in the // sample file when rendering. Sharing the same rendering configuration is a good way // to ensure homogenous output across all pages in the document. let render_config = PdfBitmapConfig::new() .set_target_width(2000) .set_maximum_height(2000) .rotate_if_landscape(PdfBitmapRotation::Degrees90, true); Pdfium::new(bindings) .load_pdf_from_file("test/test.pdf", None) // Load the sample file... .unwrap() .pages() // ... get an iterator across all pages ... .for_each(|page| { // ... and export each page to a JPEG in the current working directory, // using the rendering configuration we created earlier. let result = page .get_bitmap_with_config(&render_config) // Initializes a bitmap with the given configuration for this page ... .unwrap() .as_image() // ... renders it to an Image::DynamicImage ... .as_bgra8() // ... sets the correct color space ... .unwrap() .save_with_format( format!("test-page-{}.jpg", page.index()), ImageFormat::Jpeg, ); // ... and exports it to a JPEG. assert!(result.is_ok()); }); } Err(err) => eprintln!("Error loading pdfium library: {:#?}", err), } }
46.28125
134
0.583727
0ad86e8a3ad498880330b01fc22c24fc78fd8be4
682
use bevy_proto_aseprite::anim_id::AnimationId; use strum::{EnumIter, EnumProperty, IntoEnumIterator}; #[derive(Debug, Clone, PartialEq, Eq, Hash, EnumProperty, EnumIter)] pub enum AnimId { #[strum(props(file = "sprites/hello.aseprite"))] Dummy, #[strum(props(file = "sprites/hello.aseprite", tag = "Blue"))] DummySad, } impl AnimationId for AnimId { fn name(&self) -> (&str, Option<&str>) { let path = self .get_str("file") .expect("Attribute \"file\" is required"); let tag = self.get_str("tag"); (path, tag) } fn list_all() -> Box<dyn Iterator<Item = Self>> { Box::new(AnimId::iter()) } }
27.28
68
0.59824
e931dbe2f1f5d270eacc0422db8768df01411768
2,209
pub mod refimpl; use crate::{ core::deser::{Deser, Error as DeserError, Serialize}, value::{Addr, Value}, }; /// An alias to a [`Node`] with owned parameters. pub type NodeOwned = Node<Value, Addr>; /// A node within a [Prolly List](crate::primitive::prollylist). #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] #[derive(Debug, Clone)] pub enum Node<Value, Addr> { Branch(Vec<Addr>), Leaf(Vec<Value>), } impl<V, A> Node<V, A> { /// Push the given `KeyValue` into the `KeyValues`. /// /// # Panics /// /// If the variants are not aligned between this instance and what is being pushed /// this code will panic. pub fn push(&mut self, item: NodeItem<V, A>) { match (self, item) { (Self::Branch(ref mut v), NodeItem::Branch(item)) => v.push(item), (Self::Leaf(ref mut v), NodeItem::Leaf(item)) => v.push(item), (_, _) => panic!("NodeItem pushed to unaligned Node enum vec"), } } pub fn is_empty(&self) -> bool { match self { Self::Branch(v) => v.is_empty(), Self::Leaf(v) => v.is_empty(), } } pub fn len(&self) -> usize { match self { Self::Branch(v) => v.len(), Self::Leaf(v) => v.len(), } } } impl<V, A> IntoIterator for Node<V, A> where V: Send + 'static, A: Send + 'static, { type Item = NodeItem<V, A>; type IntoIter = Box<dyn Iterator<Item = NodeItem<V, A>> + Send>; fn into_iter(self) -> Self::IntoIter { match self { Self::Branch(v) => Box::new(v.into_iter().map(NodeItem::Branch)), Self::Leaf(v) => Box::new(v.into_iter().map(NodeItem::Leaf)), } } } pub enum NodeItem<Value, Addr> { Branch(Addr), Leaf(Value), } impl<V, A> NodeItem<V, A> where V: Serialize, A: Serialize, { pub fn serialize_inner(&self, deser: &Deser) -> Result<Vec<u8>, DeserError> { match self { Self::Branch(item) => deser.to_vec(item), Self::Leaf(item) => deser.to_vec(item), } } }
29.065789
86
0.558624
28f7c41c7307e47f8692c6ccf89bc5e9a3fd0ad7
6,455
use std::{ env, fs, io, path::{Path, PathBuf}, process::Command, }; const FFTW_TAR_URL: &str = "https://www.fftw.org/fftw-3.3.10.tar.gz"; struct Environment { build_dir: PathBuf, cache_dir: Option<PathBuf>, has_avx2: bool, has_neon: bool, include_dir: PathBuf, is_windows: bool, lib_dir: PathBuf, makeflags: String, out_dir: PathBuf, } fn main() { let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); let pkg_name = env::var("CARGO_PKG_NAME").unwrap(); let pkg_version = env::var("CARGO_PKG_VERSION").unwrap(); let cpu_features = env::var("CARGO_CFG_TARGET_FEATURE").unwrap(); let cpu_features = cpu_features.split(',').collect::<Vec<_>>(); let env = Environment { build_dir: out_dir.join("build"), cache_dir: user_cache_dir().map(|c| c.join(pkg_name).join(pkg_version)), has_avx2: cpu_features.contains(&"avx2"), has_neon: cpu_features.contains(&"neon"), include_dir: out_dir.join("include"), is_windows: env::var("CARGO_CFG_WINDOWS").is_ok(), lib_dir: out_dir.join("lib"), makeflags: "-j".to_owned(), out_dir: out_dir.clone(), }; fs::create_dir_all(&env.build_dir) .unwrap_or_else(|_| panic!("failed to create the directory: {:?}", env.build_dir)); load_cache(&env); build(&env); save_cache(&env); run_bindgen(&env); write_link_info(&env); } fn load_cache(env: &Environment) { if let Some(c) = &env.cache_dir { let _ = copy_dir_all(c.join("include"), env.include_dir.clone()); let _ = copy_dir_all(c.join("lib"), env.lib_dir.clone()); } } fn build(env: &Environment) { if env.lib_dir.join("libfftw3f.a").exists() { return; } let build_dir = env.build_dir.join("fftw-build"); if !build_dir.exists() { execute_or_panic(Command::new("wget").current_dir(&env.build_dir).args(&[ "--output-document", "fftw.tar.gz", "--quiet", FFTW_TAR_URL, ])); execute_or_panic(Command::new("mkdir").args(&[build_dir.to_str().unwrap()])); execute_or_panic(Command::new("tar").current_dir(&env.build_dir).args(&[ "xf", "fftw.tar.gz", "--directory", build_dir.to_str().unwrap(), "--strip-components=1", ])); } execute_or_panic( Command::new("sh").current_dir(&build_dir).arg("-c").arg( [ "./configure", "--prefix", &if env.is_windows { env.out_dir.to_str().unwrap().replace('\\', "/") } else { env.out_dir.to_str().unwrap().into() }, // http://www.fftw.org/install/windows.html if env.is_windows { "--with-our-malloc" } else { "" }, "--disable-doc", "--disable-fortran", "--enable-float", if env.has_avx2 { "--enable-avx2" } else { "" }, if env.has_neon { "--enable-neon" } else { "" }, ] .join(" "), ), ); execute_or_panic( Command::new("make") .current_dir(&build_dir) .env("MAKEFLAGS", &env.makeflags), ); execute_or_panic( Command::new("make") .current_dir(&build_dir) .arg("check") .env("MAKEFLAGS", &env.makeflags), ); execute_or_panic(Command::new("make").current_dir(&build_dir).arg("install")); } fn run_bindgen(env: &Environment) { let binding_file = env.out_dir.join("fftw.rs"); if binding_file.exists() { return; } bindgen::Builder::default() .header(env.include_dir.join("fftw3.h").to_str().unwrap()) .allowlist_function("fftwf_.*") .generate() .expect("failed to generate bindings") .write_to_file(binding_file.clone()) .unwrap_or_else(|_| { panic!( "failed to write to the file: {}", binding_file.to_string_lossy() ) }); } fn save_cache(env: &Environment) { if let Some(c) = &env.cache_dir { let _ = copy_dir_all(env.include_dir.clone(), c.join("include")); let _ = copy_dir_all(env.lib_dir.clone(), c.join("lib")); } } fn write_link_info(env: &Environment) { println!( "cargo:rustc-link-search=native={}", env.lib_dir.to_str().unwrap() ); println!("cargo:rustc-link-lib=static=fftw3f"); } /// Copies all files and directories in `from` into `to`, preserving the directory structure. /// /// The directory `to` is created if it does not exist. Symlinks are ignored. fn copy_dir_all<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> { fs::create_dir_all(&to)?; for entry in fs::read_dir(from)? { let entry = entry?; let from = entry.path(); let to = to.as_ref().join(entry.file_name()); let ty = entry.file_type()?; if ty.is_dir() { copy_dir_all(from, to)?; } else if ty.is_file() { fs::copy(from, to)?; } } Ok(()) } fn execute_or_panic(cmd: &mut Command) { let status = cmd .status() .unwrap_or_else(|_| panic!("failed to execute the command: {:?}", cmd)); if !status.success() { if let Some(code) = status.code() { panic!("the process exited with code {}: {:?}", code, cmd); } else { panic!("the process is terminated by a signal: {:?}", cmd); } } } fn user_cache_dir() -> Option<PathBuf> { let host = env::var("HOST").ok()?; if host.contains("darwin") { env::var_os("HOME") .filter(|s| !s.is_empty()) .map(|s| PathBuf::from(s).join("Library").join("Caches")) } else if host.contains("linux") { env::var_os("XDG_CACHE_HOME") .filter(|s| !s.is_empty()) .map(PathBuf::from) .or_else(|| { env::var_os("HOME") .filter(|s| !s.is_empty()) .map(|s| PathBuf::from(s).join(".cache")) }) } else if host.contains("windows") { env::var_os("LOCALAPPDATA") .filter(|s| !s.is_empty()) .map(PathBuf::from) } else { None } }
30.592417
93
0.531061
e9c26591da9729d30fbceae75dbf0dc1bcb6ff14
4,679
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use serde::{Deserialize, Serialize}; /// Implement this trait for all types that needs to be converted to a SignedToken pub trait Signable { /// Identifies the expiration (in seconds since encoding) after which the /// JWT must not be accepted for processing. const EXP_SECONDS: i64; fn sign(&self, encoder: &Encoder) -> SignedToken where Self: serde::ser::Serialize + std::marker::Sized, { encoder.encode(self).expect("Token is encoded") } fn try_from_token(token: &SignedToken, decoder: &Decoder) -> Option<Self> where Self: serde::de::DeserializeOwned + std::marker::Sized, { decoder.decode(&token) } } #[derive(Debug, Serialize, Deserialize)] struct Claims { exp: usize, // Expiration time (as UTC timestamp) sub: String, } #[derive(Clone)] pub struct SignedToken(String); impl Into<String> for SignedToken { fn into(self) -> String { self.0 } } impl From<String> for SignedToken { fn from(s: String) -> Self { Self(s) } } impl std::fmt::Display for SignedToken { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } pub struct Encoder { encoding_key: EncodingKey, } impl Encoder { /// Creates an HMAC encoder from a secret key pub fn new_from_secret(secret: &[u8]) -> Self { let encoding_key = EncodingKey::from_secret(secret); Self { encoding_key } } fn encode_claims(&self, claims: Claims) -> Option<SignedToken> { encode(&Header::default(), &claims, &self.encoding_key) .ok() .map(|x| SignedToken(x)) } /// Encode any Signable type pub(crate) fn encode<T>(&self, data: &T) -> Option<SignedToken> where T: serde::ser::Serialize + Signable, { let encoded_data = bincode::serialize(data).ok()?; let base64_encoded_data = base64::encode(&encoded_data); let now = chrono::Utc::now(); let exp = now.checked_add_signed(chrono::Duration::seconds(T::EXP_SECONDS))?; let exp = exp.timestamp() as usize; let claims = Claims { exp, sub: base64_encoded_data, }; self.encode_claims(claims) } } // Note: we cannot store DecodingKey here // DecodingKey has a lifetime parameter and Decoder::new() cannot // return a DecodingKey with reference to the secret. // See https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct pub struct Decoder { secret: Vec<u8>, } impl Decoder { /// Creates an HMAC decoder from a secret key pub fn new_from_secret(secret: &[u8]) -> Self { let secret = secret.to_owned(); Self { secret } } fn decode_claims(&self, token: &SignedToken) -> Option<Claims> { let decoding_key = DecodingKey::from_secret(&self.secret); let validation = Validation::default(); decode::<Claims>(&token.0, &decoding_key, &validation) .map(|x| x.claims) .ok() } /// Decode any deserializable type from a SignedToken pub(crate) fn decode<T>(&self, token: &SignedToken) -> Option<T> where T: serde::de::DeserializeOwned, { let decoded: Claims = self.decode_claims(token)?; let base64_encoded_data = decoded.sub; let encoded_data = base64::decode(base64_encoded_data).ok()?; bincode::deserialize(&encoded_data).ok() } } #[cfg(test)] mod test { use super::*; #[test] fn encode_decode() { let key = b"secret"; let encoder = Encoder::new_from_secret(key); let decoder = Decoder::new_from_secret(key); let sub = "[email protected]"; let claims = Claims { sub: sub.to_string(), exp: 9999999999, }; let token = encoder.encode_claims(claims).unwrap(); let data = decoder.decode_claims(&token).unwrap(); assert!(sub == &data.sub); } #[test] fn encode_decode_generic() { let key = b"secret"; let encoder = Encoder::new_from_secret(key); let decoder = Decoder::new_from_secret(key); #[derive(Serialize, Deserialize, Debug)] struct Data { x: u32, }; impl Signable for Data { const EXP_SECONDS: i64 = 3600; } let data = Data { x: 42 }; let token = data.sign(&encoder); let decoded = Data::try_from_token(&token, &decoder).unwrap(); assert_eq!(decoded.x, data.x); } }
27.85119
125
0.606754
797a37471eec4d3dd5da3f5f0566f2070a375756
4,659
use std::collections::HashMap; use bevy::prelude::*; use bevy_rapier2d::na::Vector2; use decorum::R32; use rand::{thread_rng, Rng as _}; pub struct Rock { size: f32, } impl Rock { pub fn new(size: f32) -> Self { Self { size } } pub fn size(&self) -> f32 { self.size } } pub struct RockSpawner { rocks: HashMap<(R32, R32), Entity>, } impl RockSpawner { const BLOCK_SIZE: f32 = 1000.0; pub fn new() -> Self { RockSpawner { rocks: HashMap::new(), } } // TASK: Improve rock generation algorithm: // - Spawn at random positions, not on a grid. // - Vary min and max size in a more interesting way. // - Vary rock density, according to position. pub fn spawn( &mut self, pos: Vector2<f32>, mut spawn: impl FnMut(Vector2<f32>, f32) -> Entity, ) { // Snap center to a grid defined by the block size. let center = pos .map(|v| ((v / Self::BLOCK_SIZE).floor() + 0.5) * Self::BLOCK_SIZE); let offsets = [ Vector2::new(-Self::BLOCK_SIZE, -Self::BLOCK_SIZE), Vector2::new(-Self::BLOCK_SIZE, 0.0), Vector2::new(-Self::BLOCK_SIZE, Self::BLOCK_SIZE), Vector2::new(0.0, -Self::BLOCK_SIZE), Vector2::new(0.0, 0.0), Vector2::new(0.0, Self::BLOCK_SIZE), Vector2::new(Self::BLOCK_SIZE, -Self::BLOCK_SIZE), Vector2::new(Self::BLOCK_SIZE, 0.0), Vector2::new(Self::BLOCK_SIZE, Self::BLOCK_SIZE), ]; for &offset in &offsets { self.spawn_block(center + offset, &mut spawn); } } pub fn clean_up( &mut self, ship_position: Vector2<f32>, rock_position: &impl Fn(Entity) -> Option<Vector2<f32>>, remove: &mut impl FnMut(Entity), ) { self.rocks .retain(|_, &mut entity| match rock_position(entity) { Some(rock_position) => { let distance = (ship_position - rock_position).magnitude(); let remove_rock = distance >= Self::BLOCK_SIZE * 3.0; if remove_rock { remove(entity) } !remove_rock } None => true, }); } fn spawn_block( &mut self, center: Vector2<f32>, spawn: &mut impl FnMut(Vector2<f32>, f32) -> Entity, ) { let area = Rect { left: center.x - Self::BLOCK_SIZE / 2.0, right: center.x + Self::BLOCK_SIZE / 2.0, top: center.y - Self::BLOCK_SIZE / 2.0, bottom: center.y + Self::BLOCK_SIZE / 2.0, }; let mut rng = thread_rng(); let mut position = Vector2::new(area.left, area.top); loop { let parameters = self.parameters(position); if parameters.density > 0.0 { let position_real = (R32::from_inner(position.x), R32::from_inner(position.y)); if !self.rocks.contains_key(&position_real) { let size = parameters.min_size + (parameters.max_size - parameters.min_size) * rng.gen::<f32>(); let entity = spawn(position, size); self.rocks.insert(position_real, entity); debug!( "Spawning rock \ (center: ({}, {}); pos: ({}, {}, total: {})", center.x, center.y, position_real.0, position_real.1, self.rocks.len(), ); } } position.x += 500.0; if position.x > area.right { position.y += 500.0; position.x = area.left; } if position.y > area.bottom { break; } } } fn parameters(&self, position: Vector2<f32>) -> SpawnParameters { let density = if position.y >= 0.0 { 1.0 } else { 0.0 }; const MIN_MIN_SIZE: f32 = 10.0; const MAX_MIN_SIZE: f32 = 250.0; let f = position.x % 5000.0 / 5000.0; let min_size = MIN_MIN_SIZE + (MAX_MIN_SIZE - MIN_MIN_SIZE) * f; let max_size = min_size * 2.0; SpawnParameters { density, min_size, max_size, } } } struct SpawnParameters { density: f32, min_size: f32, max_size: f32, }
28.408537
80
0.482507
db6405482c5969cb430b068a0f6ac4c8ebc8bed1
255
// rustfmt-edition: 2018 fn main() { let async_closure = async { let x = 3; x }; let f = async /* comment */ { let x = 3; x }; let g = async /* comment */ move { let x = 3; x }; }
13.421053
38
0.388235
09e1e8afd1ada7db341a096a576e0e14fb13c1ed
10,137
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // Test expressions fn foo() -> bool { let boxed: Box<i32> = box 5; let referenced = &5; let very_long_variable_name = (a + first + simple + test); let very_long_variable_name = (a + first + simple + test + AAAAAAAAAAAAA + BBBBBBBBBBBBBBBBB + b + c); let is_internalxxxx = self.codemap.span_to_filename(s) == self.codemap.span_to_filename(m.inner); let some_val = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * bbbb / (bbbbbb - function_call(x, *very_long_pointer, y)) + 1000; some_ridiculously_loooooooooooooooooooooong_function( 10000 * 30000000000 + 40000 / 1002200000000 - 50000 * sqrt(-1), trivial_value, ); (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + a + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaa); { for _ in 0..10 {} } { { { {} } } } if 1 + 2 > 0 { let result = 5; result } else { 4 }; if let Some(x) = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa { // Nothing } if let Some(x) = (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {} if let ( some_very_large, tuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuple, ) = 1 + 2 + 3 {} if let ( some_very_large, tuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuple, ) = 1111 + 2222 {} if let ( some_very_large, tuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuple, ) = 1 + 2 + 3 {} if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) = item.node { // nothing } let test = if true { 5 } else { 3 }; if cond() { something(); } else if different_cond() { something_else(); } else { // Check subformatting aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa } } fn bar() { let range = (111111111 + 333333333333333333 + 1111 + 400000000000000000)..(2222 + 2333333333333333); let another_range = 5..some_func(a, b /* comment */); for _ in 1.. { call_forever(); } syntactically_correct( loop { sup('?'); }, if cond { 0 } else { 1 }, ); let third = ..10; let infi_range = ..; let foo = 1..; let bar = 5; let nonsense = (10..0)..(0..10); loop { if true { break; } } let x = ( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, a, ); } fn baz() { unsafe /* {}{}{}{{{{}} */ { let foo = 1u32; } unsafe /* very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong * comment */ { } unsafe /* So this is a very long comment. * Multi-line, too. * Will it still format correctly? */ { } unsafe { // Regular unsafe block } unsafe { foo() } unsafe { foo(); } // #2289 let identifier_0 = unsafe { this_is_58_chars_long_and_line_is_93_chars_long_xxxxxxxxxx }; let identifier_1 = unsafe { this_is_59_chars_long_and_line_is_94_chars_long_xxxxxxxxxxx }; let identifier_2 = unsafe { this_is_65_chars_long_and_line_is_100_chars_long_xxxxxxxxxxxxxxxx }; let identifier_3 = unsafe { this_is_66_chars_long_and_line_is_101_chars_long_xxxxxxxxxxxxxxxxx }; } // Test some empty blocks. fn qux() { {} // FIXME this one could be done better. { /* a block with a comment */ } {} { // A block with a comment. } } fn issue227() { { let handler = box DocumentProgressHandler::new(addr, DocumentProgressTask::DOMContentLoaded); } } fn issue184(source: &str) { for c in source.chars() { if index < 'a' { continue; } } } fn arrays() { let x = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, ]; let y = [/* comment */ 1, 2 /* post comment */, 3]; let xy = [ strukt { test123: value_one_two_three_four, turbo: coolio(), }, // comment 1, ]; let a = WeightedChoice::new(&mut [ Weighted { weightweight: x, item: 0, }, Weighted { weightweight: 1, item: 1, }, Weighted { weightweight: x, item: 2, }, Weighted { weightweight: 1, item: 3, }, ]); let z = [ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzz, q, ]; [1 + 3, 4, 5, 6, 7, 7, fncall::<Vec<_>>(3 - 1)] } fn returns() { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && return; return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; } fn addrof() { &mut (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb); &(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb); } fn casts() { fn unpack(packed: u32) -> [u16; 2] { [(packed >> 16) as u16, (packed >> 0) as u16] } let some_trait_xxx = xxxxxxxxxxx + xxxxxxxxxxxxx as SomeTraitXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; let slightly_longer_trait = yyyyyyyyy + yyyyyyyyyyy as SomeTraitYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY; } fn indices() { let x = (aaaaaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccc) [x + y + z]; let y = (aaaaaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccc) [xxxxx + yyyyy + zzzzz]; let z = xxxxxxxxxx .x() .y() .zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz()[aaaaa]; let z = xxxxxxxxxx .x() .y() .zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz() [aaaaa]; } fn repeats() { let x = [aaaaaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccc; x + y + z]; let y = [aaaaaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccc; xxxxx + yyyyy + zzzzz]; } fn blocks() { if 1 + 1 == 2 { println!("yay arithmetix!"); }; } fn issue767() { if false { if false { } else { // A let binding here seems necessary to trigger it. let _ = (); } } else if let false = false { } } fn ranges() { let x = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa..bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; let y = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa..=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; let z = ..=x; // #1766 let x = [0. ..10.0]; let x = [0. ..=10.0]; a..=b // the expr below won't compile because inclusive ranges need a defined end // let a = 0 ..= ; } fn if_else() { let exact = diff / (if size == 0 { 1 } else { size }); let cx = tp1.x + any * radius * if anticlockwise { 1.0 } else { -1.0 }; } fn complex_if_else() { if let Some(x) = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx { } else if let Some(x) = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx { ha(); } else if xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxx { yo(); } else if let Some(x) = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx { ha(); } else if xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxx { yo(); } } fn issue1106() { { if let hir::ItemEnum(ref enum_def, ref generics) = self.ast_map.expect_item(enum_node_id).node {} } for entry in WalkDir::new(path) .into_iter() .filter_entry(|entry| exclusions.filter_entry(entry)) {} } fn issue1570() { a_very_long_function_name({ some_func(1, { 1 }) }) } fn issue1714() { v = &mut { v }[mid..]; let (left, right) = { v }.split_at_mut(mid); } // Multi-lined index should be put on the next line if it fits in one line. fn issue1749() { { { { if self.shape[(r as f32 + self.x_offset) as usize] [(c as f32 + self.y_offset) as usize] != 0 { // hello } } } } } // #1172 fn newlines_between_list_like_expr() { foo( xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, ); vec![ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, ]; match x { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy | zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz => foo(a, b, c), _ => bar(), }; } fn issue2178() { Ok(result .iter() .map(|item| ls_util::rls_to_location(item)) .collect()) } // #2493 impl Foo { fn bar(&self) { { let x = match () { () => { let i; i == self.install_config .storage .experimental_compressed_block_size as usize } }; } } }
24.604369
100
0.590115
bb42d79747d83a86fcf8bd00c9f48bb9d4c1b827
2,879
use crate::common::util::*; use std::time::{Duration, Instant}; #[test] fn test_sleep_no_suffix() { let millis_100 = Duration::from_millis(100); let before_test = Instant::now(); new_ucmd!().args(&["0.1"]).succeeds().stdout_only(""); let duration = before_test.elapsed(); assert!(duration >= millis_100); } #[test] fn test_sleep_s_suffix() { let millis_100 = Duration::from_millis(100); let before_test = Instant::now(); new_ucmd!().args(&["0.1s"]).succeeds().stdout_only(""); let duration = before_test.elapsed(); assert!(duration >= millis_100); } #[test] fn test_sleep_m_suffix() { let millis_600 = Duration::from_millis(600); let before_test = Instant::now(); new_ucmd!().args(&["0.01m"]).succeeds().stdout_only(""); let duration = before_test.elapsed(); assert!(duration >= millis_600); } #[test] fn test_sleep_h_suffix() { let millis_360 = Duration::from_millis(360); let before_test = Instant::now(); new_ucmd!().args(&["0.0001h"]).succeeds().stdout_only(""); let duration = before_test.elapsed(); assert!(duration >= millis_360); } #[test] fn test_sleep_negative_duration() { new_ucmd!().args(&["-1"]).fails(); new_ucmd!().args(&["-1s"]).fails(); new_ucmd!().args(&["-1m"]).fails(); new_ucmd!().args(&["-1h"]).fails(); new_ucmd!().args(&["-1d"]).fails(); } #[test] fn test_sleep_zero_duration() { new_ucmd!().args(&["0"]).succeeds().stdout_only(""); new_ucmd!().args(&["0s"]).succeeds().stdout_only(""); new_ucmd!().args(&["0m"]).succeeds().stdout_only(""); new_ucmd!().args(&["0h"]).succeeds().stdout_only(""); new_ucmd!().args(&["0d"]).succeeds().stdout_only(""); } #[test] fn test_sleep_no_argument() { new_ucmd!().fails(); } #[test] fn test_sleep_sum_duration_same_suffix() { let millis_200 = Duration::from_millis(100 + 100); let before_test = Instant::now(); new_ucmd!() .args(&["0.1s", "0.1s"]) .succeeds() .stdout_only(""); let duration = before_test.elapsed(); assert!(duration >= millis_200); } #[test] fn test_sleep_sum_duration_different_suffix() { let millis_700 = Duration::from_millis(100 + 600); let before_test = Instant::now(); new_ucmd!() .args(&["0.1s", "0.01m"]) .succeeds() .stdout_only(""); let duration = before_test.elapsed(); assert!(duration >= millis_700); } #[test] fn test_sleep_sum_duration_many() { let millis_900 = Duration::from_millis(100 + 100 + 300 + 400); let before_test = Instant::now(); new_ucmd!() .args(&["0.1s", "0.1s", "0.3s", "0.4s"]) .succeeds() .stdout_only(""); let duration = before_test.elapsed(); assert!(duration >= millis_900); } #[test] fn test_sleep_wrong_time() { new_ucmd!() .args(&["0.1s", "abc"]) .fails(); }
23.991667
66
0.602292
91bef9b9a67f9c9e7a59bae87045afa155729d2f
4,589
#![feature(allocator_api)] #![cfg_attr(target_os = "linux", no_main)] use std::fs::File; use std::io::Read; #[cfg(target_os = "linux")] use { libc, std::alloc::Allocator, std::alloc::Layout, std::io::Seek, std::io::SeekFrom, std::io::Write, std::os::unix::io::FromRawFd, std::ptr::NonNull, }; use libshim; #[cfg(target_os = "linux")] #[link(name = "c")] extern "C" { pub fn malloc(size: usize) -> *mut u8; pub fn free(ptr: *mut u8); } #[derive(Debug, Copy, Clone)] struct StephenAllocator {} #[cfg(target_os = "linux")] impl libshim::Allocator for StephenAllocator {} #[cfg(target_os = "linux")] unsafe impl Allocator for StephenAllocator { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, std::alloc::AllocError> { // It's not entirely clear what to do about the alignment. I assume we // can just assume malloc does the right thing? let size = layout.size(); let ptr: *mut u8 = unsafe { malloc(size) }; if ptr.is_null() { Err(std::alloc::AllocError) } else { NonNull::new(std::ptr::slice_from_raw_parts_mut(ptr, size)) .ok_or(std::alloc::AllocError) } } unsafe fn deallocate(&self, ptr: NonNull<u8>, _: Layout) { free(ptr.as_ptr()) } } #[cfg(target_os = "linux")] fn stdout() -> File { unsafe { File::from_raw_fd(1) } } #[cfg(target_os = "linux")] struct FilePrinter { f: File, } #[cfg(target_os = "linux")] impl libshim::Printer for FilePrinter { fn print(&mut self, text: &[u8]) { self.f.write(text).unwrap(); } } struct NormalPrinter {} impl libshim::Printer for NormalPrinter { fn print(&mut self, text: &[u8]) { print!("{}", String::from_utf8_lossy(text)); } } #[no_mangle] #[cfg(target_os = "linux")] pub fn main(argc: i32, _argv: *const *const i8) -> Result<(), std::alloc::AllocError> { let mut stdout = stdout(); // TODO: implement a REPL if argc != 2 { stdout .write(b"Expected a single script as an argument\n") .unwrap(); return Ok(()); } let allocator = StephenAllocator {}; let script_name = unsafe { *_argv.offset(1) }; // TODO: handle error codes // We open this ourselves since there's no way to open a file from a path // without using the global allocator... let fd = unsafe { libc::open(script_name, libc::O_RDONLY) }; if fd == -1 { stdout.write(b"Error while opening script\n").unwrap(); return Ok(()); } let mut file = unsafe { File::from_raw_fd(fd) }; let file_length = file.seek(SeekFrom::End(0)).unwrap() as usize; file.seek(SeekFrom::Start(0)).unwrap(); let buf_layout = Layout::array::<u8>(file_length).map_err(|_| std::alloc::AllocError)?; let buf: NonNull<[u8]> = allocator.allocate(buf_layout)?; let count = unsafe { file.read(&mut *buf.as_ptr()).unwrap() }; // Lazy file reading // TODO: did we read the whole file? assert_eq!(count, file_length); let mut interpreter = libshim::Interpreter::new(allocator); let mut stdout_printer = FilePrinter { f: stdout }; interpreter.set_print_fn(&mut stdout_printer); match interpreter.interpret(unsafe { &(*buf.as_ptr()) }) { Ok(_) => {} Err(libshim::ShimError::Other(text)) => { interpreter.print(b"ERROR: "); interpreter.print(text); interpreter.print(b"\n"); } other => { other.unwrap(); } } unsafe { allocator.deallocate(buf.cast(), buf_layout) }; Ok(()) } #[cfg(not(target_os = "linux"))] pub fn main() -> Result<(), ()> { use std::env; let mut args = env::args(); if args.len() != 2 { println!("Expected a single script as an argument\n"); return Err(()); } let _exe = args.next(); let script_name = args.next().unwrap(); println!("Loading script {}", script_name); let mut file = File::open(script_name).unwrap(); let mut buf = Vec::new(); file.read_to_end(&mut buf).unwrap(); let allocator = std::alloc::Global; let mut interpreter = libshim::Interpreter::new(allocator); let mut printer = NormalPrinter {}; interpreter.set_print_fn(&mut printer); match interpreter.interpret(&buf) { Ok(_) => {} Err(libshim::ShimError::Other(text)) => { interpreter.print(b"ERROR: "); interpreter.print(text); interpreter.print(b"\n"); } other => { other.unwrap(); } } Ok(()) }
27.315476
91
0.585966
e8f01c543698443ff9ac3e9e78a5757bbb4952ad
668
// This file is part of olympus-xmp. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/olympus-xmp/master/COPYRIGHT. No part of olympus-xmp, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2022 The developers of olympus-xmp. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/olympus-xmp/master/COPYRIGHT. #[allow(missing_docs)] pub(super) const x00F6: char = 0x00F6 as char;
95.428571
390
0.796407
263ec95caa7d6a3d31b5d4ddcd201e644ea644ab
1,207
// 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. // edition:2018 // aux-build:edition-kw-macro-2018.rs #![feature(raw_identifiers)] #[macro_use] extern crate edition_kw_macro_2018; pub fn check_async() { let mut async = 1; //~ ERROR expected identifier, found reserved keyword `async` let mut r#async = 1; // OK r#async = consumes_async!(async); // OK r#async = consumes_async!(r#async); //~ ERROR no rules expected the token `r#async` r#async = consumes_async_raw!(async); //~ ERROR no rules expected the token `async` r#async = consumes_async_raw!(r#async); // OK if passes_ident!(async) == 1 {} if passes_ident!(r#async) == 1 {} // OK module::async(); //~ ERROR expected identifier, found reserved keyword `async` module::r#async(); // OK }
36.575758
87
0.694283
e5e4be99b5b5b0a64f39f41560ae7da97f911c01
109
// http://rosettacode.org/wiki/Zero_to_the_zero_power fn main() { println!("0 ^ 0 = {}", 0i64.pow(0)); }
21.8
53
0.614679
7935a65da8f5ed8c04899d96d3329b622e5fdd4e
8,601
use std::collections::BTreeMap; use dfn_candid::candid; use ic_canister_client::Sender; use ic_nns_common::registry::encode_or_panic; use ic_nns_constants::ids::{ TEST_NEURON_1_OWNER_KEYPAIR, TEST_NEURON_1_OWNER_PRINCIPAL, TEST_USER1_KEYPAIR, }; use ic_nns_test_utils::{ itest_helpers::{local_test_on_nns_subnet, set_up_registry_canister}, registry::{get_value, invariant_compliant_mutation_as_atomic_req, prepare_add_node_payload}, }; use ic_protobuf::registry::{ crypto::v1::{PublicKey, X509PublicKeyCert}, node::v1::NodeRecord, node_operator::v1::NodeOperatorRecord, }; use ic_registry_keys::{ make_crypto_node_key, make_crypto_tls_cert_key, make_node_operator_record_key, make_node_record_key, }; use ic_registry_transport::pb::v1::{ registry_mutation, RegistryAtomicMutateRequest, RegistryMutation, }; use ic_types::{crypto::KeyPurpose, NodeId}; use registry_canister::init::RegistryCanisterInitPayloadBuilder; #[test] fn node_is_created_on_receiving_the_request() { local_test_on_nns_subnet(|runtime| async move { // First prepare the registry with a Node Operator record and make it callable // by anyone let registry = set_up_registry_canister( &runtime, RegistryCanisterInitPayloadBuilder::new() .push_init_mutate_request(invariant_compliant_mutation_as_atomic_req()) .push_init_mutate_request(init_mutation_with_node_allowance(100)) .build(), ) .await; let (payload, node_pks, node_id) = prepare_add_node_payload(); // Then, ensure there is no value for the node let node_record = get_value::<NodeRecord>(&registry, make_node_record_key(node_id).as_bytes()).await; assert_eq!(node_record, NodeRecord::default()); let response: Result<NodeId, String> = registry .update_from_sender( "add_node", candid, (payload,), &Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR), ) .await; assert!(response.is_ok()); // Now let's check directly in the registry that the mutation actually happened let node_record = get_value::<NodeRecord>(&registry, make_node_record_key(node_id).as_bytes()).await; // Check if some fields are present assert!(node_record.http.is_some()); assert_eq!(node_record.p2p_flow_endpoints.len(), 1); // Check that other fields are present let node_signing_pubkey_record = get_value::<PublicKey>( &registry, make_crypto_node_key(node_id, KeyPurpose::NodeSigning).as_bytes(), ) .await; assert_eq!( node_signing_pubkey_record, node_pks.node_signing_pk.unwrap() ); let committee_signing_pubkey_record = get_value::<PublicKey>( &registry, make_crypto_node_key(node_id, KeyPurpose::CommitteeSigning).as_bytes(), ) .await; assert_eq!( committee_signing_pubkey_record, node_pks.committee_signing_pk.unwrap() ); let ni_dkg_dealing_encryption_pubkey_record = get_value::<PublicKey>( &registry, make_crypto_node_key(node_id, KeyPurpose::DkgDealingEncryption).as_bytes(), ) .await; assert_eq!( ni_dkg_dealing_encryption_pubkey_record, node_pks.dkg_dealing_encryption_pk.unwrap() ); let transport_tls_certificate_record = get_value::<X509PublicKeyCert>(&registry, make_crypto_tls_cert_key(node_id).as_bytes()) .await; assert_eq!( transport_tls_certificate_record, node_pks.tls_certificate.unwrap() ); // Check that node allowance has decreased let node_operator_record = get_value::<NodeOperatorRecord>( &registry, make_node_operator_record_key(*TEST_NEURON_1_OWNER_PRINCIPAL).as_bytes(), ) .await; assert_eq!(node_operator_record.node_allowance, 99); Ok(()) }); } #[test] fn node_is_not_created_on_wrong_principal() { local_test_on_nns_subnet(|runtime| async move { // First prepare the registry with a Node Operator record and make it callable // by anyone let registry = set_up_registry_canister( &runtime, RegistryCanisterInitPayloadBuilder::new() .push_init_mutate_request(invariant_compliant_mutation_as_atomic_req()) .push_init_mutate_request(init_mutation_with_node_allowance(100)) .build(), ) .await; let (payload, _node_pks, node_id) = prepare_add_node_payload(); // Then, ensure there is no value for the node let node_record = get_value::<NodeRecord>(&registry, make_node_record_key(node_id).as_bytes()).await; assert_eq!(node_record, NodeRecord::default()); // Issue a request with an unauthorized sender, which should fail. let response: Result<NodeId, String> = registry .update_from_sender( "add_node", candid, (payload,), &Sender::from_keypair(&TEST_USER1_KEYPAIR), ) .await; assert!(response.is_err()); // The record should still not be there let node_record = get_value::<NodeRecord>(&registry, make_node_record_key(node_id).as_bytes()).await; assert_eq!(node_record, NodeRecord::default()); Ok(()) }); } #[test] fn node_is_not_created_when_above_capacity() { local_test_on_nns_subnet(|runtime| async move { // First prepare the registry with a DC record and make it callable by anyone let registry = set_up_registry_canister( &runtime, RegistryCanisterInitPayloadBuilder::new() .push_init_mutate_request(invariant_compliant_mutation_as_atomic_req()) .push_init_mutate_request(init_mutation_with_node_allowance(1)) .build(), ) .await; let (payload, _node_pks, node_id) = prepare_add_node_payload(); // Then, ensure there is no value for the node let node_record = get_value::<NodeRecord>(&registry, make_node_record_key(node_id).as_bytes()).await; assert_eq!(node_record, NodeRecord::default()); // This should succeed let response: Result<NodeId, String> = registry .update_from_sender( "add_node", candid, (payload,), &Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR), ) .await; assert!(response.is_ok()); // Try to add another node let (payload, _node_pks, node_id) = prepare_add_node_payload(); // Ensure there is no value for this new node let node_record = get_value::<NodeRecord>(&registry, make_node_record_key(node_id).as_bytes()).await; assert_eq!(node_record, NodeRecord::default()); // This should now be rejected let response: Result<NodeId, String> = registry .update_from_sender( "add_node", candid, (payload,), &Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR), ) .await; assert!(response.is_err()); // The record should not be there let node_record = get_value::<NodeRecord>(&registry, make_node_record_key(node_id).as_bytes()).await; assert_eq!(node_record, NodeRecord::default()); Ok(()) }); } fn init_mutation_with_node_allowance(node_allowance: u64) -> RegistryAtomicMutateRequest { let node_operator_record = NodeOperatorRecord { node_operator_principal_id: TEST_NEURON_1_OWNER_PRINCIPAL.to_vec(), node_allowance, // This doesn't go through Governance validation node_provider_principal_id: vec![], dc_id: "".into(), rewardable_nodes: BTreeMap::new(), }; RegistryAtomicMutateRequest { mutations: vec![RegistryMutation { mutation_type: registry_mutation::Type::Insert as i32, key: make_node_operator_record_key(*TEST_NEURON_1_OWNER_PRINCIPAL) .as_bytes() .to_vec(), value: encode_or_panic(&node_operator_record), }], preconditions: vec![], } }
36.291139
99
0.633996
26cf63dc696af1cf01bbc3208f1a2135d81bb853
539
//! Benchmarking setup for pallet-template use super::*; #[allow(unused)] use crate::Pallet as Template; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::RawOrigin; benchmarks! { do_something { let s in 0 .. 100; let caller: T::AccountId = whitelisted_caller(); }: _(RawOrigin::Signed(caller), s) verify { assert_eq!(Something::<T>::get(), Some(s)); } } impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,);
25.666667
86
0.680891
03cf2248104bc7b8671daa2c8f3133bc2e49945d
785
macro_rules! capture_expr_then_stringify { ($e:expr) => { stringify!($e) }; } macro_rules! capture_then_what_is { (#[$m:meta]) => {what_is!(#[$m])}; } macro_rules! what_is { (#[no_mangle]) => {"no_mangle attribute"}; (#[inline]) => {"inline attribute"}; ($($tts:tt)*) => {concat!("something else (", stringify!($($tts)*), ")")}; } #[test] fn test_capture_expr_then_stringify() { println!("{:?}", stringify!(dummy(2 * (1 + (3))))); println!("{:?}", capture_expr_then_stringify!(dummy(2 * (1 + (3))))); } #[test] fn test_capture_then_what_is() { println!( "{}\n{}\n{}\n{}", what_is!(#[no_mangle]), what_is!(#[inline]), capture_then_what_is!(#[no_mangle]), capture_then_what_is!(#[inline]), ); }
23.787879
78
0.545223
fc8f1c7b097db5eaa789bb74d884720949e74217
1,744
/* Copyright 2021 Google LLC 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 https://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. */ #![allow(dead_code)] use lockjaw::{component, epilogue, module, qualifier}; pub use String as NamedString; lockjaw::prologue!("tests/module_provides_qualifier.rs"); //ANCHOR: decl #[qualifier] pub struct Q1; //ANCHOR_END: decl #[qualifier] pub struct Q2; pub struct MyModule {} //ANCHOR: module #[module] impl MyModule { #[provides] pub fn provide_string() -> String { "string".to_owned() } #[provides] #[qualified(Q1)] pub fn provide_q1_string() -> String { "q1_string".to_owned() } #[provides] #[qualified(Q2)] pub fn provide_q2_string() -> String { "q2_string".to_owned() } } // ANCHOR_END: module //ANCHOR: component #[component(modules: [MyModule])] pub trait MyComponent { fn string(&self) -> String; #[qualified(Q1)] fn q1_string(&self) -> String; #[qualified(Q2)] fn q2_string(&self) -> String; } //ANCHOR_END: component #[test] pub fn main() { let component: Box<dyn MyComponent> = <dyn MyComponent>::new(); assert_eq!(component.string(), "string"); assert_eq!(component.q1_string(), "q1_string"); assert_eq!(component.q2_string(), "q2_string"); } epilogue!();
22.947368
72
0.686353
28878b4c71d21127f69645b38532016d1270452c
24,795
use std::fmt; use serde::de::{Error, MapAccess, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use core_consensus::SyncStatus as InnerSyncStatus; use protocol::codec::ProtocolCodec; use protocol::types::{ AccessList, Block, Bloom, Bytes, Hash, Header, Hex, Public, Receipt, SignedTransaction, H160, H256, U256, U64, }; const EIP1559_TX_TYPE: u64 = 0x02; #[allow(clippy::large_enum_variant)] #[derive(Deserialize, Clone, Debug, PartialEq, Eq)] pub enum RichTransactionOrHash { Hash(Hash), Rich(SignedTransaction), } impl Serialize for RichTransactionOrHash { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { RichTransactionOrHash::Hash(h) => h.serialize(serializer), RichTransactionOrHash::Rich(stx) => stx.serialize(serializer), } } } impl RichTransactionOrHash { pub fn get_hash(&self) -> Hash { match self { RichTransactionOrHash::Hash(hash) => *hash, RichTransactionOrHash::Rich(stx) => stx.transaction.hash, } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct Web3Transaction { #[serde(rename = "type")] pub type_: Option<U64>, pub block_number: Option<U256>, pub block_hash: Option<H256>, pub hash: Hash, pub nonce: U256, pub transaction_index: Option<U256>, pub from: H160, pub to: Option<H160>, pub value: U256, pub gas_price: U256, #[serde(skip_serializing_if = "Option::is_none")] pub max_fee_per_gas: Option<U256>, #[serde(skip_serializing_if = "Option::is_none")] pub max_priority_fee_per_gas: Option<U256>, pub raw: Hex, pub input: Hex, pub public_key: Option<Public>, #[serde(skip_serializing_if = "Option::is_none")] pub access_list: Option<AccessList>, pub chain_id: Option<U256>, #[serde(skip_serializing_if = "Option::is_none")] pub standard_v: Option<U256>, pub v: U256, pub r: U256, pub s: U256, } impl From<SignedTransaction> for Web3Transaction { fn from(stx: SignedTransaction) -> Web3Transaction { let signature = stx.transaction.signature.clone().unwrap_or_default(); Web3Transaction { type_: Some(EIP1559_TX_TYPE.into()), block_number: None, block_hash: None, raw: Hex::encode(stx.transaction.encode().unwrap()), public_key: stx.public, gas_price: stx.transaction.unsigned.gas_price, max_fee_per_gas: Some(U256::from(1337u64)), max_priority_fee_per_gas: Some(stx.transaction.unsigned.max_priority_fee_per_gas), hash: stx.transaction.hash, from: stx.sender, to: stx.get_to(), input: Hex::encode(stx.transaction.unsigned.data), nonce: stx.transaction.unsigned.value, transaction_index: None, value: stx.transaction.unsigned.value, access_list: Some(stx.transaction.unsigned.access_list.clone()), chain_id: Some(stx.transaction.chain_id.into()), standard_v: None, v: signature.standard_v.into(), r: signature.r.as_ref().into(), s: signature.s.as_ref().into(), } } } impl From<(SignedTransaction, Receipt)> for Web3Transaction { fn from(stx_receipt: (SignedTransaction, Receipt)) -> Self { let (stx, receipt) = stx_receipt; let signature = stx.transaction.signature.clone().unwrap_or_default(); Web3Transaction { type_: Some(EIP1559_TX_TYPE.into()), block_number: Some(receipt.block_number.into()), block_hash: Some(receipt.block_hash), raw: Hex::encode(stx.transaction.encode().unwrap()), public_key: stx.public, gas_price: stx.transaction.unsigned.gas_price, max_fee_per_gas: Some(U256::from(1337u64)), max_priority_fee_per_gas: Some(stx.transaction.unsigned.max_priority_fee_per_gas), hash: receipt.tx_hash, from: stx.sender, to: stx.get_to(), input: Hex::encode(stx.transaction.unsigned.data), nonce: stx.transaction.unsigned.value, transaction_index: Some(receipt.tx_index.into()), value: stx.transaction.unsigned.value, access_list: Some(stx.transaction.unsigned.access_list.clone()), chain_id: Some(stx.transaction.chain_id.into()), standard_v: None, v: signature.standard_v.into(), r: signature.r.as_ref().into(), s: signature.s.as_ref().into(), } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct Web3Receipt { pub block_number: U256, pub block_hash: H256, pub contract_address: Option<H160>, pub cumulative_gas_used: U256, pub effective_gas_price: U256, pub from: H160, pub gas_used: U256, pub logs: Vec<Web3ReceiptLog>, pub logs_bloom: Bloom, #[serde(rename = "root")] pub state_root: Hash, pub status: U256, pub to: Option<H160>, pub transaction_hash: Hash, pub transaction_index: Option<U256>, #[serde(rename = "type", skip_serializing_if = "Option::is_none")] pub transaction_type: Option<U64>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct Web3ReceiptLog { pub address: H160, pub topics: Vec<H256>, pub data: Hex, pub block_number: U256, pub block_hash: Hash, pub transaction_hash: Hash, pub transaction_index: Option<U256>, pub log_index: U256, pub removed: bool, } impl Web3Receipt { pub fn new(receipt: Receipt, stx: SignedTransaction) -> Web3Receipt { let logs_list = receipt .logs .iter() .map(|log| Web3ReceiptLog { address: log.address, topics: log.topics.clone(), data: Hex::encode(&log.data), block_number: receipt.block_number.into(), block_hash: receipt.block_hash, transaction_hash: receipt.tx_hash, transaction_index: Some(receipt.tx_index.into()), log_index: U256::zero(), removed: false, }) .collect::<Vec<_>>(); let mut web3_receipt = Web3Receipt { block_number: receipt.block_number.into(), block_hash: receipt.block_hash, contract_address: receipt.code_address.map(Into::into), cumulative_gas_used: receipt.used_gas, effective_gas_price: receipt.used_gas, from: receipt.sender, status: receipt.status(), gas_used: receipt.used_gas, logs: logs_list, logs_bloom: receipt.logs_bloom, state_root: receipt.state_root, to: stx.get_to(), transaction_hash: receipt.tx_hash, transaction_index: Some(receipt.tx_index.into()), transaction_type: Some(EIP1559_TX_TYPE.into()), }; for item in receipt.logs.into_iter() { web3_receipt.logs.push(Web3ReceiptLog { address: item.address, topics: item.topics, data: Hex::encode(item.data), block_number: receipt.block_number.into(), transaction_hash: receipt.tx_hash, transaction_index: Some(receipt.tx_index.into()), block_hash: receipt.block_hash, log_index: receipt.log_index.into(), // Todo: FIXME removed: false, }); } web3_receipt } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct Web3Block { pub hash: H256, pub parent_hash: H256, #[serde(rename = "sha3Uncles")] pub sha3_uncles: H256, pub author: H160, pub miner: H160, pub state_root: H256, pub transactions_root: H256, pub receipts_root: H256, pub number: U256, pub gas_used: U256, pub gas_limit: U256, pub extra_data: Hex, pub logs_bloom: Option<Bloom>, pub timestamp: U256, pub difficulty: U256, pub total_difficulty: Option<U256>, pub seal_fields: Vec<Bytes>, pub base_fee_per_gas: U256, pub uncles: Vec<H256>, pub transactions: Vec<RichTransactionOrHash>, pub size: Option<U256>, pub mix_hash: H256, pub nonce: U256, } impl From<Block> for Web3Block { fn from(b: Block) -> Self { Web3Block { hash: b.header_hash(), number: b.header.number.into(), author: b.header.proposer, parent_hash: b.header.prev_hash, sha3_uncles: Default::default(), logs_bloom: Some(b.header.log_bloom), transactions_root: b.header.transactions_root, state_root: b.header.state_root, receipts_root: b.header.receipts_root, miner: b.header.proposer, difficulty: b.header.difficulty, total_difficulty: None, seal_fields: vec![], base_fee_per_gas: b.header.base_fee_per_gas, extra_data: Hex::encode(&b.header.extra_data), size: Some(b.header.size().into()), gas_limit: b.header.gas_limit, gas_used: b.header.gas_used, timestamp: b.header.timestamp.into(), transactions: b .tx_hashes .iter() .map(|hash| RichTransactionOrHash::Hash(*hash)) .collect(), uncles: vec![], mix_hash: H256::default(), nonce: U256::default(), } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub enum TransactionCondition { #[serde(rename = "block")] Number(u64), } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Web3CallRequest { #[serde(rename = "type", skip_serializing_if = "Option::is_none")] pub transaction_type: Option<U64>, pub from: Option<H160>, pub to: Option<H160>, #[serde(skip_serializing_if = "Option::is_none")] pub gas_price: Option<U256>, #[serde(skip_serializing_if = "Option::is_none")] pub max_fee_per_gas: Option<U256>, pub gas: Option<U256>, pub value: Option<U256>, pub data: Hex, pub nonce: Option<U256>, #[serde(skip_serializing_if = "Option::is_none")] pub access_list: Option<AccessList>, #[serde(skip_serializing_if = "Option::is_none")] pub max_priority_fee_per_gas: Option<U256>, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum BlockId { Num(u64), Latest, } impl Default for BlockId { fn default() -> Self { BlockId::Latest } } impl From<BlockId> for Option<u64> { fn from(id: BlockId) -> Self { match id { BlockId::Num(num) => Some(num), BlockId::Latest => None, } } } impl<'a> Deserialize<'a> for BlockId { fn deserialize<D>(deserializer: D) -> Result<BlockId, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(BlockIdVisitor) } } impl Serialize for BlockId { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { BlockId::Num(ref x) => serializer.serialize_str(&format!("0x{:x}", x)), BlockId::Latest => serializer.serialize_str("latest"), } } } struct BlockIdVisitor; impl<'a> Visitor<'a> for BlockIdVisitor { type Value = BlockId; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a block number or 'latest' ") } #[allow(clippy::never_loop)] fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapAccess<'a>, { let mut block_number = None; loop { let key_str: Option<String> = visitor.next_key()?; match key_str { Some(key) => match key.as_str() { "blockNumber" => { let value: String = visitor.next_value()?; if let Some(stripper) = value.strip_prefix("0x") { let number = u64::from_str_radix(stripper, 16).map_err(|e| { Error::custom(format!("Invalid block number: {}", e)) })?; block_number = Some(number); break; } else { return Err(Error::custom( "Invalid block number: missing 0x prefix".to_string(), )); } } key => return Err(Error::custom(format!("Unknown key: {}", key))), }, None => break, }; } if let Some(number) = block_number { return Ok(BlockId::Num(number)); } Err(Error::custom("Invalid input")) } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: Error, { match value { "latest" => Ok(BlockId::Latest), _ if value.starts_with("0x") => u64::from_str_radix(&value[2..], 16) .map(BlockId::Num) .map_err(|e| Error::custom(format!("Invalid block number: {}", e))), _ => Err(Error::custom( "Invalid block number: missing 0x prefix".to_string(), )), } } fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: Error, { self.visit_str(value.as_ref()) } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum BlockIdWithPending { BlockId(BlockId), Pending, } impl<'a> Deserialize<'a> for BlockIdWithPending { fn deserialize<D>(deserializer: D) -> Result<BlockIdWithPending, D::Error> where D: Deserializer<'a>, { pub struct InnerVisitor; impl<'a> Visitor<'a> for InnerVisitor { type Value = BlockIdWithPending; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a block number or 'latest' or 'pending' ") } fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error> where V: MapAccess<'a>, { BlockIdVisitor .visit_map(visitor) .map(BlockIdWithPending::BlockId) } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: Error, { match value { "pending" => Ok(BlockIdWithPending::Pending), _ => BlockIdVisitor .visit_str(value) .map(BlockIdWithPending::BlockId), } } fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: Error, { self.visit_str(value.as_ref()) } } deserializer.deserialize_any(InnerVisitor) } } #[derive(Debug, PartialEq)] pub struct Index(usize); impl Index { pub fn _value(&self) -> usize { self.0 } } impl<'a> Deserialize<'a> for Index { fn deserialize<D>(deserializer: D) -> Result<Index, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(IndexVisitor) } } struct IndexVisitor; impl<'a> Visitor<'a> for IndexVisitor { type Value = Index; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a hex-encoded or decimal index") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: Error, { match value { _ if value.starts_with("0x") => usize::from_str_radix(&value[2..], 16) .map(Index) .map_err(|e| Error::custom(format!("Invalid index: {}", e))), _ => value .parse::<usize>() .map(Index) .map_err(|e| Error::custom(format!("Invalid index: {}", e))), } } fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: Error, { self.visit_str(value.as_ref()) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Web3Filter { pub from_block: Option<BlockId>, pub to_block: Option<BlockId>, pub block_hash: Option<H256>, #[serde(default)] pub address: MultiType<H160>, pub topics: Option<Vec<H256>>, } #[derive(PartialEq, Eq, Debug, Clone)] pub enum MultiType<T> { Single(T), Multi(Vec<T>), Null, } impl<T> Default for MultiType<T> { fn default() -> Self { MultiType::Null } } impl<T> From<MultiType<T>> for Option<Vec<T>> { fn from(src: MultiType<T>) -> Self { match src { MultiType::Null => None, MultiType::Single(i) => Some(vec![i]), MultiType::Multi(i) => Some(i), } } } impl<T> Serialize for MultiType<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { MultiType::Single(inner) => inner.serialize(serializer), MultiType::Multi(inner) => inner.serialize(serializer), MultiType::Null => serializer.serialize_none(), } } } impl<'a, T> Deserialize<'a> for MultiType<T> where T: for<'b> Deserialize<'b>, { fn deserialize<D>(deserializer: D) -> Result<MultiType<T>, D::Error> where D: Deserializer<'a>, { let v: serde_json::Value = Deserialize::deserialize(deserializer)?; if v.is_null() { return Ok(MultiType::Null); } serde_json::from_value(v.clone()) .map(MultiType::Single) .or_else(|_| serde_json::from_value(v).map(MultiType::Multi)) .map_err(|err| D::Error::custom(format!("Invalid value type: {}", err))) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Web3Log { pub address: H160, pub topics: Vec<H256>, pub data: Hex, pub block_hash: Option<H256>, pub block_number: Option<U256>, pub transaction_hash: Option<H256>, pub transaction_index: Option<U256>, pub log_index: Option<U256>, #[serde(default)] pub removed: bool, } #[derive(Clone, Debug, PartialEq, Eq)] pub enum Web3SyncStatus { Doing(SyncStatus), False, } impl From<InnerSyncStatus> for Web3SyncStatus { fn from(inner: InnerSyncStatus) -> Self { match inner { InnerSyncStatus::False => Web3SyncStatus::False, InnerSyncStatus::Syncing { start, current, highest, } => Web3SyncStatus::Doing(SyncStatus { starting_block: start, current_block: current, highest_block: highest, known_states: U256::default(), pulled_states: U256::default(), }), } } } impl Serialize for Web3SyncStatus { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { Web3SyncStatus::Doing(status) => status.serialize(serializer), Web3SyncStatus::False => false.serialize(serializer), } } } #[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct SyncStatus { pub starting_block: U256, pub current_block: U256, pub highest_block: U256, pub known_states: U256, pub pulled_states: U256, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Web3FeeHistory { pub oldest_block: U256, pub reward: Option<Vec<U256>>, pub base_fee_per_gas: Vec<U256>, pub gas_used_ratio: Vec<U256>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct Web3Header { pub difficulty: U256, pub extra_data: Hex, pub gas_limit: U256, pub gas_used: U256, pub logs_bloom: Option<Bloom>, pub miner: H160, pub nonce: U256, pub number: U256, pub parent_hash: H256, pub receipts_root: H256, #[serde(rename = "sha3Uncles")] pub sha3_uncles: H256, pub state_root: H256, pub timestamp: U256, pub transactions_root: H256, } impl From<Header> for Web3Header { fn from(h: Header) -> Self { Web3Header { number: h.number.into(), parent_hash: h.prev_hash, sha3_uncles: Default::default(), logs_bloom: Some(h.log_bloom), transactions_root: h.transactions_root, state_root: h.state_root, receipts_root: h.receipts_root, miner: h.proposer, difficulty: h.difficulty, extra_data: Hex::encode(&h.extra_data), gas_limit: h.gas_limit, gas_used: h.gas_used, timestamp: h.timestamp.into(), nonce: U256::default(), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_sync_status_json() { let status = Web3SyncStatus::False; let json = json::parse(&serde_json::to_string(&status).unwrap()).unwrap(); assert!(json.is_boolean()); let status = Web3SyncStatus::Doing(SyncStatus { starting_block: fastrand::u64(..).into(), current_block: fastrand::u64(..).into(), highest_block: fastrand::u64(..).into(), known_states: U256::default(), pulled_states: U256::default(), }); let json = json::parse(&serde_json::to_string(&status).unwrap()).unwrap(); assert!(json.is_object()); } }
33.826739
97
0.524783
56e71cab787911cbce556e5ce4473d23d546a61f
3,465
use anyhow::anyhow; use chrono::prelude::*; use config::Config; use currency::Currency; use num::Signed; use std::ops::Neg; use transaction::payee::PayeeNormalizer; use util::currency_to_string_without_delim; pub mod payee; pub mod transaction_io; #[derive(Debug)] pub struct Transaction { date: DateTime<Utc>, raw_payee_name: String, normalized_payee_id: Option<String>, normalized_payee_name: Option<String>, category: Option<String>, transaction_type: TransactionType, // Non-negative amount: Currency, status: TransactionStatus, memo: Option<String>, } #[derive(Debug, Eq, PartialEq)] enum TransactionType { Debit, Credit, } #[derive(Debug, Eq, PartialEq)] enum TransactionStatus { Pending, Cleared, } impl Transaction { fn build( date: String, date_format: String, payee: String, category: Option<String>, transaction_type: TransactionType, amount: Currency, status: TransactionStatus, memo: Option<String>, ) -> anyhow::Result<Transaction> { let date = match Utc.datetime_from_str(&date, &date_format) { Ok(date) => Ok(date), Err(e) => Err(anyhow!( "Unable to parse date string [{}] using date format string [{}]; error: {}", date, date_format, e )), }?; Ok(Transaction { date, raw_payee_name: InputCleaner::clean(payee), normalized_payee_id: Option::None, normalized_payee_name: Option::None, category: InputCleaner::clean(category), transaction_type, amount: get_currency_absolute_value(amount), status, memo: InputCleaner::clean(memo), }) } pub fn normalize_payee(&mut self, config: &Config) { self.normalized_payee_id = PayeeNormalizer::normalized_payee_id(config, &self.raw_payee_name); self.normalized_payee_name = self .normalized_payee_id .as_ref() .and_then(|p| config.account().payees.get(p)) .map(|x| x.name.to_owned()); } pub fn categorize(&mut self, config: &Config) { self.category = PayeeNormalizer::category_for_transaction(config, self); if self.category.is_none() { println!("Transaction was not categorized: [payee: {}], [amount: {}], [type: {:?}], [date: {}]", self.payee(), currency_to_string_without_delim(&self.amount), self.transaction_type, self.date); } } pub fn date(&self) -> &DateTime<Utc> { &self.date } // Get the name of the payee for this transaction. Either the raw payee name, or the // normalized name if it has been normalized. pub fn payee(&self) -> &str { if let Option::Some(ref p) = self.normalized_payee_name { p } else { &self.raw_payee_name } } } fn get_currency_absolute_value(c: Currency) -> Currency { if c.value().is_negative() { c.neg() } else { c } } struct InputCleaner; trait Clean<T> { fn clean(s: T) -> T; } impl Clean<String> for InputCleaner { fn clean(s: String) -> String { s.trim().replace('\n', " ") } } impl Clean<Option<String>> for InputCleaner { fn clean(s: Option<String>) -> Option<String> { s.map(Self::clean) } }
26.860465
117
0.590765
ff0cd943a7c8b369a3d9372bd6be15bd3e77f2ea
24,442
use ethereum::{BlockIngestor as EthereumBlockIngestor, EthereumAdapterTrait, EthereumNetworks}; use git_testament::{git_testament, render_testament}; use graph::blockchain::firehose_block_ingestor::FirehoseBlockIngestor; use graph::blockchain::{Block as BlockchainBlock, Blockchain, BlockchainKind, BlockchainMap}; use graph::components::store::BlockStore; use graph::data::graphql::effort::LoadManager; use graph::firehose::{FirehoseEndpoints, FirehoseNetworks}; use graph::log::logger; use graph::prelude::{IndexNodeServer as _, JsonRpcServer as _, *}; use graph::prometheus::Registry; use graph::url::Url; use graph_chain_ethereum as ethereum; use graph_chain_near::{self as near, HeaderOnlyBlock as NearFirehoseHeaderOnlyBlock}; use graph_core::{ LinkResolver, MetricsRegistry, SubgraphAssignmentProvider as IpfsSubgraphAssignmentProvider, SubgraphInstanceManager, SubgraphRegistrar as IpfsSubgraphRegistrar, }; use graph_graphql::prelude::GraphQlRunner; use graph_node::chain::{ connect_ethereum_networks, connect_firehose_networks, create_ethereum_networks, create_firehose_networks, create_ipfs_clients, ANCESTOR_COUNT, REORG_THRESHOLD, }; use graph_node::config::Config; use graph_node::opt; use graph_node::store_builder::StoreBuilder; use graph_server_http::GraphQLServer as GraphQLQueryServer; use graph_server_index_node::IndexNodeServer; use graph_server_json_rpc::JsonRpcServer; use graph_server_metrics::PrometheusMetricsServer; use graph_server_websocket::SubscriptionServer as GraphQLSubscriptionServer; use graph_store_postgres::{register_jobs as register_store_jobs, ChainHeadUpdateListener, Store}; use std::collections::BTreeMap; use std::io::{BufRead, BufReader}; use std::path::Path; use std::sync::atomic; use std::time::Duration; use std::{collections::HashMap, env}; use structopt::StructOpt; use tokio::sync::mpsc; git_testament!(TESTAMENT); fn read_expensive_queries() -> Result<Vec<Arc<q::Document>>, std::io::Error> { // A file with a list of expensive queries, one query per line // Attempts to run these queries will return a // QueryExecutionError::TooExpensive to clients const EXPENSIVE_QUERIES: &str = "/etc/graph-node/expensive-queries.txt"; let path = Path::new(EXPENSIVE_QUERIES); let mut queries = Vec::new(); if path.exists() { let file = std::fs::File::open(path)?; let reader = BufReader::new(file); for line in reader.lines() { let line = line?; let query = graphql_parser::parse_query(&line) .map_err(|e| { let msg = format!( "invalid GraphQL query in {}: {}\n{}", EXPENSIVE_QUERIES, e.to_string(), line ); std::io::Error::new(std::io::ErrorKind::InvalidData, msg) })? .into_static(); queries.push(Arc::new(query)); } } Ok(queries) } #[tokio::main] async fn main() { env_logger::init(); // Allow configuring fail points on debug builds. Used for integration tests. #[cfg(debug_assertions)] std::mem::forget(fail::FailScenario::setup()); let opt = opt::Opt::from_args(); // Set up logger let logger = logger(opt.debug); // Log version information info!( logger, "Graph Node version: {}", render_testament!(TESTAMENT) ); if opt.unsafe_config { warn!(logger, "allowing unsafe configurations"); graph::env::UNSAFE_CONFIG.store(true, atomic::Ordering::SeqCst); } let config = match Config::load(&logger, &opt.clone().into()) { Err(e) => { eprintln!("configuration error: {}", e); std::process::exit(1); } Ok(config) => config, }; if opt.check_config { match config.to_json() { Ok(txt) => println!("{}", txt), Err(e) => eprintln!("error serializing config: {}", e), } eprintln!("Successfully validated configuration"); std::process::exit(0); } let node_id = NodeId::new(opt.node_id.clone()).expect("Node ID must contain only a-z, A-Z, 0-9, and '_'"); let query_only = config.query_only(&node_id); // Obtain subgraph related command-line arguments let subgraph = opt.subgraph.clone(); // Obtain ports to use for the GraphQL server(s) let http_port = opt.http_port; let ws_port = opt.ws_port; // Obtain JSON-RPC server port let json_rpc_port = opt.admin_port; // Obtain index node server port let index_node_port = opt.index_node_port; // Obtain metrics server port let metrics_port = opt.metrics_port; // Obtain the fork base URL let fork_base = match &opt.fork_base { Some(url) => Some(Url::parse(url).expect("Failed to parse the fork base URL")), None => { warn!( logger, "No fork base URL specified, subgraph forking is disabled" ); None } }; info!(logger, "Starting up"); // Optionally, identify the Elasticsearch logging configuration let elastic_config = opt .elasticsearch_url .clone() .map(|endpoint| ElasticLoggingConfig { endpoint: endpoint.clone(), username: opt.elasticsearch_user.clone(), password: opt.elasticsearch_password.clone(), }); // Create a component and subgraph logger factory let logger_factory = LoggerFactory::new(logger.clone(), elastic_config); // Try to create IPFS clients for each URL specified in `--ipfs` let ipfs_clients: Vec<_> = create_ipfs_clients(&logger, &opt.ipfs); // Convert the clients into a link resolver. Since we want to get past // possible temporary DNS failures, make the resolver retry let link_resolver = Arc::new(LinkResolver::from(ipfs_clients)); // Set up Prometheus registry let prometheus_registry = Arc::new(Registry::new()); let metrics_registry = Arc::new(MetricsRegistry::new( logger.clone(), prometheus_registry.clone(), )); let mut metrics_server = PrometheusMetricsServer::new(&logger_factory, prometheus_registry.clone()); // Ethereum clients; query nodes ignore all ethereum clients and never // connect to them directly let eth_networks = if query_only { EthereumNetworks::new() } else { create_ethereum_networks(logger.clone(), metrics_registry.clone(), &config) .await .expect("Failed to parse Ethereum networks") }; let mut firehose_networks_by_kind = if query_only { BTreeMap::new() } else { create_firehose_networks(logger.clone(), metrics_registry.clone(), &config) .await .expect("Failed to parse Firehose networks") }; let graphql_metrics_registry = metrics_registry.clone(); let contention_logger = logger.clone(); let expensive_queries = read_expensive_queries().unwrap(); let store_builder = StoreBuilder::new( &logger, &node_id, &config, fork_base, metrics_registry.cheap_clone(), ) .await; let launch_services = |logger: Logger| async move { let subscription_manager = store_builder.subscription_manager(); let chain_head_update_listener = store_builder.chain_head_update_listener(); let primary_pool = store_builder.primary_pool(); // To support the ethereum block ingestor, ethereum networks are referenced both by the // `blockchain_map` and `ethereum_chains`. Future chains should be referred to only in // `blockchain_map`. let mut blockchain_map = BlockchainMap::new(); let (eth_networks, ethereum_idents) = connect_ethereum_networks(&logger, eth_networks).await; let (near_networks, near_idents) = connect_firehose_networks::<NearFirehoseHeaderOnlyBlock>( &logger, firehose_networks_by_kind .remove(&BlockchainKind::Near) .unwrap_or_else(|| FirehoseNetworks::new()), ) .await; let network_identifiers = ethereum_idents.into_iter().chain(near_idents).collect(); let network_store = store_builder.network_store(network_identifiers); let ethereum_chains = ethereum_networks_as_chains( &mut blockchain_map, &logger, node_id.clone(), metrics_registry.clone(), firehose_networks_by_kind.get(&BlockchainKind::Ethereum), &eth_networks, network_store.as_ref(), chain_head_update_listener, &logger_factory, ); let near_chains = near_networks_as_chains( &mut blockchain_map, &logger, &near_networks, network_store.as_ref(), &logger_factory, ); let blockchain_map = Arc::new(blockchain_map); let load_manager = Arc::new(LoadManager::new( &logger, expensive_queries, metrics_registry.clone(), )); let graphql_runner = Arc::new(GraphQlRunner::new( &logger, network_store.clone(), subscription_manager.clone(), load_manager, metrics_registry.clone(), )); let mut graphql_server = GraphQLQueryServer::new( &logger_factory, graphql_metrics_registry, graphql_runner.clone(), node_id.clone(), ); let subscription_server = GraphQLSubscriptionServer::new(&logger, graphql_runner.clone(), network_store.clone()); let mut index_node_server = IndexNodeServer::new( &logger_factory, graphql_runner.clone(), network_store.clone(), link_resolver.clone(), network_store.subgraph_store().clone(), ); if !opt.disable_block_ingestor { if ethereum_chains.len() > 0 { let block_polling_interval = Duration::from_millis(opt.ethereum_polling_interval); start_block_ingestor( &logger, &logger_factory, block_polling_interval, ethereum_chains, ); } start_firehose_block_ingestor::<_, NearFirehoseHeaderOnlyBlock>( &logger, &network_store, near_chains, ); // Start a task runner let mut job_runner = graph::util::jobs::Runner::new(&logger); register_store_jobs( &mut job_runner, network_store.clone(), primary_pool, metrics_registry.clone(), ); graph::spawn_blocking(job_runner.start()); } let subgraph_instance_manager = SubgraphInstanceManager::new( &logger_factory, network_store.subgraph_store(), blockchain_map.cheap_clone(), metrics_registry.clone(), link_resolver.cheap_clone(), ); // Create IPFS-based subgraph provider let subgraph_provider = IpfsSubgraphAssignmentProvider::new( &logger_factory, link_resolver.cheap_clone(), subgraph_instance_manager, ); // Check version switching mode environment variable let version_switching_mode = SubgraphVersionSwitchingMode::parse( env::var_os("EXPERIMENTAL_SUBGRAPH_VERSION_SWITCHING_MODE") .unwrap_or_else(|| "instant".into()) .to_str() .expect("invalid version switching mode"), ); // Create named subgraph provider for resolving subgraph name->ID mappings let subgraph_registrar = Arc::new(IpfsSubgraphRegistrar::new( &logger_factory, link_resolver.cheap_clone(), Arc::new(subgraph_provider), network_store.subgraph_store(), subscription_manager, blockchain_map, node_id.clone(), version_switching_mode, )); graph::spawn( subgraph_registrar .start() .map_err(|e| panic!("failed to initialize subgraph provider {}", e)) .compat(), ); // Start admin JSON-RPC server. let json_rpc_server = JsonRpcServer::serve( json_rpc_port, http_port, ws_port, subgraph_registrar.clone(), node_id.clone(), logger.clone(), ) .expect("failed to start JSON-RPC admin server"); // Let the server run forever. std::mem::forget(json_rpc_server); // Add the CLI subgraph with a REST request to the admin server. if let Some(subgraph) = subgraph { let (name, hash) = if subgraph.contains(':') { let mut split = subgraph.split(':'); (split.next().unwrap(), split.next().unwrap().to_owned()) } else { ("cli", subgraph) }; let name = SubgraphName::new(name) .expect("Subgraph name must contain only a-z, A-Z, 0-9, '-' and '_'"); let subgraph_id = DeploymentHash::new(hash).expect("Subgraph hash must be a valid IPFS hash"); graph::spawn( async move { subgraph_registrar.create_subgraph(name.clone()).await?; subgraph_registrar // TODO: Add support for `debug_fork` parameter .create_subgraph_version(name, subgraph_id, node_id, None) .await } .map_err(|e| panic!("Failed to deploy subgraph from `--subgraph` flag: {}", e)), ); } // Serve GraphQL queries over HTTP graph::spawn( graphql_server .serve(http_port, ws_port) .expect("Failed to start GraphQL query server") .compat(), ); // Serve GraphQL subscriptions over WebSockets graph::spawn(subscription_server.serve(ws_port)); // Run the index node server graph::spawn( index_node_server .serve(index_node_port) .expect("Failed to start index node server") .compat(), ); graph::spawn( metrics_server .serve(metrics_port) .expect("Failed to start metrics server") .compat(), ); }; graph::spawn(launch_services(logger.clone())); // Periodically check for contention in the tokio threadpool. First spawn a // task that simply responds to "ping" requests. Then spawn a separate // thread to periodically ping it and check responsiveness. let (ping_send, mut ping_receive) = mpsc::channel::<crossbeam_channel::Sender<()>>(1); graph::spawn(async move { while let Some(pong_send) = ping_receive.recv().await { let _ = pong_send.clone().send(()); } panic!("ping sender dropped"); }); std::thread::spawn(move || loop { std::thread::sleep(Duration::from_secs(1)); let (pong_send, pong_receive) = crossbeam_channel::bounded(1); if futures::executor::block_on(ping_send.clone().send(pong_send)).is_err() { debug!(contention_logger, "Shutting down contention checker thread"); break; } let mut timeout = Duration::from_millis(10); while pong_receive.recv_timeout(timeout) == Err(crossbeam_channel::RecvTimeoutError::Timeout) { debug!(contention_logger, "Possible contention in tokio threadpool"; "timeout_ms" => timeout.as_millis(), "code" => LogCode::TokioContention); if timeout < Duration::from_secs(10) { timeout *= 10; } else if std::env::var_os("GRAPH_KILL_IF_UNRESPONSIVE").is_some() { // The node is unresponsive, kill it in hopes it will be restarted. crit!(contention_logger, "Node is unresponsive, killing process"); std::process::abort() } } }); futures::future::pending::<()>().await; } /// Return the hashmap of ethereum chains and also add them to `blockchain_map`. fn ethereum_networks_as_chains( blockchain_map: &mut BlockchainMap, logger: &Logger, node_id: NodeId, registry: Arc<MetricsRegistry>, firehose_networks: Option<&FirehoseNetworks>, eth_networks: &EthereumNetworks, store: &Store, chain_head_update_listener: Arc<ChainHeadUpdateListener>, logger_factory: &LoggerFactory, ) -> HashMap<String, Arc<ethereum::Chain>> { let chains: Vec<_> = eth_networks .networks .iter() .filter_map(|(network_name, eth_adapters)| { store .block_store() .chain_store(network_name) .map(|chain_store| { let is_ingestible = chain_store.is_ingestible(); (network_name, eth_adapters, chain_store, is_ingestible) }) .or_else(|| { error!( logger, "No store configured for Ethereum chain {}; ignoring this chain", network_name ); None }) }) .map(|(network_name, eth_adapters, chain_store, is_ingestible)| { let firehose_endpoints = firehose_networks.and_then(|v| v.networks.get(network_name)); let chain = ethereum::Chain::new( logger_factory.clone(), network_name.clone(), node_id.clone(), registry.clone(), chain_store.cheap_clone(), chain_store, firehose_endpoints.map_or_else(|| FirehoseEndpoints::new(), |v| v.clone()), eth_adapters.clone(), chain_head_update_listener.clone(), *REORG_THRESHOLD, is_ingestible, ); (network_name.clone(), Arc::new(chain)) }) .collect(); for (network_name, chain) in chains.iter().cloned() { blockchain_map.insert::<graph_chain_ethereum::Chain>(network_name, chain) } HashMap::from_iter(chains) } /// Return the hashmap of NEAR chains and also add them to `blockchain_map`. fn near_networks_as_chains( blockchain_map: &mut BlockchainMap, logger: &Logger, firehose_networks: &FirehoseNetworks, store: &Store, logger_factory: &LoggerFactory, ) -> HashMap<String, FirehoseChain<near::Chain>> { let chains: Vec<_> = firehose_networks .networks .iter() .filter_map(|(chain_id, endpoints)| { store .block_store() .chain_store(chain_id) .map(|chain_store| (chain_id, chain_store, endpoints)) .or_else(|| { error!( logger, "No store configured for NEAR chain {}; ignoring this chain", chain_id ); None }) }) .map(|(chain_id, chain_store, endpoints)| { ( chain_id.clone(), FirehoseChain { chain: Arc::new(near::Chain::new( logger_factory.clone(), chain_id.clone(), chain_store, endpoints.clone(), )), firehose_endpoints: endpoints.clone(), }, ) }) .collect(); for (chain_id, firehose_chain) in chains.iter() { blockchain_map .insert::<graph_chain_near::Chain>(chain_id.clone(), firehose_chain.chain.clone()) } HashMap::from_iter(chains) } fn start_block_ingestor( logger: &Logger, logger_factory: &LoggerFactory, block_polling_interval: Duration, chains: HashMap<String, Arc<ethereum::Chain>>, ) { // BlockIngestor must be configured to keep at least REORG_THRESHOLD ancestors, // otherwise BlockStream will not work properly. // BlockStream expects the blocks after the reorg threshold to be present in the // database. assert!(*ANCESTOR_COUNT >= *REORG_THRESHOLD); info!( logger, "Starting block ingestors with {} chains [{}]", chains.len(), chains .keys() .map(|v| v.clone()) .collect::<Vec<String>>() .join(", ") ); // Create Ethereum block ingestors and spawn a thread to run each chains .iter() .filter(|(network_name, chain)| { if !chain.is_ingestible { error!(logger, "Not starting block ingestor (chain is defective)"; "network_name" => &network_name); } chain.is_ingestible }) .for_each(|(network_name, chain)| { info!( logger, "Starting block ingestor for network"; "network_name" => &network_name ); let eth_adapter = chain.cheapest_adapter(); let logger = logger_factory .component_logger( "BlockIngestor", Some(ComponentLoggerConfig { elastic: Some(ElasticComponentLoggerConfig { index: String::from("block-ingestor-logs"), }), }), ) .new(o!("provider" => eth_adapter.provider().to_string())); let block_ingestor = EthereumBlockIngestor::new( logger, *ANCESTOR_COUNT, eth_adapter, chain.chain_store(), block_polling_interval, ) .expect("failed to create Ethereum block ingestor"); // Run the Ethereum block ingestor in the background graph::spawn(block_ingestor.into_polling_stream()); }); } #[derive(Clone)] struct FirehoseChain<C: Blockchain> { chain: Arc<C>, firehose_endpoints: FirehoseEndpoints, } fn start_firehose_block_ingestor<C, M>( logger: &Logger, store: &Store, chains: HashMap<String, FirehoseChain<C>>, ) where C: Blockchain, M: prost::Message + BlockchainBlock + Default + 'static, { info!( logger, "Starting firehose block ingestors with {} chains [{}]", chains.len(), chains .keys() .map(|v| v.clone()) .collect::<Vec<String>>() .join(", ") ); // Create Firehose block ingestors and spawn a thread to run each chains .iter() .for_each(|(network_name, chain)| { info!( logger, "Starting firehose block ingestor for network"; "network_name" => &network_name ); let endpoint = chain .firehose_endpoints .random() .expect("One Firehose endpoint should exist at that execution point"); match store.block_store().chain_store(network_name.as_ref()) { Some(s) => { let block_ingestor = FirehoseBlockIngestor::<M>::new( s, endpoint.clone(), logger.new(o!("component" => "FirehoseBlockIngestor", "provider" => endpoint.provider.clone())), ); // Run the Firehose block ingestor in the background graph::spawn(block_ingestor.run()); }, None => { error!(logger, "Not starting firehose block ingestor (no chain store available)"; "network_name" => &network_name); } } }); }
35.474601
135
0.57393
87b8aaad95740d154eee7a8d487b694de2f6de24
659
#![feature(type_alias_impl_trait)] fn main() {} type Underconstrained<T: std::fmt::Debug> = impl 'static; //~^ ERROR `U` doesn't implement `std::fmt::Debug` //~^^ ERROR: at least one trait must be specified // not a defining use, because it doesn't define *all* possible generics fn underconstrained<U>(_: U) -> Underconstrained<U> { 5u32 } type Underconstrained2<T: std::fmt::Debug> = impl 'static; //~^ ERROR `V` doesn't implement `std::fmt::Debug` //~^^ ERROR: at least one trait must be specified // not a defining use, because it doesn't define *all* possible generics fn underconstrained2<U, V>(_: U, _: V) -> Underconstrained2<V> { 5u32 }
29.954545
72
0.685888
227dba9ee68796f4b002d79036f8aa3eed0e9694
755
// quiz1.rs // This is a quiz for the following sections: // - Variables // - Functions // Mary is buying apples. One apple usually costs 2 Rustbucks, but if you buy // more than 40 at once, each apple only costs 1! Write a function that calculates // the price of an order of apples given the order amount. No hints this time! const DISCOUNT_THRESHOLD: u32 = 40; // Put your function here! fn calculate_apple_price(amount: u32) -> u32 { if amount < DISCOUNT_THRESHOLD { return amount * 2; } else { return amount; } } // Don't modify this function! #[test] fn verify_test() { let price1 = calculate_apple_price(35); let price2 = calculate_apple_price(65); assert_eq!(70, price1); assert_eq!(65, price2); }
25.166667
82
0.680795
4bced409e9814f7b27158c4401947782f94e8da6
283
use crate::{Chain, DataSource}; use anyhow::Result; use blockchain::HostFn; use graph::blockchain; pub struct RuntimeAdapter {} impl blockchain::RuntimeAdapter<Chain> for RuntimeAdapter { fn host_fns(&self, _ds: &DataSource) -> Result<Vec<HostFn>> { Ok(vec![]) } }
21.769231
65
0.689046
e29b25fea7e3496d1f7198955f05d72e8abaa7f3
15,932
//! Presence. use super::pubsub::inject_subscribe_to; use super::util::{build_uri, handle_json_response, json_as_array, json_as_object}; use super::{error, Hyper}; use crate::core::data::{presence, request, response}; use crate::core::json; use crate::core::TransportService; use async_trait::async_trait; use hyper::{Body, Response}; use pubnub_util::uritemplate::{IfEmpty, UriTemplate}; use std::collections::HashMap; async fn handle_presence_response( response: Response<Body>, ) -> Result<json::JsonValue, error::Error> { let presence_data = handle_json_response(response).await?; if presence_data["error"] == true { let error_message = presence_data["message"].to_string(); return Err(error::Error::Server(error_message)); } Ok(presence_data) } trait HereNowParse<T: presence::respond_with::RespondWith> { fn parse(&self, _data_json: &json::JsonValue) -> Option<T::Response> { unimplemented!("Attempted parsing unsupported type"); } fn parse_global(&self, data_json: &json::JsonValue) -> Option<presence::GlobalInfo<T>> { let payload = json_as_object(&data_json["payload"])?; let total_channels = payload["total_channels"].as_u64()?; let total_occupancy = payload["total_occupancy"].as_u64()?; let channels = { let channels = json_as_object(&payload["channels"])?; let mut values = HashMap::new(); for (k, v) in channels.iter() { let channel_info = self.parse(v)?; values.insert(k.parse().ok()?, channel_info); } values }; Some(presence::GlobalInfo { total_channels, total_occupancy, channels, }) } } impl HereNowParse<presence::respond_with::OccupancyOnly> for () { fn parse( &self, data_json: &json::JsonValue, ) -> Option< <presence::respond_with::OccupancyOnly as presence::respond_with::RespondWith>::Response, > { let occupancy = data_json["occupancy"].as_u64()?; Some(presence::ChannelInfo { occupancy }) } } impl HereNowParse<presence::respond_with::OccupancyAndUUIDs> for () { fn parse( &self, data_json: &json::JsonValue, ) -> Option< <presence::respond_with::OccupancyAndUUIDs as presence::respond_with::RespondWith>::Response >{ let occupancy = data_json["occupancy"].as_u64()?; let occupants = { let uuids = json_as_array(&data_json["uuids"])?; let results: Option<_> = uuids .iter() .map(|uuid| uuid.as_str().map(Into::into)) .collect(); results? }; Some(presence::ChannelInfoWithOccupants { occupancy, occupants, }) } } impl HereNowParse<presence::respond_with::Full> for () { fn parse( &self, data_json: &json::JsonValue, ) -> Option<<presence::respond_with::Full as presence::respond_with::RespondWith>::Response> { let occupancy = data_json["occupancy"].as_u64()?; let occupants = { let uuids = json_as_array(&data_json["uuids"])?; let results: Option<_> = uuids .iter() .map(|info| { let info = json_as_object(info)?; let uuid = info["uuid"].as_str().map(Into::into)?; let state = info["state"].clone(); Some(presence::ChannelOccupantFullDetails { uuid, state }) }) .collect(); results? }; Some(presence::ChannelInfoWithOccupants { occupancy, occupants, }) } } #[async_trait] impl TransportService<request::SetState> for Hyper { type Response = response::SetState; type Error = error::Error; async fn call(&self, request: request::SetState) -> Result<Self::Response, Self::Error> { let request::SetState { channels, channel_groups, uuid, state, } = request; // Prepare the URL. let path_and_query = UriTemplate::new("/v2/presence/sub-key/{sub_key}/channel/{channel}/uuid/{uuid}/data{?channel-group,state}") .set_scalar("sub_key", self.subscribe_key.clone()) .set_list_with_if_empty("channel", channels, IfEmpty::Comma) .set_list_with_if_empty("channel-group", channel_groups, IfEmpty::Skip) .set_scalar("uuid", uuid) .set_scalar("state", json::stringify(state)) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; handle_presence_response(response).await?; Ok(()) } } #[async_trait] impl TransportService<request::GetState> for Hyper { type Response = response::GetState; type Error = error::Error; async fn call(&self, request: request::GetState) -> Result<Self::Response, Self::Error> { let request::GetState { channels, channel_groups, uuid, } = request; // Prepare the URL. let path_and_query = UriTemplate::new( "/v2/presence/sub-key/{sub_key}/channel/{channel}/uuid/{uuid}{?channel-group}", ) .set_scalar("sub_key", self.subscribe_key.clone()) .set_list_with_if_empty("channel", channels, IfEmpty::Comma) .set_list_with_if_empty("channel-group", channel_groups, IfEmpty::Skip) .set_scalar("uuid", uuid) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; let mut data_json = handle_presence_response(response).await?; // Parse response. Ok(data_json.remove("payload")) } } #[async_trait] impl TransportService<request::HereNow<presence::respond_with::OccupancyOnly>> for Hyper { type Response = response::HereNow<presence::respond_with::OccupancyOnly>; type Error = error::Error; async fn call( &self, request: request::HereNow<presence::respond_with::OccupancyOnly>, ) -> Result<Self::Response, Self::Error> { let request::HereNow { channels, channel_groups, .. } = request; // Prepare the URL. let path_and_query = UriTemplate::new( "/v2/presence/sub-key/{sub_key}/channel/{channel}?disable_uuids=1&state=0{&channel-group}", ) .set_scalar("sub_key", self.subscribe_key.clone()) .set_list_with_if_empty("channel", channels, IfEmpty::Comma) .set_list_with_if_empty("channel-group", channel_groups, IfEmpty::Skip) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; let data_json = handle_presence_response(response).await?; // Parse response. let value = HereNowParse::<presence::respond_with::OccupancyOnly>::parse(&(), &data_json) .ok_or(error::Error::UnexpectedResponseSchema(data_json))?; Ok(value) } } #[async_trait] impl TransportService<request::HereNow<presence::respond_with::OccupancyAndUUIDs>> for Hyper { type Response = response::HereNow<presence::respond_with::OccupancyAndUUIDs>; type Error = error::Error; async fn call( &self, request: request::HereNow<presence::respond_with::OccupancyAndUUIDs>, ) -> Result<Self::Response, Self::Error> { let request::HereNow { channels, channel_groups, .. } = request; // Prepare the URL. let path_and_query = UriTemplate::new( "/v2/presence/sub-key/{sub_key}/channel/{channel}?disable_uuids=0&state=0{&channel-group}", ) .set_scalar("sub_key", self.subscribe_key.clone()) .set_list_with_if_empty("channel", channels, IfEmpty::Comma) .set_list_with_if_empty("channel-group", channel_groups, IfEmpty::Skip) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; let data_json = handle_presence_response(response).await?; // Parse response. let value = HereNowParse::<presence::respond_with::OccupancyAndUUIDs>::parse(&(), &data_json) .ok_or(error::Error::UnexpectedResponseSchema(data_json))?; Ok(value) } } #[async_trait] impl TransportService<request::HereNow<presence::respond_with::Full>> for Hyper { type Response = response::HereNow<presence::respond_with::Full>; type Error = error::Error; async fn call( &self, request: request::HereNow<presence::respond_with::Full>, ) -> Result<Self::Response, Self::Error> { let request::HereNow { channels, channel_groups, .. } = request; // Prepare the URL. let path_and_query = UriTemplate::new( "/v2/presence/sub-key/{sub_key}/channel/{channel}?disable_uuids=0&state=1{&channel-group}", ) .set_scalar("sub_key", self.subscribe_key.clone()) .set_list_with_if_empty("channel", channels, IfEmpty::Comma) .set_list_with_if_empty("channel-group", channel_groups, IfEmpty::Skip) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; let data_json = handle_presence_response(response).await?; // Parse response. let value = HereNowParse::<presence::respond_with::Full>::parse(&(), &data_json) .ok_or(error::Error::UnexpectedResponseSchema(data_json))?; Ok(value) } } #[async_trait] impl TransportService<request::GlobalHereNow<presence::respond_with::OccupancyOnly>> for Hyper { type Response = response::GlobalHereNow<presence::respond_with::OccupancyOnly>; type Error = error::Error; // Clippy is glitching with `async-trait`. #[allow(clippy::used_underscore_binding)] async fn call( &self, _request: request::GlobalHereNow<presence::respond_with::OccupancyOnly>, ) -> Result<Self::Response, Self::Error> { // Prepare the URL. let path_and_query = UriTemplate::new("/v2/presence/sub-key/{sub_key}?disable_uuids=1&state=0") .set_scalar("sub_key", self.subscribe_key.clone()) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; let data_json = handle_presence_response(response).await?; // Parse response. let value = HereNowParse::<presence::respond_with::OccupancyOnly>::parse_global(&(), &data_json) .ok_or(error::Error::UnexpectedResponseSchema(data_json))?; Ok(value) } } #[async_trait] impl TransportService<request::GlobalHereNow<presence::respond_with::OccupancyAndUUIDs>> for Hyper { type Response = response::GlobalHereNow<presence::respond_with::OccupancyAndUUIDs>; type Error = error::Error; // Clippy is glitching with `async-trait`. #[allow(clippy::used_underscore_binding)] async fn call( &self, _request: request::GlobalHereNow<presence::respond_with::OccupancyAndUUIDs>, ) -> Result<Self::Response, Self::Error> { // Prepare the URL. let path_and_query = UriTemplate::new("/v2/presence/sub-key/{sub_key}?disable_uuids=0&state=0") .set_scalar("sub_key", self.subscribe_key.clone()) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; let data_json = handle_presence_response(response).await?; // Parse response. let value = HereNowParse::<presence::respond_with::OccupancyAndUUIDs>::parse_global( &(), &data_json, ) .ok_or(error::Error::UnexpectedResponseSchema(data_json))?; Ok(value) } } #[async_trait] impl TransportService<request::GlobalHereNow<presence::respond_with::Full>> for Hyper { type Response = response::GlobalHereNow<presence::respond_with::Full>; type Error = error::Error; // Clippy is glitching with `async-trait`. #[allow(clippy::used_underscore_binding)] async fn call( &self, _request: request::GlobalHereNow<presence::respond_with::Full>, ) -> Result<Self::Response, Self::Error> { // Prepare the URL. let path_and_query = UriTemplate::new("/v2/presence/sub-key/{sub_key}?disable_uuids=0&state=1") .set_scalar("sub_key", self.subscribe_key.clone()) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; let data_json = handle_presence_response(response).await?; // Parse response. let value = HereNowParse::<presence::respond_with::Full>::parse_global(&(), &data_json) .ok_or(error::Error::UnexpectedResponseSchema(data_json))?; Ok(value) } } #[async_trait] impl TransportService<request::WhereNow> for Hyper { type Response = response::WhereNow; type Error = error::Error; async fn call(&self, request: request::WhereNow) -> Result<Self::Response, Self::Error> { let request::WhereNow { uuid } = request; // Prepare the URL. let path_and_query = UriTemplate::new("/v2/presence/sub-key/{sub_key}/uuid/{uuid}") .set_scalar("sub_key", self.subscribe_key.clone()) .set_scalar("uuid", uuid) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; let data_json = handle_presence_response(response).await?; let err_fn = || error::Error::UnexpectedResponseSchema(data_json.clone()); // Parse response. let channles = { let payloads = json_as_object(&data_json["payload"]).ok_or_else(err_fn)?; let channels = json_as_array(&payloads["channels"]).ok_or_else(err_fn)?; let results: Option<_> = channels .iter() .map(|val| val.as_str().and_then(|s| s.parse().ok())) .collect(); results.ok_or_else(err_fn)? }; Ok(channles) } } #[async_trait] impl TransportService<request::Heartbeat> for Hyper { type Response = response::Heartbeat; type Error = error::Error; async fn call(&self, request: request::Heartbeat) -> Result<Self::Response, Self::Error> { let request::Heartbeat { heartbeat, to, state, uuid, } = request; // Prepare the URL. let path_and_query = UriTemplate::new("/v2/presence/sub-key/{sub_key}/channel/{channel}/heartbeat{?channel-group,uuid,state,heartbeat}") .set_scalar("sub_key", self.subscribe_key.clone()) .tap(|val| inject_subscribe_to(val, &to)) .set_scalar("uuid", uuid) .set_optional_scalar("heartbeat", heartbeat.map(|e|e.to_string())) .set_scalar("state", json::stringify(state)) .build(); let url = build_uri(&self, &path_and_query)?; // Send network request. let response = self.http_client.get(url).await?; handle_presence_response(response).await?; Ok(()) } }
35.169978
127
0.607206
38394e40205170870d6ff5365f62aaf6536b340c
1,585
use std::marker::PhantomData; use std::fmt; use gccjit_sys; use context::Context; use object::{ToObject, Object}; use object; use rvalue::{RValue, ToRValue}; use rvalue; use lvalue::{LValue, ToLValue}; use lvalue; /// Parameter represents a parameter to a function. A series of parameteres /// can be combined to form a function signature. #[derive(Copy, Clone)] pub struct Parameter<'ctx> { marker: PhantomData<&'ctx Context<'ctx>>, ptr: *mut gccjit_sys::gcc_jit_param } impl<'ctx> ToObject<'ctx> for Parameter<'ctx> { fn to_object(&self) -> Object<'ctx> { unsafe { object::from_ptr(gccjit_sys::gcc_jit_param_as_object(self.ptr)) } } } impl<'ctx> fmt::Debug for Parameter<'ctx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { let obj = self.to_object(); obj.fmt(fmt) } } impl<'ctx> ToRValue<'ctx> for Parameter<'ctx> { fn to_rvalue(&self) -> RValue<'ctx> { unsafe { let ptr = gccjit_sys::gcc_jit_param_as_rvalue(self.ptr); rvalue::from_ptr(ptr) } } } impl<'ctx> ToLValue<'ctx> for Parameter<'ctx> { fn to_lvalue(&self) -> LValue<'ctx> { unsafe { let ptr = gccjit_sys::gcc_jit_param_as_lvalue(self.ptr); lvalue::from_ptr(ptr) } } } pub unsafe fn from_ptr<'ctx>(ptr: *mut gccjit_sys::gcc_jit_param) -> Parameter<'ctx> { Parameter { marker: PhantomData, ptr: ptr } } pub unsafe fn get_ptr<'ctx>(loc: &Parameter<'ctx>) -> *mut gccjit_sys::gcc_jit_param { loc.ptr }
24.384615
86
0.618927
8afa8d3752955c9ed92afba6b7ca8234b13213d3
10,897
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: 25/04/2018 Last Modified: 25/04/2018 License: MIT */ use lidar::*; use std::env; use std::io::{Error, ErrorKind}; use std::path; use structures::BoundingBox; use time; use tools::*; use vector; use vector::{Point2D, ShapeType, Shapefile}; pub struct ErasePolygonFromLidar { name: String, description: String, toolbox: String, parameters: Vec<ToolParameter>, example_usage: String, } impl ErasePolygonFromLidar { /// public constructor pub fn new() -> ErasePolygonFromLidar { let name = "ErasePolygonFromLidar".to_string(); let toolbox = "LiDAR Tools".to_string(); let description = "Erases (cuts out) a vector polygon or polygons from a LiDAR point cloud.".to_string(); let mut parameters = vec![]; parameters.push(ToolParameter { name: "Input 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: "Input Vector Polygon File".to_owned(), flags: vec!["--polygons".to_owned()], description: "Input vector polygons file.".to_owned(), parameter_type: ParameterType::ExistingFile(ParameterFileType::Vector( VectorGeometryType::Polygon, )), default_value: None, optional: false, }); parameters.push(ToolParameter { name: "Output File".to_owned(), flags: vec!["-o".to_owned(), "--output".to_owned()], description: "Output LiDAR file.".to_owned(), parameter_type: ParameterType::NewFile(ParameterFileType::Lidar), default_value: None, 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='data.las' --polygons='lakes.shp' -o='output.las'", short_exe, name).replace("*", &sep); ErasePolygonFromLidar { name: name, description: description, toolbox: toolbox, parameters: parameters, example_usage: usage, } } } impl WhiteboxTool for ErasePolygonFromLidar { 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 { match serde_json::to_string(&self.parameters) { Ok(json_str) => return format!("{{\"parameters\":{}}}", json_str), Err(err) => return format!("{:?}", err), } } 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::new(); let mut polygons_file = String::new(); let mut output_file = String::new(); 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" { input_file = if keyval { vec[1].to_string() } else { args[i + 1].to_string() }; } else if flag_val == "-polygon" || flag_val == "-polygons" { polygons_file = if keyval { vec[1].to_string() } else { args[i + 1].to_string() }; } else if flag_val == "-o" || flag_val == "-output" { output_file = if keyval { vec[1].to_string() } else { args[i + 1].to_string() }; } } 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: String = path::MAIN_SEPARATOR.to_string(); let mut progress: usize; let mut old_progress: usize = 1; if !input_file.contains(&sep) && !input_file.contains("/") { input_file = format!("{}{}", working_directory, input_file); } if !polygons_file.contains(&sep) && !polygons_file.contains("/") { polygons_file = format!("{}{}", working_directory, polygons_file); } if !output_file.contains(&sep) && !output_file.contains("/") { output_file = format!("{}{}", working_directory, output_file); } if verbose { println!("Reading data...") }; let input = match LasFile::new(&input_file, "r") { Ok(lf) => lf, Err(err) => panic!(format!("Error reading file {}: {}", input_file, err)), }; let polygons = Shapefile::read(&polygons_file)?; let num_records = polygons.num_records; let start = time::now(); // make sure the input vector file is of points type if polygons.header.shape_type.base_shape_type() != ShapeType::Polygon { return Err(Error::new( ErrorKind::InvalidInput, "The input vector data must be of polygon base shape type.", )); } // place the bounding boxes of each of the polygons into a vector let mut bb: Vec<BoundingBox> = Vec::with_capacity(num_records); for record_num in 0..polygons.num_records { let record = polygons.get_record(record_num); bb.push(BoundingBox::new( record.x_min, record.x_max, record.y_min, record.y_max, )); } let mut output = LasFile::initialize_using_file(&output_file, &input); output.header.system_id = "EXTRACTION".to_string(); let n_points = input.header.number_of_points as usize; let num_points: f64 = (input.header.number_of_points - 1) as f64; // used for progress calculation only let mut point_in_poly: bool; let mut p: PointData; let mut start_point_in_part: usize; let mut end_point_in_part: usize; for point_num in 0..n_points { p = input.get_point_info(point_num); point_in_poly = false; for record_num in 0..polygons.num_records { if bb[record_num].is_point_in_box(p.x, p.y) { // it's in the bounding box and worth seeing if it's in the enclosed polygon let record = polygons.get_record(record_num); for part in 0..record.num_parts as usize { if !record.is_hole(part as i32) { // not holes start_point_in_part = record.parts[part] as usize; end_point_in_part = if part < record.num_parts as usize - 1 { record.parts[part + 1] as usize - 1 } else { record.num_points as usize - 1 }; if vector::point_in_poly( &Point2D { x: p.x, y: p.y }, &record.points[start_point_in_part..end_point_in_part + 1], ) { point_in_poly = true; break; } } } for part in 0..record.num_parts as usize { if record.is_hole(part as i32) { // holes start_point_in_part = record.parts[part] as usize; end_point_in_part = if part < record.num_parts as usize - 1 { record.parts[part + 1] as usize - 1 } else { record.num_points as usize - 1 }; if vector::point_in_poly( &Point2D { x: p.x, y: p.y }, &record.points[start_point_in_part..end_point_in_part + 1], ) { point_in_poly = false; break; } } } } } if !point_in_poly { output.add_point_record(input.get_record(point_num)); } if verbose { progress = (100.0_f64 * point_num as f64 / num_points) as usize; if progress != old_progress { println!("Progress: {}%", progress); old_progress = progress; } } } let end = time::now(); let elapsed_time = end - start; 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).replace("PT", "") ); } Ok(()) } }
35.611111
162
0.484904
e5a8cd1fe5546ff822971ba30ff9b87b018b8318
14,643
//! # MongoDb addon //! //! This module provide the mongodb custom resource and its definition use std::{ fmt::{self, Display, Formatter}, sync::Arc, }; use async_trait::async_trait; use clevercloud_sdk::{ v2::{ self, addon::{self, CreateOpts}, }, v4::{ self, addon_provider::{mongodb, plan, AddonProviderId}, }, }; use futures::TryFutureExt; use kube::{api::ListParams, Api, Resource, ResourceExt}; use kube_derive::CustomResource; use kube_runtime::{controller, watcher, Controller}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use tracing::{debug, error, info}; use crate::svc::{ clevercloud::{self, ext::AddonExt}, crd::Instance, k8s::{self, finalizer, recorder, resource, secret, ControllerBuilder, State}, }; // ----------------------------------------------------------------------------- // Constants pub const ADDON_FINALIZER: &str = "api.clever-cloud.com/mongodb"; // ----------------------------------------------------------------------------- // Opts structure #[derive(JsonSchema, Serialize, Deserialize, PartialEq, Clone, Debug)] pub struct Opts { #[serde(rename = "version")] pub version: mongodb::Version, #[serde(rename = "encryption")] pub encryption: bool, } #[allow(clippy::from_over_into)] impl Into<addon::Opts> for Opts { fn into(self) -> addon::Opts { addon::Opts { version: Some(self.version.to_string()), encryption: Some(self.encryption.to_string()), ..Default::default() } } } // ----------------------------------------------------------------------------- // Spec structure #[derive(CustomResource, JsonSchema, Serialize, Deserialize, PartialEq, Clone, Debug)] #[kube(group = "api.clever-cloud.com")] #[kube(version = "v1")] #[kube(kind = "MongoDb")] #[kube(singular = "mongodb")] #[kube(plural = "mongodbs")] #[kube(shortname = "mo")] #[kube(status = "Status")] #[kube(namespaced)] #[kube(apiextensions = "v1")] #[kube(derive = "PartialEq")] pub struct Spec { #[serde(rename = "organisation")] pub organisation: String, #[serde(rename = "options")] pub options: Opts, #[serde(rename = "instance")] pub instance: Instance, } // ----------------------------------------------------------------------------- // Status structure #[derive(JsonSchema, Serialize, Deserialize, PartialEq, Clone, Debug, Default)] pub struct Status { #[serde(rename = "addon")] pub addon: Option<String>, } // ----------------------------------------------------------------------------- // MongoDb implementation #[allow(clippy::from_over_into)] impl Into<CreateOpts> for MongoDb { #[cfg_attr(feature = "trace", tracing::instrument)] fn into(self) -> CreateOpts { CreateOpts { name: AddonExt::name(&self), region: self.spec.instance.region.to_owned(), provider_id: AddonProviderId::MongoDb.to_string(), plan: self.spec.instance.plan.to_owned(), options: self.spec.options.into(), } } } impl AddonExt for MongoDb { type Error = ReconcilerError; #[cfg_attr(feature = "trace", tracing::instrument)] fn id(&self) -> Option<String> { if let Some(status) = &self.status { return status.addon.to_owned(); } None } #[cfg_attr(feature = "trace", tracing::instrument)] fn organisation(&self) -> String { self.spec.organisation.to_owned() } #[cfg_attr(feature = "trace", tracing::instrument)] fn name(&self) -> String { let delimiter = Self::delimiter(); Self::prefix() + &delimiter + &Self::kind(&()).to_string() + &delimiter + &self .uid() .expect("expect all resources in kubernetes to have an identifier") } } impl MongoDb { #[cfg_attr(feature = "trace", tracing::instrument)] pub fn set_addon_id(&mut self, id: Option<String>) { let mut status = self.status.get_or_insert_with(Status::default); status.addon = id; self.status = Some(status.to_owned()); } #[cfg_attr(feature = "trace", tracing::instrument)] pub fn get_addon_id(&self) -> Option<String> { self.status.to_owned().unwrap_or_default().addon } } // ----------------------------------------------------------------------------- // MongoDbAction structure #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)] pub enum Action { UpsertFinalizer, UpsertAddon, UpsertSecret, OverridesInstancePlan, DeleteFinalizer, DeleteAddon, } impl Display for Action { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::UpsertFinalizer => write!(f, "UpsertFinalizer"), Self::UpsertAddon => write!(f, "UpsertAddon"), Self::UpsertSecret => write!(f, "UpsertSecret"), Self::OverridesInstancePlan => write!(f, "OverridesInstancePlan"), Self::DeleteFinalizer => write!(f, "DeleteFinalizer"), Self::DeleteAddon => write!(f, "DeleteAddon"), } } } // ----------------------------------------------------------------------------- // ReconcilerError enum #[derive(thiserror::Error, Debug)] pub enum ReconcilerError { #[error("failed to reconcile resource, {0}")] Reconcile(String), #[error("failed to execute request on clever-cloud api, {0}")] CleverClient(clevercloud::Error), #[error("failed to execute request on kubernetes api, {0}")] KubeClient(kube::Error), #[error("failed to compute diff between the original and modified object, {0}")] Diff(serde_json::Error), } impl From<kube::Error> for ReconcilerError { #[cfg_attr(feature = "trace", tracing::instrument)] fn from(err: kube::Error) -> Self { Self::KubeClient(err) } } impl From<clevercloud::Error> for ReconcilerError { #[cfg_attr(feature = "trace", tracing::instrument)] fn from(err: clevercloud::Error) -> Self { Self::CleverClient(err) } } impl From<v2::addon::Error> for ReconcilerError { #[cfg_attr(feature = "trace", tracing::instrument)] fn from(err: v2::addon::Error) -> Self { Self::from(clevercloud::Error::from(err)) } } impl From<v4::addon_provider::plan::Error> for ReconcilerError { #[cfg_attr(feature = "trace", tracing::instrument)] fn from(err: v4::addon_provider::plan::Error) -> Self { Self::from(clevercloud::Error::from(err)) } } impl From<controller::Error<Self, watcher::Error>> for ReconcilerError { #[cfg_attr(feature = "trace", tracing::instrument)] fn from(err: controller::Error<ReconcilerError, watcher::Error>) -> Self { Self::Reconcile(err.to_string()) } } // ----------------------------------------------------------------------------- // Reconciler structure #[derive(Clone, Default, Debug)] pub struct Reconciler {} impl ControllerBuilder<MongoDb> for Reconciler { fn build(&self, state: State) -> Controller<MongoDb> { Controller::new(Api::all(state.kube), ListParams::default()) } } #[async_trait] impl k8s::Reconciler<MongoDb> for Reconciler { type Error = ReconcilerError; async fn upsert(ctx: Arc<State>, origin: Arc<MongoDb>) -> Result<(), ReconcilerError> { let State { kube, apis, config: _, } = ctx.as_ref(); let kind = MongoDb::kind(&()).to_string(); let (namespace, name) = resource::namespaced_name(&*origin); // --------------------------------------------------------------------- // Step 1: set finalizer info!( "Set finalizer on custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); let modified = finalizer::add((*origin).to_owned(), ADDON_FINALIZER); debug!( "Update information of custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); let patch = resource::diff(&*origin, &modified).map_err(ReconcilerError::Diff)?; let mut modified = resource::patch(kube.to_owned(), &modified, patch).await?; let action = &Action::UpsertFinalizer; let message = &format!("Create finalizer '{}'", ADDON_FINALIZER); recorder::normal(kube.to_owned(), &modified, action, message).await?; // --------------------------------------------------------------------- // Step 2: translate plan if !modified.spec.instance.plan.starts_with("plan_") { info!( "Resolve plan for '{}' addon provider for resource '{}/{}' using '{}'", &kind, &namespace, &name, &modified.spec.instance.plan ); let plan = plan::find( apis, &AddonProviderId::MongoDb, &modified.spec.organisation, &modified.spec.instance.plan, ) .await?; // Update the spec is not a good practise as it lead to // no-deterministic and infinite reconciliation loop. It should be // avoided or done with caution. if let Some(plan) = plan { info!( "Override plan for custom resource '{}' ('{}/{}') with plan '{}'", &kind, &name, &namespace, &plan.id ); let oplan = modified.spec.instance.plan.to_owned(); modified.spec.instance.plan = plan.id.to_owned(); debug!( "Update information of custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); let patch = resource::diff(&*origin, &modified).map_err(ReconcilerError::Diff)?; let modified = resource::patch(kube.to_owned(), &modified, patch.to_owned()).await?; let action = &Action::OverridesInstancePlan; let message = &format!("Overrides instance plan from '{}' to '{}'", oplan, plan.id); info!( "Create '{}' event for resource '{}' ('{}/{}') with following message, {}", action, &kind, &namespace, &name, message ); recorder::normal(kube.to_owned(), &modified, action, message).await?; } // Stop reconciliation here and wait for next iteration, already // triggered by the above patch request return Ok(()); } // --------------------------------------------------------------------- // Step 3: upsert addon info!( "Upsert addon for custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); let addon = modified.upsert(apis).await?; modified.set_addon_id(Some(addon.id.to_owned())); debug!( "Update information and status of custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); let patch = resource::diff(&*origin, &modified).map_err(ReconcilerError::Diff)?; let modified = resource::patch(kube.to_owned(), &modified, patch.to_owned()) .and_then(|modified| resource::patch_status(kube.to_owned(), modified, patch)) .await?; let action = &Action::UpsertAddon; let message = &format!( "Create managed mongodb instance on clever-cloud '{}'", addon.id ); recorder::normal(kube.to_owned(), &modified, action, message).await?; // --------------------------------------------------------------------- // Step 4: create the secret let secrets = modified.secrets(apis).await?; if let Some(secrets) = secrets { let s = secret::new(&modified, secrets); let (s_ns, s_name) = resource::namespaced_name(&s); info!( "Upsert kubernetes secret resource for custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); info!("Upsert kubernetes secret '{}/{}'", &s_ns, &s_name); let secret = resource::upsert(kube.to_owned(), &s, false).await?; let action = &Action::UpsertSecret; let message = &format!("Create kubernetes secret '{}'", secret.name()); recorder::normal(kube.to_owned(), &modified, action, message).await?; } Ok(()) } async fn delete(ctx: Arc<State>, origin: Arc<MongoDb>) -> Result<(), ReconcilerError> { let State { apis, kube, config: _, } = ctx.as_ref(); let mut modified = (*origin).to_owned(); let kind = MongoDb::kind(&()).to_string(); let (namespace, name) = resource::namespaced_name(&*origin); // --------------------------------------------------------------------- // Step 1: delete the addon info!( "Delete addon for custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); modified.delete(apis).await?; modified.set_addon_id(None); debug!( "Update information and status of custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); let patch = resource::diff(&*origin, &modified).map_err(ReconcilerError::Diff)?; let modified = resource::patch(kube.to_owned(), &modified, patch.to_owned()) .and_then(|modified| resource::patch_status(kube.to_owned(), modified, patch)) .await?; let action = &Action::DeleteAddon; let message = "Delete managed mongodb instance on clever-cloud"; recorder::normal(kube.to_owned(), &modified, action, message).await?; // --------------------------------------------------------------------- // Step 2: remove the finalizer info!( "Remove finalizer on custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); let modified = finalizer::remove(modified, ADDON_FINALIZER); let action = &Action::DeleteFinalizer; let message = "Delete finalizer from custom resource"; recorder::normal(kube.to_owned(), &modified, action, message).await?; debug!( "Update information of custom resource '{}' ('{}/{}')", &kind, &namespace, &name ); let patch = resource::diff(&*origin, &modified).map_err(ReconcilerError::Diff)?; resource::patch(kube.to_owned(), &modified, patch.to_owned()).await?; Ok(()) } }
33.817552
100
0.533497
22f09234f64e30b08ba597029133bc1a259e342e
8,408
use crate::constants::{CURVE_ORDER, GROUP_G2_SIZE, FIELD_ORDER_ELEMENT_SIZE}; use crate::errors::{SerzDeserzError, ValueError}; use crate::curve_order_elem::{CurveOrderElement, CurveOrderElementVector}; use crate::group_elem::{GroupElement, GroupElementVector}; use crate::types::{GroupG2, FP2, BigNum}; use crate::utils::hash_msg; use std::iter; use std::ops::{Add, AddAssign, Index, IndexMut, Mul, Neg, Sub, SubAssign}; use std::fmt; use std::hash::{Hash, Hasher}; use std::slice::Iter; use crate::group_elem_g1::parse_hex_as_fp; use rayon::prelude::*; use serde::{Serialize, Serializer, Deserialize, Deserializer}; use serde::de::{Error as DError, Visitor}; use std::str::SplitWhitespace; use zeroize::Zeroize; #[derive(Clone, Debug)] pub struct G2 { value: GroupG2, } impl GroupElement for G2 { fn new() -> Self { Self { value: GroupG2::new(), } } fn identity() -> Self { let mut v = GroupG2::new(); v.inf(); Self { value: v } } /// This is an arbitrary choice. Any group element can be a generator fn generator() -> Self { GroupG2::generator().into() } fn is_identity(&self) -> bool { self.value.is_infinity() } fn set_to_identity(&mut self) { self.value.inf() } fn from_msg_hash(msg: &[u8]) -> Self { GroupG2::mapit(&hash_msg(msg)).into() } /// TODO: call the appropriate function once implemented in `hash2curve` crate fn hash_to_curve(_msg: &[u8], _dst: &hash2curve::DomainSeparationTag) -> Self { unimplemented!(); } fn to_vec(&self) -> Vec<u8> { let mut bytes: [u8; GROUP_G2_SIZE] = [0; GROUP_G2_SIZE]; self.write_to_slice_unchecked(&mut bytes); bytes.to_vec() } fn from_slice(bytes: &[u8]) -> Result<Self, SerzDeserzError> { if bytes.len() != GROUP_G2_SIZE { return Err(SerzDeserzError::G2BytesIncorrectSize( bytes.len(), GROUP_G2_SIZE, )); } Ok(GroupG2::frombytes(bytes).into()) } fn write_to_slice(&self, target: &mut [u8]) -> Result<(), SerzDeserzError> { if target.len() != GROUP_G2_SIZE { return Err(SerzDeserzError::G2BytesIncorrectSize( target.len(), GROUP_G2_SIZE, )); } self.write_to_slice_unchecked(target); Ok(()) } fn write_to_slice_unchecked(&self, target: &mut [u8]) { let mut temp = GroupG2::new(); temp.copy(&self.value); temp.tobytes(target); } fn add_assign_(&mut self, b: &Self) { self.value.add(&b.value); } fn sub_assign_(&mut self, b: &Self) { self.value.sub(&b.value); } fn plus(&self, b: &Self) -> Self { let mut sum = self.value.clone(); sum.add(&b.value); sum.into() } fn minus(&self, b: &Self) -> Self { let mut diff = self.value.clone(); diff.sub(&b.value); diff.into() } fn scalar_mul_const_time(&self, a: &CurveOrderElement) -> Self { self.value.mul(&a.to_bignum()).into() } fn double(&self) -> Self { let mut d = self.value.clone(); d.dbl(); d.into() } fn double_mut(&mut self) { self.value.dbl(); } fn to_hex(&self) -> String { self.value.to_hex() } fn from_hex(s: String) -> Result<Self, SerzDeserzError> { let mut iter = s.split_whitespace(); let x = parse_hex_as_fp2(&mut iter)?; let y = parse_hex_as_fp2(&mut iter)?; let z = parse_hex_as_fp2(&mut iter)?; let mut value = GroupG2::new(); value.setpx(x); value.setpy(y); value.setpz(z); Ok(Self { value }) } fn negation(&self) -> Self { let mut n = self.to_ecp(); n.neg(); n.into() } fn is_extension() -> bool { return true; } fn has_correct_order(&self) -> bool { return self.value.mul(&CURVE_ORDER).is_infinity(); } } impl G2 { pub fn to_bytes(&self) -> [u8; 4 * FIELD_ORDER_ELEMENT_SIZE] { let mut bytes = [0u8; 4 * FIELD_ORDER_ELEMENT_SIZE]; self.value.tobytes(&mut bytes[..]); bytes } pub fn to_compressed_bytes(&self) -> [u8; 2 * FIELD_ORDER_ELEMENT_SIZE] { let mut bytes = [0u8; 2 * FIELD_ORDER_ELEMENT_SIZE]; let mut temp = GroupG2::new(); temp.copy(&self.value); temp.affine(); temp.x.geta().tobytes(&mut bytes[..FIELD_ORDER_ELEMENT_SIZE]); temp.x.getb().tobytes(&mut bytes[FIELD_ORDER_ELEMENT_SIZE..]); let a = temp.y.geta().parity() as u8; let b = temp.y.getb().parity() as u8; let parity = a << 1 | b; bytes[0] |= parity << 6; bytes } } impl From<[u8; 2*FIELD_ORDER_ELEMENT_SIZE]> for G2 { fn from(data: [u8; 2*FIELD_ORDER_ELEMENT_SIZE]) -> Self { Self::from(&data) } } impl From<&[u8; 2*FIELD_ORDER_ELEMENT_SIZE]> for G2 { fn from(data: &[u8; 2*FIELD_ORDER_ELEMENT_SIZE]) -> Self { let mut temp = data.clone(); let parity = (temp[0] >> 6) & 3u8; let pa = if parity & 2u8 == 2 { 1 } else { 0 }; let pb = if parity & 1u8 == 1 { 1 } else { 0 }; temp[0] &= 0x3F; let mut a = BigNum::frombytes(&temp[..FIELD_ORDER_ELEMENT_SIZE]); let mut b = BigNum::frombytes(&temp[FIELD_ORDER_ELEMENT_SIZE..]); a.norm(); b.norm(); let mut x = FP2::new_bigs(&a, &b); x.norm(); let mut y = GroupG2::rhs(&x); if y.sqrt() { if y.geta().parity() != pa { y.a.neg(); } if y.getb().parity() != pb { y.b.neg(); } y.reduce(); } let g2 = GroupG2::new_fp2s(&x, &y); Self { value: g2 } } } /// Parse given hex string as FP2 pub fn parse_hex_as_fp2(iter: &mut SplitWhitespace) -> Result<FP2, SerzDeserzError> { // Logic almost copied from AMCL but with error handling and constant time execution. // Constant time is important as hex is used during serialization and deserialization. // A seemingly effortless solution is to filter string for errors and pad with 0s before // passing to AMCL but that would be expensive as the string is scanned twice let a = parse_hex_as_fp(iter)?; let b = parse_hex_as_fp(iter)?; let mut fp2 = FP2::new(); fp2.seta(a); fp2.setb(b); Ok(fp2) } impl_group_elem_traits!(G2, GroupG2); impl_group_elem_conversions!(G2, GroupG2, GROUP_G2_SIZE); impl_group_elem_ops!(G2); impl_scalar_mul_ops!(G2); impl_group_element_lookup_table!(G2, G2LookupTable); // Represents an element of the sub-group of the elliptic curve over prime the extension field impl_optmz_scalar_mul_ops!(G2, GroupG2, G2LookupTable); #[derive(Clone, Debug, Serialize, Deserialize)] pub struct G2Vector { elems: Vec<G2>, } impl_group_elem_vec_ops!(G2, G2Vector); impl_group_elem_vec_product_ops!(G2, G2Vector, G2LookupTable); impl_group_elem_vec_conversions!(G2, G2Vector); impl G2 { /// Computes sum of 2 scalar multiplications. /// Faster than doing the scalar multiplications individually and then adding them. Uses lookup table /// returns self*a + h*b pub fn binary_scalar_mul(&self, h: &Self, a: &CurveOrderElement, b: &CurveOrderElement) -> Self { // TODO: Replace with faster let group_elems = iter::once(self).chain(iter::once(h)); let field_elems = iter::once(a).chain(iter::once(b)); G2Vector::multi_scalar_mul_const_time_without_precomputation(group_elems, field_elems) .unwrap() } } #[cfg(test)] mod test { use super::G2; use crate::group_elem::GroupElement; use crate::curve_order_elem::CurveOrderElement; #[test] fn test_compression() { let g2 = G2::generator(); let bytes = g2.to_compressed_bytes(); assert_eq!(G2::from(bytes), g2); for _ in 0..30 { let sk = CurveOrderElement::random(); let pk = &g2 * &sk; let bytes = pk.to_compressed_bytes(); let t = G2::from(bytes); assert_eq!(t, pk); } } #[test] fn test_parse_hex_for_fp2() { // TODO: } #[test] fn test_parse_bad_hex_for_fp2() { // TODO: } }
27.657895
105
0.585633
0e6970317db4c13afae87c80784d868594a063d7
68
#[derive(Debug, Clone)] pub struct Channel { pub size: usize, }
13.6
23
0.647059
c115c237750ac4d6ca7c3245bd4a476fe809fff6
35,008
use crate::algorithm::bulk_load; use crate::algorithm::intersection_iterator::IntersectionIterator; use crate::algorithm::iterators::*; use crate::algorithm::nearest_neighbor; use crate::algorithm::nearest_neighbor::NearestNeighborDistance2Iterator; use crate::algorithm::nearest_neighbor::NearestNeighborIterator; use crate::algorithm::removal; use crate::algorithm::removal::DrainIterator; use crate::algorithm::selection_functions::*; use crate::envelope::Envelope; use crate::node::ParentNode; use crate::object::{PointDistance, RTreeObject}; use crate::params::{verify_parameters, DefaultParams, InsertionStrategy, RTreeParams}; use crate::Point; use alloc::vec::Vec; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; impl<T, Params> Default for RTree<T, Params> where T: RTreeObject, Params: RTreeParams, { fn default() -> Self { Self::new_with_params() } } /// An n-dimensional r-tree data structure. /// /// # R-Trees /// R-Trees are data structures containing multi-dimensional objects like points, rectangles /// or polygons. They are optimized for retrieving the nearest neighbor at any point. /// /// R-trees can efficiently find answers to queries like "Find the nearest point of a polygon", /// "Find all police stations within a rectangle" or "Find the 10 nearest restaurants, sorted /// by their distances". Compared to a naive implementation for these scenarios that runs /// in `O(n)` for `n` inserted elements, r-trees reduce this time to `O(log(n))`. /// /// However, creating an r-tree is time consuming /// and runs in `O(n * log(n))`. Thus, r-trees are suited best if many queries and only few /// insertions are made. rstar also supports [bulk loading](RTree::bulk_load), /// which cuts down the constant factors when creating an r-tree significantly compared to /// sequential insertions. /// /// R-trees are also _dynamic_: points can be inserted and removed from an existing tree. /// /// ## Partitioning heuristics /// The inserted objects are internally partitioned into several boxes which should have small /// overlap and volume. This is done heuristically. While the originally proposed heuristic focused /// on fast insertion operations, the resulting r-trees were often suboptimally structured. Another /// heuristic, called `R*-tree` (r-star-tree), was proposed to improve the tree structure at the cost of /// longer insertion operations and is currently the crate's only implemented /// [insertion strategy]. /// /// ## Further reading /// For more information refer to the [wikipedia article](https://en.wikipedia.org/wiki/R-tree). /// /// # Usage /// The items inserted into an r-tree must implement the [RTreeObject] /// trait. To support nearest neighbor queries, implement the [PointDistance] /// trait. Some useful geometric primitives that implement the above traits can be found in the /// [crate::primitives]x module. Several primitives in the [`geo-types`](https://docs.rs/geo-types/) crate also /// implement these traits. /// /// ## Example /// ``` /// use rstar::RTree; /// /// let mut tree = RTree::new(); /// tree.insert([0.1, 0.0f32]); /// tree.insert([0.2, 0.1]); /// tree.insert([0.3, 0.0]); /// /// assert_eq!(tree.nearest_neighbor(&[0.4, -0.1]), Some(&[0.3, 0.0])); /// tree.remove(&[0.3, 0.0]); /// assert_eq!(tree.nearest_neighbor(&[0.4, 0.3]), Some(&[0.2, 0.1])); /// /// assert_eq!(tree.size(), 2); /// // &RTree implements IntoIterator! /// for point in &tree { /// println!("Tree contains a point {:?}", point); /// } /// ``` /// /// ## Supported point types /// All types implementing the [Point] trait can be used as underlying point type. /// By default, fixed size arrays can be used as points. /// /// ## Type Parameters /// * `T`: The type of objects stored in the r-tree. /// * `Params`: Compile time parameters that change the r-tree's internal layout. Refer to the /// [RTreeParams] trait for more information. /// /// ## Defining methods generic over r-trees /// If a library defines a method that should be generic over the r-tree type signature, make /// sure to include both type parameters like this: /// ``` /// # use rstar::{RTree,RTreeObject, RTreeParams}; /// pub fn generic_rtree_function<T, Params>(tree: &mut RTree<T, Params>) /// where /// T: RTreeObject, /// Params: RTreeParams /// { /// // ... /// } /// ``` /// Otherwise, any user of `generic_rtree_function` would be forced to use /// a tree with default parameters. /// /// # Runtime and Performance /// The runtime of query operations (e.g. `nearest neighbor` or `contains`) is usually /// `O(log(n))`, where `n` refers to the number of elements contained in the r-tree. /// A naive sequential algorithm would take `O(n)` time. However, r-trees incur higher /// build up times: inserting an element into an r-tree costs `O(log(n))` time. /// /// ## Bulk loading /// In many scenarios, insertion is only carried out once for many points. In this case, /// [RTree::bulk_load] will be considerably faster. Its total run time /// is still `O(log(n))`. /// /// ## Element distribution /// The tree's performance heavily relies on the spatial distribution of its elements. /// Best performance is achieved if: /// * No element is inserted more than once /// * The overlapping area of elements is as small as /// possible. /// /// For the edge case that all elements are overlapping (e.g, one and the same element /// is contained `n` times), the performance of most operations usually degrades to `O(n)`. /// /// # (De)Serialization /// Enable the `serde` feature for [Serde](https://crates.io/crates/serde) support. /// #[derive(Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( feature = "serde", serde(bound( serialize = "T: Serialize, T::Envelope: Serialize", deserialize = "T: Deserialize<'de>, T::Envelope: Deserialize<'de>" )) )] pub struct RTree<T, Params = DefaultParams> where Params: RTreeParams, T: RTreeObject, { root: ParentNode<T>, size: usize, _params: ::core::marker::PhantomData<Params>, } struct DebugHelper<'a, T, Params> where T: RTreeObject + ::core::fmt::Debug + 'a, Params: RTreeParams + 'a, { rtree: &'a RTree<T, Params>, } impl<'a, T, Params> ::core::fmt::Debug for DebugHelper<'a, T, Params> where T: RTreeObject + ::core::fmt::Debug, Params: RTreeParams, { fn fmt(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { formatter.debug_set().entries(self.rtree.iter()).finish() } } impl<T, Params> ::core::fmt::Debug for RTree<T, Params> where Params: RTreeParams, T: RTreeObject + ::core::fmt::Debug, { fn fmt(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { formatter .debug_struct("RTree") .field("size", &self.size) .field("items", &DebugHelper { rtree: &self }) .finish() } } impl<T> RTree<T> where T: RTreeObject, { /// Creates a new, empty r-tree. /// /// The created r-tree is configured with [default parameters](DefaultParams). pub fn new() -> Self { Self::new_with_params() } /// Creates a new r-tree with some elements already inserted. /// /// This method should be the preferred way for creating r-trees. It both /// runs faster and yields an r-tree with better internal structure that /// improves query performance. /// /// This method implements the overlap minimizing top-down bulk loading algorithm (OMT) /// as described in [this paper by Lee and Lee (2003)](http://ceur-ws.org/Vol-74/files/FORUM_18.pdf). /// /// # Runtime /// Bulk loading runs in `O(n * log(n))`, where `n` is the number of loaded /// elements. pub fn bulk_load(elements: Vec<T>) -> Self { Self::bulk_load_with_params(elements) } } impl<T, Params> RTree<T, Params> where Params: RTreeParams, T: RTreeObject, { /// Creates a new, empty r-tree. /// /// The tree's compile time parameters must be specified. Refer to the /// [RTreeParams] trait for more information and a usage example. pub fn new_with_params() -> Self { verify_parameters::<T, Params>(); RTree { root: ParentNode::new_root::<Params>(), size: 0, _params: Default::default(), } } /// Creates a new r-tree with some given elements and configurable parameters. /// /// For more information refer to [RTree::bulk_load] /// and [RTreeParams]. pub fn bulk_load_with_params(elements: Vec<T>) -> Self { Self::new_from_bulk_loading(elements, bulk_load::bulk_load_sequential::<_, Params>) } /// Returns the number of objects in an r-tree. /// /// # Example /// ``` /// use rstar::RTree; /// /// let mut tree = RTree::new(); /// assert_eq!(tree.size(), 0); /// tree.insert([0.0, 1.0, 2.0]); /// assert_eq!(tree.size(), 1); /// tree.remove(&[0.0, 1.0, 2.0]); /// assert_eq!(tree.size(), 0); /// ``` pub fn size(&self) -> usize { self.size } pub(crate) fn size_mut(&mut self) -> &mut usize { &mut self.size } /// Returns an iterator over all elements contained in the tree. /// /// The order in which the elements are returned is not specified. /// /// # Example /// ``` /// use rstar::RTree; /// let tree = RTree::bulk_load(vec![(0.0, 0.1), (0.3, 0.2), (0.4, 0.2)]); /// for point in tree.iter() { /// println!("This tree contains point {:?}", point); /// } /// ``` pub fn iter(&self) -> RTreeIterator<T> { RTreeIterator::new(&self.root, SelectAllFunc) } /// Returns an iterator over all mutable elements contained in the tree. /// /// The order in which the elements are returned is not specified. /// /// *Note*: It is a logic error to change an inserted item's position or dimensions. This /// method is primarily meant for own implementations of [RTreeObject] /// which can contain arbitrary additional data. /// If the position or location of an inserted object need to change, you will need to [RTree::remove] /// and reinsert it. /// pub fn iter_mut(&mut self) -> RTreeIteratorMut<T> { RTreeIteratorMut::new(&mut self.root, SelectAllFunc) } /// Returns all elements contained in an [Envelope]. /// /// Usually, an envelope is an [axis aligned bounding box](crate::AABB). This /// method can be used to retrieve all elements that are fully contained within an envelope. /// /// # Example /// ``` /// use rstar::{RTree, AABB}; /// let mut tree = RTree::bulk_load(vec![ /// [0.0, 0.0], /// [0.0, 1.0], /// [1.0, 1.0] /// ]); /// let half_unit_square = AABB::from_corners([0.0, 0.0], [0.5, 1.0]); /// let unit_square = AABB::from_corners([0.0, 0.0], [1.0, 1.0]); /// let elements_in_half_unit_square = tree.locate_in_envelope(&half_unit_square); /// let elements_in_unit_square = tree.locate_in_envelope(&unit_square); /// assert_eq!(elements_in_half_unit_square.count(), 2); /// assert_eq!(elements_in_unit_square.count(), 3); /// ``` pub fn locate_in_envelope(&self, envelope: &T::Envelope) -> LocateInEnvelope<T> { LocateInEnvelope::new(&self.root, SelectInEnvelopeFunction::new(*envelope)) } /// Mutable variant of [locate_in_envelope](#method.locate_in_envelope). pub fn locate_in_envelope_mut(&mut self, envelope: &T::Envelope) -> LocateInEnvelopeMut<T> { LocateInEnvelopeMut::new(&mut self.root, SelectInEnvelopeFunction::new(*envelope)) } /// Draining variant of [locate_in_envelope](#method.locate_in_envelope). pub fn drain_in_envelope(&mut self, envelope: T::Envelope) -> DrainIterator<T, SelectInEnvelopeFunction<T>, Params> { let sel = SelectInEnvelopeFunction::new(envelope); self.drain_with_selection_function(sel) } /// Returns all elements whose envelope intersects a given envelope. /// /// Any element fully contained within an envelope is also returned by this method. Two /// envelopes that "touch" each other (e.g. by sharing only a common corner) are also /// considered to intersect. Usually, an envelope is an [axis aligned bounding box](crate::AABB). /// This method will return all elements whose AABB has some common area with /// a given AABB. /// /// # Example /// ``` /// use rstar::{RTree, AABB}; /// use rstar::primitives::Rectangle; /// /// let left_piece = AABB::from_corners([0.0, 0.0], [0.4, 1.0]); /// let right_piece = AABB::from_corners([0.6, 0.0], [1.0, 1.0]); /// let middle_piece = AABB::from_corners([0.25, 0.0], [0.75, 1.0]); /// /// let mut tree = RTree::<Rectangle<_>>::bulk_load(vec![ /// left_piece.into(), /// right_piece.into(), /// middle_piece.into(), /// ]); /// /// let elements_intersecting_left_piece = tree.locate_in_envelope_intersecting(&left_piece); /// // The left piece should not intersect the right piece! /// assert_eq!(elements_intersecting_left_piece.count(), 2); /// let elements_intersecting_middle = tree.locate_in_envelope_intersecting(&middle_piece); /// // Only the middle piece intersects all pieces within the tree /// assert_eq!(elements_intersecting_middle.count(), 3); /// /// let large_piece = AABB::from_corners([-100., -100.], [100., 100.]); /// let elements_intersecting_large_piece = tree.locate_in_envelope_intersecting(&large_piece); /// // Any element that is fully contained should also be returned: /// assert_eq!(elements_intersecting_large_piece.count(), 3); pub fn locate_in_envelope_intersecting( &self, envelope: &T::Envelope, ) -> LocateInEnvelopeIntersecting<T> { LocateInEnvelopeIntersecting::new( &self.root, SelectInEnvelopeFuncIntersecting::new(*envelope), ) } /// Mutable variant of [locate_in_envelope_intersecting](#method.locate_in_envelope_intersecting) pub fn locate_in_envelope_intersecting_mut( &mut self, envelope: &T::Envelope, ) -> LocateInEnvelopeIntersectingMut<T> { LocateInEnvelopeIntersectingMut::new( &mut self.root, SelectInEnvelopeFuncIntersecting::new(*envelope), ) } /// Locates elements in the r-tree defined by a selection function. /// /// Refer to the documentation of [`SelectionFunction`] for /// more information. /// /// Usually, other `locate` methods should cover most common use cases. This method is only required /// in more specific situations. pub fn locate_with_selection_function<S: SelectionFunction<T>>( &self, selection_function: S, ) -> SelectionIterator<T, S> { SelectionIterator::new(&self.root, selection_function) } /// Mutable variant of [`locate_with_selection_function`](#method.locate_with_selection_function). pub fn locate_with_selection_function_mut<S: SelectionFunction<T>>( &mut self, selection_function: S, ) -> SelectionIteratorMut<T, S> { SelectionIteratorMut::new(&mut self.root, selection_function) } /// Returns all possible intersecting objects of this and another tree. /// /// This will return all objects whose _envelopes_ intersect. No geometric intersection /// checking is performed. pub fn intersection_candidates_with_other_tree<'a, U>( &'a self, other: &'a RTree<U>, ) -> IntersectionIterator<T, U> where U: RTreeObject<Envelope = T::Envelope>, { IntersectionIterator::new(self.root(), other.root()) } /// Returns the tree's root node. /// /// Usually, you will not need to call this method. However, for debugging purposes or for /// advanced algorithms, knowledge about the tree's internal structure may be required. /// For these cases, this method serves as an entry point. pub fn root(&self) -> &ParentNode<T> { &self.root } pub(crate) fn root_mut(&mut self) -> &mut ParentNode<T> { &mut self.root } fn new_from_bulk_loading( elements: Vec<T>, root_loader: impl Fn(Vec<T>) -> ParentNode<T>, ) -> Self { verify_parameters::<T, Params>(); let size = elements.len(); let root = if size == 0 { ParentNode::new_root::<Params>() } else { root_loader(elements) }; RTree { root, size, _params: Default::default(), } } /// Removes and returns a single element from the tree. The element to remove is specified /// by a [`SelectionFunction`]. /// /// See also: [`RTree::remove`], [`RTree::remove_at_point`] /// pub fn remove_with_selection_function<F>(&mut self, function: F) -> Option<T> where F: SelectionFunction<T>, { removal::DrainIterator::new(self, function).take(1).last() } /// Drain elements selected by a [`SelectionFunction`]. Returns an /// iterator that successively removes selected elements and returns /// them. This is the most generic drain API, see also: /// [`RTree::drain_in_envelope_intersecting`], /// [`RTree::drain_within_distance`]. /// /// # Remarks /// /// This API is similar to `Vec::drain_filter`, but stopping the /// iteration would stop the removal. However, the returned iterator /// must be properly dropped. Leaking this iterator leads to a leak /// amplification, where all the elements in the tree are leaked. pub fn drain_with_selection_function<F>(&mut self, function: F) -> DrainIterator<T, F, Params> where F: SelectionFunction<T>, { removal::DrainIterator::new(self, function) } /// Drains elements intersecting the `envelope`. Similar to /// `locate_in_envelope_intersecting`, except the elements are removed /// and returned via an iterator. pub fn drain_in_envelope_intersecting(&mut self, envelope: T::Envelope) -> DrainIterator<T, SelectInEnvelopeFuncIntersecting<T>, Params> { let selection_function = SelectInEnvelopeFuncIntersecting::new(envelope); self.drain_with_selection_function(selection_function) } } impl<T, Params> RTree<T, Params> where Params: RTreeParams, T: PointDistance, { /// Returns a single object that covers a given point. /// /// Method [contains_point](PointDistance::contains_point) /// is used to determine if a tree element contains the given point. /// /// If multiple elements contain the given point, any of them is returned. pub fn locate_at_point(&self, point: &<T::Envelope as Envelope>::Point) -> Option<&T> { self.locate_all_at_point(point).next() } /// Mutable variant of [RTree::locate_at_point]. pub fn locate_at_point_mut( &mut self, point: &<T::Envelope as Envelope>::Point, ) -> Option<&mut T> { self.locate_all_at_point_mut(point).next() } /// Locate all elements containing a given point. /// /// Method [PointDistance::contains_point] is used /// to determine if a tree element contains the given point. /// # Example /// ``` /// use rstar::RTree; /// use rstar::primitives::Rectangle; /// /// let tree = RTree::bulk_load(vec![ /// Rectangle::from_corners([0.0, 0.0], [2.0, 2.0]), /// Rectangle::from_corners([1.0, 1.0], [3.0, 3.0]) /// ]); /// /// assert_eq!(tree.locate_all_at_point(&[1.5, 1.5]).count(), 2); /// assert_eq!(tree.locate_all_at_point(&[0.0, 0.0]).count(), 1); /// assert_eq!(tree.locate_all_at_point(&[-1., 0.0]).count(), 0); /// ``` pub fn locate_all_at_point( &self, point: &<T::Envelope as Envelope>::Point, ) -> LocateAllAtPoint<T> { LocateAllAtPoint::new(&self.root, SelectAtPointFunction::new(*point)) } /// Mutable variant of [locate_all_at_point](#method.locate_all_at_point). pub fn locate_all_at_point_mut( &mut self, point: &<T::Envelope as Envelope>::Point, ) -> LocateAllAtPointMut<T> { LocateAllAtPointMut::new(&mut self.root, SelectAtPointFunction::new(*point)) } /// Removes an element containing a given point. /// /// The removed element, if any, is returned. If multiple elements cover the given point, /// only one of them is removed and returned. /// /// # Example /// ``` /// use rstar::RTree; /// use rstar::primitives::Rectangle; /// /// let mut tree = RTree::bulk_load(vec![ /// Rectangle::from_corners([0.0, 0.0], [2.0, 2.0]), /// Rectangle::from_corners([1.0, 1.0], [3.0, 3.0]) /// ]); /// /// assert!(tree.remove_at_point(&[1.5, 1.5]).is_some()); /// assert!(tree.remove_at_point(&[1.5, 1.5]).is_some()); /// assert!(tree.remove_at_point(&[1.5, 1.5]).is_none()); ///``` pub fn remove_at_point(&mut self, point: &<T::Envelope as Envelope>::Point) -> Option<T> { let removal_function = SelectAtPointFunction::new(*point); self.remove_with_selection_function(removal_function) } } impl<T, Params> RTree<T, Params> where Params: RTreeParams, T: RTreeObject + PartialEq, { /// Returns `true` if a given element is equal (`==`) to an element in the /// r-tree. /// /// This method will only work correctly if two equal elements also have the /// same envelope. /// /// # Example /// ``` /// use rstar::RTree; /// /// let mut tree = RTree::new(); /// assert!(!tree.contains(&[0.0, 2.0])); /// tree.insert([0.0, 2.0]); /// assert!(tree.contains(&[0.0, 2.0])); /// ``` pub fn contains(&self, t: &T) -> bool { self.locate_in_envelope(&t.envelope()).any(|e| e == t) } /// Removes and returns an element of the r-tree equal (`==`) to a given element. /// /// If multiple elements equal to the given elements are contained in the tree, only /// one of them is removed and returned. /// /// This method will only work correctly if two equal elements also have the /// same envelope. /// /// # Example /// ``` /// use rstar::RTree; /// /// let mut tree = RTree::new(); /// tree.insert([0.0, 2.0]); /// // The element can be inserted twice just fine /// tree.insert([0.0, 2.0]); /// assert!(tree.remove(&[0.0, 2.0]).is_some()); /// assert!(tree.remove(&[0.0, 2.0]).is_some()); /// assert!(tree.remove(&[0.0, 2.0]).is_none()); /// ``` pub fn remove(&mut self, t: &T) -> Option<T> { let removal_function = SelectEqualsFunction::new(t); self.remove_with_selection_function(removal_function) } } impl<T, Params> RTree<T, Params> where Params: RTreeParams, T: PointDistance, { /// Returns the nearest neighbor for a given point. /// /// The distance is calculated by calling /// [PointDistance::distance_2] /// /// # Example /// ``` /// use rstar::RTree; /// let tree = RTree::bulk_load(vec![ /// [0.0, 0.0], /// [0.0, 1.0], /// ]); /// assert_eq!(tree.nearest_neighbor(&[-1., 0.0]), Some(&[0.0, 0.0])); /// assert_eq!(tree.nearest_neighbor(&[0.0, 2.0]), Some(&[0.0, 1.0])); /// ``` pub fn nearest_neighbor(&self, query_point: &<T::Envelope as Envelope>::Point) -> Option<&T> { if self.size > 0 { // The single-nearest-neighbor retrieval may in rare cases return None due to // rounding issues. The iterator will still work, though. nearest_neighbor::nearest_neighbor(&self.root, *query_point) .or_else(|| self.nearest_neighbor_iter(query_point).next()) } else { None } } /// Returns the nearest neighbors for a given point. /// /// The distance is calculated by calling /// [PointDistance::distance_2] /// /// All returned values will have the exact same distance from the given query point. /// Returns an empty `Vec` if the tree is empty. /// /// # Example /// ``` /// use rstar::RTree; /// let tree = RTree::bulk_load(vec![ /// [0.0, 0.0], /// [0.0, 1.0], /// [1.0, 0.0], /// ]); /// assert_eq!(tree.nearest_neighbors(&[1.0, 1.0]), &[&[0.0, 1.0], &[1.0, 0.0]]); /// assert_eq!(tree.nearest_neighbors(&[0.01, 0.01]), &[&[0.0, 0.0]]); /// ``` pub fn nearest_neighbors(&self, query_point: &<T::Envelope as Envelope>::Point) -> Vec<&T> { nearest_neighbor::nearest_neighbors(&self.root, *query_point) } /// Returns all elements of the tree within a certain distance. /// /// The elements may be returned in any order. Each returned element /// will have a squared distance less or equal to the given squared distance. /// /// This method makes use of [PointDistance::distance_2_if_less_or_equal]. /// If performance is critical and the distance calculation to the object is fast, /// overwriting this function may be beneficial. pub fn locate_within_distance( &self, query_point: <T::Envelope as Envelope>::Point, max_squared_radius: <<T::Envelope as Envelope>::Point as Point>::Scalar, ) -> LocateWithinDistanceIterator<T> { let selection_function = SelectWithinDistanceFunction::new(query_point, max_squared_radius); LocateWithinDistanceIterator::new(self.root(), selection_function) } /// Drain all elements of the tree within a certain distance. /// /// Similar to [`RTree::locate_within_distance`], but removes and /// returns the elements via an iterator. pub fn drain_within_distance( &mut self, query_point: <T::Envelope as Envelope>::Point, max_squared_radius: <<T::Envelope as Envelope>::Point as Point>::Scalar, ) -> DrainIterator<T, SelectWithinDistanceFunction<T>, Params> { let selection_function = SelectWithinDistanceFunction::new(query_point, max_squared_radius); self.drain_with_selection_function(selection_function) } /// Returns all elements of the tree sorted by their distance to a given point. /// /// # Runtime /// Every `next()` call runs in `O(log(n))`. Creating the iterator runs in /// `O(log(n))`. /// The [r-tree documentation](RTree) contains more information about /// r-tree performance. /// /// # Example /// ``` /// use rstar::RTree; /// let tree = RTree::bulk_load(vec![ /// [0.0, 0.0], /// [0.0, 1.0], /// ]); /// /// let nearest_neighbors = tree.nearest_neighbor_iter(&[0.5, 0.0]).collect::<Vec<_>>(); /// assert_eq!(nearest_neighbors, vec![&[0.0, 0.0], &[0.0, 1.0]]); /// ``` pub fn nearest_neighbor_iter( &self, query_point: &<T::Envelope as Envelope>::Point, ) -> NearestNeighborIterator<T> { nearest_neighbor::NearestNeighborIterator::new(&self.root, *query_point) } /// Returns `(element, distance^2)` tuples of the tree sorted by their distance to a given point. /// /// The distance is calculated by calling /// [PointDistance::distance_2]. #[deprecated(note = "Please use nearest_neighbor_iter_with_distance_2 instead")] pub fn nearest_neighbor_iter_with_distance( &self, query_point: &<T::Envelope as Envelope>::Point, ) -> NearestNeighborDistance2Iterator<T> { nearest_neighbor::NearestNeighborDistance2Iterator::new(&self.root, *query_point) } /// Returns `(element, distance^2)` tuples of the tree sorted by their distance to a given point. /// /// The distance is calculated by calling /// [PointDistance::distance_2]. pub fn nearest_neighbor_iter_with_distance_2( &self, query_point: &<T::Envelope as Envelope>::Point, ) -> NearestNeighborDistance2Iterator<T> { nearest_neighbor::NearestNeighborDistance2Iterator::new(&self.root, *query_point) } /// Removes the nearest neighbor for a given point and returns it. /// /// The distance is calculated by calling /// [PointDistance::distance_2]. /// /// # Example /// ``` /// use rstar::RTree; /// let mut tree = RTree::bulk_load(vec![ /// [0.0, 0.0], /// [0.0, 1.0], /// ]); /// assert_eq!(tree.pop_nearest_neighbor(&[0.0, 0.0]), Some([0.0, 0.0])); /// assert_eq!(tree.pop_nearest_neighbor(&[0.0, 0.0]), Some([0.0, 1.0])); /// assert_eq!(tree.pop_nearest_neighbor(&[0.0, 0.0]), None); /// ``` pub fn pop_nearest_neighbor( &mut self, query_point: &<T::Envelope as Envelope>::Point, ) -> Option<T> { if let Some(neighbor) = self.nearest_neighbor(query_point) { let removal_function = SelectByAddressFunction::new(neighbor.envelope(), neighbor); self.remove_with_selection_function(removal_function) } else { None } } } impl<T, Params> RTree<T, Params> where T: RTreeObject, Params: RTreeParams, { /// Inserts a new element into the r-tree. /// /// If the element is already present in the tree, it will now be present twice. /// /// # Runtime /// This method runs in `O(log(n))`. /// The [r-tree documentation](RTree) contains more information about /// r-tree performance. pub fn insert(&mut self, t: T) { Params::DefaultInsertionStrategy::insert(self, t); self.size += 1; } } impl<T, Params> RTree<T, Params> where T: RTreeObject, <T::Envelope as Envelope>::Point: Point, Params: RTreeParams, { } impl<'a, T, Params> IntoIterator for &'a RTree<T, Params> where T: RTreeObject, Params: RTreeParams, { type IntoIter = RTreeIterator<'a, T>; type Item = &'a T; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, T, Params> IntoIterator for &'a mut RTree<T, Params> where T: RTreeObject, Params: RTreeParams, { type IntoIter = RTreeIteratorMut<'a, T>; type Item = &'a mut T; fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } #[cfg(test)] mod test { use super::RTree; use crate::algorithm::rstar::RStarInsertionStrategy; use crate::params::RTreeParams; use crate::test_utilities::{create_random_points, SEED_1}; use crate::DefaultParams; struct TestParams; impl RTreeParams for TestParams { const MIN_SIZE: usize = 10; const MAX_SIZE: usize = 20; const REINSERTION_COUNT: usize = 1; type DefaultInsertionStrategy = RStarInsertionStrategy; } #[test] fn test_create_rtree_with_parameters() { let tree: RTree<[f32; 2], TestParams> = RTree::new_with_params(); assert_eq!(tree.size(), 0); } #[test] fn test_insert_single() { let mut tree: RTree<_> = RTree::new(); tree.insert([0.02f32, 0.4f32]); assert_eq!(tree.size(), 1); assert!(tree.contains(&[0.02, 0.4])); assert!(!tree.contains(&[0.3, 0.2])); } #[test] fn test_insert_many() { const NUM_POINTS: usize = 1000; let points = create_random_points(NUM_POINTS, SEED_1); let mut tree = RTree::new(); for p in &points { tree.insert(*p); tree.root.sanity_check::<DefaultParams>(true); } assert_eq!(tree.size(), NUM_POINTS); for p in &points { assert!(tree.contains(p)); } } #[test] fn test_fmt_debug() { let tree = RTree::bulk_load(vec![[0, 1], [0, 1]]); let debug: String = format!("{:?}", tree); assert_eq!(debug, "RTree { size: 2, items: {[0, 1], [0, 1]} }"); } #[test] fn test_default() { let tree: RTree<[f32; 2]> = Default::default(); assert_eq!(tree.size(), 0); } #[cfg(feature = "serde")] #[test] fn test_serialization() { use crate::test_utilities::create_random_integers; use serde_json; const SIZE: usize = 20; let points = create_random_integers::<[i32; 2]>(SIZE, SEED_1); let tree = RTree::bulk_load(points.clone()); let json = serde_json::to_string(&tree).expect("Serializing tree failed"); let parsed: RTree<[i32; 2]> = serde_json::from_str(&json).expect("Deserializing tree failed"); assert_eq!(parsed.size(), SIZE); for point in &points { assert!(parsed.contains(point)); } } #[test] fn test_bulk_load_crash() { let bulk_nodes = vec![ [570.0, 1080.0, 89.0], [30.0, 1080.0, 627.0], [1916.0, 1080.0, 68.0], [274.0, 1080.0, 790.0], [476.0, 1080.0, 895.0], [1557.0, 1080.0, 250.0], [1546.0, 1080.0, 883.0], [1512.0, 1080.0, 610.0], [1729.0, 1080.0, 358.0], [1841.0, 1080.0, 434.0], [1752.0, 1080.0, 696.0], [1674.0, 1080.0, 705.0], [136.0, 1080.0, 22.0], [1593.0, 1080.0, 71.0], [586.0, 1080.0, 272.0], [348.0, 1080.0, 373.0], [502.0, 1080.0, 2.0], [1488.0, 1080.0, 1072.0], [31.0, 1080.0, 526.0], [1695.0, 1080.0, 559.0], [1663.0, 1080.0, 298.0], [316.0, 1080.0, 417.0], [1348.0, 1080.0, 731.0], [784.0, 1080.0, 126.0], [225.0, 1080.0, 847.0], [79.0, 1080.0, 819.0], [320.0, 1080.0, 504.0], [1714.0, 1080.0, 1026.0], [264.0, 1080.0, 229.0], [108.0, 1080.0, 158.0], [1665.0, 1080.0, 604.0], [496.0, 1080.0, 231.0], [1813.0, 1080.0, 865.0], [1200.0, 1080.0, 326.0], [1661.0, 1080.0, 818.0], [135.0, 1080.0, 229.0], [424.0, 1080.0, 1016.0], [1708.0, 1080.0, 791.0], [1626.0, 1080.0, 682.0], [442.0, 1080.0, 895.0], ]; let nodes = vec![ [1916.0, 1060.0, 68.0], [1664.0, 1060.0, 298.0], [1594.0, 1060.0, 71.0], [225.0, 1060.0, 846.0], [1841.0, 1060.0, 434.0], [502.0, 1060.0, 2.0], [1625.5852, 1060.0122, 682.0], [1348.5273, 1060.0029, 731.08124], [316.36127, 1060.0298, 418.24515], [1729.3253, 1060.0023, 358.50134], ]; let mut tree = RTree::bulk_load(bulk_nodes); for node in nodes { // Bulk loading will create nodes larger than Params::MAX_SIZE, // which is intentional and not harmful. tree.insert(node); tree.root().sanity_check::<DefaultParams>(false); } } }
35.722449
140
0.610689
1eda730eb6b24e1c102346383a0a66b5568af50d
470
pub const MEMORY_OFFSET: usize = 0; pub const KERNEL_OFFSET: usize = 0xFFFF_0000_0000_0000; pub const PHYSICAL_MEMORY_OFFSET: usize = 0xFFFF_8000_0000_0000; pub const KERNEL_HEAP_SIZE: usize = 8 * 1024 * 1024; pub const USER_STACK_OFFSET: usize = 0x0000_8000_0000_0000 - USER_STACK_SIZE; pub const USER_STACK_SIZE: usize = 1 * 1024 * 1024; pub const KSEG2_START: usize = 0xffff_fe80_0000_0000; #[cfg(target_arch = "aarch64")] pub const ARCH: &'static str = "aarch64";
39.166667
77
0.776596
1c950474e80dcbb494807af75ff8fe22545f0004
11,557
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Service config. /// /// /// Service configuration allows for customization of endpoints, region, credentials providers, /// and retry configuration. Generally, it is constructed automatically for you from a shared /// configuration loaded by the `aws-config` crate. For example: /// /// ```ignore /// // Load a shared config from the environment /// let shared_config = aws_config::from_env().load().await; /// // The client constructor automatically converts the shared config into the service config /// let client = Client::new(&shared_config); /// ``` /// /// The service config can also be constructed manually using its builder. /// pub struct Config { app_name: Option<aws_types::app_name::AppName>, pub(crate) timeout_config: Option<aws_smithy_types::timeout::TimeoutConfig>, pub(crate) sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>, pub(crate) retry_config: Option<aws_smithy_types::retry::RetryConfig>, pub(crate) endpoint_resolver: ::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>, pub(crate) region: Option<aws_types::region::Region>, pub(crate) credentials_provider: aws_types::credentials::SharedCredentialsProvider, } impl std::fmt::Debug for Config { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut config = f.debug_struct("Config"); config.finish() } } impl Config { /// Constructs a config builder. pub fn builder() -> Builder { Builder::default() } /// Returns the name of the app that is using the client, if it was provided. /// /// This _optional_ name is used to identify the application in the user agent that /// gets sent along with requests. pub fn app_name(&self) -> Option<&aws_types::app_name::AppName> { self.app_name.as_ref() } /// Creates a new [service config](crate::Config) from a [shared `config`](aws_types::config::Config). pub fn new(config: &aws_types::config::Config) -> Self { Builder::from(config).build() } /// The signature version 4 service signing name to use in the credential scope when signing requests. /// /// The signing service may be overridden by the `Endpoint`, or by specifying a custom /// [`SigningService`](aws_types::SigningService) during operation construction pub fn signing_service(&self) -> &'static str { "forecast" } } /// Builder for creating a `Config`. #[derive(Default)] pub struct Builder { app_name: Option<aws_types::app_name::AppName>, timeout_config: Option<aws_smithy_types::timeout::TimeoutConfig>, sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>, retry_config: Option<aws_smithy_types::retry::RetryConfig>, endpoint_resolver: Option<::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>>, region: Option<aws_types::region::Region>, credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>, } impl Builder { /// Constructs a config builder. pub fn new() -> Self { Self::default() } /// Sets the name of the app that is using the client. /// /// This _optional_ name is used to identify the application in the user agent that /// gets sent along with requests. pub fn app_name(mut self, app_name: aws_types::app_name::AppName) -> Self { self.set_app_name(Some(app_name)); self } /// Sets the name of the app that is using the client. /// /// This _optional_ name is used to identify the application in the user agent that /// gets sent along with requests. pub fn set_app_name(&mut self, app_name: Option<aws_types::app_name::AppName>) -> &mut Self { self.app_name = app_name; self } /// Set the timeout_config for the builder /// /// # Examples /// /// ```no_run /// # use std::time::Duration; /// use aws_sdk_forecast::config::Config; /// use aws_smithy_types::timeout::TimeoutConfig; /// /// let timeout_config = TimeoutConfig::new() /// .with_api_call_attempt_timeout(Some(Duration::from_secs(1))); /// let config = Config::builder().timeout_config(timeout_config).build(); /// ``` pub fn timeout_config( mut self, timeout_config: aws_smithy_types::timeout::TimeoutConfig, ) -> Self { self.set_timeout_config(Some(timeout_config)); self } /// Set the timeout_config for the builder /// /// # Examples /// /// ```no_run /// # use std::time::Duration; /// use aws_sdk_forecast::config::{Builder, Config}; /// use aws_smithy_types::timeout::TimeoutConfig; /// /// fn set_request_timeout(builder: &mut Builder) { /// let timeout_config = TimeoutConfig::new() /// .with_api_call_timeout(Some(Duration::from_secs(3))); /// builder.set_timeout_config(Some(timeout_config)); /// } /// /// let mut builder = Config::builder(); /// set_request_timeout(&mut builder); /// let config = builder.build(); /// ``` pub fn set_timeout_config( &mut self, timeout_config: Option<aws_smithy_types::timeout::TimeoutConfig>, ) -> &mut Self { self.timeout_config = timeout_config; self } /// Set the sleep_impl for the builder /// /// # Examples /// /// ```no_run /// use aws_sdk_forecast::config::Config; /// use aws_smithy_async::rt::sleep::AsyncSleep; /// use aws_smithy_async::rt::sleep::Sleep; /// /// #[derive(Debug)] /// pub struct ForeverSleep; /// /// impl AsyncSleep for ForeverSleep { /// fn sleep(&self, duration: std::time::Duration) -> Sleep { /// Sleep::new(std::future::pending()) /// } /// } /// /// let sleep_impl = std::sync::Arc::new(ForeverSleep); /// let config = Config::builder().sleep_impl(sleep_impl).build(); /// ``` pub fn sleep_impl( mut self, sleep_impl: std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>, ) -> Self { self.set_sleep_impl(Some(sleep_impl)); self } /// Set the sleep_impl for the builder /// /// # Examples /// /// ```no_run /// use aws_sdk_forecast::config::{Builder, Config}; /// use aws_smithy_async::rt::sleep::AsyncSleep; /// use aws_smithy_async::rt::sleep::Sleep; /// /// #[derive(Debug)] /// pub struct ForeverSleep; /// /// impl AsyncSleep for ForeverSleep { /// fn sleep(&self, duration: std::time::Duration) -> Sleep { /// Sleep::new(std::future::pending()) /// } /// } /// /// fn set_never_ending_sleep_impl(builder: &mut Builder) { /// let sleep_impl = std::sync::Arc::new(ForeverSleep); /// builder.set_sleep_impl(Some(sleep_impl)); /// } /// /// let mut builder = Config::builder(); /// set_never_ending_sleep_impl(&mut builder); /// let config = builder.build(); /// ``` pub fn set_sleep_impl( &mut self, sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>, ) -> &mut Self { self.sleep_impl = sleep_impl; self } /// Set the retry_config for the builder /// /// # Examples /// ```no_run /// use aws_sdk_forecast::config::Config; /// use aws_smithy_types::retry::RetryConfig; /// /// let retry_config = RetryConfig::new().with_max_attempts(5); /// let config = Config::builder().retry_config(retry_config).build(); /// ``` pub fn retry_config(mut self, retry_config: aws_smithy_types::retry::RetryConfig) -> Self { self.set_retry_config(Some(retry_config)); self } /// Set the retry_config for the builder /// /// # Examples /// ```no_run /// use aws_sdk_forecast::config::{Builder, Config}; /// use aws_smithy_types::retry::RetryConfig; /// /// fn disable_retries(builder: &mut Builder) { /// let retry_config = RetryConfig::new().with_max_attempts(1); /// builder.set_retry_config(Some(retry_config)); /// } /// /// let mut builder = Config::builder(); /// disable_retries(&mut builder); /// let config = builder.build(); /// ``` pub fn set_retry_config( &mut self, retry_config: Option<aws_smithy_types::retry::RetryConfig>, ) -> &mut Self { self.retry_config = retry_config; self } // TODO(docs): include an example of using a static endpoint /// Sets the endpoint resolver to use when making requests. pub fn endpoint_resolver( mut self, endpoint_resolver: impl aws_endpoint::ResolveAwsEndpoint + 'static, ) -> Self { self.endpoint_resolver = Some(::std::sync::Arc::new(endpoint_resolver)); self } /// Sets the AWS region to use when making requests. /// /// # Examples /// ```no_run /// use aws_types::region::Region; /// use aws_sdk_forecast::config::{Builder, Config}; /// /// let config = aws_sdk_forecast::Config::builder() /// .region(Region::new("us-east-1")) /// .build(); /// ``` pub fn region(mut self, region: impl Into<Option<aws_types::region::Region>>) -> Self { self.region = region.into(); self } /// Sets the credentials provider for this service pub fn credentials_provider( mut self, credentials_provider: impl aws_types::credentials::ProvideCredentials + 'static, ) -> Self { self.credentials_provider = Some(aws_types::credentials::SharedCredentialsProvider::new( credentials_provider, )); self } /// Sets the credentials provider for this service pub fn set_credentials_provider( &mut self, credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>, ) -> &mut Self { self.credentials_provider = credentials_provider; self } /// Builds a [`Config`]. pub fn build(self) -> Config { Config { app_name: self.app_name, timeout_config: self.timeout_config, sleep_impl: self.sleep_impl, retry_config: self.retry_config, endpoint_resolver: self .endpoint_resolver .unwrap_or_else(|| ::std::sync::Arc::new(crate::aws_endpoint::endpoint_resolver())), region: self.region, credentials_provider: self.credentials_provider.unwrap_or_else(|| { aws_types::credentials::SharedCredentialsProvider::new( crate::no_credentials::NoCredentials, ) }), } } } impl From<&aws_types::config::Config> for Builder { fn from(input: &aws_types::config::Config) -> Self { let mut builder = Builder::default(); builder = builder.region(input.region().cloned()); builder.set_retry_config(input.retry_config().cloned()); builder.set_timeout_config(input.timeout_config().cloned()); builder.set_sleep_impl(input.sleep_impl().clone()); builder.set_credentials_provider(input.credentials_provider().cloned()); builder.set_app_name(input.app_name().cloned()); builder } } impl From<&aws_types::config::Config> for Config { fn from(config: &aws_types::config::Config) -> Self { Builder::from(config).build() } }
36.22884
106
0.623432
d55f5018dffd0a4ece79540a2a6afea38e3f5eeb
547
pub struct Bdimentions{ pub unit_size:i32, pub left:i32, pub right:i32, pub bottom:i32, pub top:i32, pub width:i32, pub height:i32, } impl Bdimentions { pub fn new() -> Bdimentions { let width = 1280; let height = 720; Bdimentions{ unit_size:height / 22, left:(width /2) - (5 * (height / 22)), right:(width /2) + (5 * (height / 22)), bottom:height - (1*(height / 22)), top:height - (21*(height / 22)), width:width, height:height } } }
18.862069
47
0.52468
89a765f1e03de2c5ce61447937cf4015ded37529
4,479
use futures::{future, ready, TryFutureExt}; use linkerd2_app_core::proxy::{http, identity}; use linkerd2_app_core::{dns, errors::HttpError, Error, NameAddr}; use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; #[derive(Clone, Debug)] pub(crate) enum Gateway<O> { NoAuthority, NoIdentity, BadDomain(dns::Name), Outbound { outbound: O, local_identity: identity::Name, host_header: http::header::HeaderValue, forwarded_header: http::header::HeaderValue, }, } impl<O> Gateway<O> { pub fn new( outbound: O, dst: NameAddr, source_identity: identity::Name, local_identity: identity::Name, ) -> Self { let host = dst.as_http_authority().to_string(); let fwd = format!( "by={};for={};host={};proto=https", local_identity, source_identity, host ); Gateway::Outbound { outbound, local_identity, host_header: http::header::HeaderValue::from_str(&host) .expect("Host header value must be valid"), forwarded_header: http::header::HeaderValue::from_str(&fwd) .expect("Forwarded header value must be valid"), } } } impl<B, O> tower::Service<http::Request<B>> for Gateway<O> where B: http::HttpBody + 'static, O: tower::Service<http::Request<B>, Response = http::Response<http::boxed::BoxBody>>, O::Error: Into<Error> + 'static, O::Future: Send + 'static, { type Response = O::Response; type Error = Error; type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { match self { Self::Outbound { outbound, .. } => { Poll::Ready(ready!(outbound.poll_ready(cx)).map_err(Into::into)) } _ => Poll::Ready(Ok(())), } } fn call(&mut self, mut request: http::Request<B>) -> Self::Future { match self { Self::Outbound { ref mut outbound, ref local_identity, ref host_header, ref forwarded_header, } => { // Check forwarded headers to see if this request has already // transited through this gateway. for forwarded in request .headers() .get_all(http::header::FORWARDED) .into_iter() .filter_map(|h| h.to_str().ok()) { if let Some(by) = fwd_by(forwarded) { tracing::info!(%forwarded); if by == local_identity.as_ref() { return Box::pin(future::err(HttpError::gateway_loop().into())); } } } // Add a forwarded header. request .headers_mut() .append(http::header::FORWARDED, forwarded_header.clone()); // If we're forwarding HTTP/1 requests, the old `Host` header // was stripped on the peer's outbound proxy. But the request // should have an updated `Host` header now that it's being // routed in the cluster. if let ::http::Version::HTTP_11 | ::http::Version::HTTP_10 = request.version() { request .headers_mut() .insert(http::header::HOST, host_header.clone()); } tracing::debug!( headers = ?request.headers(), "Passing request to outbound" ); Box::pin(outbound.call(request).map_err(Into::into)) } Self::NoAuthority => Box::pin(future::err(HttpError::not_found("no authority").into())), Self::NoIdentity => Box::pin(future::err( HttpError::identity_required("no identity").into(), )), Self::BadDomain(..) => Box::pin(future::err(HttpError::not_found("bad domain").into())), } } } fn fwd_by(fwd: &str) -> Option<&str> { for kv in fwd.split(';') { let mut kv = kv.split('='); if let Some("by") = kv.next() { return kv.next(); } } None }
34.992188
100
0.510382
cc78fed904c4e26cbf65540ec7c90329ff6fc77e
11,298
//! # ConDow //! //! ## Overview //! //! ConDow is a CONcurrent DOWnloader which downloads BLOBs //! by splitting the download into parts and downloading them //! concurrently. //! //! Some services/technologies/backends can have their download //! speed improved, if BLOBs are downloaded concurrently by //! "opening multiple connections". An example for this is AWS S3. //! //! This crate provides the core functionality only. To actually //! use it, use one of the implementation crates: //! //! * [condow_rusoto] for downloading AWS S3 via the rusoto //! * [condow_fs] for using async file access via [tokio] //! //! All that is required to add more "services" is to implement //! the [CondowClient] trait. //! //! ## Retries //! //! ConDow supports retries. These can be done on the downloads themselves //! as well on the byte streams returned from a client. If an error occurs //! while streaming bytes ConDow will try to reconnect with retries and //! resume streaming where the previous stream failed. //! //! Retries can also be attempted on size requests. //! //! Be aware that some clients might also do retries themselves based on //! their underlying implementation. In this case you should disable retries for either the //! client or ConDow itself. //! //! [condow_rusoto]:https://docs.rs/condow_rusoto //! [condow_fs]:https://docs.rs/condow_fs use std::sync::Arc; use futures::{future::BoxFuture, FutureExt, Stream}; use condow_client::CondowClient; use config::{AlwaysGetSize, ClientRetryWrapper, Config}; use errors::CondowError; use reader::RandomAccessReader; use reporter::{NoReporting, Reporter, ReporterFactory}; use streams::{ChunkStream, ChunkStreamItem, PartStream}; #[macro_use] pub(crate) mod helpers; pub mod condow_client; pub mod config; mod download_range; mod download_session; mod downloader; pub mod errors; pub mod logging; mod machinery; pub mod reader; pub mod reporter; mod retry; pub mod streams; pub use download_range::*; pub use download_session::*; pub use downloader::*; #[cfg(test)] pub mod test_utils; /// A common interface for downloading pub trait Downloads<L> where L: std::fmt::Debug + std::fmt::Display + Clone + Send + Sync + 'static, { /// Download a BLOB range concurrently /// /// Returns a stream of [Chunk](streams::Chunk)s. fn download<'a, R: Into<DownloadRange> + Send + Sync + 'static>( &'a self, location: L, range: R, ) -> BoxFuture<'a, Result<PartStream<ChunkStream>, CondowError>>; /// Download a BLOB range concurrently /// /// Returns a stream of [Parts](streams::Part)s. fn download_chunks<'a, R: Into<DownloadRange> + Send + Sync + 'static>( &'a self, location: L, range: R, ) -> BoxFuture<'a, Result<ChunkStream, CondowError>>; /// Get the size of a file at the BLOB location fn get_size<'a>(&'a self, location: L) -> BoxFuture<'a, Result<u64, CondowError>>; /// Creates a [RandomAccessReader] for the given location /// /// This function will query the size of the BLOB. If the size is already known /// call [Downloads::reader_with_length] fn reader<'a>( &'a self, location: L, ) -> BoxFuture<'a, Result<RandomAccessReader<Self, L>, CondowError>> where Self: Sized + Sync, { let me = self; async move { let length = me.get_size(location.clone()).await?; Ok(me.reader_with_length(location, length)) } .boxed() } /// Creates a [RandomAccessReader] for the given location /// /// This function will create a new reader immediately fn reader_with_length(&self, location: L, length: u64) -> RandomAccessReader<Self, L> where Self: Sized; } /// The CONcurrent DOWnloader /// /// Downloads BLOBs by splitting the download into parts /// which are downloaded concurrently. /// /// The API of `Condow` itself should be sufficient for most use cases. /// /// If reporting/metrics is required, see [Downloader] and [DownloadSession] /// /// ## Wording /// /// * `Range`: A range to be downloaded of a BLOB (Can also be the complete BLOB) /// * `Part`: The downloaded range is split into parts of certain ranges which are downloaded concurrently /// * `Chunk`: A chunk of bytes received from the network (or else). Multiple chunks make a part. pub struct Condow<C> { client: ClientRetryWrapper<C>, config: Config, } impl<C: CondowClient> Clone for Condow<C> { fn clone(&self) -> Self { Self { client: self.client.clone(), config: self.config.clone(), } } } impl<C: CondowClient> Condow<C> { /// Create a new CONcurrent DOWnloader. /// /// Fails if the [Config] is not valid. pub fn new(client: C, config: Config) -> Result<Self, anyhow::Error> { let config = config.validated()?; Ok(Self { client: ClientRetryWrapper::new(client, config.retries.clone()), config, }) } /// Create a reusable [Downloader] which has a richer API. pub fn downloader(&self) -> Downloader<C, NoReporting> { Downloader::new(self.clone()) } /// Create a reusable [Downloader] which has a richer API. pub fn downloader_with_reporting<RF: ReporterFactory>(&self, rep_fac: RF) -> Downloader<C, RF> { self.downloader_with_reporting_arc(Arc::new(rep_fac)) } /// Create a reusable [Downloader] which has a richer API. pub fn downloader_with_reporting_arc<RF: ReporterFactory>( &self, rep_fac: Arc<RF>, ) -> Downloader<C, RF> { Downloader::new_with_reporting_arc(self.clone(), rep_fac) } /// Create a [DownloadSession] to track all downloads. pub fn download_session<RF: ReporterFactory>(&self, rep_fac: RF) -> DownloadSession<C, RF> { self.download_session_arc(Arc::new(rep_fac)) } /// Create a [DownloadSession] to track all downloads. pub fn download_session_arc<RF: ReporterFactory>( &self, rep_fac: Arc<RF>, ) -> DownloadSession<C, RF> { DownloadSession::new_with_reporting_arc(self.clone(), rep_fac) } /// Download a BLOB range (potentially) concurrently /// /// Returns a stream of [Chunk](streams::Chunk)s. pub async fn download_chunks<R: Into<DownloadRange>>( &self, location: C::Location, range: R, ) -> Result<ChunkStream, CondowError> { machinery::download(self, location, range, GetSizeMode::Default, NoReporting) .await .map(|o| o.into_stream()) } /// Download a BLOB range (potentially) concurrently /// /// Returns a stream of [Parts](streams::Part)s. pub async fn download<R: Into<DownloadRange>>( &self, location: C::Location, range: R, ) -> Result<PartStream<ChunkStream>, CondowError> { let chunk_stream = machinery::download(self, location, range, GetSizeMode::Default, NoReporting) .await .map(|o| o.into_stream())?; PartStream::from_chunk_stream(chunk_stream) } /// Get the size of a file at the given location pub async fn get_size(&self, location: C::Location) -> Result<u64, CondowError> { self.client.get_size(location, &NoReporting).await } /// Creates a [RandomAccessReader] for the given location pub async fn reader( &self, location: C::Location, ) -> Result<RandomAccessReader<Self, C::Location>, CondowError> { RandomAccessReader::new(self.clone(), location).await } /// Creates a [RandomAccessReader] for the given location pub fn reader_with_length( &self, location: C::Location, length: u64, ) -> RandomAccessReader<Self, C::Location> { RandomAccessReader::new_with_length(self.clone(), location, length) } } impl<C> Downloads<C::Location> for Condow<C> where C: CondowClient, { fn download<'a, R: Into<DownloadRange> + Send + Sync + 'static>( &'a self, location: C::Location, range: R, ) -> BoxFuture<'a, Result<PartStream<ChunkStream>, CondowError>> { Box::pin(self.download(location, range)) } fn download_chunks<'a, R: Into<DownloadRange> + Send + Sync + 'static>( &'a self, location: C::Location, range: R, ) -> BoxFuture<'a, Result<ChunkStream, CondowError>> { Box::pin(self.download_chunks(location, range)) } fn get_size<'a>(&'a self, location: C::Location) -> BoxFuture<'a, Result<u64, CondowError>> { Box::pin(self.get_size(location)) } fn reader_with_length( &self, location: C::Location, length: u64, ) -> RandomAccessReader<Self, C::Location> { Condow::reader_with_length(self, location, length) } } /// A composite struct of a stream and a [Reporter] /// /// Returned from functions which have reporting enabled. pub struct StreamWithReport<St: Stream, R: Reporter> { pub stream: St, pub reporter: R, } impl<St, R> StreamWithReport<St, R> where St: Stream, R: Reporter, { pub fn new(stream: St, reporter: R) -> Self { Self { stream, reporter } } pub fn into_stream(self) -> St { self.stream } pub fn into_parts(self) -> (St, R) { (self.stream, self.reporter) } } impl<R> StreamWithReport<ChunkStream, R> where R: Reporter, { pub fn part_stream(self) -> Result<StreamWithReport<PartStream<ChunkStream>, R>, CondowError> { let StreamWithReport { stream, reporter } = self; let part_stream = PartStream::from_chunk_stream(stream)?; Ok(StreamWithReport::new(part_stream, reporter)) } pub async fn write_buffer(self, buffer: &mut [u8]) -> Result<usize, CondowError> { self.stream.write_buffer(buffer).await } pub async fn into_vec(self) -> Result<Vec<u8>, CondowError> { self.stream.into_vec().await } } impl<S, R> StreamWithReport<PartStream<S>, R> where S: Stream<Item = ChunkStreamItem> + Send + Sync + 'static + Unpin, R: Reporter, { pub async fn write_buffer(self, buffer: &mut [u8]) -> Result<usize, CondowError> { self.stream.write_buffer(buffer).await } pub async fn into_vec(self) -> Result<Vec<u8>, CondowError> { self.stream.into_vec().await } } /// Overide the behaviour when [Condow] does a request to get /// the size of a BLOB #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum GetSizeMode { /// Request a size on open ranges and also closed ranges /// so that a given upper bound can be adjusted/corrected Always, /// Only request the size of a BLOB when required. This is when an open /// range (e.g. complete BLOB or from x to end) Required, /// As configured with [Condow] itself. Default, } impl GetSizeMode { fn is_load_size_enforced(self, always_by_default: AlwaysGetSize) -> bool { match self { GetSizeMode::Always => true, GetSizeMode::Required => false, GetSizeMode::Default => always_by_default.into_inner(), } } } impl Default for GetSizeMode { fn default() -> Self { Self::Default } } #[cfg(test)] mod condow_tests;
30.617886
106
0.643477
8fdf92eeac1c6b7696842699da9cceda31e3fa79
2,288
/// Config contains all customizable options of the Client pub struct Config { pub(crate) gateway_large_treshold: u8, pub(crate) gateway_guilds_subscriptions: bool, pub(crate) gateway_shard_id: u64, pub(crate) gateway_num_shards: u64, } impl Config { pub fn new() -> ConfigBuilder { ConfigBuilder::new() } pub(crate) fn new_default() -> Config { Config { gateway_large_treshold: 50, gateway_guilds_subscriptions: true, gateway_shard_id: 0, gateway_num_shards: 1, } } } pub struct ConfigBuilder { pub(crate) gateway_large_treshold: u8, pub(crate) gateway_guilds_subscriptions: bool, pub(crate) gateway_shard_id: u64, pub(crate) gateway_num_shards: u64, } impl ConfigBuilder { fn new() -> ConfigBuilder { ConfigBuilder { gateway_large_treshold: 50, gateway_guilds_subscriptions: true, gateway_shard_id: 0, gateway_num_shards: 1, } } /// Set largue threshold, It's value between 50 and 250, it's total number of members where the gateway /// will stop sending offline members in the guild member list. Default is 50. pub fn set_large_threshold(mut self, threshold: u8) -> Self { self.gateway_large_treshold = threshold; self } /// A true value enables dispatching of guild subscription events (presence and typing events). Default true. pub fn set_guild_subscriptions(mut self, subscriptions: bool) -> Self { self.gateway_guilds_subscriptions = subscriptions; self } /// Set shard for [Guild Sharding](https://discordapp.com/developers/docs/topics/gateway#sharding). /// Default [0, 1] pub fn set_shards(mut self, shard_id: u64, num_shards: u64) -> Self { self.gateway_shard_id = shard_id; self.gateway_num_shards = num_shards; self } /// Build a Config struct pub fn build(self) -> Config { Config { gateway_large_treshold: self.gateway_large_treshold, gateway_guilds_subscriptions: self.gateway_guilds_subscriptions, gateway_shard_id: self.gateway_shard_id, gateway_num_shards: self.gateway_num_shards, } } }
30.506667
113
0.653846
ffcc925bc582769434920f624528cda87d557dd4
7,026
//! Provides the decision stump class. use crate::{Data, Sample}; use crate::BaseLearner; use super::{DStumpClassifier, PositiveSide}; pub(self) type IndicesByValue = Vec<usize>; pub(self) type FeatureIndex = Vec<IndicesByValue>; /// The struct `DStump` generates a `DStumpClassifier` /// for each call of `self.produce(..)`. pub struct DStump { pub(crate) indices: Vec<FeatureIndex>, } impl DStump { /// Construct an empty Decision Stump class. pub fn new() -> DStump { DStump { indices: Vec::new() } } /// Initializes and produce an instance of `DStump`. pub fn init<T>(sample: &Sample<T, f64>) -> DStump where T: Data<Output = f64>, { let dim = sample.dim(); // indices: Vec<FeatureIndex> // the j'th element of this vector stores // the grouped indices by value. let mut indices: Vec<_> = Vec::with_capacity(dim); for j in 0..dim { let mut vals = sample.iter() .enumerate() .map(|(i, (dat, _))| (i, dat.value_at(j))) // .map(|(i, example)| (i, example.value_at(j))) .collect::<Vec<(usize, f64)>>(); vals.sort_by(|(_, a), (_, b)| a.partial_cmp(&b).unwrap()); let mut vals = vals.into_iter(); // Group the indices by j'th value // recall that IndicesByValue = Vec<usize> let mut temp: IndicesByValue; let mut v; { // Initialize `temp` and `v` let (i, _v) = vals.next().unwrap(); temp = vec![i]; v = _v; } // recall that // FeatureIndex = Vec<IndicesByValue> // = Vec<Vec<usize>> let mut index: FeatureIndex = Vec::new(); while let Some((i, vv)) = vals.next() { if vv == v { temp.push(i); } else { v = vv; index.push(temp); temp = vec![i]; } } index.push(temp); indices.push(index); } // Construct DStump DStump { indices } } // pub fn init<T>(sample: &Sample<T>) -> DStump // where T: Data<Output = f64>, // { // let dim = sample.dim(); // // indices: Vec<FeatureIndex> // // the j'th element of this vector stores // // the grouped indices by value. // let mut indices: Vec<_> = Vec::with_capacity(dim); // for j in 0..dim { // let mut vals = sample.iter() // .enumerate() // .map(|(i, (dat, _))| (i, dat.value_at(j))) // // .map(|(i, example)| (i, example.value_at(j))) // .collect::<Vec<(usize, f64)>>(); // vals.sort_by(|(_, a), (_, b)| a.partial_cmp(&b).unwrap()); // let mut vals = vals.into_iter(); // // Group the indices by j'th value // // recall that IndicesByValue = Vec<usize> // let mut temp: IndicesByValue; // let mut v; // { // // Initialize `temp` and `v` // let (i, _v) = vals.next().unwrap(); // temp = vec![i]; // v = _v; // } // // recall that // // FeatureIndex = Vec<IndicesByValue> // // = Vec<Vec<usize>> // let mut index: FeatureIndex = Vec::new(); // while let Some((i, vv)) = vals.next() { // if vv == v { // temp.push(i); // } else { // v = vv; // index.push(temp); // temp = vec![i]; // } // } // index.push(temp); // indices.push(index); // } // // Construct DStump // DStump { indices } // } } impl<D: Data<Output = f64>> BaseLearner<D, f64> for DStump { type Clf = DStumpClassifier; fn produce(&self, sample: &Sample<D, f64>, distribution: &[f64]) -> Self::Clf { let init_edge = distribution.iter() .zip(sample.iter()) .fold(0.0, |acc, (dist, (_, lab))| acc + dist * *lab); let mut best_edge = init_edge - 1e-2; // This is the output of this function. // Initialize with some init value. let mut dstump = { let (min_dat, _) = &sample[self.indices[0][0][0]]; DStumpClassifier { threshold: min_dat.value_at(0) - 1.0, feature_index: 0_usize, positive_side: PositiveSide::RHS } }; { // `self.indidces[i][j][k]` is the `k`th index // of the `j`th block of the `i`th feature // TODO this line may fail since self.indices[0][0] // may have no element. let i = self.indices[0][0][0]; let (ith_dat, _) = &sample[i]; let val = ith_dat.value_at(0); if val > 0.0 { dstump.threshold = val / 2.0; } } let mut update_params_mut = |edge: f64, threshold: f64, j: usize| { if best_edge < edge.abs() { dstump.threshold = threshold; dstump.feature_index = j; best_edge = edge.abs(); if edge > 0.0 { dstump.positive_side = PositiveSide::RHS; } else { dstump.positive_side = PositiveSide::LHS; } } }; for (j, index) in self.indices.iter().enumerate() { let mut edge = init_edge; let mut index = index.iter().peekable(); let mut right = { let idx = index.peek().unwrap(); let (first_dat, _) = &sample[idx[0]]; first_dat.value_at(j) }; let mut left; while let Some(idx) = index.next() { let temp = idx.iter() .fold(0.0, |acc, &i| { let (_, lab) = &sample[i]; acc + distribution[i] * lab }); edge -= 2.0 * temp; left = right; right = match index.peek() { Some(next_index) => { // TODO: This line can be replaced by // `get_unchecked` let i = next_index[0]; let (ith_dat, _) = &sample[i]; ith_dat.value_at(j) }, None => { left + 2.0 } }; update_params_mut(edge, (left + right) / 2.0, j); } } dstump } }
30.025641
75
0.426274
26b360fd93d2684b7dd91cd71fb2c4812410b023
6,539
mod movingrms; mod movingrmsexact; mod loudnessbuffer; use cpal::traits::{HostTrait, DeviceTrait, StreamTrait}; use buttplug::{ client::{ ButtplugClient, ButtplugClientEvent, ButtplugClientDeviceMessageType, VibrateCommand, }, server::ButtplugServerOptions, }; use tokio::io::{self, AsyncBufReadExt, BufReader}; use futures::{StreamExt, Stream}; use futures_timer::Delay; use std::sync::{Arc, Mutex}; use std::{error::Error, io::Write}; fn prompt_host() -> Result<cpal::Host, Box<dyn Error>> { let mut hosts = cpal::available_hosts(); let id: Result<cpal::HostId, Box<dyn Error>> = match hosts.len() { 0 => Err("no available host found".into()), 1 => { println!( "selecting only available host: {}", hosts[0].name() ); Ok(hosts.pop().unwrap()) }, _ => { println!("available hosts:"); for (i, h) in hosts.iter().enumerate() { println!("{}: {}", i, h.name()); } print!("select host: "); std::io::stdout().flush()?; let mut input = String::new(); std::io::stdin().read_line(&mut input)?; Ok( hosts.into_iter().nth( input.trim().parse::<usize>()? ).ok_or("invalid host selected")? ) }, }; Ok(cpal::host_from_id(id?)?) } fn prompt_device(host: &cpal::Host) -> Result<cpal::Device, Box<dyn Error>> { let mut devices = host.input_devices()?.collect::<Vec<cpal::Device>>(); match devices.len() { 0 => Err("no available audio input device found".into()), 1 => { println!( "selecting only available audio input device: {}", devices[0].name()? ); Ok(devices.pop().unwrap()) }, _ => { println!("available audio input devices:"); for (i, d) in devices.iter().enumerate() { println!("{}: {}", i, d.name()?); } print!("select audio input device: "); std::io::stdout().flush()?; let mut input = String::new(); std::io::stdin().read_line(&mut input)?; Ok( devices.into_iter().nth( input.trim().parse::<usize>()? ).ok_or("invalid input device selected")? ) }, } } fn handle_input_data(data: &[f32], lb: &Arc<Mutex<loudnessbuffer::LoudnessBuffer>>) { (*lb.lock().unwrap()).extend(data.iter().copied()); } async fn handle_scanning(mut event_stream: impl Stream<Item = ButtplugClientEvent> + Unpin) { loop { match event_stream.next().await.unwrap() { ButtplugClientEvent::DeviceAdded(dev) => { tokio::spawn(async move { println!("device added: {}", dev.name); }); }, ButtplugClientEvent::ScanningFinished => { println!("scanning finished signaled!"); return; }, ButtplugClientEvent::ServerDisconnect => { println!("server disconnected!"); }, _ => { println!("something happened!"); }, } } } async fn run(lb: Arc<Mutex<loudnessbuffer::LoudnessBuffer>>) -> Result<(), Box<dyn Error>> { // connect Buttplug devices let client = ButtplugClient::new("buzznoise buttplug client"); let event_stream = client.event_stream(); client.connect_in_process(&ButtplugServerOptions::default()).await?; client.start_scanning().await?; let scan_handler = tokio::spawn(handle_scanning(event_stream)); println!("\nscanning for devices! press enter at any point to stop scanning and start listening to audio input."); BufReader::new(io::stdin()).lines().next_line().await?; client.stop_scanning().await?; scan_handler.await?; // poll average let devices = client.devices(); tokio::spawn(async move { loop { let power = 3.0 * (*lb.lock().unwrap()).rms(); let speed = if power < 0.01 { 0_f64 } else { f64::from(power.min(1.0)) }; println!( "power: {:.5} | vibration speed: {:.5} [{:<5}]", power, speed, "=".repeat((speed * 5.0) as usize) ); for dev in devices.clone() { tokio::spawn(async move { if dev.allowed_messages.contains_key(&ButtplugClientDeviceMessageType::VibrateCmd) { dev.vibrate(VibrateCommand::Speed(speed)).await.unwrap(); } }); } Delay::new(std::time::Duration::from_millis(50)).await; } }); println!("\nconnected MIDI input to device output! press enter at any point to quit."); BufReader::new(io::stdin()).lines().next_line().await?; println!("stopping all devices and quitting..."); client.stop_all_devices().await?; Ok(()) } fn main() { // get command-line arguments let _matches = clap::App::new("buzznoise") .version("0.1") .about("get a buzz on audio input!") .get_matches(); // connect audio stream to Buttplug let ending: Result<(), Box<dyn Error>> = (|| -> Result<(), Box<dyn Error>> { // get audio stream let host = prompt_host()?; let device = prompt_device(&host)?; let config = device.default_input_config()?; let width = 0.05; // seconds let capacity = (config.sample_rate().0 as f32 * width) as usize; let lb_a = Arc::new(Mutex::new(loudnessbuffer::LoudnessBuffer::new(capacity))); let lb_b = lb_a.clone(); let err_fn = move |err| { eprintln!("an error occurred on stream: {}", err); }; let stream = match config.sample_format() { cpal::SampleFormat::F32 => device.build_input_stream( &config.into(), move |data, _: &_| handle_input_data(data, &lb_b), err_fn )?, _ => todo!(), }; stream.play()?; // start async runtime let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; runtime.block_on(run(lb_a))?; Ok(()) })(); // say goodbye match ending { Ok(()) => { println!("bye-bye! >:3c"); }, Err(e) => { eprintln!("error: {}", e); }, } }
36.327778
118
0.527604
bb3c52bfc7578a9182a949104ddc51d08fe976c7
1,803
// An imaginary magical school has a new report card generation system written in Rust! // Currently the system only supports creating report cards where the student's grade // is represented numerically (e.g. 1.0 -> 5.5). // However, the school also issues alphabetical grades (A+ -> F-) and needs // to be able to print both types of report card! // Make the necessary code changes in the struct ReportCard and the impl block // to support alphabetical report cards. Change the Grade in the second test to "A+" // to show that your changes allow alphabetical grades. // Execute 'rustlings hint generics3' for hints! // I AM NOT DONE use std::fmt::Display; pub struct ReportCard<T: Display> { pub grade: T, pub student_name: String, pub student_age: u8, } impl<T> ReportCard<T> { pub fn print(&self) -> String { format!( "{} ({}) - achieved a grade of {:?}", &self.student_name, &self.student_age, &self.grade ) } } #[cfg(test)] mod tests { use super::*; #[test] fn generate_numeric_report_card() { let report_card = ReportCard { grade: 2.1, student_name: "Tom Wriggle".to_string(), student_age: 12, }; assert_eq!( report_card.print(), "Tom Wriggle (12) - achieved a grade of 2.1" ); } #[test] fn generate_alphabetic_report_card() { // TODO: Make sure to change the grade here after you finish the exercise. let report_card = ReportCard { grade: String::from("A+"), student_name: "Gary Plotter".to_string(), student_age: 11, }; assert_eq!( report_card.print(), "Gary Plotter (11) - achieved a grade of A+" ); } }
28.619048
87
0.602329
75696873b6cce54dbf770c8c9993e0ea67be595d
24,558
use crate::{ dns::Resolver, event::{self, Event}, region::RegionOrEndpoint, sinks::util::{ retries::RetryLogic, rusoto, BatchBytesConfig, Buffer, PartitionBuffer, PartitionInnerBuffer, ServiceBuilderExt, SinkExt, TowerRequestConfig, }, template::Template, topology::config::{DataType, SinkConfig, SinkContext, SinkDescription}, }; use bytes::Bytes; use chrono::Utc; use futures::{stream::iter_ok, Future, Poll, Sink}; use lazy_static::lazy_static; use rusoto_core::{Region, RusotoError, RusotoFuture}; use rusoto_s3::{ HeadBucketRequest, PutObjectError, PutObjectOutput, PutObjectRequest, S3Client, S3, }; use serde::{Deserialize, Serialize}; use snafu::Snafu; use std::collections::HashMap; use std::convert::TryInto; use tower::{Service, ServiceBuilder}; use tracing::field; use tracing_futures::{Instrument, Instrumented}; use uuid::Uuid; #[derive(Clone)] pub struct S3Sink { client: S3Client, } #[derive(Deserialize, Serialize, Debug, Default)] #[serde(deny_unknown_fields)] pub struct S3SinkConfig { pub bucket: String, pub key_prefix: Option<String>, pub filename_time_format: Option<String>, pub filename_append_uuid: Option<bool>, pub filename_extension: Option<String>, #[serde(flatten)] options: S3Options, #[serde(flatten)] pub region: RegionOrEndpoint, pub encoding: Encoding, pub compression: Compression, #[serde(default)] pub batch: BatchBytesConfig, #[serde(default)] pub request: TowerRequestConfig, pub assume_role: Option<String>, } #[derive(Clone, Debug, Default, Deserialize, Serialize)] struct S3Options { acl: Option<S3CannedAcl>, grant_full_control: Option<String>, grant_read: Option<String>, grant_read_acp: Option<String>, grant_write_acp: Option<String>, server_side_encryption: Option<S3ServerSideEncryption>, ssekms_key_id: Option<String>, storage_class: Option<S3StorageClass>, tags: Option<HashMap<String, String>>, } #[derive(Clone, Copy, Debug, Derivative, Deserialize, Serialize)] #[derivative(Default)] #[serde(rename_all = "kebab-case")] enum S3CannedAcl { #[derivative(Default)] Private, PublicRead, PublicReadWrite, AwsExecRead, AuthenticatedRead, LogDeliveryWrite, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] enum S3ServerSideEncryption { #[serde(rename = "AES256")] AES256, #[serde(rename = "aws:kms")] AwsKms, } #[derive(Clone, Copy, Debug, Derivative, Deserialize, Serialize)] #[derivative(Default)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] enum S3StorageClass { #[derivative(Default)] Standard, ReducedRedundancy, IntelligentTiering, StandardIA, OnezoneIA, Glacier, DeepArchive, } lazy_static! { static ref REQUEST_DEFAULTS: TowerRequestConfig = TowerRequestConfig { in_flight_limit: Some(25), rate_limit_num: Some(25), ..Default::default() }; } #[derive(Deserialize, Serialize, Debug, Eq, PartialEq, Clone, Derivative)] #[serde(rename_all = "snake_case")] #[derivative(Default)] pub enum Encoding { #[derivative(Default)] Text, Ndjson, } #[derive(Deserialize, Serialize, Debug, Clone, Derivative)] #[serde(rename_all = "snake_case")] #[derivative(Default)] pub enum Compression { #[derivative(Default)] Gzip, None, } inventory::submit! { SinkDescription::new::<S3SinkConfig>("aws_s3") } #[typetag::serde(name = "aws_s3")] impl SinkConfig for S3SinkConfig { fn build(&self, cx: SinkContext) -> crate::Result<(super::RouterSink, super::Healthcheck)> { let healthcheck = S3Sink::healthcheck(self, cx.resolver())?; let sink = S3Sink::new(self, cx)?; Ok((sink, healthcheck)) } fn input_type(&self) -> DataType { DataType::Log } fn sink_type(&self) -> &'static str { "aws_s3" } } #[derive(Debug, Snafu)] enum HealthcheckError { #[snafu(display("Invalid credentials"))] InvalidCredentials, #[snafu(display("Unknown bucket: {:?}", bucket))] UnknownBucket { bucket: String }, #[snafu(display("Unknown status code: {}", status))] UnknownStatus { status: http::StatusCode }, } impl S3Sink { pub fn new(config: &S3SinkConfig, cx: SinkContext) -> crate::Result<super::RouterSink> { let request = config.request.unwrap_with(&REQUEST_DEFAULTS); let encoding = config.encoding.clone(); let compression = match config.compression { Compression::Gzip => true, Compression::None => false, }; let filename_time_format = config.filename_time_format.clone().unwrap_or("%s".into()); let filename_append_uuid = config.filename_append_uuid.unwrap_or(true); let batch = config.batch.unwrap_or(bytesize::mib(10u64), 300); let key_prefix = if let Some(kp) = &config.key_prefix { Template::from(kp.as_str()) } else { Template::from("date=%F/") }; let region = config.region.clone().try_into()?; let s3 = S3Sink { client: Self::create_client(region, config.assume_role.clone(), cx.resolver())?, }; let filename_extension = config.filename_extension.clone(); let bucket = config.bucket.clone(); let options = config.options.clone(); let svc = ServiceBuilder::new() .map(move |req| { build_request( req, filename_time_format.clone(), filename_extension.clone(), filename_append_uuid, compression, bucket.clone(), options.clone(), ) }) .settings(request, S3RetryLogic) .service(s3); let sink = crate::sinks::util::BatchServiceSink::new(svc, cx.acker()) .partitioned_batched_with_min(PartitionBuffer::new(Buffer::new(compression)), &batch) .with_flat_map(move |e| iter_ok(encode_event(e, &key_prefix, &encoding))); Ok(Box::new(sink)) } pub fn healthcheck( config: &S3SinkConfig, resolver: Resolver, ) -> crate::Result<super::Healthcheck> { let client = Self::create_client( config.region.clone().try_into()?, config.assume_role.clone(), resolver, )?; let request = HeadBucketRequest { bucket: config.bucket.clone(), }; let response = client.head_bucket(request); let bucket = config.bucket.clone(); let healthcheck = response.map_err(|err| match err { RusotoError::Unknown(response) => match response.status { http::status::StatusCode::FORBIDDEN => HealthcheckError::InvalidCredentials.into(), http::status::StatusCode::NOT_FOUND => { HealthcheckError::UnknownBucket { bucket }.into() } status => HealthcheckError::UnknownStatus { status }.into(), }, err => err.into(), }); Ok(Box::new(healthcheck)) } pub fn create_client( region: Region, _assume_role: Option<String>, resolver: Resolver, ) -> crate::Result<S3Client> { let client = rusoto::client(resolver)?; #[cfg(not(test))] let creds = rusoto::AwsCredentialsProvider::new(&region, _assume_role)?; // Hack around the fact that rusoto will not pick up runtime // env vars. This is designed to only for test purposes use // static credentials. #[cfg(test)] let creds = rusoto::AwsCredentialsProvider::new_minimal("test-access-key", "test-secret-key"); Ok(S3Client::new_with(client, creds, region)) } } impl Service<Request> for S3Sink { type Response = PutObjectOutput; type Error = RusotoError<PutObjectError>; type Future = Instrumented<RusotoFuture<PutObjectOutput, PutObjectError>>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Ok(().into()) } fn call(&mut self, request: Request) -> Self::Future { let options = request.options; let mut tagging = url::form_urlencoded::Serializer::new(String::new()); if let Some(tags) = options.tags { for (p, v) in tags { tagging.append_pair(&p, &v); } } let tagging = tagging.finish(); self.client .put_object(PutObjectRequest { body: Some(request.body.into()), bucket: request.bucket, key: request.key, content_encoding: request.content_encoding, acl: options.acl.map(to_string), grant_full_control: options.grant_full_control, grant_read: options.grant_read, grant_read_acp: options.grant_read_acp, grant_write_acp: options.grant_write_acp, server_side_encryption: options.server_side_encryption.map(to_string), ssekms_key_id: options.ssekms_key_id, storage_class: options.storage_class.map(to_string), tagging: Some(tagging), ..Default::default() }) .instrument(info_span!("request")) } } fn to_string(value: impl Serialize) -> String { serde_json::to_value(&value).unwrap().to_string() } fn build_request( req: PartitionInnerBuffer<Vec<u8>, Bytes>, time_format: String, extension: Option<String>, uuid: bool, gzip: bool, bucket: String, options: S3Options, ) -> Request { let (inner, key) = req.into_parts(); // TODO: pull the seconds from the last event let filename = { let seconds = Utc::now().format(&time_format); if uuid { let uuid = Uuid::new_v4(); format!("{}-{}", seconds, uuid.to_hyphenated()) } else { seconds.to_string() } }; let extension = extension.unwrap_or_else(|| if gzip { "log.gz".into() } else { "log".into() }); let key = String::from_utf8_lossy(&key[..]).into_owned(); let key = format!("{}{}.{}", key, filename, extension); debug!( message = "sending events.", bytes = &field::debug(inner.len()), bucket = &field::debug(&bucket), key = &field::debug(&key) ); Request { body: inner, bucket, key, content_encoding: if gzip { Some("gzip".to_string()) } else { None }, options, } } #[derive(Debug, Clone)] struct Request { body: Vec<u8>, bucket: String, key: String, content_encoding: Option<String>, options: S3Options, } #[derive(Debug, Clone)] struct S3RetryLogic; impl RetryLogic for S3RetryLogic { type Error = RusotoError<PutObjectError>; type Response = PutObjectOutput; fn is_retriable_error(&self, error: &Self::Error) -> bool { match error { RusotoError::HttpDispatch(_) => true, RusotoError::Unknown(res) if res.status.is_server_error() => true, _ => false, } } } fn encode_event( event: Event, key_prefix: &Template, encoding: &Encoding, ) -> Option<PartitionInnerBuffer<Vec<u8>, Bytes>> { let key = key_prefix .render_string(&event) .map_err(|missing_keys| { warn!( message = "Keys do not exist on the event. Dropping event.", ?missing_keys, rate_limit_secs = 30, ); }) .ok()?; let log = event.into_log(); let bytes = match encoding { Encoding::Ndjson => serde_json::to_vec(&log.unflatten()) .map(|mut b| { b.push(b'\n'); b }) .expect("Failed to encode event as json, this is a bug!"), &Encoding::Text => { let mut bytes = log .get(&event::log_schema().message_key()) .map(|v| v.as_bytes().to_vec()) .unwrap_or_default(); bytes.push(b'\n'); bytes } }; Some(PartitionInnerBuffer::new(bytes, key.into())) } #[cfg(test)] mod tests { use super::*; use crate::event::{self, Event}; use std::collections::HashMap; #[test] fn s3_encode_event_text() { let message = "hello world".to_string(); let batch_time_format = Template::from("date=%F"); let bytes = encode_event(message.clone().into(), &batch_time_format, &Encoding::Text).unwrap(); let encoded_message = message + "\n"; let (bytes, _) = bytes.into_parts(); assert_eq!(&bytes[..], encoded_message.as_bytes()); } #[test] fn s3_encode_event_ndjson() { let message = "hello world".to_string(); let mut event = Event::from(message.clone()); event.as_mut_log().insert("key", "value"); let batch_time_format = Template::from("date=%F"); let bytes = encode_event(event, &batch_time_format, &Encoding::Ndjson).unwrap(); let (bytes, _) = bytes.into_parts(); let map: HashMap<String, String> = serde_json::from_slice(&bytes[..]).unwrap(); assert_eq!(map[&event::log_schema().message_key().to_string()], message); assert_eq!(map["key"], "value".to_string()); } #[test] fn s3_build_request() { let buf = PartitionInnerBuffer::new(vec![0u8; 10], Bytes::from("key/")); let req = build_request( buf.clone(), "date".into(), Some("ext".into()), false, false, "bucket".into(), S3Options::default(), ); assert_eq!(req.key, "key/date.ext".to_string()); let req = build_request( buf.clone(), "date".into(), None, false, false, "bucket".into(), S3Options::default(), ); assert_eq!(req.key, "key/date.log".to_string()); let req = build_request( buf.clone(), "date".into(), None, false, true, "bucket".into(), S3Options::default(), ); assert_eq!(req.key, "key/date.log.gz".to_string()); let req = build_request( buf.clone(), "date".into(), None, true, true, "bucket".into(), S3Options::default(), ); assert_ne!(req.key, "key/date.log.gz".to_string()); } } #[cfg(feature = "s3-integration-tests")] #[cfg(test)] mod integration_tests { use super::*; use crate::{ assert_downcast_matches, dns::Resolver, event::Event, region::RegionOrEndpoint, runtime::Runtime, sinks::aws_s3::{S3Sink, S3SinkConfig}, test_util::{random_lines_with_stream, random_string, runtime}, topology::config::SinkContext, }; use flate2::read::GzDecoder; use futures::{Future, Sink}; use pretty_assertions::assert_eq; use rusoto_core::region::Region; use rusoto_s3::{S3Client, S3}; use std::io::{BufRead, BufReader}; const BUCKET: &str = "router-tests"; #[test] fn s3_insert_message_into() { let mut rt = runtime(); let cx = SinkContext::new_test(rt.executor()); let config = config(1000000); let prefix = config.key_prefix.clone(); let sink = S3Sink::new(&config, cx).unwrap(); let (lines, events) = random_lines_with_stream(100, 10); let pump = sink.send_all(events); let _ = rt.block_on(pump).unwrap(); let keys = get_keys(prefix.unwrap()); assert_eq!(keys.len(), 1); let key = keys[0].clone(); assert!(key.ends_with(".log")); let obj = get_object(key); assert_eq!(obj.content_encoding, None); let response_lines = get_lines(obj); assert_eq!(lines, response_lines); } #[test] fn s3_rotate_files_after_the_buffer_size_is_reached() { let mut rt = runtime(); let cx = SinkContext::new_test(rt.executor()); ensure_bucket(&client()); let config = S3SinkConfig { key_prefix: Some(format!("{}/{}", random_string(10), "{{i}}")), filename_time_format: Some("waitsforfullbatch".into()), filename_append_uuid: Some(false), ..config(1000) }; let prefix = config.key_prefix.clone(); let sink = S3Sink::new(&config, cx).unwrap(); let (lines, _events) = random_lines_with_stream(100, 30); let events = lines.clone().into_iter().enumerate().map(|(i, line)| { let mut e = Event::from(line); let i = if i < 10 { 1 } else if i < 20 { 2 } else { 3 }; e.as_mut_log().insert("i", format!("{}", i)); e }); let pump = sink.send_all(futures::stream::iter_ok(events)); let _ = rt.block_on(pump).unwrap(); let keys = get_keys(prefix.unwrap()); assert_eq!(keys.len(), 3); let response_lines = keys .into_iter() .map(|key| get_lines(get_object(key))) .collect::<Vec<_>>(); assert_eq!(&lines[00..10], response_lines[0].as_slice()); assert_eq!(&lines[10..20], response_lines[1].as_slice()); assert_eq!(&lines[20..30], response_lines[2].as_slice()); } #[test] fn s3_waits_for_full_batch_or_timeout_before_sending() { let rt = runtime(); let cx = SinkContext::new_test(rt.executor()); ensure_bucket(&client()); let config = S3SinkConfig { key_prefix: Some(format!("{}/{}", random_string(10), "{{i}}")), filename_time_format: Some("waitsforfullbatch".into()), filename_append_uuid: Some(false), ..config(1000) }; let prefix = config.key_prefix.clone(); let sink = S3Sink::new(&config, cx).unwrap(); let (lines, _) = random_lines_with_stream(100, 30); let (tx, rx) = futures::sync::mpsc::channel(1); let pump = sink.send_all(rx).map(|_| ()).map_err(|_| ()); let mut rt = Runtime::new().unwrap(); rt.spawn(pump); let mut tx = tx.wait(); for (i, line) in lines.iter().enumerate().take(15) { let mut event = Event::from(line.as_str()); let i = if i < 10 { 1 } else { 2 }; event.as_mut_log().insert("i", format!("{}", i)); tx.send(event).unwrap(); } std::thread::sleep(std::time::Duration::from_millis(100)); for (i, line) in lines.iter().skip(15).enumerate() { let mut event = Event::from(line.as_str()); let i = if i < 5 { 2 } else { 3 }; event.as_mut_log().insert("i", format!("{}", i)); tx.send(event).unwrap(); } drop(tx); crate::test_util::shutdown_on_idle(rt); let keys = get_keys(prefix.unwrap()); assert_eq!(keys.len(), 3); let response_lines = keys .into_iter() .map(|key| get_lines(get_object(key))) .collect::<Vec<_>>(); assert_eq!(&lines[00..10], response_lines[0].as_slice()); assert_eq!(&lines[10..20], response_lines[1].as_slice()); assert_eq!(&lines[20..30], response_lines[2].as_slice()); } #[test] fn s3_gzip() { let mut rt = runtime(); let cx = SinkContext::new_test(rt.executor()); ensure_bucket(&client()); let config = S3SinkConfig { compression: Compression::Gzip, filename_time_format: Some("%S%f".into()), ..config(1000) }; let prefix = config.key_prefix.clone(); let sink = S3Sink::new(&config, cx).unwrap(); let (lines, events) = random_lines_with_stream(100, 500); let pump = sink.send_all(events); let _ = rt.block_on(pump).unwrap(); let keys = get_keys(prefix.unwrap()); assert_eq!(keys.len(), 2); let response_lines = keys .into_iter() .map(|key| { assert!(key.ends_with(".log.gz")); let obj = get_object(key); assert_eq!(obj.content_encoding, Some("gzip".to_string())); get_gzipped_lines(obj) }) .flatten() .collect::<Vec<_>>(); assert_eq!(lines, response_lines); } #[test] fn s3_healthchecks() { let mut rt = Runtime::new().unwrap(); let resolver = Resolver::new(Vec::new(), rt.executor()).unwrap(); let healthcheck = S3Sink::healthcheck(&config(1), resolver).unwrap(); rt.block_on(healthcheck).unwrap(); } #[test] fn s3_healthchecks_invalid_bucket() { let mut rt = Runtime::new().unwrap(); let resolver = Resolver::new(Vec::new(), rt.executor()).unwrap(); let config = S3SinkConfig { bucket: "asdflkjadskdaadsfadf".to_string(), ..config(1) }; let healthcheck = S3Sink::healthcheck(&config, resolver).unwrap(); assert_downcast_matches!( rt.block_on(healthcheck).unwrap_err(), HealthcheckError, HealthcheckError::UnknownBucket{ .. } ); } fn client() -> S3Client { let region = Region::Custom { name: "minio".to_owned(), endpoint: "http://localhost:9000".to_owned(), }; use rusoto_core::HttpClient; use rusoto_credential::StaticProvider; let p = StaticProvider::new_minimal("test-access-key".into(), "test-secret-key".into()); let d = HttpClient::new().unwrap(); S3Client::new_with(d, p, region) } fn config(batch_size: usize) -> S3SinkConfig { ensure_bucket(&client()); S3SinkConfig { key_prefix: Some(random_string(10) + "/date=%F/"), bucket: BUCKET.to_string(), compression: Compression::None, batch: BatchBytesConfig { max_size: Some(batch_size), timeout_secs: Some(5), }, region: RegionOrEndpoint::with_endpoint("http://localhost:9000".to_owned()), ..Default::default() } } fn ensure_bucket(client: &S3Client) { use rusoto_s3::{CreateBucketError, CreateBucketRequest}; let req = CreateBucketRequest { bucket: BUCKET.to_string(), ..Default::default() }; let res = client.create_bucket(req); match res.sync() { Ok(_) | Err(RusotoError::Service(CreateBucketError::BucketAlreadyOwnedByYou(_))) => {} Err(e) => match e { RusotoError::Unknown(b) => { let body = String::from_utf8_lossy(&b.body[..]); panic!("Couldn't create bucket: {:?}; Body {}", b, body); } _ => panic!("Couldn't create bucket: {}", e), }, } } fn get_keys(prefix: String) -> Vec<String> { let prefix = prefix.split("/").into_iter().next().unwrap().to_string(); let list_res = client() .list_objects_v2(rusoto_s3::ListObjectsV2Request { bucket: BUCKET.to_string(), prefix: Some(prefix), ..Default::default() }) .sync() .unwrap(); list_res .contents .unwrap() .into_iter() .map(|obj| obj.key.unwrap()) .collect() } fn get_object(key: String) -> rusoto_s3::GetObjectOutput { client() .get_object(rusoto_s3::GetObjectRequest { bucket: BUCKET.to_string(), key, ..Default::default() }) .sync() .unwrap() } fn get_lines(obj: rusoto_s3::GetObjectOutput) -> Vec<String> { let buf_read = BufReader::new(obj.body.unwrap().into_blocking_read()); buf_read.lines().map(|l| l.unwrap()).collect() } fn get_gzipped_lines(obj: rusoto_s3::GetObjectOutput) -> Vec<String> { let buf_read = BufReader::new(GzDecoder::new(obj.body.unwrap().into_blocking_read())); buf_read.lines().map(|l| l.unwrap()).collect() } }
29.94878
99
0.565966
0358448254558e9c2a4a38243ac2750e51719f9e
2,683
//! Base optimization solver types and trait. use std::fmt; use simple_error::SimpleError; use std::collections::HashMap; use crate::problem::base::{Problem, ProblemSol}; /// Optimization solver status. #[derive(Debug, PartialEq)] pub enum SolverStatus { /// Optimization solver successfully solved problem /// to the specified accuracy. Solved, /// Optimization solver determined that problem /// is infeasible. Infeasible, /// Optimization solver has unknown status. Unknown, /// Optimization problem terminated with error. Error, } /// Optimization solver parameter. #[derive(Clone)] pub enum SolverParam { /// Integer solver parameter. IntParam(i32), /// Float solver parameter. FloatParam(f64), /// String solver parameter. StrParam(String), } /// A trait for optimization solvers. pub trait Solver { /// Gets optimization solver parameter value. fn get_param(&self, name: &str) -> Option<&SolverParam> { self.get_params().get(name) } /// Gets reference of optimization solver parameters. fn get_params(&self) -> &HashMap<String, SolverParam>; /// Gets mutable reference of optimization solver parameters. fn get_params_mut(&mut self) -> &mut HashMap<String, SolverParam>; /// Sets optimization solver parameter. fn set_param(&mut self, name: &str, value: SolverParam) -> Result<(), SimpleError> { let v = match self.get_params_mut().get_mut(name) { Some(x) => x, None => return Err(SimpleError::new("unknown parameter")) }; *v = match ((*v).clone(), value) { (SolverParam::IntParam(_x), SolverParam::IntParam(y)) => { SolverParam::IntParam(y) }, (SolverParam::FloatParam(_x), SolverParam::FloatParam(y)) => { SolverParam::FloatParam(y) }, (SolverParam::StrParam(_x), SolverParam::StrParam(y)) => { SolverParam::StrParam(y) }, _ => return Err(SimpleError::new("invalid parameter type")) }; Ok(()) } /// Solves optimization problem. fn solve(&self, problem: &mut Problem) -> Result<(SolverStatus, ProblemSol), SimpleError>; } impl Eq for SolverStatus {} impl fmt::Display for SolverStatus { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { SolverStatus::Error => write!(f, "error"), SolverStatus::Unknown => write!(f, "unknown"), SolverStatus::Solved => write!(f, "solved"), SolverStatus::Infeasible => write!(f, "infeasible") } } }
27.947917
94
0.607156
085f7f5a1ad6dcb6a9964aa74d43633e5fe74461
7,441
use std::net::SocketAddr; use std::process::exit; use std::time::Duration; use clap::{crate_description, crate_name, crate_version, App, Arg, ArgMatches}; use solana_drone::drone::DRONE_PORT; use solana_sdk::fee_calculator::FeeCalculator; use solana_sdk::signature::{read_keypair, Keypair, KeypairUtil}; /// Holds the configuration for a single run of the benchmark pub struct Config { pub entrypoint_addr: SocketAddr, pub drone_addr: SocketAddr, pub id: Keypair, pub threads: usize, pub num_nodes: usize, pub duration: Duration, pub tx_count: usize, pub thread_batch_sleep_ms: usize, pub sustained: bool, pub client_ids_and_stake_file: String, pub write_to_client_file: bool, pub read_from_client_file: bool, pub target_lamports_per_signature: u64, } impl Default for Config { fn default() -> Config { Config { entrypoint_addr: SocketAddr::from(([127, 0, 0, 1], 8001)), drone_addr: SocketAddr::from(([127, 0, 0, 1], DRONE_PORT)), id: Keypair::new(), threads: 4, num_nodes: 1, duration: Duration::new(std::u64::MAX, 0), tx_count: 500_000, thread_batch_sleep_ms: 0, sustained: false, client_ids_and_stake_file: String::new(), write_to_client_file: false, read_from_client_file: false, target_lamports_per_signature: FeeCalculator::default().target_lamports_per_signature, } } } /// Defines and builds the CLI args for a run of the benchmark pub fn build_args<'a, 'b>() -> App<'a, 'b> { App::new(crate_name!()).about(crate_description!()) .version(crate_version!()) .arg( Arg::with_name("entrypoint") .short("n") .long("entrypoint") .value_name("HOST:PORT") .takes_value(true) .help("Rendezvous with the cluster at this entry point; defaults to 127.0.0.1:8001"), ) .arg( Arg::with_name("drone") .short("d") .long("drone") .value_name("HOST:PORT") .takes_value(true) .help("Location of the drone; defaults to entrypoint:DRONE_PORT"), ) .arg( Arg::with_name("identity") .short("i") .long("identity") .value_name("PATH") .takes_value(true) .help("File containing a client identity (keypair)"), ) .arg( Arg::with_name("num-nodes") .short("N") .long("num-nodes") .value_name("NUM") .takes_value(true) .help("Wait for NUM nodes to converge"), ) .arg( Arg::with_name("threads") .short("t") .long("threads") .value_name("NUM") .takes_value(true) .help("Number of threads"), ) .arg( Arg::with_name("duration") .long("duration") .value_name("SECS") .takes_value(true) .help("Seconds to run benchmark, then exit; default is forever"), ) .arg( Arg::with_name("sustained") .long("sustained") .help("Use sustained performance mode vs. peak mode. This overlaps the tx generation with transfers."), ) .arg( Arg::with_name("tx_count") .long("tx_count") .value_name("NUM") .takes_value(true) .help("Number of transactions to send per batch") ) .arg( Arg::with_name("thread-batch-sleep-ms") .short("z") .long("thread-batch-sleep-ms") .value_name("NUM") .takes_value(true) .help("Per-thread-per-iteration sleep in ms"), ) .arg( Arg::with_name("write-client-keys") .long("write-client-keys") .value_name("FILENAME") .takes_value(true) .help("Generate client keys and stakes and write the list to YAML file"), ) .arg( Arg::with_name("read-client-keys") .long("read-client-keys") .value_name("FILENAME") .takes_value(true) .help("Read client keys and stakes from the YAML file"), ) .arg( Arg::with_name("target_lamports_per_signature") .long("target-lamports-per-signature") .value_name("LAMPORTS") .takes_value(true) .help( "The cost in lamports that the cluster will charge for signature \ verification when the cluster is operating at target-signatures-per-slot", ), ) } /// Parses a clap `ArgMatches` structure into a `Config` /// # Arguments /// * `matches` - command line arguments parsed by clap /// # Panics /// Panics if there is trouble parsing any of the arguments pub fn extract_args<'a>(matches: &ArgMatches<'a>) -> Config { let mut args = Config::default(); if let Some(addr) = matches.value_of("entrypoint") { args.entrypoint_addr = solana_netutil::parse_host_port(addr).unwrap_or_else(|e| { eprintln!("failed to parse entrypoint address: {}", e); exit(1) }); } if let Some(addr) = matches.value_of("drone") { args.drone_addr = solana_netutil::parse_host_port(addr).unwrap_or_else(|e| { eprintln!("failed to parse drone address: {}", e); exit(1) }); } if matches.is_present("identity") { args.id = read_keypair(matches.value_of("identity").unwrap()) .expect("can't read client identity"); } if let Some(t) = matches.value_of("threads") { args.threads = t.to_string().parse().expect("can't parse threads"); } if let Some(n) = matches.value_of("num-nodes") { args.num_nodes = n.to_string().parse().expect("can't parse num-nodes"); } if let Some(duration) = matches.value_of("duration") { args.duration = Duration::new( duration.to_string().parse().expect("can't parse duration"), 0, ); } if let Some(s) = matches.value_of("tx_count") { args.tx_count = s.to_string().parse().expect("can't parse tx_account"); } if let Some(t) = matches.value_of("thread-batch-sleep-ms") { args.thread_batch_sleep_ms = t .to_string() .parse() .expect("can't parse thread-batch-sleep-ms"); } args.sustained = matches.is_present("sustained"); if let Some(s) = matches.value_of("write-client-keys") { args.write_to_client_file = true; args.client_ids_and_stake_file = s.to_string(); } if let Some(s) = matches.value_of("read-client-keys") { assert!(!args.write_to_client_file); args.read_from_client_file = true; args.client_ids_and_stake_file = s.to_string(); } if let Some(v) = matches.value_of("target_lamports_per_signature") { args.target_lamports_per_signature = v.to_string().parse().expect("can't parse lamports"); } args }
34.449074
119
0.550329
9c069aa654c1c5231a940313c2ac98953edf74a9
19,127
#[doc = "Register `GPIO_38` reader"] pub struct R(crate::R<GPIO_38_SPEC>); impl core::ops::Deref for R { type Target = crate::R<GPIO_38_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<GPIO_38_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<GPIO_38_SPEC>) -> Self { R(reader) } } #[doc = "Register `GPIO_38` writer"] pub struct W(crate::W<GPIO_38_SPEC>); impl core::ops::Deref for W { type Target = crate::W<GPIO_38_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<GPIO_38_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<GPIO_38_SPEC>) -> Self { W(writer) } } #[doc = "Field `MCU_OE` reader - Output enable of the pad in sleep mode. 1: Output enabled. 0: Output disabled."] pub struct MCU_OE_R(crate::FieldReader<bool, bool>); impl MCU_OE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MCU_OE_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MCU_OE_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MCU_OE` writer - Output enable of the pad in sleep mode. 1: Output enabled. 0: Output disabled."] pub struct MCU_OE_W<'a> { w: &'a mut W, } impl<'a> MCU_OE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w } } #[doc = "Field `SLP_SEL` reader - Sleep mode selection of this pad. Set to 1 to put the pad in sleep mode."] pub struct SLP_SEL_R(crate::FieldReader<bool, bool>); impl SLP_SEL_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { SLP_SEL_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SLP_SEL_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SLP_SEL` writer - Sleep mode selection of this pad. Set to 1 to put the pad in sleep mode."] pub struct SLP_SEL_W<'a> { w: &'a mut W, } impl<'a> SLP_SEL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1); self.w } } #[doc = "Field `MCU_WPD` reader - Pull-down enable of the pad in sleep mode. 1: Internal pull-down enabled. 0: internal pull-down disabled."] pub struct MCU_WPD_R(crate::FieldReader<bool, bool>); impl MCU_WPD_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MCU_WPD_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MCU_WPD_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MCU_WPD` writer - Pull-down enable of the pad in sleep mode. 1: Internal pull-down enabled. 0: internal pull-down disabled."] pub struct MCU_WPD_W<'a> { w: &'a mut W, } impl<'a> MCU_WPD_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2); self.w } } #[doc = "Field `MCU_WPU` reader - Pull-up enable of the pad during sleep mode. 1: Internal pull-up enabled. 0: Internal pull-up disabled."] pub struct MCU_WPU_R(crate::FieldReader<bool, bool>); impl MCU_WPU_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MCU_WPU_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MCU_WPU_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MCU_WPU` writer - Pull-up enable of the pad during sleep mode. 1: Internal pull-up enabled. 0: Internal pull-up disabled."] pub struct MCU_WPU_W<'a> { w: &'a mut W, } impl<'a> MCU_WPU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3); self.w } } #[doc = "Field `MCU_IE` reader - Input enable of the pad during sleep mode. 1: Input enabled. 0: Input disabled."] pub struct MCU_IE_R(crate::FieldReader<bool, bool>); impl MCU_IE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MCU_IE_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MCU_IE_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MCU_IE` writer - Input enable of the pad during sleep mode. 1: Input enabled. 0: Input disabled."] pub struct MCU_IE_W<'a> { w: &'a mut W, } impl<'a> MCU_IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4); self.w } } #[doc = "Field `FUN_WPD` reader - Pull-down enable of the pad. 1: Internal pull-down enabled. 0: internal pull-down disabled."] pub struct FUN_WPD_R(crate::FieldReader<bool, bool>); impl FUN_WPD_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { FUN_WPD_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for FUN_WPD_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `FUN_WPD` writer - Pull-down enable of the pad. 1: Internal pull-down enabled. 0: internal pull-down disabled."] pub struct FUN_WPD_W<'a> { w: &'a mut W, } impl<'a> FUN_WPD_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7); self.w } } #[doc = "Field `FUN_WPU` reader - Pull-up enable of the pad. 1: Internal pull-up enabled. 0: Internal pull-up disabled."] pub struct FUN_WPU_R(crate::FieldReader<bool, bool>); impl FUN_WPU_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { FUN_WPU_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for FUN_WPU_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `FUN_WPU` writer - Pull-up enable of the pad. 1: Internal pull-up enabled. 0: Internal pull-up disabled."] pub struct FUN_WPU_W<'a> { w: &'a mut W, } impl<'a> FUN_WPU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u32 & 0x01) << 8); self.w } } #[doc = "Field `FUN_IE` reader - Input enable of the pad. 1: Input enabled. 0: Input disabled."] pub struct FUN_IE_R(crate::FieldReader<bool, bool>); impl FUN_IE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { FUN_IE_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for FUN_IE_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `FUN_IE` writer - Input enable of the pad. 1: Input enabled. 0: Input disabled."] pub struct FUN_IE_W<'a> { w: &'a mut W, } impl<'a> FUN_IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | ((value as u32 & 0x01) << 9); self.w } } #[doc = "Field `FUN_DRV` reader - Select the drive strength of the pad. 0: ~5 mA. 1: ~10 mA. 2: ~20 mA. 3: ~40 mA."] pub struct FUN_DRV_R(crate::FieldReader<u8, u8>); impl FUN_DRV_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { FUN_DRV_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for FUN_DRV_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `FUN_DRV` writer - Select the drive strength of the pad. 0: ~5 mA. 1: ~10 mA. 2: ~20 mA. 3: ~40 mA."] pub struct FUN_DRV_W<'a> { w: &'a mut W, } impl<'a> FUN_DRV_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 & !(0x03 << 10)) | ((value as u32 & 0x03) << 10); self.w } } #[doc = "Field `MCU_SEL` reader - Select IO MUX function for this signal. 0: Select Function 1. 1: Select Function 2, etc."] pub struct MCU_SEL_R(crate::FieldReader<u8, u8>); impl MCU_SEL_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { MCU_SEL_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MCU_SEL_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MCU_SEL` writer - Select IO MUX function for this signal. 0: Select Function 1. 1: Select Function 2, etc."] pub struct MCU_SEL_W<'a> { w: &'a mut W, } impl<'a> MCU_SEL_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 & !(0x07 << 12)) | ((value as u32 & 0x07) << 12); self.w } } #[doc = "Field `FILTER_EN` reader - Enable filter for pin input signals. 1: Filter enabled. 2: Filter disabled."] pub struct FILTER_EN_R(crate::FieldReader<bool, bool>); impl FILTER_EN_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { FILTER_EN_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for FILTER_EN_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `FILTER_EN` writer - Enable filter for pin input signals. 1: Filter enabled. 2: Filter disabled."] pub struct FILTER_EN_W<'a> { w: &'a mut W, } impl<'a> FILTER_EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | ((value as u32 & 0x01) << 15); self.w } } impl R { #[doc = "Bit 0 - Output enable of the pad in sleep mode. 1: Output enabled. 0: Output disabled."] #[inline(always)] pub fn mcu_oe(&self) -> MCU_OE_R { MCU_OE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Sleep mode selection of this pad. Set to 1 to put the pad in sleep mode."] #[inline(always)] pub fn slp_sel(&self) -> SLP_SEL_R { SLP_SEL_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Pull-down enable of the pad in sleep mode. 1: Internal pull-down enabled. 0: internal pull-down disabled."] #[inline(always)] pub fn mcu_wpd(&self) -> MCU_WPD_R { MCU_WPD_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Pull-up enable of the pad during sleep mode. 1: Internal pull-up enabled. 0: Internal pull-up disabled."] #[inline(always)] pub fn mcu_wpu(&self) -> MCU_WPU_R { MCU_WPU_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Input enable of the pad during sleep mode. 1: Input enabled. 0: Input disabled."] #[inline(always)] pub fn mcu_ie(&self) -> MCU_IE_R { MCU_IE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 7 - Pull-down enable of the pad. 1: Internal pull-down enabled. 0: internal pull-down disabled."] #[inline(always)] pub fn fun_wpd(&self) -> FUN_WPD_R { FUN_WPD_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - Pull-up enable of the pad. 1: Internal pull-up enabled. 0: Internal pull-up disabled."] #[inline(always)] pub fn fun_wpu(&self) -> FUN_WPU_R { FUN_WPU_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - Input enable of the pad. 1: Input enabled. 0: Input disabled."] #[inline(always)] pub fn fun_ie(&self) -> FUN_IE_R { FUN_IE_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bits 10:11 - Select the drive strength of the pad. 0: ~5 mA. 1: ~10 mA. 2: ~20 mA. 3: ~40 mA."] #[inline(always)] pub fn fun_drv(&self) -> FUN_DRV_R { FUN_DRV_R::new(((self.bits >> 10) & 0x03) as u8) } #[doc = "Bits 12:14 - Select IO MUX function for this signal. 0: Select Function 1. 1: Select Function 2, etc."] #[inline(always)] pub fn mcu_sel(&self) -> MCU_SEL_R { MCU_SEL_R::new(((self.bits >> 12) & 0x07) as u8) } #[doc = "Bit 15 - Enable filter for pin input signals. 1: Filter enabled. 2: Filter disabled."] #[inline(always)] pub fn filter_en(&self) -> FILTER_EN_R { FILTER_EN_R::new(((self.bits >> 15) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Output enable of the pad in sleep mode. 1: Output enabled. 0: Output disabled."] #[inline(always)] pub fn mcu_oe(&mut self) -> MCU_OE_W { MCU_OE_W { w: self } } #[doc = "Bit 1 - Sleep mode selection of this pad. Set to 1 to put the pad in sleep mode."] #[inline(always)] pub fn slp_sel(&mut self) -> SLP_SEL_W { SLP_SEL_W { w: self } } #[doc = "Bit 2 - Pull-down enable of the pad in sleep mode. 1: Internal pull-down enabled. 0: internal pull-down disabled."] #[inline(always)] pub fn mcu_wpd(&mut self) -> MCU_WPD_W { MCU_WPD_W { w: self } } #[doc = "Bit 3 - Pull-up enable of the pad during sleep mode. 1: Internal pull-up enabled. 0: Internal pull-up disabled."] #[inline(always)] pub fn mcu_wpu(&mut self) -> MCU_WPU_W { MCU_WPU_W { w: self } } #[doc = "Bit 4 - Input enable of the pad during sleep mode. 1: Input enabled. 0: Input disabled."] #[inline(always)] pub fn mcu_ie(&mut self) -> MCU_IE_W { MCU_IE_W { w: self } } #[doc = "Bit 7 - Pull-down enable of the pad. 1: Internal pull-down enabled. 0: internal pull-down disabled."] #[inline(always)] pub fn fun_wpd(&mut self) -> FUN_WPD_W { FUN_WPD_W { w: self } } #[doc = "Bit 8 - Pull-up enable of the pad. 1: Internal pull-up enabled. 0: Internal pull-up disabled."] #[inline(always)] pub fn fun_wpu(&mut self) -> FUN_WPU_W { FUN_WPU_W { w: self } } #[doc = "Bit 9 - Input enable of the pad. 1: Input enabled. 0: Input disabled."] #[inline(always)] pub fn fun_ie(&mut self) -> FUN_IE_W { FUN_IE_W { w: self } } #[doc = "Bits 10:11 - Select the drive strength of the pad. 0: ~5 mA. 1: ~10 mA. 2: ~20 mA. 3: ~40 mA."] #[inline(always)] pub fn fun_drv(&mut self) -> FUN_DRV_W { FUN_DRV_W { w: self } } #[doc = "Bits 12:14 - Select IO MUX function for this signal. 0: Select Function 1. 1: Select Function 2, etc."] #[inline(always)] pub fn mcu_sel(&mut self) -> MCU_SEL_W { MCU_SEL_W { w: self } } #[doc = "Bit 15 - Enable filter for pin input signals. 1: Filter enabled. 2: Filter disabled."] #[inline(always)] pub fn filter_en(&mut self) -> FILTER_EN_W { FILTER_EN_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 = "Configuration register for pad GPIO38\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 [gpio_38](index.html) module"] pub struct GPIO_38_SPEC; impl crate::RegisterSpec for GPIO_38_SPEC { type Ux = u32; } #[doc = "`read()` method returns [gpio_38::R](R) reader structure"] impl crate::Readable for GPIO_38_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [gpio_38::W](W) writer structure"] impl crate::Writable for GPIO_38_SPEC { type Writer = W; } #[doc = "`reset()` method sets GPIO_38 to value 0x0b00"] impl crate::Resettable for GPIO_38_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0x0b00 } }
33.913121
425
0.587337
d608318e79fdd4dd86a0dcf265b7f015d2940f21
1,733
use std::str; use slog::Logger; use crate::com::ComObject; use crate::ctsndcr::{FeatureInfo, ISoundCore}; use super::SoundCoreParameterIterator; /// Represents a feature of a device. #[derive(Debug)] pub struct SoundCoreFeature { core: ComObject<ISoundCore>, logger: Logger, context: u32, /// A numeric ID of the feature pub id: u32, /// A description of the feature pub description: String, /// A version number of the feature implementation pub version: String, } impl SoundCoreFeature { pub(crate) fn new( core: ComObject<ISoundCore>, logger: Logger, context: u32, info: &FeatureInfo, ) -> Self { let description_length = info .description .iter() .position(|i| *i == 0) .unwrap_or_else(|| info.description.len()); let version_length = info .version .iter() .position(|i| *i == 0) .unwrap_or_else(|| info.version.len()); Self { core, logger, context, id: info.feature_id, description: str::from_utf8(&info.description[0..description_length]) .unwrap() .to_owned(), version: str::from_utf8(&info.version[0..version_length]) .unwrap() .to_owned(), } } /// Gets an iterator over the parameters of this feature. pub fn parameters(&self) -> SoundCoreParameterIterator { SoundCoreParameterIterator::new( self.core.clone(), self.logger.clone(), self.context, self.id, self.description.clone(), ) } }
26.661538
81
0.548759
e2b0b35241db29bee94075a6f24586a61a126e92
1,617
fn i32_to_bcd(x: i32) -> i32 { let mut power_of_ten: i32 = 10; let mut digits: i32 = 2; while (x / power_of_ten) >= 1 { power_of_ten = power_of_ten * 10; digits = digits + 1; } // One power greater than needed, so decrease it power_of_ten = power_of_ten / 10; digits = digits - 2; let mut bcd_number: i32 = 0; let mut number: i32 = x; while digits >= 0 { let div_result: i32 = (number / power_of_ten) as i32; // Add n-th digit to bcd_number and shift it to n-th bcd nibble bcd_number = bcd_number + (div_result << digits*4); // Decrease number by the calculated power_of_ten (e.g. 312 - 300 = 12) number = number - div_result * power_of_ten; power_of_ten = power_of_ten / 10; digits = digits - 1; } bcd_number } fn i32_to_bcd_base10(x: i32) -> i32 { let tenths: i32; tenths = (x / 10) as i32; let ones: i32; ones = x - (tenths * 10); let shifted_tenths: i32; shifted_tenths = tenths << 4; shifted_tenths + ones } #[cfg(test)] mod tests { use super::i32_to_bcd_base10; use super::i32_to_bcd; #[test] fn i32_to_bcd_base10_test() { let x: i32; x = 12; let result = i32_to_bcd_base10(x); assert_eq!(result, 18); } #[test] fn i32_to_bcd_test() { let x: i32 = 132; let result = i32_to_bcd(x); assert_eq!(result, 306); } #[test] fn i32_to_bcd_test_single_digit() { let x: i32 = 3; let result = i32_to_bcd(x); assert_eq!(result, 3); } }
23.434783
79
0.567718
de560d50795b0cf3e178967b164150034792d78a
60,607
use super::coercion::CoerceMany; use super::compare_method::check_type_bounds; use super::compare_method::{compare_const_impl, compare_impl_method, compare_ty_impl}; use super::*; use rustc_attr as attr; use rustc_errors::{Applicability, ErrorReported}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{def::Res, ItemKind, Node, PathSegment}; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt}; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::layout::MAX_SIMD_LANES; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::util::{Discr, IntTypeExt}; use rustc_middle::ty::{self, OpaqueTypeKey, ParamEnv, RegionKind, Ty, TyCtxt}; use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS}; use rustc_span::symbol::sym; use rustc_span::{self, MultiSpan, Span}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits; use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _; use rustc_ty_utils::representability::{self, Representability}; use std::iter; use std::ops::ControlFlow; pub fn check_wf_new(tcx: TyCtxt<'_>) { let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx); tcx.hir().par_visit_all_item_likes(&visit); } pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) { match tcx.sess.target.is_abi_supported(abi) { Some(true) => (), Some(false) => struct_span_err!( tcx.sess, span, E0570, "`{}` is not a supported ABI for the current target", abi ) .emit(), None => { tcx.struct_span_lint_hir(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| { lint.build("use of calling convention not supported on this target").emit() }); } } // This ABI is only allowed on function pointers if abi == Abi::CCmseNonSecureCall { struct_span_err!( tcx.sess, span, E0781, "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers" ) .emit() } } /// Helper used for fns and closures. Does the grungy work of checking a function /// body and returns the function context used for that purpose, since in the case of a fn item /// there is still a bit more to do. /// /// * ... /// * inherited: other fields inherited from the enclosing fn (if any) #[instrument(skip(inherited, body), level = "debug")] pub(super) fn check_fn<'a, 'tcx>( inherited: &'a Inherited<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, fn_sig: ty::FnSig<'tcx>, decl: &'tcx hir::FnDecl<'tcx>, fn_id: hir::HirId, body: &'tcx hir::Body<'tcx>, can_be_generator: Option<hir::Movability>, return_type_pre_known: bool, ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) { let mut fn_sig = fn_sig; // Create the function context. This is either derived from scratch or, // in the case of closures, based on the outer context. let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id); fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id)); fcx.return_type_pre_known = return_type_pre_known; let tcx = fcx.tcx; let sess = tcx.sess; let hir = tcx.hir(); let declared_ret_ty = fn_sig.output(); let revealed_ret_ty = fcx.instantiate_opaque_types_from_value(declared_ret_ty, decl.output.span()); debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty); fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty))); fcx.ret_type_span = Some(decl.output.span()); if let ty::Opaque(..) = declared_ret_ty.kind() { fcx.ret_coercion_impl_trait = Some(declared_ret_ty); } fn_sig = tcx.mk_fn_sig( fn_sig.inputs().iter().cloned(), revealed_ret_ty, fn_sig.c_variadic, fn_sig.unsafety, fn_sig.abi, ); let span = body.value.span; fn_maybe_err(tcx, span, fn_sig.abi); if fn_sig.abi == Abi::RustCall { let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 }; let err = || { let item = match tcx.hir().get(fn_id) { Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header), Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(header, ..), .. }) => Some(header), Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(header, ..), .. }) => Some(header), // Closures are RustCall, but they tuple their arguments, so shouldn't be checked Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None, node => bug!("Item being checked wasn't a function/closure: {:?}", node), }; if let Some(header) = item { tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple") } }; if fn_sig.inputs().len() != expected_args { err() } else { // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on // This will probably require wide-scale changes to support a TupleKind obligation // We can't resolve this without knowing the type of the param if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) { err() } } } if body.generator_kind.is_some() && can_be_generator.is_some() { let yield_ty = fcx .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span }); fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType); // Resume type defaults to `()` if the generator has no argument. let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit()); fcx.resume_yield_tys = Some((resume_ty, yield_ty)); } GatherLocalsVisitor::new(&fcx).visit_body(body); // C-variadic fns also have a `VaList` input that's not listed in `fn_sig` // (as it's created inside the body itself, not passed in from outside). let maybe_va_list = if fn_sig.c_variadic { let span = body.params.last().unwrap().span; let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span)); let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span)); Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()])) } else { None }; // Add formal parameters. let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs); let inputs_fn = fn_sig.inputs().iter().copied(); for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() { // Check the pattern. let ty_span = try { inputs_hir?.get(idx)?.span }; fcx.check_pat_top(&param.pat, param_ty, ty_span, false); // Check that argument is Sized. // The check for a non-trivial pattern is a hack to avoid duplicate warnings // for simple cases like `fn foo(x: Trait)`, // where we would error once on the parameter as a whole, and once on the binding `x`. if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params { fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span)); } fcx.write_ty(param.hir_id, param_ty); } inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig); fcx.in_tail_expr = true; if let ty::Dynamic(..) = declared_ret_ty.kind() { // FIXME: We need to verify that the return type is `Sized` after the return expression has // been evaluated so that we have types available for all the nodes being returned, but that // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this // causes unsized errors caused by the `declared_ret_ty` to point at the return expression, // while keeping the current ordering we will ignore the tail expression's type because we // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr` // because we will trigger "unreachable expression" lints unconditionally. // Because of all of this, we perform a crude check to know whether the simplest `!Sized` // case that a newcomer might make, returning a bare trait, and in that case we populate // the tail expression's type so that the suggestion will be correct, but ignore all other // possible cases. fcx.check_expr(&body.value); fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); } else { fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); fcx.check_return_expr(&body.value, false); } fcx.in_tail_expr = false; // We insert the deferred_generator_interiors entry after visiting the body. // This ensures that all nested generators appear before the entry of this generator. // resolve_generator_interiors relies on this property. let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) { let interior = fcx .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span }); fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind)); let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap(); Some(GeneratorTypes { resume_ty, yield_ty, interior, movability: can_be_generator.unwrap(), }) } else { None }; // Finalize the return check by taking the LUB of the return types // we saw and assigning it to the expected return type. This isn't // really expected to fail, since the coercions would have failed // earlier when trying to find a LUB. let coercion = fcx.ret_coercion.take().unwrap().into_inner(); let mut actual_return_ty = coercion.complete(&fcx); debug!("actual_return_ty = {:?}", actual_return_ty); if let ty::Dynamic(..) = declared_ret_ty.kind() { // We have special-cased the case where the function is declared // `-> dyn Foo` and we don't actually relate it to the // `fcx.ret_coercion`, so just substitute a type variable. actual_return_ty = fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span }); debug!("actual_return_ty replaced with {:?}", actual_return_ty); } fcx.demand_suptype(span, revealed_ret_ty, actual_return_ty); // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !` if let Some(panic_impl_did) = tcx.lang_items().panic_impl() { if panic_impl_did == hir.local_def_id(fn_id).to_def_id() { if let Some(panic_info_did) = tcx.lang_items().panic_info() { if *declared_ret_ty.kind() != ty::Never { sess.span_err(decl.output.span(), "return type should be `!`"); } let inputs = fn_sig.inputs(); let span = hir.span(fn_id); if inputs.len() == 1 { let arg_is_panic_info = match *inputs[0].kind() { ty::Ref(region, ty, mutbl) => match *ty.kind() { ty::Adt(ref adt, _) => { adt.did == panic_info_did && mutbl == hir::Mutability::Not && *region != RegionKind::ReStatic } _ => false, }, _ => false, }; if !arg_is_panic_info { sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`"); } if let Node::Item(item) = hir.get(fn_id) { if let ItemKind::Fn(_, ref generics, _) = item.kind { if !generics.params.is_empty() { sess.span_err(span, "should have no type parameters"); } } } } else { let span = sess.source_map().guess_head_span(span); sess.span_err(span, "function should have one argument"); } } else { sess.err("language item required, but not found: `panic_info`"); } } } // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !` if let Some(alloc_error_handler_did) = tcx.lang_items().oom() { if alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id() { if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() { if *declared_ret_ty.kind() != ty::Never { sess.span_err(decl.output.span(), "return type should be `!`"); } let inputs = fn_sig.inputs(); let span = hir.span(fn_id); if inputs.len() == 1 { let arg_is_alloc_layout = match inputs[0].kind() { ty::Adt(ref adt, _) => adt.did == alloc_layout_did, _ => false, }; if !arg_is_alloc_layout { sess.span_err(decl.inputs[0].span, "argument should be `Layout`"); } if let Node::Item(item) = hir.get(fn_id) { if let ItemKind::Fn(_, ref generics, _) = item.kind { if !generics.params.is_empty() { sess.span_err( span, "`#[alloc_error_handler]` function should have no type \ parameters", ); } } } } else { let span = sess.source_map().guess_head_span(span); sess.span_err(span, "function should have one argument"); } } else { sess.err("language item required, but not found: `alloc_layout`"); } } } (fcx, gen_ty) } fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) { let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated check_representable(tcx, span, def_id); if def.repr.simd() { check_simd(tcx, span, def_id); } check_transparent(tcx, span, def); check_packed(tcx, span, def); } fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) { let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated check_representable(tcx, span, def_id); check_transparent(tcx, span, def); check_union_fields(tcx, span, def_id); check_packed(tcx, span, def); } /// Check that the fields of the `union` do not need dropping. fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool { let item_type = tcx.type_of(item_def_id); if let ty::Adt(def, substs) = item_type.kind() { assert!(def.is_union()); let fields = &def.non_enum_variant().fields; let param_env = tcx.param_env(item_def_id); for field in fields { let field_ty = field.ty(tcx, substs); if field_ty.needs_drop(tcx, param_env) { let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) { // We are currently checking the type this field came from, so it must be local. Some(Node::Field(field)) => (field.span, field.ty.span), _ => unreachable!("mir field has to correspond to hir field"), }; struct_span_err!( tcx.sess, field_span, E0740, "unions may not contain fields that need dropping" ) .multipart_suggestion_verbose( "wrap the type with `std::mem::ManuallyDrop` and ensure it is manually dropped", vec![ (ty_span.shrink_to_lo(), format!("std::mem::ManuallyDrop<")), (ty_span.shrink_to_hi(), ">".into()), ], Applicability::MaybeIncorrect, ) .emit(); return false; } } } else { span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind()); } true } /// Check that a `static` is inhabited. fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) { // Make sure statics are inhabited. // Other parts of the compiler assume that there are no uninhabited places. In principle it // would be enough to check this for `extern` statics, as statics with an initializer will // have UB during initialization if they are uninhabited, but there also seems to be no good // reason to allow any statics to be uninhabited. let ty = tcx.type_of(def_id); let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) { Ok(l) => l, Err(_) => { // Generic statics are rejected, but we still reach this case. tcx.sess.delay_span_bug(span, "generic static must be rejected"); return; } }; if layout.abi.is_uninhabited() { tcx.struct_span_lint_hir( UNINHABITED_STATIC, tcx.hir().local_def_id_to_hir_id(def_id), span, |lint| { lint.build("static of uninhabited type") .note("uninhabited statics cannot be initialized, and any access would be an immediate error") .emit(); }, ); } } /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo` /// projections that would result in "inheriting lifetimes". pub(super) fn check_opaque<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, substs: SubstsRef<'tcx>, span: Span, origin: &hir::OpaqueTyOrigin, ) { check_opaque_for_inheriting_lifetimes(tcx, def_id, span); if tcx.type_of(def_id).references_error() { return; } if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() { return; } check_opaque_meets_bounds(tcx, def_id, substs, span, origin); } /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result /// in "inheriting lifetimes". #[instrument(level = "debug", skip(tcx, span))] pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span, ) { let item = tcx.hir().expect_item(def_id); debug!(?item, ?span); struct FoundParentLifetime; struct FindParentLifetimeVisitor<'tcx>(TyCtxt<'tcx>, &'tcx ty::Generics); impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> { type BreakTy = FoundParentLifetime; fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> { Some(self.0) } fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> { debug!("FindParentLifetimeVisitor: r={:?}", r); if let RegionKind::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = r { if *index < self.1.parent_count as u32 { return ControlFlow::Break(FoundParentLifetime); } else { return ControlFlow::CONTINUE; } } r.super_visit_with(self) } fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> { if let ty::ConstKind::Unevaluated(..) = c.val { // FIXME(#72219) We currently don't detect lifetimes within substs // which would violate this check. Even though the particular substitution is not used // within the const, this should still be fixed. return ControlFlow::CONTINUE; } c.super_visit_with(self) } } struct ProhibitOpaqueVisitor<'tcx> { tcx: TyCtxt<'tcx>, opaque_identity_ty: Ty<'tcx>, generics: &'tcx ty::Generics, selftys: Vec<(Span, Option<String>)>, } impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> { type BreakTy = Ty<'tcx>; fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> { Some(self.tcx) } fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t); if t == self.opaque_identity_ty { ControlFlow::CONTINUE } else { t.super_visit_with(&mut FindParentLifetimeVisitor(self.tcx, self.generics)) .map_break(|FoundParentLifetime| t) } } } impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> { type Map = rustc_middle::hir::map::Map<'tcx>; fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> { hir::intravisit::NestedVisitorMap::OnlyBodies(self.tcx.hir()) } fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) { match arg.kind { hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments { [PathSegment { res: Some(Res::SelfTy(_, impl_ref)), .. }] => { let impl_ty_name = impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id)); self.selftys.push((path.span, impl_ty_name)); } _ => {} }, _ => {} } hir::intravisit::walk_ty(self, arg); } } if let ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..), .. }) = item.kind { let mut visitor = ProhibitOpaqueVisitor { opaque_identity_ty: tcx.mk_opaque( def_id.to_def_id(), InternalSubsts::identity_for_item(tcx, def_id.to_def_id()), ), generics: tcx.generics_of(def_id), tcx, selftys: vec![], }; let prohibit_opaque = tcx .explicit_item_bounds(def_id) .iter() .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor)); debug!( "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}", prohibit_opaque, visitor.opaque_identity_ty, visitor.generics ); if let Some(ty) = prohibit_opaque.break_value() { visitor.visit_item(&item); let is_async = match item.kind { ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => { matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..)) } _ => unreachable!(), }; let mut err = struct_span_err!( tcx.sess, span, E0760, "`{}` return type cannot contain a projection or `Self` that references lifetimes from \ a parent scope", if is_async { "async fn" } else { "impl Trait" }, ); for (span, name) in visitor.selftys { err.span_suggestion( span, "consider spelling out the type instead", name.unwrap_or_else(|| format!("{:?}", ty)), Applicability::MaybeIncorrect, ); } err.emit(); } } } /// Checks that an opaque type does not contain cycles. pub(super) fn check_opaque_for_cycles<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, substs: SubstsRef<'tcx>, span: Span, origin: &hir::OpaqueTyOrigin, ) -> Result<(), ErrorReported> { if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() { match origin { hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span), _ => opaque_type_cycle_error(tcx, def_id, span), } Err(ErrorReported) } else { Ok(()) } } /// Check that the concrete type behind `impl Trait` actually implements `Trait`. /// /// This is mostly checked at the places that specify the opaque type, but we /// check those cases in the `param_env` of that function, which may have /// bounds not on this opaque type: /// /// type X<T> = impl Clone /// fn f<T: Clone>(t: T) -> X<T> { /// t /// } /// /// Without this check the above code is incorrectly accepted: we would ICE if /// some tried, for example, to clone an `Option<X<&mut ()>>`. #[instrument(level = "debug", skip(tcx))] fn check_opaque_meets_bounds<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, substs: SubstsRef<'tcx>, span: Span, origin: &hir::OpaqueTyOrigin, ) { let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); let defining_use_anchor = match *origin { hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did, hir::OpaqueTyOrigin::TyAlias => def_id, }; let param_env = tcx.param_env(defining_use_anchor); tcx.infer_ctxt().with_opaque_type_inference(defining_use_anchor).enter(move |infcx| { let inh = Inherited::new(infcx, def_id); let infcx = &inh.infcx; let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs); let misc_cause = traits::ObligationCause::misc(span, hir_id); let _ = inh.register_infer_ok_obligations( infcx.instantiate_opaque_types(hir_id, param_env, opaque_ty, span), ); let opaque_type_map = infcx.inner.borrow().opaque_types.clone(); for (OpaqueTypeKey { def_id, substs }, opaque_defn) in opaque_type_map { let hidden_type = tcx.type_of(def_id).subst(tcx, substs); trace!(?hidden_type); match infcx.at(&misc_cause, param_env).eq(opaque_defn.concrete_ty, hidden_type) { Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok), Err(ty_err) => tcx.sess.delay_span_bug( span, &format!( "could not check bounds on revealed type `{}`:\n{}", hidden_type, ty_err, ), ), } } // Check that all obligations are satisfied by the implementation's // version. let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx); if !errors.is_empty() { infcx.report_fulfillment_errors(&errors, None, false); } match origin { // Checked when type checking the function containing them. hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => return, // Can have different predicates to their defining use hir::OpaqueTyOrigin::TyAlias => { // Finally, resolve all regions. This catches wily misuses of // lifetime parameters. let fcx = FnCtxt::new(&inh, param_env, hir_id); fcx.regionck_item(hir_id, span, FxHashSet::default()); } } }); } pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { debug!( "check_item_type(it.def_id={:?}, it.name={})", it.def_id, tcx.def_path_str(it.def_id.to_def_id()) ); let _indenter = indenter(); match it.kind { // Consts can play a role in type-checking, so they are included here. hir::ItemKind::Static(..) => { tcx.ensure().typeck(it.def_id); maybe_check_static_with_link_section(tcx, it.def_id, it.span); check_static_inhabited(tcx, it.def_id, it.span); } hir::ItemKind::Const(..) => { tcx.ensure().typeck(it.def_id); } hir::ItemKind::Enum(ref enum_definition, _) => { check_enum(tcx, it.span, &enum_definition.variants, it.def_id); } hir::ItemKind::Fn(..) => {} // entirely within check_item_body hir::ItemKind::Impl(ref impl_) => { debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id); if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) { check_impl_items_against_trait( tcx, it.span, it.def_id, impl_trait_ref, &impl_.items, ); let trait_def_id = impl_trait_ref.def_id; check_on_unimplemented(tcx, trait_def_id, it); } } hir::ItemKind::Trait(_, _, _, _, ref items) => { check_on_unimplemented(tcx, it.def_id.to_def_id(), it); for item in items.iter() { let item = tcx.hir().trait_item(item.id); match item.kind { hir::TraitItemKind::Fn(ref sig, _) => { let abi = sig.header.abi; fn_maybe_err(tcx, item.ident.span, abi); } hir::TraitItemKind::Type(.., Some(default)) => { let assoc_item = tcx.associated_item(item.def_id); let trait_substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id()); let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds( tcx, assoc_item, assoc_item, default.span, ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs }, ); } _ => {} } } } hir::ItemKind::Struct(..) => { check_struct(tcx, it.def_id, it.span); } hir::ItemKind::Union(..) => { check_union(tcx, it.def_id, it.span); } hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => { // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting // `async-std` (and `pub async fn` in general). // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it! // See https://github.com/rust-lang/rust/issues/75100 if !tcx.sess.opts.actually_rustdoc { let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id()); check_opaque(tcx, it.def_id, substs, it.span, &origin); } } hir::ItemKind::TyAlias(..) => { let pty_ty = tcx.type_of(it.def_id); let generics = tcx.generics_of(it.def_id); check_type_params_are_used(tcx, &generics, pty_ty); } hir::ItemKind::ForeignMod { abi, items } => { check_abi(tcx, it.hir_id(), it.span, abi); if abi == Abi::RustIntrinsic { for item in items { let item = tcx.hir().foreign_item(item.id); intrinsic::check_intrinsic_type(tcx, item); } } else if abi == Abi::PlatformIntrinsic { for item in items { let item = tcx.hir().foreign_item(item.id); intrinsic::check_platform_intrinsic_type(tcx, item); } } else { for item in items { let def_id = item.id.def_id; let generics = tcx.generics_of(def_id); let own_counts = generics.own_counts(); if generics.params.len() - own_counts.lifetimes != 0 { let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) { (_, 0) => ("type", "types", Some("u32")), // We don't specify an example value, because we can't generate // a valid value for any type. (0, _) => ("const", "consts", None), _ => ("type or const", "types or consts", None), }; struct_span_err!( tcx.sess, item.span, E0044, "foreign items may not have {} parameters", kinds, ) .span_label(item.span, &format!("can't have {} parameters", kinds)) .help( // FIXME: once we start storing spans for type arguments, turn this // into a suggestion. &format!( "replace the {} parameters with concrete {}{}", kinds, kinds_pl, egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(), ), ) .emit(); } let item = tcx.hir().foreign_item(item.id); match item.kind { hir::ForeignItemKind::Fn(ref fn_decl, _, _) => { require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span); } hir::ForeignItemKind::Static(..) => { check_static_inhabited(tcx, def_id, item.span); } _ => {} } } } } _ => { /* nothing to do */ } } } pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) { // an error would be reported if this fails. let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item.def_id.to_def_id()); } pub(super) fn check_specialization_validity<'tcx>( tcx: TyCtxt<'tcx>, trait_def: &ty::TraitDef, trait_item: &ty::AssocItem, impl_id: DefId, impl_item: &hir::ImplItemRef, ) { let ancestors = match trait_def.ancestors(tcx, impl_id) { Ok(ancestors) => ancestors, Err(_) => return, }; let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| { if parent.is_from_trait() { None } else { Some((parent, parent.item(tcx, trait_item.def_id))) } }); let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| { match parent_item { // Parent impl exists, and contains the parent item we're trying to specialize, but // doesn't mark it `default`. Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => { Some(Err(parent_impl.def_id())) } // Parent impl contains item and makes it specializable. Some(_) => Some(Ok(())), // Parent impl doesn't mention the item. This means it's inherited from the // grandparent. In that case, if parent is a `default impl`, inherited items use the // "defaultness" from the grandparent, else they are final. None => { if tcx.impl_defaultness(parent_impl.def_id()).is_default() { None } else { Some(Err(parent_impl.def_id())) } } } }); // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the // item. This is allowed, the item isn't actually getting specialized here. let result = opt_result.unwrap_or(Ok(())); if let Err(parent_impl) = result { report_forbidden_specialization(tcx, impl_item, parent_impl); } } fn check_impl_items_against_trait<'tcx>( tcx: TyCtxt<'tcx>, full_impl_span: Span, impl_id: LocalDefId, impl_trait_ref: ty::TraitRef<'tcx>, impl_item_refs: &[hir::ImplItemRef], ) { // If the trait reference itself is erroneous (so the compilation is going // to fail), skip checking the items here -- the `impl_item` table in `tcx` // isn't populated for such impls. if impl_trait_ref.references_error() { return; } // Negative impls are not expected to have any items match tcx.impl_polarity(impl_id) { ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {} ty::ImplPolarity::Negative => { if let [first_item_ref, ..] = impl_item_refs { let first_item_span = tcx.hir().impl_item(first_item_ref.id).span; struct_span_err!( tcx.sess, first_item_span, E0749, "negative impls cannot have any items" ) .emit(); } return; } } let trait_def = tcx.trait_def(impl_trait_ref.def_id); for impl_item in impl_item_refs { let ty_impl_item = tcx.associated_item(impl_item.id.def_id); let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id { tcx.associated_item(trait_item_id) } else { // Checked in `associated_item`. tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait"); continue; }; let impl_item_full = tcx.hir().impl_item(impl_item.id); match impl_item_full.kind { hir::ImplItemKind::Const(..) => { // Find associated const definition. compare_const_impl( tcx, &ty_impl_item, impl_item.span, &ty_trait_item, impl_trait_ref, ); } hir::ImplItemKind::Fn(..) => { let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id); compare_impl_method( tcx, &ty_impl_item, impl_item.span, &ty_trait_item, impl_trait_ref, opt_trait_span, ); } hir::ImplItemKind::TyAlias(impl_ty) => { let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id); compare_ty_impl( tcx, &ty_impl_item, impl_ty.span, &ty_trait_item, impl_trait_ref, opt_trait_span, ); } } check_specialization_validity( tcx, trait_def, &ty_trait_item, impl_id.to_def_id(), impl_item, ); } if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) { // Check for missing items from trait let mut missing_items = Vec::new(); for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) { let is_implemented = ancestors .leaf_def(tcx, trait_item_id) .map_or(false, |node_item| node_item.item.defaultness.has_value()); if !is_implemented && tcx.impl_defaultness(impl_id).is_final() { missing_items.push(tcx.associated_item(trait_item_id)); } } if !missing_items.is_empty() { let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span); missing_items_err(tcx, impl_span, &missing_items, full_impl_span); } } } /// Checks whether a type can be represented in memory. In particular, it /// identifies types that contain themselves without indirection through a /// pointer, which would mean their size is unbounded. pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool { let rty = tcx.type_of(item_def_id); // Check that it is possible to represent this type. This call identifies // (1) types that contain themselves and (2) types that contain a different // recursive type. It is only necessary to throw an error on those that // contain themselves. For case 2, there must be an inner type that will be // caught by case 1. match representability::ty_is_representable(tcx, rty, sp) { Representability::SelfRecursive(spans) => { recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans); return false; } Representability::Representable | Representability::ContainsRecursive => (), } true } pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { let t = tcx.type_of(def_id); if let ty::Adt(def, substs) = t.kind() { if def.is_struct() { let fields = &def.non_enum_variant().fields; if fields.is_empty() { struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit(); return; } let e = fields[0].ty(tcx, substs); if !fields.iter().all(|f| f.ty(tcx, substs) == e) { struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous") .span_label(sp, "SIMD elements must have the same type") .emit(); return; } let len = if let ty::Array(_ty, c) = e.kind() { c.try_eval_usize(tcx, tcx.param_env(def.did)) } else { Some(fields.len() as u64) }; if let Some(len) = len { if len == 0 { struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit(); return; } else if len > MAX_SIMD_LANES { struct_span_err!( tcx.sess, sp, E0075, "SIMD vector cannot have more than {} elements", MAX_SIMD_LANES, ) .emit(); return; } } // Check that we use types valid for use in the lanes of a SIMD "vector register" // These are scalar types which directly match a "machine" type // Yes: Integers, floats, "thin" pointers // No: char, "fat" pointers, compound types match e.kind() { ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors ty::Array(t, _clen) if matches!( t.kind(), ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) ) => { /* struct([f32; 4]) is ok */ } _ => { struct_span_err!( tcx.sess, sp, E0077, "SIMD vector element type should be a \ primitive scalar (integer/float/pointer) type" ) .emit(); return; } } } } } pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) { let repr = def.repr; if repr.packed() { for attr in tcx.get_attrs(def.did).iter() { for r in attr::find_repr_attrs(&tcx.sess, attr) { if let attr::ReprPacked(pack) = r { if let Some(repr_pack) = repr.pack { if pack as u64 != repr_pack.bytes() { struct_span_err!( tcx.sess, sp, E0634, "type has conflicting packed representation hints" ) .emit(); } } } } } if repr.align.is_some() { struct_span_err!( tcx.sess, sp, E0587, "type has conflicting packed and align representation hints" ) .emit(); } else { if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) { let mut err = struct_span_err!( tcx.sess, sp, E0588, "packed type cannot transitively contain a `#[repr(align)]` type" ); err.span_note( tcx.def_span(def_spans[0].0), &format!( "`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0) ), ); if def_spans.len() > 2 { let mut first = true; for (adt_def, span) in def_spans.iter().skip(1).rev() { let ident = tcx.item_name(*adt_def); err.span_note( *span, &if first { format!( "`{}` contains a field of type `{}`", tcx.type_of(def.did), ident ) } else { format!("...which contains a field of type `{}`", ident) }, ); first = false; } } err.emit(); } } } } pub(super) fn check_packed_inner( tcx: TyCtxt<'_>, def_id: DefId, stack: &mut Vec<DefId>, ) -> Option<Vec<(DefId, Span)>> { if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() { if def.is_struct() || def.is_union() { if def.repr.align.is_some() { return Some(vec![(def.did, DUMMY_SP)]); } stack.push(def_id); for field in &def.non_enum_variant().fields { if let ty::Adt(def, _) = field.ty(tcx, substs).kind() { if !stack.contains(&def.did) { if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) { defs.push((def.did, field.ident(tcx).span)); return Some(defs); } } } } stack.pop(); } } None } pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) { if !adt.repr.transparent() { return; } let sp = tcx.sess.source_map().guess_head_span(sp); if adt.is_union() && !tcx.features().transparent_unions { feature_err( &tcx.sess.parse_sess, sym::transparent_unions, sp, "transparent unions are unstable", ) .emit(); } if adt.variants.len() != 1 { bad_variant_count(tcx, adt, sp, adt.did); if adt.variants.is_empty() { // Don't bother checking the fields. No variants (and thus no fields) exist. return; } } // For each field, figure out if it's known to be a ZST and align(1) let field_infos = adt.all_fields().map(|field| { let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did)); let param_env = tcx.param_env(field.did); let layout = tcx.layout_of(param_env.and(ty)); // We are currently checking the type this field came from, so it must be local let span = tcx.hir().span_if_local(field.did).unwrap(); let zst = layout.map_or(false, |layout| layout.is_zst()); let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1); (span, zst, align1) }); let non_zst_fields = field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None }); let non_zst_count = non_zst_fields.clone().count(); if non_zst_count >= 2 { bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp); } for (span, zst, align1) in field_infos { if zst && !align1 { struct_span_err!( tcx.sess, span, E0691, "zero-sized field in transparent {} has alignment larger than 1", adt.descr(), ) .span_label(span, "has alignment larger than 1") .emit(); } } } #[allow(trivial_numeric_casts)] fn check_enum<'tcx>( tcx: TyCtxt<'tcx>, sp: Span, vs: &'tcx [hir::Variant<'tcx>], def_id: LocalDefId, ) { let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated if vs.is_empty() { let attributes = tcx.get_attrs(def_id.to_def_id()); if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) { struct_span_err!( tcx.sess, attr.span, E0084, "unsupported representation for zero-variant enum" ) .span_label(sp, "zero-variant enum") .emit(); } } let repr_type_ty = def.repr.discr_type().to_ty(tcx); if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 { if !tcx.features().repr128 { feature_err( &tcx.sess.parse_sess, sym::repr128, sp, "repr with 128-bit type is unstable", ) .emit(); } } for v in vs { if let Some(ref e) = v.disr_expr { tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id)); } } if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant { let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..)); let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some(); let has_non_units = vs.iter().any(|var| !is_unit(var)); let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var)); let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var)); if disr_non_unit || (disr_units && has_non_units) { let mut err = struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified"); err.emit(); } } let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len()); for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) { // Check for duplicate discriminant values if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) { let variant_did = def.variants[VariantIdx::new(i)].def_id; let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local()); let variant_i = tcx.hir().expect_variant(variant_i_hir_id); let i_span = match variant_i.disr_expr { Some(ref expr) => tcx.hir().span(expr.hir_id), None => tcx.hir().span(variant_i_hir_id), }; let span = match v.disr_expr { Some(ref expr) => tcx.hir().span(expr.hir_id), None => v.span, }; let display_discr = display_discriminant_value(tcx, v, discr.val); let display_discr_i = display_discriminant_value(tcx, variant_i, disr_vals[i].val); struct_span_err!( tcx.sess, span, E0081, "discriminant value `{}` already exists", discr.val, ) .span_label(i_span, format!("first use of {}", display_discr_i)) .span_label(span, format!("enum already has {}", display_discr)) .emit(); } disr_vals.push(discr); } check_representable(tcx, sp, def_id); check_transparent(tcx, sp, def); } /// Format an enum discriminant value for use in a diagnostic message. fn display_discriminant_value<'tcx>( tcx: TyCtxt<'tcx>, variant: &hir::Variant<'_>, evaluated: u128, ) -> String { if let Some(expr) = &variant.disr_expr { let body = &tcx.hir().body(expr.body).value; if let hir::ExprKind::Lit(lit) = &body.kind { if let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node { if evaluated != *lit_value { return format!("`{}` (overflowed from `{}`)", evaluated, lit_value); } } } } format!("`{}`", evaluated) } pub(super) fn check_type_params_are_used<'tcx>( tcx: TyCtxt<'tcx>, generics: &ty::Generics, ty: Ty<'tcx>, ) { debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty); assert_eq!(generics.parent, None); if generics.own_counts().types == 0 { return; } let mut params_used = BitSet::new_empty(generics.params.len()); if ty.references_error() { // If there is already another error, do not emit // an error for not using a type parameter. assert!(tcx.sess.has_errors()); return; } for leaf in ty.walk(tcx) { if let GenericArgKind::Type(leaf_ty) = leaf.unpack() { if let ty::Param(param) = leaf_ty.kind() { debug!("found use of ty param {:?}", param); params_used.insert(param.index); } } } for param in &generics.params { if !params_used.contains(param.index) { if let ty::GenericParamDefKind::Type { .. } = param.kind { let span = tcx.def_span(param.def_id); struct_span_err!( tcx.sess, span, E0091, "type parameter `{}` is unused", param.name, ) .span_label(span, "unused type parameter") .emit(); } } } } pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx }); } pub(super) use wfcheck::check_item_well_formed; pub(super) use wfcheck::check_trait_item as check_trait_item_well_formed; pub(super) use wfcheck::check_impl_item as check_impl_item_well_formed; fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) { struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing") .span_label(span, "recursive `async fn`") .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`") .note( "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion", ) .emit(); } /// Emit an error for recursive opaque types. /// /// If this is a return `impl Trait`, find the item's return expressions and point at them. For /// direct recursion this is enough, but for indirect recursion also point at the last intermediary /// `impl Trait`. /// /// If all the return expressions evaluate to `!`, then we explain that the error will go away /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder. fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) { let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type"); let mut label = false; if let Some((hir_id, visitor)) = get_owner_return_paths(tcx, def_id) { let typeck_results = tcx.typeck(tcx.hir().local_def_id(hir_id)); if visitor .returns .iter() .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id)) .all(|ty| matches!(ty.kind(), ty::Never)) { let spans = visitor .returns .iter() .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some()) .map(|expr| expr.span) .collect::<Vec<Span>>(); let span_len = spans.len(); if span_len == 1 { err.span_label(spans[0], "this returned value is of `!` type"); } else { let mut multispan: MultiSpan = spans.clone().into(); for span in spans { multispan .push_span_label(span, "this returned value is of `!` type".to_string()); } err.span_note(multispan, "these returned values have a concrete \"never\" type"); } err.help("this error will resolve once the item's body returns a concrete type"); } else { let mut seen = FxHashSet::default(); seen.insert(span); err.span_label(span, "recursive opaque type"); label = true; for (sp, ty) in visitor .returns .iter() .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t))) .filter(|(_, ty)| !matches!(ty.kind(), ty::Never)) { struct OpaqueTypeCollector(Vec<DefId>); impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypeCollector { fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> { // Default anon const substs cannot contain opaque types. None } fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { match *t.kind() { ty::Opaque(def, _) => { self.0.push(def); ControlFlow::CONTINUE } _ => t.super_visit_with(self), } } } let mut visitor = OpaqueTypeCollector(vec![]); ty.visit_with(&mut visitor); for def_id in visitor.0 { let ty_span = tcx.def_span(def_id); if !seen.contains(&ty_span) { err.span_label(ty_span, &format!("returning this opaque type `{}`", ty)); seen.insert(ty_span); } err.span_label(sp, &format!("returning here with type `{}`", ty)); } } } } if !label { err.span_label(span, "cannot resolve opaque type"); } err.emit(); }
40.031044
143
0.536456
3374a5d2bbaf5aa2b83033c31b17443083bbcd11
708
use span; use tokio_trace_core::{subscriber::Interest, Metadata}; pub trait Filter<N> { fn callsite_enabled(&self, metadata: &Metadata, ctx: &span::Context<N>) -> Interest { if self.enabled(metadata, ctx) { Interest::always() } else { Interest::never() } } fn enabled(&self, metadata: &Metadata, ctx: &span::Context<N>) -> bool; } pub mod env; pub mod reload; pub use self::{env::EnvFilter, reload::ReloadFilter}; impl<'a, F, N> Filter<N> for F where F: Fn(&Metadata, &span::Context<N>) -> bool, N: ::NewVisitor<'a>, { fn enabled(&self, metadata: &Metadata, ctx: &span::Context<N>) -> bool { (self)(metadata, ctx) } }
22.83871
89
0.588983
4a5d313c6e4cf0c2ff4e3ae1f523b4d1eb938c7e
22,923
//! Runs `!Send` futures on the current thread. use crate::loom::sync::{Arc, Mutex}; use crate::runtime::task::{self, JoinHandle, LocalOwnedTasks, Task}; use crate::sync::AtomicWaker; use crate::util::VecDequeCell; use std::cell::Cell; use std::collections::VecDeque; use std::fmt; use std::future::Future; use std::marker::PhantomData; use std::pin::Pin; use std::task::Poll; use pin_project_lite::pin_project; cfg_rt! { /// A set of tasks which are executed on the same thread. /// /// In some cases, it is necessary to run one or more futures that do not /// implement [`Send`] and thus are unsafe to send between threads. In these /// cases, a [local task set] may be used to schedule one or more `!Send` /// futures to run together on the same thread. /// /// For example, the following code will not compile: /// /// ```rust,compile_fail /// use std::rc::Rc; /// /// #[tokio::main] /// async fn main() { /// // `Rc` does not implement `Send`, and thus may not be sent between /// // threads safely. /// let unsend_data = Rc::new("my unsend data..."); /// /// let unsend_data = unsend_data.clone(); /// // Because the `async` block here moves `unsend_data`, the future is `!Send`. /// // Since `tokio::spawn` requires the spawned future to implement `Send`, this /// // will not compile. /// tokio::spawn(async move { /// println!("{}", unsend_data); /// // ... /// }).await.unwrap(); /// } /// ``` /// /// # Use with `run_until` /// /// To spawn `!Send` futures, we can use a local task set to schedule them /// on the thread calling [`Runtime::block_on`]. When running inside of the /// local task set, we can use [`task::spawn_local`], which can spawn /// `!Send` futures. For example: /// /// ```rust /// use std::rc::Rc; /// use tokio::task; /// /// #[tokio::main] /// async fn main() { /// let unsend_data = Rc::new("my unsend data..."); /// /// // Construct a local task set that can run `!Send` futures. /// let local = task::LocalSet::new(); /// /// // Run the local task set. /// local.run_until(async move { /// let unsend_data = unsend_data.clone(); /// // `spawn_local` ensures that the future is spawned on the local /// // task set. /// task::spawn_local(async move { /// println!("{}", unsend_data); /// // ... /// }).await.unwrap(); /// }).await; /// } /// ``` /// **Note:** The `run_until` method can only be used in `#[tokio::main]`, /// `#[tokio::test]` or directly inside a call to [`Runtime::block_on`]. It /// cannot be used inside a task spawned with `tokio::spawn`. /// /// ## Awaiting a `LocalSet` /// /// Additionally, a `LocalSet` itself implements `Future`, completing when /// *all* tasks spawned on the `LocalSet` complete. This can be used to run /// several futures on a `LocalSet` and drive the whole set until they /// complete. For example, /// /// ```rust /// use tokio::{task, time}; /// use std::rc::Rc; /// /// #[tokio::main] /// async fn main() { /// let unsend_data = Rc::new("world"); /// let local = task::LocalSet::new(); /// /// let unsend_data2 = unsend_data.clone(); /// local.spawn_local(async move { /// // ... /// println!("hello {}", unsend_data2) /// }); /// /// local.spawn_local(async move { /// time::sleep(time::Duration::from_millis(100)).await; /// println!("goodbye {}", unsend_data) /// }); /// /// // ... /// /// local.await; /// } /// ``` /// **Note:** Awaiting a `LocalSet` can only be done inside /// `#[tokio::main]`, `#[tokio::test]` or directly inside a call to /// [`Runtime::block_on`]. It cannot be used inside a task spawned with /// `tokio::spawn`. /// /// ## Use inside `tokio::spawn` /// /// The two methods mentioned above cannot be used inside `tokio::spawn`, so /// to spawn `!Send` futures from inside `tokio::spawn`, we need to do /// something else. The solution is to create the `LocalSet` somewhere else, /// and communicate with it using an [`mpsc`] channel. /// /// The following example puts the `LocalSet` inside a new thread. /// ``` /// use tokio::runtime::Builder; /// use tokio::sync::{mpsc, oneshot}; /// use tokio::task::LocalSet; /// /// // This struct describes the task you want to spawn. Here we include /// // some simple examples. The oneshot channel allows sending a response /// // to the spawner. /// #[derive(Debug)] /// enum Task { /// PrintNumber(u32), /// AddOne(u32, oneshot::Sender<u32>), /// } /// /// #[derive(Clone)] /// struct LocalSpawner { /// send: mpsc::UnboundedSender<Task>, /// } /// /// impl LocalSpawner { /// pub fn new() -> Self { /// let (send, mut recv) = mpsc::unbounded_channel(); /// /// let rt = Builder::new_current_thread() /// .enable_all() /// .build() /// .unwrap(); /// /// std::thread::spawn(move || { /// let local = LocalSet::new(); /// /// local.spawn_local(async move { /// while let Some(new_task) = recv.recv().await { /// tokio::task::spawn_local(run_task(new_task)); /// } /// // If the while loop returns, then all the LocalSpawner /// // objects have have been dropped. /// }); /// /// // This will return once all senders are dropped and all /// // spawned tasks have returned. /// rt.block_on(local); /// }); /// /// Self { /// send, /// } /// } /// /// pub fn spawn(&self, task: Task) { /// self.send.send(task).expect("Thread with LocalSet has shut down."); /// } /// } /// /// // This task may do !Send stuff. We use printing a number as an example, /// // but it could be anything. /// // /// // The Task struct is an enum to support spawning many different kinds /// // of operations. /// async fn run_task(task: Task) { /// match task { /// Task::PrintNumber(n) => { /// println!("{}", n); /// }, /// Task::AddOne(n, response) => { /// // We ignore failures to send the response. /// let _ = response.send(n + 1); /// }, /// } /// } /// /// #[tokio::main] /// async fn main() { /// let spawner = LocalSpawner::new(); /// /// let (send, response) = oneshot::channel(); /// spawner.spawn(Task::AddOne(10, send)); /// let eleven = response.await.unwrap(); /// assert_eq!(eleven, 11); /// } /// ``` /// /// [`Send`]: trait@std::marker::Send /// [local task set]: struct@LocalSet /// [`Runtime::block_on`]: method@crate::runtime::Runtime::block_on /// [`task::spawn_local`]: fn@spawn_local /// [`mpsc`]: mod@crate::sync::mpsc pub struct LocalSet { /// Current scheduler tick. tick: Cell<u8>, /// State available from thread-local. context: Context, /// This type should not be Send. _not_send: PhantomData<*const ()>, } } /// State available from the thread-local. struct Context { /// Collection of all active tasks spawned onto this executor. owned: LocalOwnedTasks<Arc<Shared>>, /// Local run queue sender and receiver. queue: VecDequeCell<task::Notified<Arc<Shared>>>, /// State shared between threads. shared: Arc<Shared>, } /// LocalSet state shared between threads. struct Shared { /// Remote run queue sender. queue: Mutex<Option<VecDeque<task::Notified<Arc<Shared>>>>>, /// Wake the `LocalSet` task. waker: AtomicWaker, } pin_project! { #[derive(Debug)] struct RunUntil<'a, F> { local_set: &'a LocalSet, #[pin] future: F, } } scoped_thread_local!(static CURRENT: Context); cfg_rt! { /// Spawns a `!Send` future on the local task set. /// /// The spawned future will be run on the same thread that called `spawn_local.` /// This may only be called from the context of a local task set. /// /// # Panics /// /// - This function panics if called outside of a local task set. /// /// # Examples /// /// ```rust /// use std::rc::Rc; /// use tokio::task; /// /// #[tokio::main] /// async fn main() { /// let unsend_data = Rc::new("my unsend data..."); /// /// let local = task::LocalSet::new(); /// /// // Run the local task set. /// local.run_until(async move { /// let unsend_data = unsend_data.clone(); /// task::spawn_local(async move { /// println!("{}", unsend_data); /// // ... /// }).await.unwrap(); /// }).await; /// } /// ``` #[cfg_attr(tokio_track_caller, track_caller)] pub fn spawn_local<F>(future: F) -> JoinHandle<F::Output> where F: Future + 'static, F::Output: 'static, { spawn_local_inner(future, None) } pub(super) fn spawn_local_inner<F>(future: F, name: Option<&str>) -> JoinHandle<F::Output> where F: Future + 'static, F::Output: 'static { let future = crate::util::trace::task(future, "local", name); CURRENT.with(|maybe_cx| { let cx = maybe_cx .expect("`spawn_local` called from outside of a `task::LocalSet`"); let (handle, notified) = cx.owned.bind(future, cx.shared.clone()); if let Some(notified) = notified { cx.shared.schedule(notified); } handle }) } } /// Initial queue capacity. const INITIAL_CAPACITY: usize = 64; /// Max number of tasks to poll per tick. const MAX_TASKS_PER_TICK: usize = 61; /// How often it check the remote queue first. const REMOTE_FIRST_INTERVAL: u8 = 31; impl LocalSet { /// Returns a new local task set. pub fn new() -> LocalSet { LocalSet { tick: Cell::new(0), context: Context { owned: LocalOwnedTasks::new(), queue: VecDequeCell::with_capacity(INITIAL_CAPACITY), shared: Arc::new(Shared { queue: Mutex::new(Some(VecDeque::with_capacity(INITIAL_CAPACITY))), waker: AtomicWaker::new(), }), }, _not_send: PhantomData, } } /// Spawns a `!Send` task onto the local task set. /// /// This task is guaranteed to be run on the current thread. /// /// Unlike the free function [`spawn_local`], this method may be used to /// spawn local tasks when the task set is _not_ running. For example: /// ```rust /// use tokio::task; /// /// #[tokio::main] /// async fn main() { /// let local = task::LocalSet::new(); /// /// // Spawn a future on the local set. This future will be run when /// // we call `run_until` to drive the task set. /// local.spawn_local(async { /// // ... /// }); /// /// // Run the local task set. /// local.run_until(async move { /// // ... /// }).await; /// /// // When `run` finishes, we can spawn _more_ futures, which will /// // run in subsequent calls to `run_until`. /// local.spawn_local(async { /// // ... /// }); /// /// local.run_until(async move { /// // ... /// }).await; /// } /// ``` /// [`spawn_local`]: fn@spawn_local #[cfg_attr(tokio_track_caller, track_caller)] pub fn spawn_local<F>(&self, future: F) -> JoinHandle<F::Output> where F: Future + 'static, F::Output: 'static, { let future = crate::util::trace::task(future, "local", None); let (handle, notified) = self.context.owned.bind(future, self.context.shared.clone()); if let Some(notified) = notified { self.context.shared.schedule(notified); } self.context.shared.waker.wake(); handle } /// Runs a future to completion on the provided runtime, driving any local /// futures spawned on this task set on the current thread. /// /// This runs the given future on the runtime, blocking until it is /// complete, and yielding its resolved result. Any tasks or timers which /// the future spawns internally will be executed on the runtime. The future /// may also call [`spawn_local`] to spawn_local additional local futures on the /// current thread. /// /// This method should not be called from an asynchronous context. /// /// # Panics /// /// This function panics if the executor is at capacity, if the provided /// future panics, or if called within an asynchronous execution context. /// /// # Notes /// /// Since this function internally calls [`Runtime::block_on`], and drives /// futures in the local task set inside that call to `block_on`, the local /// futures may not use [in-place blocking]. If a blocking call needs to be /// issued from a local task, the [`spawn_blocking`] API may be used instead. /// /// For example, this will panic: /// ```should_panic /// use tokio::runtime::Runtime; /// use tokio::task; /// /// let rt = Runtime::new().unwrap(); /// let local = task::LocalSet::new(); /// local.block_on(&rt, async { /// let join = task::spawn_local(async { /// let blocking_result = task::block_in_place(|| { /// // ... /// }); /// // ... /// }); /// join.await.unwrap(); /// }) /// ``` /// This, however, will not panic: /// ``` /// use tokio::runtime::Runtime; /// use tokio::task; /// /// let rt = Runtime::new().unwrap(); /// let local = task::LocalSet::new(); /// local.block_on(&rt, async { /// let join = task::spawn_local(async { /// let blocking_result = task::spawn_blocking(|| { /// // ... /// }).await; /// // ... /// }); /// join.await.unwrap(); /// }) /// ``` /// /// [`spawn_local`]: fn@spawn_local /// [`Runtime::block_on`]: method@crate::runtime::Runtime::block_on /// [in-place blocking]: fn@crate::task::block_in_place /// [`spawn_blocking`]: fn@crate::task::spawn_blocking #[cfg(feature = "rt")] #[cfg_attr(docsrs, doc(cfg(feature = "rt")))] pub fn block_on<F>(&self, rt: &crate::runtime::Runtime, future: F) -> F::Output where F: Future, { rt.block_on(self.run_until(future)) } /// Runs a future to completion on the local set, returning its output. /// /// This returns a future that runs the given future with a local set, /// allowing it to call [`spawn_local`] to spawn additional `!Send` futures. /// Any local futures spawned on the local set will be driven in the /// background until the future passed to `run_until` completes. When the future /// passed to `run` finishes, any local futures which have not completed /// will remain on the local set, and will be driven on subsequent calls to /// `run_until` or when [awaiting the local set] itself. /// /// # Examples /// /// ```rust /// use tokio::task; /// /// #[tokio::main] /// async fn main() { /// task::LocalSet::new().run_until(async { /// task::spawn_local(async move { /// // ... /// }).await.unwrap(); /// // ... /// }).await; /// } /// ``` /// /// [`spawn_local`]: fn@spawn_local /// [awaiting the local set]: #awaiting-a-localset pub async fn run_until<F>(&self, future: F) -> F::Output where F: Future, { let run_until = RunUntil { future, local_set: self, }; run_until.await } /// Ticks the scheduler, returning whether the local future needs to be /// notified again. fn tick(&self) -> bool { for _ in 0..MAX_TASKS_PER_TICK { match self.next_task() { // Run the task // // Safety: As spawned tasks are `!Send`, `run_unchecked` must be // used. We are responsible for maintaining the invariant that // `run_unchecked` is only called on threads that spawned the // task initially. Because `LocalSet` itself is `!Send`, and // `spawn_local` spawns into the `LocalSet` on the current // thread, the invariant is maintained. Some(task) => crate::coop::budget(|| task.run()), // We have fully drained the queue of notified tasks, so the // local future doesn't need to be notified again — it can wait // until something else wakes a task in the local set. None => return false, } } true } fn next_task(&self) -> Option<task::LocalNotified<Arc<Shared>>> { let tick = self.tick.get(); self.tick.set(tick.wrapping_add(1)); let task = if tick % REMOTE_FIRST_INTERVAL == 0 { self.context .shared .queue .lock() .as_mut() .and_then(|queue| queue.pop_front()) .or_else(|| self.context.queue.pop_front()) } else { self.context.queue.pop_front().or_else(|| { self.context .shared .queue .lock() .as_mut() .and_then(|queue| queue.pop_front()) }) }; task.map(|task| self.context.owned.assert_owner(task)) } fn with<T>(&self, f: impl FnOnce() -> T) -> T { CURRENT.set(&self.context, f) } } impl fmt::Debug for LocalSet { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("LocalSet").finish() } } impl Future for LocalSet { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { // Register the waker before starting to work self.context.shared.waker.register_by_ref(cx.waker()); if self.with(|| self.tick()) { // If `tick` returns true, we need to notify the local future again: // there are still tasks remaining in the run queue. cx.waker().wake_by_ref(); Poll::Pending } else if self.context.owned.is_empty() { // If the scheduler has no remaining futures, we're done! Poll::Ready(()) } else { // There are still futures in the local set, but we've polled all the // futures in the run queue. Therefore, we can just return Pending // since the remaining futures will be woken from somewhere else. Poll::Pending } } } impl Default for LocalSet { fn default() -> LocalSet { LocalSet::new() } } impl Drop for LocalSet { fn drop(&mut self) { self.with(|| { // Shut down all tasks in the LocalOwnedTasks and close it to // prevent new tasks from ever being added. self.context.owned.close_and_shutdown_all(); // We already called shutdown on all tasks above, so there is no // need to call shutdown. for task in self.context.queue.take() { drop(task); } // Take the queue from the Shared object to prevent pushing // notifications to it in the future. let queue = self.context.shared.queue.lock().take().unwrap(); for task in queue { drop(task); } assert!(self.context.owned.is_empty()); }); } } // === impl LocalFuture === impl<T: Future> Future for RunUntil<'_, T> { type Output = T::Output; fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { let me = self.project(); me.local_set.with(|| { me.local_set .context .shared .waker .register_by_ref(cx.waker()); let _no_blocking = crate::runtime::enter::disallow_blocking(); let f = me.future; if let Poll::Ready(output) = crate::coop::budget(|| f.poll(cx)) { return Poll::Ready(output); } if me.local_set.tick() { // If `tick` returns `true`, we need to notify the local future again: // there are still tasks remaining in the run queue. cx.waker().wake_by_ref(); } Poll::Pending }) } } impl Shared { /// Schedule the provided task on the scheduler. fn schedule(&self, task: task::Notified<Arc<Self>>) { CURRENT.with(|maybe_cx| match maybe_cx { Some(cx) if cx.shared.ptr_eq(self) => { cx.queue.push_back(task); } _ => { // First check whether the queue is still there (if not, the // LocalSet is dropped). Then push to it if so, and if not, // do nothing. let mut lock = self.queue.lock(); if let Some(queue) = lock.as_mut() { queue.push_back(task); drop(lock); self.waker.wake(); } } }); } fn ptr_eq(&self, other: &Shared) -> bool { std::ptr::eq(self, other) } } impl task::Schedule for Arc<Shared> { fn release(&self, task: &Task<Self>) -> Option<Task<Self>> { CURRENT.with(|maybe_cx| { let cx = maybe_cx.expect("scheduler context missing"); assert!(cx.shared.ptr_eq(self)); cx.owned.remove(task) }) } fn schedule(&self, task: task::Notified<Self>) { Shared::schedule(self, task); } }
32.888092
94
0.521398
edf5042c00fab19a1025564583336848881500d1
187,872
//! Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Rust p434 64 '2^216 * 3^137 - 1' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one msat divstep divstep_precomp //! curve description: p434 //! machine_wordsize = 64 (from "64") //! requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp //! m = 0x2341f271773446cfc5fd681c520567bc65c783158aea3fdc1767ae2ffffffffffffffffffffffffffffffffffffffffffffffffffffff (from "2^216 * 3^137 - 1") //! //! NOTE: In addition to the bounds specified above each function, all //! functions synthesized for this Montgomery arithmetic require the //! input to be strictly less than the prime modulus (m), and also //! require the input to be in the unique saturated representation. //! All functions also ensure that these two properties are true of //! return values. //! //! Computed values: //! eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) + (z[4] << 256) + (z[5] << 0x140) + (z[6] << 0x180) //! bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) + (z[32] << 256) + (z[33] << 0x108) + (z[34] << 0x110) + (z[35] << 0x118) + (z[36] << 0x120) + (z[37] << 0x128) + (z[38] << 0x130) + (z[39] << 0x138) + (z[40] << 0x140) + (z[41] << 0x148) + (z[42] << 0x150) + (z[43] << 0x158) + (z[44] << 0x160) + (z[45] << 0x168) + (z[46] << 0x170) + (z[47] << 0x178) + (z[48] << 0x180) + (z[49] << 0x188) + (z[50] << 0x190) + (z[51] << 0x198) + (z[52] << 0x1a0) + (z[53] << 0x1a8) + (z[54] << 0x1b0) #![allow(unused_parens)] #[allow(non_camel_case_types)] pub type fiat_p434_u1 = u8; pub type fiat_p434_i1 = i8; pub type fiat_p434_u2 = u8; pub type fiat_p434_i2 = i8; /// The function fiat_p434_addcarryx_u64 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^64 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] #[inline] pub fn fiat_p434_addcarryx_u64(out1: &mut u64, out2: &mut fiat_p434_u1, arg1: fiat_p434_u1, arg2: u64, arg3: u64) -> () { let x1: u128 = (((arg1 as u128) + (arg2 as u128)) + (arg3 as u128)); let x2: u64 = ((x1 & (0xffffffffffffffff as u128)) as u64); let x3: fiat_p434_u1 = ((x1 >> 64) as fiat_p434_u1); *out1 = x2; *out2 = x3; } /// The function fiat_p434_subborrowx_u64 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^64 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] #[inline] pub fn fiat_p434_subborrowx_u64(out1: &mut u64, out2: &mut fiat_p434_u1, arg1: fiat_p434_u1, arg2: u64, arg3: u64) -> () { let x1: i128 = (((arg2 as i128) - (arg1 as i128)) - (arg3 as i128)); let x2: fiat_p434_i1 = ((x1 >> 64) as fiat_p434_i1); let x3: u64 = ((x1 & (0xffffffffffffffff as i128)) as u64); *out1 = x3; *out2 = (((0x0 as fiat_p434_i2) - (x2 as fiat_p434_i2)) as fiat_p434_u1); } /// The function fiat_p434_mulx_u64 is a multiplication, returning the full double-width result. /// Postconditions: /// out1 = (arg1 * arg2) mod 2^64 /// out2 = ⌊arg1 * arg2 / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0xffffffffffffffff] #[inline] pub fn fiat_p434_mulx_u64(out1: &mut u64, out2: &mut u64, arg1: u64, arg2: u64) -> () { let x1: u128 = ((arg1 as u128) * (arg2 as u128)); let x2: u64 = ((x1 & (0xffffffffffffffff as u128)) as u64); let x3: u64 = ((x1 >> 64) as u64); *out1 = x2; *out2 = x3; } /// The function fiat_p434_cmovznz_u64 is a single-word conditional move. /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] #[inline] pub fn fiat_p434_cmovznz_u64(out1: &mut u64, arg1: fiat_p434_u1, arg2: u64, arg3: u64) -> () { let x1: fiat_p434_u1 = (!(!arg1)); let x2: u64 = ((((((0x0 as fiat_p434_i2) - (x1 as fiat_p434_i2)) as fiat_p434_i1) as i128) & (0xffffffffffffffff as i128)) as u64); let x3: u64 = ((x2 & arg3) | ((!x2) & arg2)); *out1 = x3; } /// The function fiat_p434_mul multiplies two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_mul(out1: &mut [u64; 7], arg1: &[u64; 7], arg2: &[u64; 7]) -> () { let x1: u64 = (arg1[1]); let x2: u64 = (arg1[2]); let x3: u64 = (arg1[3]); let x4: u64 = (arg1[4]); let x5: u64 = (arg1[5]); let x6: u64 = (arg1[6]); let x7: u64 = (arg1[0]); let mut x8: u64 = 0; let mut x9: u64 = 0; fiat_p434_mulx_u64(&mut x8, &mut x9, x7, (arg2[6])); let mut x10: u64 = 0; let mut x11: u64 = 0; fiat_p434_mulx_u64(&mut x10, &mut x11, x7, (arg2[5])); let mut x12: u64 = 0; let mut x13: u64 = 0; fiat_p434_mulx_u64(&mut x12, &mut x13, x7, (arg2[4])); let mut x14: u64 = 0; let mut x15: u64 = 0; fiat_p434_mulx_u64(&mut x14, &mut x15, x7, (arg2[3])); let mut x16: u64 = 0; let mut x17: u64 = 0; fiat_p434_mulx_u64(&mut x16, &mut x17, x7, (arg2[2])); let mut x18: u64 = 0; let mut x19: u64 = 0; fiat_p434_mulx_u64(&mut x18, &mut x19, x7, (arg2[1])); let mut x20: u64 = 0; let mut x21: u64 = 0; fiat_p434_mulx_u64(&mut x20, &mut x21, x7, (arg2[0])); let mut x22: u64 = 0; let mut x23: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x22, &mut x23, 0x0, x21, x18); let mut x24: u64 = 0; let mut x25: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x24, &mut x25, x23, x19, x16); let mut x26: u64 = 0; let mut x27: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x26, &mut x27, x25, x17, x14); let mut x28: u64 = 0; let mut x29: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x28, &mut x29, x27, x15, x12); let mut x30: u64 = 0; let mut x31: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x30, &mut x31, x29, x13, x10); let mut x32: u64 = 0; let mut x33: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x32, &mut x33, x31, x11, x8); let x34: u64 = ((x33 as u64) + x9); let mut x35: u64 = 0; let mut x36: u64 = 0; fiat_p434_mulx_u64(&mut x35, &mut x36, x20, 0x2341f27177344); let mut x37: u64 = 0; let mut x38: u64 = 0; fiat_p434_mulx_u64(&mut x37, &mut x38, x20, 0x6cfc5fd681c52056); let mut x39: u64 = 0; let mut x40: u64 = 0; fiat_p434_mulx_u64(&mut x39, &mut x40, x20, 0x7bc65c783158aea3); let mut x41: u64 = 0; let mut x42: u64 = 0; fiat_p434_mulx_u64(&mut x41, &mut x42, x20, 0xfdc1767ae2ffffff); let mut x43: u64 = 0; let mut x44: u64 = 0; fiat_p434_mulx_u64(&mut x43, &mut x44, x20, 0xffffffffffffffff); let mut x45: u64 = 0; let mut x46: u64 = 0; fiat_p434_mulx_u64(&mut x45, &mut x46, x20, 0xffffffffffffffff); let mut x47: u64 = 0; let mut x48: u64 = 0; fiat_p434_mulx_u64(&mut x47, &mut x48, x20, 0xffffffffffffffff); let mut x49: u64 = 0; let mut x50: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x49, &mut x50, 0x0, x48, x45); let mut x51: u64 = 0; let mut x52: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x51, &mut x52, x50, x46, x43); let mut x53: u64 = 0; let mut x54: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x53, &mut x54, x52, x44, x41); let mut x55: u64 = 0; let mut x56: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x55, &mut x56, x54, x42, x39); let mut x57: u64 = 0; let mut x58: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x57, &mut x58, x56, x40, x37); let mut x59: u64 = 0; let mut x60: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x59, &mut x60, x58, x38, x35); let x61: u64 = ((x60 as u64) + x36); let mut x62: u64 = 0; let mut x63: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x62, &mut x63, 0x0, x20, x47); let mut x64: u64 = 0; let mut x65: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x64, &mut x65, x63, x22, x49); let mut x66: u64 = 0; let mut x67: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x66, &mut x67, x65, x24, x51); let mut x68: u64 = 0; let mut x69: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x68, &mut x69, x67, x26, x53); let mut x70: u64 = 0; let mut x71: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x70, &mut x71, x69, x28, x55); let mut x72: u64 = 0; let mut x73: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x72, &mut x73, x71, x30, x57); let mut x74: u64 = 0; let mut x75: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x74, &mut x75, x73, x32, x59); let mut x76: u64 = 0; let mut x77: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x76, &mut x77, x75, x34, x61); let mut x78: u64 = 0; let mut x79: u64 = 0; fiat_p434_mulx_u64(&mut x78, &mut x79, x1, (arg2[6])); let mut x80: u64 = 0; let mut x81: u64 = 0; fiat_p434_mulx_u64(&mut x80, &mut x81, x1, (arg2[5])); let mut x82: u64 = 0; let mut x83: u64 = 0; fiat_p434_mulx_u64(&mut x82, &mut x83, x1, (arg2[4])); let mut x84: u64 = 0; let mut x85: u64 = 0; fiat_p434_mulx_u64(&mut x84, &mut x85, x1, (arg2[3])); let mut x86: u64 = 0; let mut x87: u64 = 0; fiat_p434_mulx_u64(&mut x86, &mut x87, x1, (arg2[2])); let mut x88: u64 = 0; let mut x89: u64 = 0; fiat_p434_mulx_u64(&mut x88, &mut x89, x1, (arg2[1])); let mut x90: u64 = 0; let mut x91: u64 = 0; fiat_p434_mulx_u64(&mut x90, &mut x91, x1, (arg2[0])); let mut x92: u64 = 0; let mut x93: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x92, &mut x93, 0x0, x91, x88); let mut x94: u64 = 0; let mut x95: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x94, &mut x95, x93, x89, x86); let mut x96: u64 = 0; let mut x97: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x96, &mut x97, x95, x87, x84); let mut x98: u64 = 0; let mut x99: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x98, &mut x99, x97, x85, x82); let mut x100: u64 = 0; let mut x101: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x100, &mut x101, x99, x83, x80); let mut x102: u64 = 0; let mut x103: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x102, &mut x103, x101, x81, x78); let x104: u64 = ((x103 as u64) + x79); let mut x105: u64 = 0; let mut x106: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x105, &mut x106, 0x0, x64, x90); let mut x107: u64 = 0; let mut x108: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x107, &mut x108, x106, x66, x92); let mut x109: u64 = 0; let mut x110: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x109, &mut x110, x108, x68, x94); let mut x111: u64 = 0; let mut x112: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x111, &mut x112, x110, x70, x96); let mut x113: u64 = 0; let mut x114: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x113, &mut x114, x112, x72, x98); let mut x115: u64 = 0; let mut x116: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x115, &mut x116, x114, x74, x100); let mut x117: u64 = 0; let mut x118: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x117, &mut x118, x116, x76, x102); let mut x119: u64 = 0; let mut x120: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x119, &mut x120, x118, (x77 as u64), x104); let mut x121: u64 = 0; let mut x122: u64 = 0; fiat_p434_mulx_u64(&mut x121, &mut x122, x105, 0x2341f27177344); let mut x123: u64 = 0; let mut x124: u64 = 0; fiat_p434_mulx_u64(&mut x123, &mut x124, x105, 0x6cfc5fd681c52056); let mut x125: u64 = 0; let mut x126: u64 = 0; fiat_p434_mulx_u64(&mut x125, &mut x126, x105, 0x7bc65c783158aea3); let mut x127: u64 = 0; let mut x128: u64 = 0; fiat_p434_mulx_u64(&mut x127, &mut x128, x105, 0xfdc1767ae2ffffff); let mut x129: u64 = 0; let mut x130: u64 = 0; fiat_p434_mulx_u64(&mut x129, &mut x130, x105, 0xffffffffffffffff); let mut x131: u64 = 0; let mut x132: u64 = 0; fiat_p434_mulx_u64(&mut x131, &mut x132, x105, 0xffffffffffffffff); let mut x133: u64 = 0; let mut x134: u64 = 0; fiat_p434_mulx_u64(&mut x133, &mut x134, x105, 0xffffffffffffffff); let mut x135: u64 = 0; let mut x136: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x135, &mut x136, 0x0, x134, x131); let mut x137: u64 = 0; let mut x138: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x137, &mut x138, x136, x132, x129); let mut x139: u64 = 0; let mut x140: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x139, &mut x140, x138, x130, x127); let mut x141: u64 = 0; let mut x142: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x141, &mut x142, x140, x128, x125); let mut x143: u64 = 0; let mut x144: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x143, &mut x144, x142, x126, x123); let mut x145: u64 = 0; let mut x146: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x145, &mut x146, x144, x124, x121); let x147: u64 = ((x146 as u64) + x122); let mut x148: u64 = 0; let mut x149: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x148, &mut x149, 0x0, x105, x133); let mut x150: u64 = 0; let mut x151: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x150, &mut x151, x149, x107, x135); let mut x152: u64 = 0; let mut x153: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x152, &mut x153, x151, x109, x137); let mut x154: u64 = 0; let mut x155: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x154, &mut x155, x153, x111, x139); let mut x156: u64 = 0; let mut x157: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x156, &mut x157, x155, x113, x141); let mut x158: u64 = 0; let mut x159: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x158, &mut x159, x157, x115, x143); let mut x160: u64 = 0; let mut x161: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x160, &mut x161, x159, x117, x145); let mut x162: u64 = 0; let mut x163: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x162, &mut x163, x161, x119, x147); let x164: u64 = ((x163 as u64) + (x120 as u64)); let mut x165: u64 = 0; let mut x166: u64 = 0; fiat_p434_mulx_u64(&mut x165, &mut x166, x2, (arg2[6])); let mut x167: u64 = 0; let mut x168: u64 = 0; fiat_p434_mulx_u64(&mut x167, &mut x168, x2, (arg2[5])); let mut x169: u64 = 0; let mut x170: u64 = 0; fiat_p434_mulx_u64(&mut x169, &mut x170, x2, (arg2[4])); let mut x171: u64 = 0; let mut x172: u64 = 0; fiat_p434_mulx_u64(&mut x171, &mut x172, x2, (arg2[3])); let mut x173: u64 = 0; let mut x174: u64 = 0; fiat_p434_mulx_u64(&mut x173, &mut x174, x2, (arg2[2])); let mut x175: u64 = 0; let mut x176: u64 = 0; fiat_p434_mulx_u64(&mut x175, &mut x176, x2, (arg2[1])); let mut x177: u64 = 0; let mut x178: u64 = 0; fiat_p434_mulx_u64(&mut x177, &mut x178, x2, (arg2[0])); let mut x179: u64 = 0; let mut x180: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x179, &mut x180, 0x0, x178, x175); let mut x181: u64 = 0; let mut x182: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x181, &mut x182, x180, x176, x173); let mut x183: u64 = 0; let mut x184: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x183, &mut x184, x182, x174, x171); let mut x185: u64 = 0; let mut x186: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x185, &mut x186, x184, x172, x169); let mut x187: u64 = 0; let mut x188: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x187, &mut x188, x186, x170, x167); let mut x189: u64 = 0; let mut x190: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x189, &mut x190, x188, x168, x165); let x191: u64 = ((x190 as u64) + x166); let mut x192: u64 = 0; let mut x193: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x192, &mut x193, 0x0, x150, x177); let mut x194: u64 = 0; let mut x195: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x194, &mut x195, x193, x152, x179); let mut x196: u64 = 0; let mut x197: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x196, &mut x197, x195, x154, x181); let mut x198: u64 = 0; let mut x199: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x198, &mut x199, x197, x156, x183); let mut x200: u64 = 0; let mut x201: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x200, &mut x201, x199, x158, x185); let mut x202: u64 = 0; let mut x203: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x202, &mut x203, x201, x160, x187); let mut x204: u64 = 0; let mut x205: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x204, &mut x205, x203, x162, x189); let mut x206: u64 = 0; let mut x207: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x206, &mut x207, x205, x164, x191); let mut x208: u64 = 0; let mut x209: u64 = 0; fiat_p434_mulx_u64(&mut x208, &mut x209, x192, 0x2341f27177344); let mut x210: u64 = 0; let mut x211: u64 = 0; fiat_p434_mulx_u64(&mut x210, &mut x211, x192, 0x6cfc5fd681c52056); let mut x212: u64 = 0; let mut x213: u64 = 0; fiat_p434_mulx_u64(&mut x212, &mut x213, x192, 0x7bc65c783158aea3); let mut x214: u64 = 0; let mut x215: u64 = 0; fiat_p434_mulx_u64(&mut x214, &mut x215, x192, 0xfdc1767ae2ffffff); let mut x216: u64 = 0; let mut x217: u64 = 0; fiat_p434_mulx_u64(&mut x216, &mut x217, x192, 0xffffffffffffffff); let mut x218: u64 = 0; let mut x219: u64 = 0; fiat_p434_mulx_u64(&mut x218, &mut x219, x192, 0xffffffffffffffff); let mut x220: u64 = 0; let mut x221: u64 = 0; fiat_p434_mulx_u64(&mut x220, &mut x221, x192, 0xffffffffffffffff); let mut x222: u64 = 0; let mut x223: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x222, &mut x223, 0x0, x221, x218); let mut x224: u64 = 0; let mut x225: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x224, &mut x225, x223, x219, x216); let mut x226: u64 = 0; let mut x227: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x226, &mut x227, x225, x217, x214); let mut x228: u64 = 0; let mut x229: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x228, &mut x229, x227, x215, x212); let mut x230: u64 = 0; let mut x231: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x230, &mut x231, x229, x213, x210); let mut x232: u64 = 0; let mut x233: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x232, &mut x233, x231, x211, x208); let x234: u64 = ((x233 as u64) + x209); let mut x235: u64 = 0; let mut x236: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x235, &mut x236, 0x0, x192, x220); let mut x237: u64 = 0; let mut x238: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x237, &mut x238, x236, x194, x222); let mut x239: u64 = 0; let mut x240: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x239, &mut x240, x238, x196, x224); let mut x241: u64 = 0; let mut x242: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x241, &mut x242, x240, x198, x226); let mut x243: u64 = 0; let mut x244: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x243, &mut x244, x242, x200, x228); let mut x245: u64 = 0; let mut x246: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x245, &mut x246, x244, x202, x230); let mut x247: u64 = 0; let mut x248: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x247, &mut x248, x246, x204, x232); let mut x249: u64 = 0; let mut x250: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x249, &mut x250, x248, x206, x234); let x251: u64 = ((x250 as u64) + (x207 as u64)); let mut x252: u64 = 0; let mut x253: u64 = 0; fiat_p434_mulx_u64(&mut x252, &mut x253, x3, (arg2[6])); let mut x254: u64 = 0; let mut x255: u64 = 0; fiat_p434_mulx_u64(&mut x254, &mut x255, x3, (arg2[5])); let mut x256: u64 = 0; let mut x257: u64 = 0; fiat_p434_mulx_u64(&mut x256, &mut x257, x3, (arg2[4])); let mut x258: u64 = 0; let mut x259: u64 = 0; fiat_p434_mulx_u64(&mut x258, &mut x259, x3, (arg2[3])); let mut x260: u64 = 0; let mut x261: u64 = 0; fiat_p434_mulx_u64(&mut x260, &mut x261, x3, (arg2[2])); let mut x262: u64 = 0; let mut x263: u64 = 0; fiat_p434_mulx_u64(&mut x262, &mut x263, x3, (arg2[1])); let mut x264: u64 = 0; let mut x265: u64 = 0; fiat_p434_mulx_u64(&mut x264, &mut x265, x3, (arg2[0])); let mut x266: u64 = 0; let mut x267: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x266, &mut x267, 0x0, x265, x262); let mut x268: u64 = 0; let mut x269: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x268, &mut x269, x267, x263, x260); let mut x270: u64 = 0; let mut x271: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x270, &mut x271, x269, x261, x258); let mut x272: u64 = 0; let mut x273: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x272, &mut x273, x271, x259, x256); let mut x274: u64 = 0; let mut x275: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x274, &mut x275, x273, x257, x254); let mut x276: u64 = 0; let mut x277: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x276, &mut x277, x275, x255, x252); let x278: u64 = ((x277 as u64) + x253); let mut x279: u64 = 0; let mut x280: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x279, &mut x280, 0x0, x237, x264); let mut x281: u64 = 0; let mut x282: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x281, &mut x282, x280, x239, x266); let mut x283: u64 = 0; let mut x284: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x283, &mut x284, x282, x241, x268); let mut x285: u64 = 0; let mut x286: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x285, &mut x286, x284, x243, x270); let mut x287: u64 = 0; let mut x288: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x287, &mut x288, x286, x245, x272); let mut x289: u64 = 0; let mut x290: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x289, &mut x290, x288, x247, x274); let mut x291: u64 = 0; let mut x292: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x291, &mut x292, x290, x249, x276); let mut x293: u64 = 0; let mut x294: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x293, &mut x294, x292, x251, x278); let mut x295: u64 = 0; let mut x296: u64 = 0; fiat_p434_mulx_u64(&mut x295, &mut x296, x279, 0x2341f27177344); let mut x297: u64 = 0; let mut x298: u64 = 0; fiat_p434_mulx_u64(&mut x297, &mut x298, x279, 0x6cfc5fd681c52056); let mut x299: u64 = 0; let mut x300: u64 = 0; fiat_p434_mulx_u64(&mut x299, &mut x300, x279, 0x7bc65c783158aea3); let mut x301: u64 = 0; let mut x302: u64 = 0; fiat_p434_mulx_u64(&mut x301, &mut x302, x279, 0xfdc1767ae2ffffff); let mut x303: u64 = 0; let mut x304: u64 = 0; fiat_p434_mulx_u64(&mut x303, &mut x304, x279, 0xffffffffffffffff); let mut x305: u64 = 0; let mut x306: u64 = 0; fiat_p434_mulx_u64(&mut x305, &mut x306, x279, 0xffffffffffffffff); let mut x307: u64 = 0; let mut x308: u64 = 0; fiat_p434_mulx_u64(&mut x307, &mut x308, x279, 0xffffffffffffffff); let mut x309: u64 = 0; let mut x310: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x309, &mut x310, 0x0, x308, x305); let mut x311: u64 = 0; let mut x312: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x311, &mut x312, x310, x306, x303); let mut x313: u64 = 0; let mut x314: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x313, &mut x314, x312, x304, x301); let mut x315: u64 = 0; let mut x316: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x315, &mut x316, x314, x302, x299); let mut x317: u64 = 0; let mut x318: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x317, &mut x318, x316, x300, x297); let mut x319: u64 = 0; let mut x320: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x319, &mut x320, x318, x298, x295); let x321: u64 = ((x320 as u64) + x296); let mut x322: u64 = 0; let mut x323: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x322, &mut x323, 0x0, x279, x307); let mut x324: u64 = 0; let mut x325: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x324, &mut x325, x323, x281, x309); let mut x326: u64 = 0; let mut x327: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x326, &mut x327, x325, x283, x311); let mut x328: u64 = 0; let mut x329: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x328, &mut x329, x327, x285, x313); let mut x330: u64 = 0; let mut x331: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x330, &mut x331, x329, x287, x315); let mut x332: u64 = 0; let mut x333: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x332, &mut x333, x331, x289, x317); let mut x334: u64 = 0; let mut x335: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x334, &mut x335, x333, x291, x319); let mut x336: u64 = 0; let mut x337: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x336, &mut x337, x335, x293, x321); let x338: u64 = ((x337 as u64) + (x294 as u64)); let mut x339: u64 = 0; let mut x340: u64 = 0; fiat_p434_mulx_u64(&mut x339, &mut x340, x4, (arg2[6])); let mut x341: u64 = 0; let mut x342: u64 = 0; fiat_p434_mulx_u64(&mut x341, &mut x342, x4, (arg2[5])); let mut x343: u64 = 0; let mut x344: u64 = 0; fiat_p434_mulx_u64(&mut x343, &mut x344, x4, (arg2[4])); let mut x345: u64 = 0; let mut x346: u64 = 0; fiat_p434_mulx_u64(&mut x345, &mut x346, x4, (arg2[3])); let mut x347: u64 = 0; let mut x348: u64 = 0; fiat_p434_mulx_u64(&mut x347, &mut x348, x4, (arg2[2])); let mut x349: u64 = 0; let mut x350: u64 = 0; fiat_p434_mulx_u64(&mut x349, &mut x350, x4, (arg2[1])); let mut x351: u64 = 0; let mut x352: u64 = 0; fiat_p434_mulx_u64(&mut x351, &mut x352, x4, (arg2[0])); let mut x353: u64 = 0; let mut x354: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x353, &mut x354, 0x0, x352, x349); let mut x355: u64 = 0; let mut x356: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x355, &mut x356, x354, x350, x347); let mut x357: u64 = 0; let mut x358: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x357, &mut x358, x356, x348, x345); let mut x359: u64 = 0; let mut x360: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x359, &mut x360, x358, x346, x343); let mut x361: u64 = 0; let mut x362: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x361, &mut x362, x360, x344, x341); let mut x363: u64 = 0; let mut x364: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x363, &mut x364, x362, x342, x339); let x365: u64 = ((x364 as u64) + x340); let mut x366: u64 = 0; let mut x367: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x366, &mut x367, 0x0, x324, x351); let mut x368: u64 = 0; let mut x369: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x368, &mut x369, x367, x326, x353); let mut x370: u64 = 0; let mut x371: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x370, &mut x371, x369, x328, x355); let mut x372: u64 = 0; let mut x373: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x372, &mut x373, x371, x330, x357); let mut x374: u64 = 0; let mut x375: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x374, &mut x375, x373, x332, x359); let mut x376: u64 = 0; let mut x377: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x376, &mut x377, x375, x334, x361); let mut x378: u64 = 0; let mut x379: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x378, &mut x379, x377, x336, x363); let mut x380: u64 = 0; let mut x381: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x380, &mut x381, x379, x338, x365); let mut x382: u64 = 0; let mut x383: u64 = 0; fiat_p434_mulx_u64(&mut x382, &mut x383, x366, 0x2341f27177344); let mut x384: u64 = 0; let mut x385: u64 = 0; fiat_p434_mulx_u64(&mut x384, &mut x385, x366, 0x6cfc5fd681c52056); let mut x386: u64 = 0; let mut x387: u64 = 0; fiat_p434_mulx_u64(&mut x386, &mut x387, x366, 0x7bc65c783158aea3); let mut x388: u64 = 0; let mut x389: u64 = 0; fiat_p434_mulx_u64(&mut x388, &mut x389, x366, 0xfdc1767ae2ffffff); let mut x390: u64 = 0; let mut x391: u64 = 0; fiat_p434_mulx_u64(&mut x390, &mut x391, x366, 0xffffffffffffffff); let mut x392: u64 = 0; let mut x393: u64 = 0; fiat_p434_mulx_u64(&mut x392, &mut x393, x366, 0xffffffffffffffff); let mut x394: u64 = 0; let mut x395: u64 = 0; fiat_p434_mulx_u64(&mut x394, &mut x395, x366, 0xffffffffffffffff); let mut x396: u64 = 0; let mut x397: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x396, &mut x397, 0x0, x395, x392); let mut x398: u64 = 0; let mut x399: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x398, &mut x399, x397, x393, x390); let mut x400: u64 = 0; let mut x401: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x400, &mut x401, x399, x391, x388); let mut x402: u64 = 0; let mut x403: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x402, &mut x403, x401, x389, x386); let mut x404: u64 = 0; let mut x405: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x404, &mut x405, x403, x387, x384); let mut x406: u64 = 0; let mut x407: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x406, &mut x407, x405, x385, x382); let x408: u64 = ((x407 as u64) + x383); let mut x409: u64 = 0; let mut x410: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x409, &mut x410, 0x0, x366, x394); let mut x411: u64 = 0; let mut x412: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x411, &mut x412, x410, x368, x396); let mut x413: u64 = 0; let mut x414: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x413, &mut x414, x412, x370, x398); let mut x415: u64 = 0; let mut x416: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x415, &mut x416, x414, x372, x400); let mut x417: u64 = 0; let mut x418: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x417, &mut x418, x416, x374, x402); let mut x419: u64 = 0; let mut x420: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x419, &mut x420, x418, x376, x404); let mut x421: u64 = 0; let mut x422: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x421, &mut x422, x420, x378, x406); let mut x423: u64 = 0; let mut x424: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x423, &mut x424, x422, x380, x408); let x425: u64 = ((x424 as u64) + (x381 as u64)); let mut x426: u64 = 0; let mut x427: u64 = 0; fiat_p434_mulx_u64(&mut x426, &mut x427, x5, (arg2[6])); let mut x428: u64 = 0; let mut x429: u64 = 0; fiat_p434_mulx_u64(&mut x428, &mut x429, x5, (arg2[5])); let mut x430: u64 = 0; let mut x431: u64 = 0; fiat_p434_mulx_u64(&mut x430, &mut x431, x5, (arg2[4])); let mut x432: u64 = 0; let mut x433: u64 = 0; fiat_p434_mulx_u64(&mut x432, &mut x433, x5, (arg2[3])); let mut x434: u64 = 0; let mut x435: u64 = 0; fiat_p434_mulx_u64(&mut x434, &mut x435, x5, (arg2[2])); let mut x436: u64 = 0; let mut x437: u64 = 0; fiat_p434_mulx_u64(&mut x436, &mut x437, x5, (arg2[1])); let mut x438: u64 = 0; let mut x439: u64 = 0; fiat_p434_mulx_u64(&mut x438, &mut x439, x5, (arg2[0])); let mut x440: u64 = 0; let mut x441: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x440, &mut x441, 0x0, x439, x436); let mut x442: u64 = 0; let mut x443: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x442, &mut x443, x441, x437, x434); let mut x444: u64 = 0; let mut x445: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x444, &mut x445, x443, x435, x432); let mut x446: u64 = 0; let mut x447: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x446, &mut x447, x445, x433, x430); let mut x448: u64 = 0; let mut x449: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x448, &mut x449, x447, x431, x428); let mut x450: u64 = 0; let mut x451: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x450, &mut x451, x449, x429, x426); let x452: u64 = ((x451 as u64) + x427); let mut x453: u64 = 0; let mut x454: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x453, &mut x454, 0x0, x411, x438); let mut x455: u64 = 0; let mut x456: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x455, &mut x456, x454, x413, x440); let mut x457: u64 = 0; let mut x458: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x457, &mut x458, x456, x415, x442); let mut x459: u64 = 0; let mut x460: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x459, &mut x460, x458, x417, x444); let mut x461: u64 = 0; let mut x462: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x461, &mut x462, x460, x419, x446); let mut x463: u64 = 0; let mut x464: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x463, &mut x464, x462, x421, x448); let mut x465: u64 = 0; let mut x466: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x465, &mut x466, x464, x423, x450); let mut x467: u64 = 0; let mut x468: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x467, &mut x468, x466, x425, x452); let mut x469: u64 = 0; let mut x470: u64 = 0; fiat_p434_mulx_u64(&mut x469, &mut x470, x453, 0x2341f27177344); let mut x471: u64 = 0; let mut x472: u64 = 0; fiat_p434_mulx_u64(&mut x471, &mut x472, x453, 0x6cfc5fd681c52056); let mut x473: u64 = 0; let mut x474: u64 = 0; fiat_p434_mulx_u64(&mut x473, &mut x474, x453, 0x7bc65c783158aea3); let mut x475: u64 = 0; let mut x476: u64 = 0; fiat_p434_mulx_u64(&mut x475, &mut x476, x453, 0xfdc1767ae2ffffff); let mut x477: u64 = 0; let mut x478: u64 = 0; fiat_p434_mulx_u64(&mut x477, &mut x478, x453, 0xffffffffffffffff); let mut x479: u64 = 0; let mut x480: u64 = 0; fiat_p434_mulx_u64(&mut x479, &mut x480, x453, 0xffffffffffffffff); let mut x481: u64 = 0; let mut x482: u64 = 0; fiat_p434_mulx_u64(&mut x481, &mut x482, x453, 0xffffffffffffffff); let mut x483: u64 = 0; let mut x484: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x483, &mut x484, 0x0, x482, x479); let mut x485: u64 = 0; let mut x486: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x485, &mut x486, x484, x480, x477); let mut x487: u64 = 0; let mut x488: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x487, &mut x488, x486, x478, x475); let mut x489: u64 = 0; let mut x490: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x489, &mut x490, x488, x476, x473); let mut x491: u64 = 0; let mut x492: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x491, &mut x492, x490, x474, x471); let mut x493: u64 = 0; let mut x494: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x493, &mut x494, x492, x472, x469); let x495: u64 = ((x494 as u64) + x470); let mut x496: u64 = 0; let mut x497: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x496, &mut x497, 0x0, x453, x481); let mut x498: u64 = 0; let mut x499: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x498, &mut x499, x497, x455, x483); let mut x500: u64 = 0; let mut x501: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x500, &mut x501, x499, x457, x485); let mut x502: u64 = 0; let mut x503: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x502, &mut x503, x501, x459, x487); let mut x504: u64 = 0; let mut x505: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x504, &mut x505, x503, x461, x489); let mut x506: u64 = 0; let mut x507: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x506, &mut x507, x505, x463, x491); let mut x508: u64 = 0; let mut x509: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x508, &mut x509, x507, x465, x493); let mut x510: u64 = 0; let mut x511: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x510, &mut x511, x509, x467, x495); let x512: u64 = ((x511 as u64) + (x468 as u64)); let mut x513: u64 = 0; let mut x514: u64 = 0; fiat_p434_mulx_u64(&mut x513, &mut x514, x6, (arg2[6])); let mut x515: u64 = 0; let mut x516: u64 = 0; fiat_p434_mulx_u64(&mut x515, &mut x516, x6, (arg2[5])); let mut x517: u64 = 0; let mut x518: u64 = 0; fiat_p434_mulx_u64(&mut x517, &mut x518, x6, (arg2[4])); let mut x519: u64 = 0; let mut x520: u64 = 0; fiat_p434_mulx_u64(&mut x519, &mut x520, x6, (arg2[3])); let mut x521: u64 = 0; let mut x522: u64 = 0; fiat_p434_mulx_u64(&mut x521, &mut x522, x6, (arg2[2])); let mut x523: u64 = 0; let mut x524: u64 = 0; fiat_p434_mulx_u64(&mut x523, &mut x524, x6, (arg2[1])); let mut x525: u64 = 0; let mut x526: u64 = 0; fiat_p434_mulx_u64(&mut x525, &mut x526, x6, (arg2[0])); let mut x527: u64 = 0; let mut x528: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x527, &mut x528, 0x0, x526, x523); let mut x529: u64 = 0; let mut x530: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x529, &mut x530, x528, x524, x521); let mut x531: u64 = 0; let mut x532: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x531, &mut x532, x530, x522, x519); let mut x533: u64 = 0; let mut x534: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x533, &mut x534, x532, x520, x517); let mut x535: u64 = 0; let mut x536: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x535, &mut x536, x534, x518, x515); let mut x537: u64 = 0; let mut x538: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x537, &mut x538, x536, x516, x513); let x539: u64 = ((x538 as u64) + x514); let mut x540: u64 = 0; let mut x541: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x540, &mut x541, 0x0, x498, x525); let mut x542: u64 = 0; let mut x543: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x542, &mut x543, x541, x500, x527); let mut x544: u64 = 0; let mut x545: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x544, &mut x545, x543, x502, x529); let mut x546: u64 = 0; let mut x547: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x546, &mut x547, x545, x504, x531); let mut x548: u64 = 0; let mut x549: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x548, &mut x549, x547, x506, x533); let mut x550: u64 = 0; let mut x551: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x550, &mut x551, x549, x508, x535); let mut x552: u64 = 0; let mut x553: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x552, &mut x553, x551, x510, x537); let mut x554: u64 = 0; let mut x555: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x554, &mut x555, x553, x512, x539); let mut x556: u64 = 0; let mut x557: u64 = 0; fiat_p434_mulx_u64(&mut x556, &mut x557, x540, 0x2341f27177344); let mut x558: u64 = 0; let mut x559: u64 = 0; fiat_p434_mulx_u64(&mut x558, &mut x559, x540, 0x6cfc5fd681c52056); let mut x560: u64 = 0; let mut x561: u64 = 0; fiat_p434_mulx_u64(&mut x560, &mut x561, x540, 0x7bc65c783158aea3); let mut x562: u64 = 0; let mut x563: u64 = 0; fiat_p434_mulx_u64(&mut x562, &mut x563, x540, 0xfdc1767ae2ffffff); let mut x564: u64 = 0; let mut x565: u64 = 0; fiat_p434_mulx_u64(&mut x564, &mut x565, x540, 0xffffffffffffffff); let mut x566: u64 = 0; let mut x567: u64 = 0; fiat_p434_mulx_u64(&mut x566, &mut x567, x540, 0xffffffffffffffff); let mut x568: u64 = 0; let mut x569: u64 = 0; fiat_p434_mulx_u64(&mut x568, &mut x569, x540, 0xffffffffffffffff); let mut x570: u64 = 0; let mut x571: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x570, &mut x571, 0x0, x569, x566); let mut x572: u64 = 0; let mut x573: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x572, &mut x573, x571, x567, x564); let mut x574: u64 = 0; let mut x575: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x574, &mut x575, x573, x565, x562); let mut x576: u64 = 0; let mut x577: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x576, &mut x577, x575, x563, x560); let mut x578: u64 = 0; let mut x579: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x578, &mut x579, x577, x561, x558); let mut x580: u64 = 0; let mut x581: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x580, &mut x581, x579, x559, x556); let x582: u64 = ((x581 as u64) + x557); let mut x583: u64 = 0; let mut x584: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x583, &mut x584, 0x0, x540, x568); let mut x585: u64 = 0; let mut x586: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x585, &mut x586, x584, x542, x570); let mut x587: u64 = 0; let mut x588: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x587, &mut x588, x586, x544, x572); let mut x589: u64 = 0; let mut x590: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x589, &mut x590, x588, x546, x574); let mut x591: u64 = 0; let mut x592: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x591, &mut x592, x590, x548, x576); let mut x593: u64 = 0; let mut x594: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x593, &mut x594, x592, x550, x578); let mut x595: u64 = 0; let mut x596: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x595, &mut x596, x594, x552, x580); let mut x597: u64 = 0; let mut x598: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x597, &mut x598, x596, x554, x582); let x599: u64 = ((x598 as u64) + (x555 as u64)); let mut x600: u64 = 0; let mut x601: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x600, &mut x601, 0x0, x585, 0xffffffffffffffff); let mut x602: u64 = 0; let mut x603: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x602, &mut x603, x601, x587, 0xffffffffffffffff); let mut x604: u64 = 0; let mut x605: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x604, &mut x605, x603, x589, 0xffffffffffffffff); let mut x606: u64 = 0; let mut x607: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x606, &mut x607, x605, x591, 0xfdc1767ae2ffffff); let mut x608: u64 = 0; let mut x609: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x608, &mut x609, x607, x593, 0x7bc65c783158aea3); let mut x610: u64 = 0; let mut x611: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x610, &mut x611, x609, x595, 0x6cfc5fd681c52056); let mut x612: u64 = 0; let mut x613: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x612, &mut x613, x611, x597, 0x2341f27177344); let mut x614: u64 = 0; let mut x615: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x614, &mut x615, x613, x599, (0x0 as u64)); let mut x616: u64 = 0; fiat_p434_cmovznz_u64(&mut x616, x615, x600, x585); let mut x617: u64 = 0; fiat_p434_cmovznz_u64(&mut x617, x615, x602, x587); let mut x618: u64 = 0; fiat_p434_cmovznz_u64(&mut x618, x615, x604, x589); let mut x619: u64 = 0; fiat_p434_cmovznz_u64(&mut x619, x615, x606, x591); let mut x620: u64 = 0; fiat_p434_cmovznz_u64(&mut x620, x615, x608, x593); let mut x621: u64 = 0; fiat_p434_cmovznz_u64(&mut x621, x615, x610, x595); let mut x622: u64 = 0; fiat_p434_cmovznz_u64(&mut x622, x615, x612, x597); out1[0] = x616; out1[1] = x617; out1[2] = x618; out1[3] = x619; out1[4] = x620; out1[5] = x621; out1[6] = x622; } /// The function fiat_p434_square squares a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_square(out1: &mut [u64; 7], arg1: &[u64; 7]) -> () { let x1: u64 = (arg1[1]); let x2: u64 = (arg1[2]); let x3: u64 = (arg1[3]); let x4: u64 = (arg1[4]); let x5: u64 = (arg1[5]); let x6: u64 = (arg1[6]); let x7: u64 = (arg1[0]); let mut x8: u64 = 0; let mut x9: u64 = 0; fiat_p434_mulx_u64(&mut x8, &mut x9, x7, (arg1[6])); let mut x10: u64 = 0; let mut x11: u64 = 0; fiat_p434_mulx_u64(&mut x10, &mut x11, x7, (arg1[5])); let mut x12: u64 = 0; let mut x13: u64 = 0; fiat_p434_mulx_u64(&mut x12, &mut x13, x7, (arg1[4])); let mut x14: u64 = 0; let mut x15: u64 = 0; fiat_p434_mulx_u64(&mut x14, &mut x15, x7, (arg1[3])); let mut x16: u64 = 0; let mut x17: u64 = 0; fiat_p434_mulx_u64(&mut x16, &mut x17, x7, (arg1[2])); let mut x18: u64 = 0; let mut x19: u64 = 0; fiat_p434_mulx_u64(&mut x18, &mut x19, x7, (arg1[1])); let mut x20: u64 = 0; let mut x21: u64 = 0; fiat_p434_mulx_u64(&mut x20, &mut x21, x7, (arg1[0])); let mut x22: u64 = 0; let mut x23: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x22, &mut x23, 0x0, x21, x18); let mut x24: u64 = 0; let mut x25: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x24, &mut x25, x23, x19, x16); let mut x26: u64 = 0; let mut x27: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x26, &mut x27, x25, x17, x14); let mut x28: u64 = 0; let mut x29: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x28, &mut x29, x27, x15, x12); let mut x30: u64 = 0; let mut x31: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x30, &mut x31, x29, x13, x10); let mut x32: u64 = 0; let mut x33: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x32, &mut x33, x31, x11, x8); let x34: u64 = ((x33 as u64) + x9); let mut x35: u64 = 0; let mut x36: u64 = 0; fiat_p434_mulx_u64(&mut x35, &mut x36, x20, 0x2341f27177344); let mut x37: u64 = 0; let mut x38: u64 = 0; fiat_p434_mulx_u64(&mut x37, &mut x38, x20, 0x6cfc5fd681c52056); let mut x39: u64 = 0; let mut x40: u64 = 0; fiat_p434_mulx_u64(&mut x39, &mut x40, x20, 0x7bc65c783158aea3); let mut x41: u64 = 0; let mut x42: u64 = 0; fiat_p434_mulx_u64(&mut x41, &mut x42, x20, 0xfdc1767ae2ffffff); let mut x43: u64 = 0; let mut x44: u64 = 0; fiat_p434_mulx_u64(&mut x43, &mut x44, x20, 0xffffffffffffffff); let mut x45: u64 = 0; let mut x46: u64 = 0; fiat_p434_mulx_u64(&mut x45, &mut x46, x20, 0xffffffffffffffff); let mut x47: u64 = 0; let mut x48: u64 = 0; fiat_p434_mulx_u64(&mut x47, &mut x48, x20, 0xffffffffffffffff); let mut x49: u64 = 0; let mut x50: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x49, &mut x50, 0x0, x48, x45); let mut x51: u64 = 0; let mut x52: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x51, &mut x52, x50, x46, x43); let mut x53: u64 = 0; let mut x54: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x53, &mut x54, x52, x44, x41); let mut x55: u64 = 0; let mut x56: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x55, &mut x56, x54, x42, x39); let mut x57: u64 = 0; let mut x58: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x57, &mut x58, x56, x40, x37); let mut x59: u64 = 0; let mut x60: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x59, &mut x60, x58, x38, x35); let x61: u64 = ((x60 as u64) + x36); let mut x62: u64 = 0; let mut x63: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x62, &mut x63, 0x0, x20, x47); let mut x64: u64 = 0; let mut x65: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x64, &mut x65, x63, x22, x49); let mut x66: u64 = 0; let mut x67: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x66, &mut x67, x65, x24, x51); let mut x68: u64 = 0; let mut x69: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x68, &mut x69, x67, x26, x53); let mut x70: u64 = 0; let mut x71: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x70, &mut x71, x69, x28, x55); let mut x72: u64 = 0; let mut x73: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x72, &mut x73, x71, x30, x57); let mut x74: u64 = 0; let mut x75: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x74, &mut x75, x73, x32, x59); let mut x76: u64 = 0; let mut x77: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x76, &mut x77, x75, x34, x61); let mut x78: u64 = 0; let mut x79: u64 = 0; fiat_p434_mulx_u64(&mut x78, &mut x79, x1, (arg1[6])); let mut x80: u64 = 0; let mut x81: u64 = 0; fiat_p434_mulx_u64(&mut x80, &mut x81, x1, (arg1[5])); let mut x82: u64 = 0; let mut x83: u64 = 0; fiat_p434_mulx_u64(&mut x82, &mut x83, x1, (arg1[4])); let mut x84: u64 = 0; let mut x85: u64 = 0; fiat_p434_mulx_u64(&mut x84, &mut x85, x1, (arg1[3])); let mut x86: u64 = 0; let mut x87: u64 = 0; fiat_p434_mulx_u64(&mut x86, &mut x87, x1, (arg1[2])); let mut x88: u64 = 0; let mut x89: u64 = 0; fiat_p434_mulx_u64(&mut x88, &mut x89, x1, (arg1[1])); let mut x90: u64 = 0; let mut x91: u64 = 0; fiat_p434_mulx_u64(&mut x90, &mut x91, x1, (arg1[0])); let mut x92: u64 = 0; let mut x93: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x92, &mut x93, 0x0, x91, x88); let mut x94: u64 = 0; let mut x95: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x94, &mut x95, x93, x89, x86); let mut x96: u64 = 0; let mut x97: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x96, &mut x97, x95, x87, x84); let mut x98: u64 = 0; let mut x99: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x98, &mut x99, x97, x85, x82); let mut x100: u64 = 0; let mut x101: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x100, &mut x101, x99, x83, x80); let mut x102: u64 = 0; let mut x103: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x102, &mut x103, x101, x81, x78); let x104: u64 = ((x103 as u64) + x79); let mut x105: u64 = 0; let mut x106: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x105, &mut x106, 0x0, x64, x90); let mut x107: u64 = 0; let mut x108: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x107, &mut x108, x106, x66, x92); let mut x109: u64 = 0; let mut x110: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x109, &mut x110, x108, x68, x94); let mut x111: u64 = 0; let mut x112: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x111, &mut x112, x110, x70, x96); let mut x113: u64 = 0; let mut x114: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x113, &mut x114, x112, x72, x98); let mut x115: u64 = 0; let mut x116: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x115, &mut x116, x114, x74, x100); let mut x117: u64 = 0; let mut x118: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x117, &mut x118, x116, x76, x102); let mut x119: u64 = 0; let mut x120: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x119, &mut x120, x118, (x77 as u64), x104); let mut x121: u64 = 0; let mut x122: u64 = 0; fiat_p434_mulx_u64(&mut x121, &mut x122, x105, 0x2341f27177344); let mut x123: u64 = 0; let mut x124: u64 = 0; fiat_p434_mulx_u64(&mut x123, &mut x124, x105, 0x6cfc5fd681c52056); let mut x125: u64 = 0; let mut x126: u64 = 0; fiat_p434_mulx_u64(&mut x125, &mut x126, x105, 0x7bc65c783158aea3); let mut x127: u64 = 0; let mut x128: u64 = 0; fiat_p434_mulx_u64(&mut x127, &mut x128, x105, 0xfdc1767ae2ffffff); let mut x129: u64 = 0; let mut x130: u64 = 0; fiat_p434_mulx_u64(&mut x129, &mut x130, x105, 0xffffffffffffffff); let mut x131: u64 = 0; let mut x132: u64 = 0; fiat_p434_mulx_u64(&mut x131, &mut x132, x105, 0xffffffffffffffff); let mut x133: u64 = 0; let mut x134: u64 = 0; fiat_p434_mulx_u64(&mut x133, &mut x134, x105, 0xffffffffffffffff); let mut x135: u64 = 0; let mut x136: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x135, &mut x136, 0x0, x134, x131); let mut x137: u64 = 0; let mut x138: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x137, &mut x138, x136, x132, x129); let mut x139: u64 = 0; let mut x140: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x139, &mut x140, x138, x130, x127); let mut x141: u64 = 0; let mut x142: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x141, &mut x142, x140, x128, x125); let mut x143: u64 = 0; let mut x144: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x143, &mut x144, x142, x126, x123); let mut x145: u64 = 0; let mut x146: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x145, &mut x146, x144, x124, x121); let x147: u64 = ((x146 as u64) + x122); let mut x148: u64 = 0; let mut x149: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x148, &mut x149, 0x0, x105, x133); let mut x150: u64 = 0; let mut x151: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x150, &mut x151, x149, x107, x135); let mut x152: u64 = 0; let mut x153: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x152, &mut x153, x151, x109, x137); let mut x154: u64 = 0; let mut x155: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x154, &mut x155, x153, x111, x139); let mut x156: u64 = 0; let mut x157: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x156, &mut x157, x155, x113, x141); let mut x158: u64 = 0; let mut x159: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x158, &mut x159, x157, x115, x143); let mut x160: u64 = 0; let mut x161: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x160, &mut x161, x159, x117, x145); let mut x162: u64 = 0; let mut x163: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x162, &mut x163, x161, x119, x147); let x164: u64 = ((x163 as u64) + (x120 as u64)); let mut x165: u64 = 0; let mut x166: u64 = 0; fiat_p434_mulx_u64(&mut x165, &mut x166, x2, (arg1[6])); let mut x167: u64 = 0; let mut x168: u64 = 0; fiat_p434_mulx_u64(&mut x167, &mut x168, x2, (arg1[5])); let mut x169: u64 = 0; let mut x170: u64 = 0; fiat_p434_mulx_u64(&mut x169, &mut x170, x2, (arg1[4])); let mut x171: u64 = 0; let mut x172: u64 = 0; fiat_p434_mulx_u64(&mut x171, &mut x172, x2, (arg1[3])); let mut x173: u64 = 0; let mut x174: u64 = 0; fiat_p434_mulx_u64(&mut x173, &mut x174, x2, (arg1[2])); let mut x175: u64 = 0; let mut x176: u64 = 0; fiat_p434_mulx_u64(&mut x175, &mut x176, x2, (arg1[1])); let mut x177: u64 = 0; let mut x178: u64 = 0; fiat_p434_mulx_u64(&mut x177, &mut x178, x2, (arg1[0])); let mut x179: u64 = 0; let mut x180: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x179, &mut x180, 0x0, x178, x175); let mut x181: u64 = 0; let mut x182: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x181, &mut x182, x180, x176, x173); let mut x183: u64 = 0; let mut x184: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x183, &mut x184, x182, x174, x171); let mut x185: u64 = 0; let mut x186: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x185, &mut x186, x184, x172, x169); let mut x187: u64 = 0; let mut x188: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x187, &mut x188, x186, x170, x167); let mut x189: u64 = 0; let mut x190: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x189, &mut x190, x188, x168, x165); let x191: u64 = ((x190 as u64) + x166); let mut x192: u64 = 0; let mut x193: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x192, &mut x193, 0x0, x150, x177); let mut x194: u64 = 0; let mut x195: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x194, &mut x195, x193, x152, x179); let mut x196: u64 = 0; let mut x197: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x196, &mut x197, x195, x154, x181); let mut x198: u64 = 0; let mut x199: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x198, &mut x199, x197, x156, x183); let mut x200: u64 = 0; let mut x201: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x200, &mut x201, x199, x158, x185); let mut x202: u64 = 0; let mut x203: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x202, &mut x203, x201, x160, x187); let mut x204: u64 = 0; let mut x205: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x204, &mut x205, x203, x162, x189); let mut x206: u64 = 0; let mut x207: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x206, &mut x207, x205, x164, x191); let mut x208: u64 = 0; let mut x209: u64 = 0; fiat_p434_mulx_u64(&mut x208, &mut x209, x192, 0x2341f27177344); let mut x210: u64 = 0; let mut x211: u64 = 0; fiat_p434_mulx_u64(&mut x210, &mut x211, x192, 0x6cfc5fd681c52056); let mut x212: u64 = 0; let mut x213: u64 = 0; fiat_p434_mulx_u64(&mut x212, &mut x213, x192, 0x7bc65c783158aea3); let mut x214: u64 = 0; let mut x215: u64 = 0; fiat_p434_mulx_u64(&mut x214, &mut x215, x192, 0xfdc1767ae2ffffff); let mut x216: u64 = 0; let mut x217: u64 = 0; fiat_p434_mulx_u64(&mut x216, &mut x217, x192, 0xffffffffffffffff); let mut x218: u64 = 0; let mut x219: u64 = 0; fiat_p434_mulx_u64(&mut x218, &mut x219, x192, 0xffffffffffffffff); let mut x220: u64 = 0; let mut x221: u64 = 0; fiat_p434_mulx_u64(&mut x220, &mut x221, x192, 0xffffffffffffffff); let mut x222: u64 = 0; let mut x223: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x222, &mut x223, 0x0, x221, x218); let mut x224: u64 = 0; let mut x225: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x224, &mut x225, x223, x219, x216); let mut x226: u64 = 0; let mut x227: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x226, &mut x227, x225, x217, x214); let mut x228: u64 = 0; let mut x229: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x228, &mut x229, x227, x215, x212); let mut x230: u64 = 0; let mut x231: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x230, &mut x231, x229, x213, x210); let mut x232: u64 = 0; let mut x233: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x232, &mut x233, x231, x211, x208); let x234: u64 = ((x233 as u64) + x209); let mut x235: u64 = 0; let mut x236: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x235, &mut x236, 0x0, x192, x220); let mut x237: u64 = 0; let mut x238: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x237, &mut x238, x236, x194, x222); let mut x239: u64 = 0; let mut x240: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x239, &mut x240, x238, x196, x224); let mut x241: u64 = 0; let mut x242: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x241, &mut x242, x240, x198, x226); let mut x243: u64 = 0; let mut x244: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x243, &mut x244, x242, x200, x228); let mut x245: u64 = 0; let mut x246: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x245, &mut x246, x244, x202, x230); let mut x247: u64 = 0; let mut x248: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x247, &mut x248, x246, x204, x232); let mut x249: u64 = 0; let mut x250: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x249, &mut x250, x248, x206, x234); let x251: u64 = ((x250 as u64) + (x207 as u64)); let mut x252: u64 = 0; let mut x253: u64 = 0; fiat_p434_mulx_u64(&mut x252, &mut x253, x3, (arg1[6])); let mut x254: u64 = 0; let mut x255: u64 = 0; fiat_p434_mulx_u64(&mut x254, &mut x255, x3, (arg1[5])); let mut x256: u64 = 0; let mut x257: u64 = 0; fiat_p434_mulx_u64(&mut x256, &mut x257, x3, (arg1[4])); let mut x258: u64 = 0; let mut x259: u64 = 0; fiat_p434_mulx_u64(&mut x258, &mut x259, x3, (arg1[3])); let mut x260: u64 = 0; let mut x261: u64 = 0; fiat_p434_mulx_u64(&mut x260, &mut x261, x3, (arg1[2])); let mut x262: u64 = 0; let mut x263: u64 = 0; fiat_p434_mulx_u64(&mut x262, &mut x263, x3, (arg1[1])); let mut x264: u64 = 0; let mut x265: u64 = 0; fiat_p434_mulx_u64(&mut x264, &mut x265, x3, (arg1[0])); let mut x266: u64 = 0; let mut x267: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x266, &mut x267, 0x0, x265, x262); let mut x268: u64 = 0; let mut x269: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x268, &mut x269, x267, x263, x260); let mut x270: u64 = 0; let mut x271: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x270, &mut x271, x269, x261, x258); let mut x272: u64 = 0; let mut x273: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x272, &mut x273, x271, x259, x256); let mut x274: u64 = 0; let mut x275: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x274, &mut x275, x273, x257, x254); let mut x276: u64 = 0; let mut x277: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x276, &mut x277, x275, x255, x252); let x278: u64 = ((x277 as u64) + x253); let mut x279: u64 = 0; let mut x280: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x279, &mut x280, 0x0, x237, x264); let mut x281: u64 = 0; let mut x282: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x281, &mut x282, x280, x239, x266); let mut x283: u64 = 0; let mut x284: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x283, &mut x284, x282, x241, x268); let mut x285: u64 = 0; let mut x286: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x285, &mut x286, x284, x243, x270); let mut x287: u64 = 0; let mut x288: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x287, &mut x288, x286, x245, x272); let mut x289: u64 = 0; let mut x290: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x289, &mut x290, x288, x247, x274); let mut x291: u64 = 0; let mut x292: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x291, &mut x292, x290, x249, x276); let mut x293: u64 = 0; let mut x294: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x293, &mut x294, x292, x251, x278); let mut x295: u64 = 0; let mut x296: u64 = 0; fiat_p434_mulx_u64(&mut x295, &mut x296, x279, 0x2341f27177344); let mut x297: u64 = 0; let mut x298: u64 = 0; fiat_p434_mulx_u64(&mut x297, &mut x298, x279, 0x6cfc5fd681c52056); let mut x299: u64 = 0; let mut x300: u64 = 0; fiat_p434_mulx_u64(&mut x299, &mut x300, x279, 0x7bc65c783158aea3); let mut x301: u64 = 0; let mut x302: u64 = 0; fiat_p434_mulx_u64(&mut x301, &mut x302, x279, 0xfdc1767ae2ffffff); let mut x303: u64 = 0; let mut x304: u64 = 0; fiat_p434_mulx_u64(&mut x303, &mut x304, x279, 0xffffffffffffffff); let mut x305: u64 = 0; let mut x306: u64 = 0; fiat_p434_mulx_u64(&mut x305, &mut x306, x279, 0xffffffffffffffff); let mut x307: u64 = 0; let mut x308: u64 = 0; fiat_p434_mulx_u64(&mut x307, &mut x308, x279, 0xffffffffffffffff); let mut x309: u64 = 0; let mut x310: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x309, &mut x310, 0x0, x308, x305); let mut x311: u64 = 0; let mut x312: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x311, &mut x312, x310, x306, x303); let mut x313: u64 = 0; let mut x314: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x313, &mut x314, x312, x304, x301); let mut x315: u64 = 0; let mut x316: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x315, &mut x316, x314, x302, x299); let mut x317: u64 = 0; let mut x318: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x317, &mut x318, x316, x300, x297); let mut x319: u64 = 0; let mut x320: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x319, &mut x320, x318, x298, x295); let x321: u64 = ((x320 as u64) + x296); let mut x322: u64 = 0; let mut x323: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x322, &mut x323, 0x0, x279, x307); let mut x324: u64 = 0; let mut x325: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x324, &mut x325, x323, x281, x309); let mut x326: u64 = 0; let mut x327: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x326, &mut x327, x325, x283, x311); let mut x328: u64 = 0; let mut x329: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x328, &mut x329, x327, x285, x313); let mut x330: u64 = 0; let mut x331: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x330, &mut x331, x329, x287, x315); let mut x332: u64 = 0; let mut x333: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x332, &mut x333, x331, x289, x317); let mut x334: u64 = 0; let mut x335: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x334, &mut x335, x333, x291, x319); let mut x336: u64 = 0; let mut x337: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x336, &mut x337, x335, x293, x321); let x338: u64 = ((x337 as u64) + (x294 as u64)); let mut x339: u64 = 0; let mut x340: u64 = 0; fiat_p434_mulx_u64(&mut x339, &mut x340, x4, (arg1[6])); let mut x341: u64 = 0; let mut x342: u64 = 0; fiat_p434_mulx_u64(&mut x341, &mut x342, x4, (arg1[5])); let mut x343: u64 = 0; let mut x344: u64 = 0; fiat_p434_mulx_u64(&mut x343, &mut x344, x4, (arg1[4])); let mut x345: u64 = 0; let mut x346: u64 = 0; fiat_p434_mulx_u64(&mut x345, &mut x346, x4, (arg1[3])); let mut x347: u64 = 0; let mut x348: u64 = 0; fiat_p434_mulx_u64(&mut x347, &mut x348, x4, (arg1[2])); let mut x349: u64 = 0; let mut x350: u64 = 0; fiat_p434_mulx_u64(&mut x349, &mut x350, x4, (arg1[1])); let mut x351: u64 = 0; let mut x352: u64 = 0; fiat_p434_mulx_u64(&mut x351, &mut x352, x4, (arg1[0])); let mut x353: u64 = 0; let mut x354: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x353, &mut x354, 0x0, x352, x349); let mut x355: u64 = 0; let mut x356: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x355, &mut x356, x354, x350, x347); let mut x357: u64 = 0; let mut x358: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x357, &mut x358, x356, x348, x345); let mut x359: u64 = 0; let mut x360: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x359, &mut x360, x358, x346, x343); let mut x361: u64 = 0; let mut x362: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x361, &mut x362, x360, x344, x341); let mut x363: u64 = 0; let mut x364: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x363, &mut x364, x362, x342, x339); let x365: u64 = ((x364 as u64) + x340); let mut x366: u64 = 0; let mut x367: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x366, &mut x367, 0x0, x324, x351); let mut x368: u64 = 0; let mut x369: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x368, &mut x369, x367, x326, x353); let mut x370: u64 = 0; let mut x371: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x370, &mut x371, x369, x328, x355); let mut x372: u64 = 0; let mut x373: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x372, &mut x373, x371, x330, x357); let mut x374: u64 = 0; let mut x375: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x374, &mut x375, x373, x332, x359); let mut x376: u64 = 0; let mut x377: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x376, &mut x377, x375, x334, x361); let mut x378: u64 = 0; let mut x379: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x378, &mut x379, x377, x336, x363); let mut x380: u64 = 0; let mut x381: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x380, &mut x381, x379, x338, x365); let mut x382: u64 = 0; let mut x383: u64 = 0; fiat_p434_mulx_u64(&mut x382, &mut x383, x366, 0x2341f27177344); let mut x384: u64 = 0; let mut x385: u64 = 0; fiat_p434_mulx_u64(&mut x384, &mut x385, x366, 0x6cfc5fd681c52056); let mut x386: u64 = 0; let mut x387: u64 = 0; fiat_p434_mulx_u64(&mut x386, &mut x387, x366, 0x7bc65c783158aea3); let mut x388: u64 = 0; let mut x389: u64 = 0; fiat_p434_mulx_u64(&mut x388, &mut x389, x366, 0xfdc1767ae2ffffff); let mut x390: u64 = 0; let mut x391: u64 = 0; fiat_p434_mulx_u64(&mut x390, &mut x391, x366, 0xffffffffffffffff); let mut x392: u64 = 0; let mut x393: u64 = 0; fiat_p434_mulx_u64(&mut x392, &mut x393, x366, 0xffffffffffffffff); let mut x394: u64 = 0; let mut x395: u64 = 0; fiat_p434_mulx_u64(&mut x394, &mut x395, x366, 0xffffffffffffffff); let mut x396: u64 = 0; let mut x397: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x396, &mut x397, 0x0, x395, x392); let mut x398: u64 = 0; let mut x399: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x398, &mut x399, x397, x393, x390); let mut x400: u64 = 0; let mut x401: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x400, &mut x401, x399, x391, x388); let mut x402: u64 = 0; let mut x403: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x402, &mut x403, x401, x389, x386); let mut x404: u64 = 0; let mut x405: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x404, &mut x405, x403, x387, x384); let mut x406: u64 = 0; let mut x407: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x406, &mut x407, x405, x385, x382); let x408: u64 = ((x407 as u64) + x383); let mut x409: u64 = 0; let mut x410: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x409, &mut x410, 0x0, x366, x394); let mut x411: u64 = 0; let mut x412: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x411, &mut x412, x410, x368, x396); let mut x413: u64 = 0; let mut x414: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x413, &mut x414, x412, x370, x398); let mut x415: u64 = 0; let mut x416: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x415, &mut x416, x414, x372, x400); let mut x417: u64 = 0; let mut x418: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x417, &mut x418, x416, x374, x402); let mut x419: u64 = 0; let mut x420: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x419, &mut x420, x418, x376, x404); let mut x421: u64 = 0; let mut x422: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x421, &mut x422, x420, x378, x406); let mut x423: u64 = 0; let mut x424: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x423, &mut x424, x422, x380, x408); let x425: u64 = ((x424 as u64) + (x381 as u64)); let mut x426: u64 = 0; let mut x427: u64 = 0; fiat_p434_mulx_u64(&mut x426, &mut x427, x5, (arg1[6])); let mut x428: u64 = 0; let mut x429: u64 = 0; fiat_p434_mulx_u64(&mut x428, &mut x429, x5, (arg1[5])); let mut x430: u64 = 0; let mut x431: u64 = 0; fiat_p434_mulx_u64(&mut x430, &mut x431, x5, (arg1[4])); let mut x432: u64 = 0; let mut x433: u64 = 0; fiat_p434_mulx_u64(&mut x432, &mut x433, x5, (arg1[3])); let mut x434: u64 = 0; let mut x435: u64 = 0; fiat_p434_mulx_u64(&mut x434, &mut x435, x5, (arg1[2])); let mut x436: u64 = 0; let mut x437: u64 = 0; fiat_p434_mulx_u64(&mut x436, &mut x437, x5, (arg1[1])); let mut x438: u64 = 0; let mut x439: u64 = 0; fiat_p434_mulx_u64(&mut x438, &mut x439, x5, (arg1[0])); let mut x440: u64 = 0; let mut x441: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x440, &mut x441, 0x0, x439, x436); let mut x442: u64 = 0; let mut x443: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x442, &mut x443, x441, x437, x434); let mut x444: u64 = 0; let mut x445: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x444, &mut x445, x443, x435, x432); let mut x446: u64 = 0; let mut x447: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x446, &mut x447, x445, x433, x430); let mut x448: u64 = 0; let mut x449: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x448, &mut x449, x447, x431, x428); let mut x450: u64 = 0; let mut x451: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x450, &mut x451, x449, x429, x426); let x452: u64 = ((x451 as u64) + x427); let mut x453: u64 = 0; let mut x454: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x453, &mut x454, 0x0, x411, x438); let mut x455: u64 = 0; let mut x456: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x455, &mut x456, x454, x413, x440); let mut x457: u64 = 0; let mut x458: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x457, &mut x458, x456, x415, x442); let mut x459: u64 = 0; let mut x460: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x459, &mut x460, x458, x417, x444); let mut x461: u64 = 0; let mut x462: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x461, &mut x462, x460, x419, x446); let mut x463: u64 = 0; let mut x464: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x463, &mut x464, x462, x421, x448); let mut x465: u64 = 0; let mut x466: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x465, &mut x466, x464, x423, x450); let mut x467: u64 = 0; let mut x468: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x467, &mut x468, x466, x425, x452); let mut x469: u64 = 0; let mut x470: u64 = 0; fiat_p434_mulx_u64(&mut x469, &mut x470, x453, 0x2341f27177344); let mut x471: u64 = 0; let mut x472: u64 = 0; fiat_p434_mulx_u64(&mut x471, &mut x472, x453, 0x6cfc5fd681c52056); let mut x473: u64 = 0; let mut x474: u64 = 0; fiat_p434_mulx_u64(&mut x473, &mut x474, x453, 0x7bc65c783158aea3); let mut x475: u64 = 0; let mut x476: u64 = 0; fiat_p434_mulx_u64(&mut x475, &mut x476, x453, 0xfdc1767ae2ffffff); let mut x477: u64 = 0; let mut x478: u64 = 0; fiat_p434_mulx_u64(&mut x477, &mut x478, x453, 0xffffffffffffffff); let mut x479: u64 = 0; let mut x480: u64 = 0; fiat_p434_mulx_u64(&mut x479, &mut x480, x453, 0xffffffffffffffff); let mut x481: u64 = 0; let mut x482: u64 = 0; fiat_p434_mulx_u64(&mut x481, &mut x482, x453, 0xffffffffffffffff); let mut x483: u64 = 0; let mut x484: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x483, &mut x484, 0x0, x482, x479); let mut x485: u64 = 0; let mut x486: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x485, &mut x486, x484, x480, x477); let mut x487: u64 = 0; let mut x488: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x487, &mut x488, x486, x478, x475); let mut x489: u64 = 0; let mut x490: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x489, &mut x490, x488, x476, x473); let mut x491: u64 = 0; let mut x492: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x491, &mut x492, x490, x474, x471); let mut x493: u64 = 0; let mut x494: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x493, &mut x494, x492, x472, x469); let x495: u64 = ((x494 as u64) + x470); let mut x496: u64 = 0; let mut x497: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x496, &mut x497, 0x0, x453, x481); let mut x498: u64 = 0; let mut x499: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x498, &mut x499, x497, x455, x483); let mut x500: u64 = 0; let mut x501: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x500, &mut x501, x499, x457, x485); let mut x502: u64 = 0; let mut x503: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x502, &mut x503, x501, x459, x487); let mut x504: u64 = 0; let mut x505: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x504, &mut x505, x503, x461, x489); let mut x506: u64 = 0; let mut x507: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x506, &mut x507, x505, x463, x491); let mut x508: u64 = 0; let mut x509: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x508, &mut x509, x507, x465, x493); let mut x510: u64 = 0; let mut x511: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x510, &mut x511, x509, x467, x495); let x512: u64 = ((x511 as u64) + (x468 as u64)); let mut x513: u64 = 0; let mut x514: u64 = 0; fiat_p434_mulx_u64(&mut x513, &mut x514, x6, (arg1[6])); let mut x515: u64 = 0; let mut x516: u64 = 0; fiat_p434_mulx_u64(&mut x515, &mut x516, x6, (arg1[5])); let mut x517: u64 = 0; let mut x518: u64 = 0; fiat_p434_mulx_u64(&mut x517, &mut x518, x6, (arg1[4])); let mut x519: u64 = 0; let mut x520: u64 = 0; fiat_p434_mulx_u64(&mut x519, &mut x520, x6, (arg1[3])); let mut x521: u64 = 0; let mut x522: u64 = 0; fiat_p434_mulx_u64(&mut x521, &mut x522, x6, (arg1[2])); let mut x523: u64 = 0; let mut x524: u64 = 0; fiat_p434_mulx_u64(&mut x523, &mut x524, x6, (arg1[1])); let mut x525: u64 = 0; let mut x526: u64 = 0; fiat_p434_mulx_u64(&mut x525, &mut x526, x6, (arg1[0])); let mut x527: u64 = 0; let mut x528: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x527, &mut x528, 0x0, x526, x523); let mut x529: u64 = 0; let mut x530: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x529, &mut x530, x528, x524, x521); let mut x531: u64 = 0; let mut x532: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x531, &mut x532, x530, x522, x519); let mut x533: u64 = 0; let mut x534: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x533, &mut x534, x532, x520, x517); let mut x535: u64 = 0; let mut x536: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x535, &mut x536, x534, x518, x515); let mut x537: u64 = 0; let mut x538: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x537, &mut x538, x536, x516, x513); let x539: u64 = ((x538 as u64) + x514); let mut x540: u64 = 0; let mut x541: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x540, &mut x541, 0x0, x498, x525); let mut x542: u64 = 0; let mut x543: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x542, &mut x543, x541, x500, x527); let mut x544: u64 = 0; let mut x545: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x544, &mut x545, x543, x502, x529); let mut x546: u64 = 0; let mut x547: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x546, &mut x547, x545, x504, x531); let mut x548: u64 = 0; let mut x549: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x548, &mut x549, x547, x506, x533); let mut x550: u64 = 0; let mut x551: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x550, &mut x551, x549, x508, x535); let mut x552: u64 = 0; let mut x553: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x552, &mut x553, x551, x510, x537); let mut x554: u64 = 0; let mut x555: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x554, &mut x555, x553, x512, x539); let mut x556: u64 = 0; let mut x557: u64 = 0; fiat_p434_mulx_u64(&mut x556, &mut x557, x540, 0x2341f27177344); let mut x558: u64 = 0; let mut x559: u64 = 0; fiat_p434_mulx_u64(&mut x558, &mut x559, x540, 0x6cfc5fd681c52056); let mut x560: u64 = 0; let mut x561: u64 = 0; fiat_p434_mulx_u64(&mut x560, &mut x561, x540, 0x7bc65c783158aea3); let mut x562: u64 = 0; let mut x563: u64 = 0; fiat_p434_mulx_u64(&mut x562, &mut x563, x540, 0xfdc1767ae2ffffff); let mut x564: u64 = 0; let mut x565: u64 = 0; fiat_p434_mulx_u64(&mut x564, &mut x565, x540, 0xffffffffffffffff); let mut x566: u64 = 0; let mut x567: u64 = 0; fiat_p434_mulx_u64(&mut x566, &mut x567, x540, 0xffffffffffffffff); let mut x568: u64 = 0; let mut x569: u64 = 0; fiat_p434_mulx_u64(&mut x568, &mut x569, x540, 0xffffffffffffffff); let mut x570: u64 = 0; let mut x571: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x570, &mut x571, 0x0, x569, x566); let mut x572: u64 = 0; let mut x573: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x572, &mut x573, x571, x567, x564); let mut x574: u64 = 0; let mut x575: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x574, &mut x575, x573, x565, x562); let mut x576: u64 = 0; let mut x577: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x576, &mut x577, x575, x563, x560); let mut x578: u64 = 0; let mut x579: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x578, &mut x579, x577, x561, x558); let mut x580: u64 = 0; let mut x581: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x580, &mut x581, x579, x559, x556); let x582: u64 = ((x581 as u64) + x557); let mut x583: u64 = 0; let mut x584: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x583, &mut x584, 0x0, x540, x568); let mut x585: u64 = 0; let mut x586: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x585, &mut x586, x584, x542, x570); let mut x587: u64 = 0; let mut x588: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x587, &mut x588, x586, x544, x572); let mut x589: u64 = 0; let mut x590: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x589, &mut x590, x588, x546, x574); let mut x591: u64 = 0; let mut x592: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x591, &mut x592, x590, x548, x576); let mut x593: u64 = 0; let mut x594: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x593, &mut x594, x592, x550, x578); let mut x595: u64 = 0; let mut x596: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x595, &mut x596, x594, x552, x580); let mut x597: u64 = 0; let mut x598: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x597, &mut x598, x596, x554, x582); let x599: u64 = ((x598 as u64) + (x555 as u64)); let mut x600: u64 = 0; let mut x601: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x600, &mut x601, 0x0, x585, 0xffffffffffffffff); let mut x602: u64 = 0; let mut x603: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x602, &mut x603, x601, x587, 0xffffffffffffffff); let mut x604: u64 = 0; let mut x605: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x604, &mut x605, x603, x589, 0xffffffffffffffff); let mut x606: u64 = 0; let mut x607: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x606, &mut x607, x605, x591, 0xfdc1767ae2ffffff); let mut x608: u64 = 0; let mut x609: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x608, &mut x609, x607, x593, 0x7bc65c783158aea3); let mut x610: u64 = 0; let mut x611: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x610, &mut x611, x609, x595, 0x6cfc5fd681c52056); let mut x612: u64 = 0; let mut x613: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x612, &mut x613, x611, x597, 0x2341f27177344); let mut x614: u64 = 0; let mut x615: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x614, &mut x615, x613, x599, (0x0 as u64)); let mut x616: u64 = 0; fiat_p434_cmovznz_u64(&mut x616, x615, x600, x585); let mut x617: u64 = 0; fiat_p434_cmovznz_u64(&mut x617, x615, x602, x587); let mut x618: u64 = 0; fiat_p434_cmovznz_u64(&mut x618, x615, x604, x589); let mut x619: u64 = 0; fiat_p434_cmovznz_u64(&mut x619, x615, x606, x591); let mut x620: u64 = 0; fiat_p434_cmovznz_u64(&mut x620, x615, x608, x593); let mut x621: u64 = 0; fiat_p434_cmovznz_u64(&mut x621, x615, x610, x595); let mut x622: u64 = 0; fiat_p434_cmovznz_u64(&mut x622, x615, x612, x597); out1[0] = x616; out1[1] = x617; out1[2] = x618; out1[3] = x619; out1[4] = x620; out1[5] = x621; out1[6] = x622; } /// The function fiat_p434_add adds two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_add(out1: &mut [u64; 7], arg1: &[u64; 7], arg2: &[u64; 7]) -> () { let mut x1: u64 = 0; let mut x2: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x1, &mut x2, 0x0, (arg1[0]), (arg2[0])); let mut x3: u64 = 0; let mut x4: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x3, &mut x4, x2, (arg1[1]), (arg2[1])); let mut x5: u64 = 0; let mut x6: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x5, &mut x6, x4, (arg1[2]), (arg2[2])); let mut x7: u64 = 0; let mut x8: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x7, &mut x8, x6, (arg1[3]), (arg2[3])); let mut x9: u64 = 0; let mut x10: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x9, &mut x10, x8, (arg1[4]), (arg2[4])); let mut x11: u64 = 0; let mut x12: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x11, &mut x12, x10, (arg1[5]), (arg2[5])); let mut x13: u64 = 0; let mut x14: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x13, &mut x14, x12, (arg1[6]), (arg2[6])); let mut x15: u64 = 0; let mut x16: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x15, &mut x16, 0x0, x1, 0xffffffffffffffff); let mut x17: u64 = 0; let mut x18: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x17, &mut x18, x16, x3, 0xffffffffffffffff); let mut x19: u64 = 0; let mut x20: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x19, &mut x20, x18, x5, 0xffffffffffffffff); let mut x21: u64 = 0; let mut x22: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x21, &mut x22, x20, x7, 0xfdc1767ae2ffffff); let mut x23: u64 = 0; let mut x24: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x23, &mut x24, x22, x9, 0x7bc65c783158aea3); let mut x25: u64 = 0; let mut x26: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x25, &mut x26, x24, x11, 0x6cfc5fd681c52056); let mut x27: u64 = 0; let mut x28: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x27, &mut x28, x26, x13, 0x2341f27177344); let mut x29: u64 = 0; let mut x30: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x29, &mut x30, x28, (x14 as u64), (0x0 as u64)); let mut x31: u64 = 0; fiat_p434_cmovznz_u64(&mut x31, x30, x15, x1); let mut x32: u64 = 0; fiat_p434_cmovznz_u64(&mut x32, x30, x17, x3); let mut x33: u64 = 0; fiat_p434_cmovznz_u64(&mut x33, x30, x19, x5); let mut x34: u64 = 0; fiat_p434_cmovznz_u64(&mut x34, x30, x21, x7); let mut x35: u64 = 0; fiat_p434_cmovznz_u64(&mut x35, x30, x23, x9); let mut x36: u64 = 0; fiat_p434_cmovznz_u64(&mut x36, x30, x25, x11); let mut x37: u64 = 0; fiat_p434_cmovznz_u64(&mut x37, x30, x27, x13); out1[0] = x31; out1[1] = x32; out1[2] = x33; out1[3] = x34; out1[4] = x35; out1[5] = x36; out1[6] = x37; } /// The function fiat_p434_sub subtracts two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_sub(out1: &mut [u64; 7], arg1: &[u64; 7], arg2: &[u64; 7]) -> () { let mut x1: u64 = 0; let mut x2: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x1, &mut x2, 0x0, (arg1[0]), (arg2[0])); let mut x3: u64 = 0; let mut x4: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x3, &mut x4, x2, (arg1[1]), (arg2[1])); let mut x5: u64 = 0; let mut x6: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x5, &mut x6, x4, (arg1[2]), (arg2[2])); let mut x7: u64 = 0; let mut x8: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x7, &mut x8, x6, (arg1[3]), (arg2[3])); let mut x9: u64 = 0; let mut x10: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x9, &mut x10, x8, (arg1[4]), (arg2[4])); let mut x11: u64 = 0; let mut x12: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x11, &mut x12, x10, (arg1[5]), (arg2[5])); let mut x13: u64 = 0; let mut x14: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x13, &mut x14, x12, (arg1[6]), (arg2[6])); let mut x15: u64 = 0; fiat_p434_cmovznz_u64(&mut x15, x14, (0x0 as u64), 0xffffffffffffffff); let mut x16: u64 = 0; let mut x17: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x16, &mut x17, 0x0, x1, x15); let mut x18: u64 = 0; let mut x19: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x18, &mut x19, x17, x3, x15); let mut x20: u64 = 0; let mut x21: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x20, &mut x21, x19, x5, x15); let mut x22: u64 = 0; let mut x23: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x22, &mut x23, x21, x7, (x15 & 0xfdc1767ae2ffffff)); let mut x24: u64 = 0; let mut x25: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x24, &mut x25, x23, x9, (x15 & 0x7bc65c783158aea3)); let mut x26: u64 = 0; let mut x27: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x26, &mut x27, x25, x11, (x15 & 0x6cfc5fd681c52056)); let mut x28: u64 = 0; let mut x29: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x28, &mut x29, x27, x13, (x15 & 0x2341f27177344)); out1[0] = x16; out1[1] = x18; out1[2] = x20; out1[3] = x22; out1[4] = x24; out1[5] = x26; out1[6] = x28; } /// The function fiat_p434_opp negates a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_opp(out1: &mut [u64; 7], arg1: &[u64; 7]) -> () { let mut x1: u64 = 0; let mut x2: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x1, &mut x2, 0x0, (0x0 as u64), (arg1[0])); let mut x3: u64 = 0; let mut x4: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x3, &mut x4, x2, (0x0 as u64), (arg1[1])); let mut x5: u64 = 0; let mut x6: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x5, &mut x6, x4, (0x0 as u64), (arg1[2])); let mut x7: u64 = 0; let mut x8: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x7, &mut x8, x6, (0x0 as u64), (arg1[3])); let mut x9: u64 = 0; let mut x10: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x9, &mut x10, x8, (0x0 as u64), (arg1[4])); let mut x11: u64 = 0; let mut x12: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x11, &mut x12, x10, (0x0 as u64), (arg1[5])); let mut x13: u64 = 0; let mut x14: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x13, &mut x14, x12, (0x0 as u64), (arg1[6])); let mut x15: u64 = 0; fiat_p434_cmovznz_u64(&mut x15, x14, (0x0 as u64), 0xffffffffffffffff); let mut x16: u64 = 0; let mut x17: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x16, &mut x17, 0x0, x1, x15); let mut x18: u64 = 0; let mut x19: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x18, &mut x19, x17, x3, x15); let mut x20: u64 = 0; let mut x21: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x20, &mut x21, x19, x5, x15); let mut x22: u64 = 0; let mut x23: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x22, &mut x23, x21, x7, (x15 & 0xfdc1767ae2ffffff)); let mut x24: u64 = 0; let mut x25: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x24, &mut x25, x23, x9, (x15 & 0x7bc65c783158aea3)); let mut x26: u64 = 0; let mut x27: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x26, &mut x27, x25, x11, (x15 & 0x6cfc5fd681c52056)); let mut x28: u64 = 0; let mut x29: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x28, &mut x29, x27, x13, (x15 & 0x2341f27177344)); out1[0] = x16; out1[1] = x18; out1[2] = x20; out1[3] = x22; out1[4] = x24; out1[5] = x26; out1[6] = x28; } /// The function fiat_p434_from_montgomery translates a field element out of the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^7) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_from_montgomery(out1: &mut [u64; 7], arg1: &[u64; 7]) -> () { let x1: u64 = (arg1[0]); let mut x2: u64 = 0; let mut x3: u64 = 0; fiat_p434_mulx_u64(&mut x2, &mut x3, x1, 0x2341f27177344); let mut x4: u64 = 0; let mut x5: u64 = 0; fiat_p434_mulx_u64(&mut x4, &mut x5, x1, 0x6cfc5fd681c52056); let mut x6: u64 = 0; let mut x7: u64 = 0; fiat_p434_mulx_u64(&mut x6, &mut x7, x1, 0x7bc65c783158aea3); let mut x8: u64 = 0; let mut x9: u64 = 0; fiat_p434_mulx_u64(&mut x8, &mut x9, x1, 0xfdc1767ae2ffffff); let mut x10: u64 = 0; let mut x11: u64 = 0; fiat_p434_mulx_u64(&mut x10, &mut x11, x1, 0xffffffffffffffff); let mut x12: u64 = 0; let mut x13: u64 = 0; fiat_p434_mulx_u64(&mut x12, &mut x13, x1, 0xffffffffffffffff); let mut x14: u64 = 0; let mut x15: u64 = 0; fiat_p434_mulx_u64(&mut x14, &mut x15, x1, 0xffffffffffffffff); let mut x16: u64 = 0; let mut x17: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x16, &mut x17, 0x0, x15, x12); let mut x18: u64 = 0; let mut x19: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x18, &mut x19, x17, x13, x10); let mut x20: u64 = 0; let mut x21: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x20, &mut x21, x19, x11, x8); let mut x22: u64 = 0; let mut x23: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x22, &mut x23, x21, x9, x6); let mut x24: u64 = 0; let mut x25: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x24, &mut x25, x23, x7, x4); let mut x26: u64 = 0; let mut x27: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x26, &mut x27, x25, x5, x2); let mut x28: u64 = 0; let mut x29: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x28, &mut x29, 0x0, x1, x14); let mut x30: u64 = 0; let mut x31: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x30, &mut x31, x29, (0x0 as u64), x16); let mut x32: u64 = 0; let mut x33: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x32, &mut x33, x31, (0x0 as u64), x18); let mut x34: u64 = 0; let mut x35: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x34, &mut x35, x33, (0x0 as u64), x20); let mut x36: u64 = 0; let mut x37: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x36, &mut x37, x35, (0x0 as u64), x22); let mut x38: u64 = 0; let mut x39: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x38, &mut x39, x37, (0x0 as u64), x24); let mut x40: u64 = 0; let mut x41: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x40, &mut x41, x39, (0x0 as u64), x26); let mut x42: u64 = 0; let mut x43: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x42, &mut x43, 0x0, x30, (arg1[1])); let mut x44: u64 = 0; let mut x45: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x44, &mut x45, x43, x32, (0x0 as u64)); let mut x46: u64 = 0; let mut x47: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x46, &mut x47, x45, x34, (0x0 as u64)); let mut x48: u64 = 0; let mut x49: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x48, &mut x49, x47, x36, (0x0 as u64)); let mut x50: u64 = 0; let mut x51: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x50, &mut x51, x49, x38, (0x0 as u64)); let mut x52: u64 = 0; let mut x53: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x52, &mut x53, x51, x40, (0x0 as u64)); let mut x54: u64 = 0; let mut x55: u64 = 0; fiat_p434_mulx_u64(&mut x54, &mut x55, x42, 0x2341f27177344); let mut x56: u64 = 0; let mut x57: u64 = 0; fiat_p434_mulx_u64(&mut x56, &mut x57, x42, 0x6cfc5fd681c52056); let mut x58: u64 = 0; let mut x59: u64 = 0; fiat_p434_mulx_u64(&mut x58, &mut x59, x42, 0x7bc65c783158aea3); let mut x60: u64 = 0; let mut x61: u64 = 0; fiat_p434_mulx_u64(&mut x60, &mut x61, x42, 0xfdc1767ae2ffffff); let mut x62: u64 = 0; let mut x63: u64 = 0; fiat_p434_mulx_u64(&mut x62, &mut x63, x42, 0xffffffffffffffff); let mut x64: u64 = 0; let mut x65: u64 = 0; fiat_p434_mulx_u64(&mut x64, &mut x65, x42, 0xffffffffffffffff); let mut x66: u64 = 0; let mut x67: u64 = 0; fiat_p434_mulx_u64(&mut x66, &mut x67, x42, 0xffffffffffffffff); let mut x68: u64 = 0; let mut x69: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x68, &mut x69, 0x0, x67, x64); let mut x70: u64 = 0; let mut x71: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x70, &mut x71, x69, x65, x62); let mut x72: u64 = 0; let mut x73: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x72, &mut x73, x71, x63, x60); let mut x74: u64 = 0; let mut x75: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x74, &mut x75, x73, x61, x58); let mut x76: u64 = 0; let mut x77: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x76, &mut x77, x75, x59, x56); let mut x78: u64 = 0; let mut x79: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x78, &mut x79, x77, x57, x54); let mut x80: u64 = 0; let mut x81: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x80, &mut x81, 0x0, x42, x66); let mut x82: u64 = 0; let mut x83: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x82, &mut x83, x81, x44, x68); let mut x84: u64 = 0; let mut x85: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x84, &mut x85, x83, x46, x70); let mut x86: u64 = 0; let mut x87: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x86, &mut x87, x85, x48, x72); let mut x88: u64 = 0; let mut x89: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x88, &mut x89, x87, x50, x74); let mut x90: u64 = 0; let mut x91: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x90, &mut x91, x89, x52, x76); let mut x92: u64 = 0; let mut x93: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x92, &mut x93, x91, ((x53 as u64) + ((x41 as u64) + ((x27 as u64) + x3))), x78); let mut x94: u64 = 0; let mut x95: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x94, &mut x95, 0x0, x82, (arg1[2])); let mut x96: u64 = 0; let mut x97: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x96, &mut x97, x95, x84, (0x0 as u64)); let mut x98: u64 = 0; let mut x99: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x98, &mut x99, x97, x86, (0x0 as u64)); let mut x100: u64 = 0; let mut x101: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x100, &mut x101, x99, x88, (0x0 as u64)); let mut x102: u64 = 0; let mut x103: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x102, &mut x103, x101, x90, (0x0 as u64)); let mut x104: u64 = 0; let mut x105: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x104, &mut x105, x103, x92, (0x0 as u64)); let mut x106: u64 = 0; let mut x107: u64 = 0; fiat_p434_mulx_u64(&mut x106, &mut x107, x94, 0x2341f27177344); let mut x108: u64 = 0; let mut x109: u64 = 0; fiat_p434_mulx_u64(&mut x108, &mut x109, x94, 0x6cfc5fd681c52056); let mut x110: u64 = 0; let mut x111: u64 = 0; fiat_p434_mulx_u64(&mut x110, &mut x111, x94, 0x7bc65c783158aea3); let mut x112: u64 = 0; let mut x113: u64 = 0; fiat_p434_mulx_u64(&mut x112, &mut x113, x94, 0xfdc1767ae2ffffff); let mut x114: u64 = 0; let mut x115: u64 = 0; fiat_p434_mulx_u64(&mut x114, &mut x115, x94, 0xffffffffffffffff); let mut x116: u64 = 0; let mut x117: u64 = 0; fiat_p434_mulx_u64(&mut x116, &mut x117, x94, 0xffffffffffffffff); let mut x118: u64 = 0; let mut x119: u64 = 0; fiat_p434_mulx_u64(&mut x118, &mut x119, x94, 0xffffffffffffffff); let mut x120: u64 = 0; let mut x121: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x120, &mut x121, 0x0, x119, x116); let mut x122: u64 = 0; let mut x123: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x122, &mut x123, x121, x117, x114); let mut x124: u64 = 0; let mut x125: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x124, &mut x125, x123, x115, x112); let mut x126: u64 = 0; let mut x127: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x126, &mut x127, x125, x113, x110); let mut x128: u64 = 0; let mut x129: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x128, &mut x129, x127, x111, x108); let mut x130: u64 = 0; let mut x131: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x130, &mut x131, x129, x109, x106); let mut x132: u64 = 0; let mut x133: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x132, &mut x133, 0x0, x94, x118); let mut x134: u64 = 0; let mut x135: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x134, &mut x135, x133, x96, x120); let mut x136: u64 = 0; let mut x137: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x136, &mut x137, x135, x98, x122); let mut x138: u64 = 0; let mut x139: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x138, &mut x139, x137, x100, x124); let mut x140: u64 = 0; let mut x141: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x140, &mut x141, x139, x102, x126); let mut x142: u64 = 0; let mut x143: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x142, &mut x143, x141, x104, x128); let mut x144: u64 = 0; let mut x145: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x144, &mut x145, x143, ((x105 as u64) + ((x93 as u64) + ((x79 as u64) + x55))), x130); let mut x146: u64 = 0; let mut x147: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x146, &mut x147, 0x0, x134, (arg1[3])); let mut x148: u64 = 0; let mut x149: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x148, &mut x149, x147, x136, (0x0 as u64)); let mut x150: u64 = 0; let mut x151: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x150, &mut x151, x149, x138, (0x0 as u64)); let mut x152: u64 = 0; let mut x153: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x152, &mut x153, x151, x140, (0x0 as u64)); let mut x154: u64 = 0; let mut x155: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x154, &mut x155, x153, x142, (0x0 as u64)); let mut x156: u64 = 0; let mut x157: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x156, &mut x157, x155, x144, (0x0 as u64)); let mut x158: u64 = 0; let mut x159: u64 = 0; fiat_p434_mulx_u64(&mut x158, &mut x159, x146, 0x2341f27177344); let mut x160: u64 = 0; let mut x161: u64 = 0; fiat_p434_mulx_u64(&mut x160, &mut x161, x146, 0x6cfc5fd681c52056); let mut x162: u64 = 0; let mut x163: u64 = 0; fiat_p434_mulx_u64(&mut x162, &mut x163, x146, 0x7bc65c783158aea3); let mut x164: u64 = 0; let mut x165: u64 = 0; fiat_p434_mulx_u64(&mut x164, &mut x165, x146, 0xfdc1767ae2ffffff); let mut x166: u64 = 0; let mut x167: u64 = 0; fiat_p434_mulx_u64(&mut x166, &mut x167, x146, 0xffffffffffffffff); let mut x168: u64 = 0; let mut x169: u64 = 0; fiat_p434_mulx_u64(&mut x168, &mut x169, x146, 0xffffffffffffffff); let mut x170: u64 = 0; let mut x171: u64 = 0; fiat_p434_mulx_u64(&mut x170, &mut x171, x146, 0xffffffffffffffff); let mut x172: u64 = 0; let mut x173: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x172, &mut x173, 0x0, x171, x168); let mut x174: u64 = 0; let mut x175: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x174, &mut x175, x173, x169, x166); let mut x176: u64 = 0; let mut x177: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x176, &mut x177, x175, x167, x164); let mut x178: u64 = 0; let mut x179: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x178, &mut x179, x177, x165, x162); let mut x180: u64 = 0; let mut x181: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x180, &mut x181, x179, x163, x160); let mut x182: u64 = 0; let mut x183: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x182, &mut x183, x181, x161, x158); let mut x184: u64 = 0; let mut x185: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x184, &mut x185, 0x0, x146, x170); let mut x186: u64 = 0; let mut x187: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x186, &mut x187, x185, x148, x172); let mut x188: u64 = 0; let mut x189: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x188, &mut x189, x187, x150, x174); let mut x190: u64 = 0; let mut x191: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x190, &mut x191, x189, x152, x176); let mut x192: u64 = 0; let mut x193: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x192, &mut x193, x191, x154, x178); let mut x194: u64 = 0; let mut x195: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x194, &mut x195, x193, x156, x180); let mut x196: u64 = 0; let mut x197: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x196, &mut x197, x195, ((x157 as u64) + ((x145 as u64) + ((x131 as u64) + x107))), x182); let mut x198: u64 = 0; let mut x199: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x198, &mut x199, 0x0, x186, (arg1[4])); let mut x200: u64 = 0; let mut x201: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x200, &mut x201, x199, x188, (0x0 as u64)); let mut x202: u64 = 0; let mut x203: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x202, &mut x203, x201, x190, (0x0 as u64)); let mut x204: u64 = 0; let mut x205: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x204, &mut x205, x203, x192, (0x0 as u64)); let mut x206: u64 = 0; let mut x207: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x206, &mut x207, x205, x194, (0x0 as u64)); let mut x208: u64 = 0; let mut x209: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x208, &mut x209, x207, x196, (0x0 as u64)); let mut x210: u64 = 0; let mut x211: u64 = 0; fiat_p434_mulx_u64(&mut x210, &mut x211, x198, 0x2341f27177344); let mut x212: u64 = 0; let mut x213: u64 = 0; fiat_p434_mulx_u64(&mut x212, &mut x213, x198, 0x6cfc5fd681c52056); let mut x214: u64 = 0; let mut x215: u64 = 0; fiat_p434_mulx_u64(&mut x214, &mut x215, x198, 0x7bc65c783158aea3); let mut x216: u64 = 0; let mut x217: u64 = 0; fiat_p434_mulx_u64(&mut x216, &mut x217, x198, 0xfdc1767ae2ffffff); let mut x218: u64 = 0; let mut x219: u64 = 0; fiat_p434_mulx_u64(&mut x218, &mut x219, x198, 0xffffffffffffffff); let mut x220: u64 = 0; let mut x221: u64 = 0; fiat_p434_mulx_u64(&mut x220, &mut x221, x198, 0xffffffffffffffff); let mut x222: u64 = 0; let mut x223: u64 = 0; fiat_p434_mulx_u64(&mut x222, &mut x223, x198, 0xffffffffffffffff); let mut x224: u64 = 0; let mut x225: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x224, &mut x225, 0x0, x223, x220); let mut x226: u64 = 0; let mut x227: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x226, &mut x227, x225, x221, x218); let mut x228: u64 = 0; let mut x229: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x228, &mut x229, x227, x219, x216); let mut x230: u64 = 0; let mut x231: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x230, &mut x231, x229, x217, x214); let mut x232: u64 = 0; let mut x233: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x232, &mut x233, x231, x215, x212); let mut x234: u64 = 0; let mut x235: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x234, &mut x235, x233, x213, x210); let mut x236: u64 = 0; let mut x237: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x236, &mut x237, 0x0, x198, x222); let mut x238: u64 = 0; let mut x239: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x238, &mut x239, x237, x200, x224); let mut x240: u64 = 0; let mut x241: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x240, &mut x241, x239, x202, x226); let mut x242: u64 = 0; let mut x243: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x242, &mut x243, x241, x204, x228); let mut x244: u64 = 0; let mut x245: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x244, &mut x245, x243, x206, x230); let mut x246: u64 = 0; let mut x247: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x246, &mut x247, x245, x208, x232); let mut x248: u64 = 0; let mut x249: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x248, &mut x249, x247, ((x209 as u64) + ((x197 as u64) + ((x183 as u64) + x159))), x234); let mut x250: u64 = 0; let mut x251: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x250, &mut x251, 0x0, x238, (arg1[5])); let mut x252: u64 = 0; let mut x253: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x252, &mut x253, x251, x240, (0x0 as u64)); let mut x254: u64 = 0; let mut x255: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x254, &mut x255, x253, x242, (0x0 as u64)); let mut x256: u64 = 0; let mut x257: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x256, &mut x257, x255, x244, (0x0 as u64)); let mut x258: u64 = 0; let mut x259: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x258, &mut x259, x257, x246, (0x0 as u64)); let mut x260: u64 = 0; let mut x261: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x260, &mut x261, x259, x248, (0x0 as u64)); let mut x262: u64 = 0; let mut x263: u64 = 0; fiat_p434_mulx_u64(&mut x262, &mut x263, x250, 0x2341f27177344); let mut x264: u64 = 0; let mut x265: u64 = 0; fiat_p434_mulx_u64(&mut x264, &mut x265, x250, 0x6cfc5fd681c52056); let mut x266: u64 = 0; let mut x267: u64 = 0; fiat_p434_mulx_u64(&mut x266, &mut x267, x250, 0x7bc65c783158aea3); let mut x268: u64 = 0; let mut x269: u64 = 0; fiat_p434_mulx_u64(&mut x268, &mut x269, x250, 0xfdc1767ae2ffffff); let mut x270: u64 = 0; let mut x271: u64 = 0; fiat_p434_mulx_u64(&mut x270, &mut x271, x250, 0xffffffffffffffff); let mut x272: u64 = 0; let mut x273: u64 = 0; fiat_p434_mulx_u64(&mut x272, &mut x273, x250, 0xffffffffffffffff); let mut x274: u64 = 0; let mut x275: u64 = 0; fiat_p434_mulx_u64(&mut x274, &mut x275, x250, 0xffffffffffffffff); let mut x276: u64 = 0; let mut x277: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x276, &mut x277, 0x0, x275, x272); let mut x278: u64 = 0; let mut x279: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x278, &mut x279, x277, x273, x270); let mut x280: u64 = 0; let mut x281: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x280, &mut x281, x279, x271, x268); let mut x282: u64 = 0; let mut x283: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x282, &mut x283, x281, x269, x266); let mut x284: u64 = 0; let mut x285: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x284, &mut x285, x283, x267, x264); let mut x286: u64 = 0; let mut x287: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x286, &mut x287, x285, x265, x262); let mut x288: u64 = 0; let mut x289: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x288, &mut x289, 0x0, x250, x274); let mut x290: u64 = 0; let mut x291: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x290, &mut x291, x289, x252, x276); let mut x292: u64 = 0; let mut x293: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x292, &mut x293, x291, x254, x278); let mut x294: u64 = 0; let mut x295: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x294, &mut x295, x293, x256, x280); let mut x296: u64 = 0; let mut x297: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x296, &mut x297, x295, x258, x282); let mut x298: u64 = 0; let mut x299: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x298, &mut x299, x297, x260, x284); let mut x300: u64 = 0; let mut x301: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x300, &mut x301, x299, ((x261 as u64) + ((x249 as u64) + ((x235 as u64) + x211))), x286); let mut x302: u64 = 0; let mut x303: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x302, &mut x303, 0x0, x290, (arg1[6])); let mut x304: u64 = 0; let mut x305: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x304, &mut x305, x303, x292, (0x0 as u64)); let mut x306: u64 = 0; let mut x307: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x306, &mut x307, x305, x294, (0x0 as u64)); let mut x308: u64 = 0; let mut x309: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x308, &mut x309, x307, x296, (0x0 as u64)); let mut x310: u64 = 0; let mut x311: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x310, &mut x311, x309, x298, (0x0 as u64)); let mut x312: u64 = 0; let mut x313: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x312, &mut x313, x311, x300, (0x0 as u64)); let mut x314: u64 = 0; let mut x315: u64 = 0; fiat_p434_mulx_u64(&mut x314, &mut x315, x302, 0x2341f27177344); let mut x316: u64 = 0; let mut x317: u64 = 0; fiat_p434_mulx_u64(&mut x316, &mut x317, x302, 0x6cfc5fd681c52056); let mut x318: u64 = 0; let mut x319: u64 = 0; fiat_p434_mulx_u64(&mut x318, &mut x319, x302, 0x7bc65c783158aea3); let mut x320: u64 = 0; let mut x321: u64 = 0; fiat_p434_mulx_u64(&mut x320, &mut x321, x302, 0xfdc1767ae2ffffff); let mut x322: u64 = 0; let mut x323: u64 = 0; fiat_p434_mulx_u64(&mut x322, &mut x323, x302, 0xffffffffffffffff); let mut x324: u64 = 0; let mut x325: u64 = 0; fiat_p434_mulx_u64(&mut x324, &mut x325, x302, 0xffffffffffffffff); let mut x326: u64 = 0; let mut x327: u64 = 0; fiat_p434_mulx_u64(&mut x326, &mut x327, x302, 0xffffffffffffffff); let mut x328: u64 = 0; let mut x329: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x328, &mut x329, 0x0, x327, x324); let mut x330: u64 = 0; let mut x331: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x330, &mut x331, x329, x325, x322); let mut x332: u64 = 0; let mut x333: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x332, &mut x333, x331, x323, x320); let mut x334: u64 = 0; let mut x335: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x334, &mut x335, x333, x321, x318); let mut x336: u64 = 0; let mut x337: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x336, &mut x337, x335, x319, x316); let mut x338: u64 = 0; let mut x339: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x338, &mut x339, x337, x317, x314); let mut x340: u64 = 0; let mut x341: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x340, &mut x341, 0x0, x302, x326); let mut x342: u64 = 0; let mut x343: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x342, &mut x343, x341, x304, x328); let mut x344: u64 = 0; let mut x345: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x344, &mut x345, x343, x306, x330); let mut x346: u64 = 0; let mut x347: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x346, &mut x347, x345, x308, x332); let mut x348: u64 = 0; let mut x349: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x348, &mut x349, x347, x310, x334); let mut x350: u64 = 0; let mut x351: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x350, &mut x351, x349, x312, x336); let mut x352: u64 = 0; let mut x353: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x352, &mut x353, x351, ((x313 as u64) + ((x301 as u64) + ((x287 as u64) + x263))), x338); let x354: u64 = ((x353 as u64) + ((x339 as u64) + x315)); let mut x355: u64 = 0; let mut x356: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x355, &mut x356, 0x0, x342, 0xffffffffffffffff); let mut x357: u64 = 0; let mut x358: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x357, &mut x358, x356, x344, 0xffffffffffffffff); let mut x359: u64 = 0; let mut x360: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x359, &mut x360, x358, x346, 0xffffffffffffffff); let mut x361: u64 = 0; let mut x362: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x361, &mut x362, x360, x348, 0xfdc1767ae2ffffff); let mut x363: u64 = 0; let mut x364: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x363, &mut x364, x362, x350, 0x7bc65c783158aea3); let mut x365: u64 = 0; let mut x366: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x365, &mut x366, x364, x352, 0x6cfc5fd681c52056); let mut x367: u64 = 0; let mut x368: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x367, &mut x368, x366, x354, 0x2341f27177344); let mut x369: u64 = 0; let mut x370: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x369, &mut x370, x368, (0x0 as u64), (0x0 as u64)); let mut x371: u64 = 0; fiat_p434_cmovznz_u64(&mut x371, x370, x355, x342); let mut x372: u64 = 0; fiat_p434_cmovznz_u64(&mut x372, x370, x357, x344); let mut x373: u64 = 0; fiat_p434_cmovznz_u64(&mut x373, x370, x359, x346); let mut x374: u64 = 0; fiat_p434_cmovznz_u64(&mut x374, x370, x361, x348); let mut x375: u64 = 0; fiat_p434_cmovznz_u64(&mut x375, x370, x363, x350); let mut x376: u64 = 0; fiat_p434_cmovznz_u64(&mut x376, x370, x365, x352); let mut x377: u64 = 0; fiat_p434_cmovznz_u64(&mut x377, x370, x367, x354); out1[0] = x371; out1[1] = x372; out1[2] = x373; out1[3] = x374; out1[4] = x375; out1[5] = x376; out1[6] = x377; } /// The function fiat_p434_to_montgomery translates a field element into the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_to_montgomery(out1: &mut [u64; 7], arg1: &[u64; 7]) -> () { let x1: u64 = (arg1[1]); let x2: u64 = (arg1[2]); let x3: u64 = (arg1[3]); let x4: u64 = (arg1[4]); let x5: u64 = (arg1[5]); let x6: u64 = (arg1[6]); let x7: u64 = (arg1[0]); let mut x8: u64 = 0; let mut x9: u64 = 0; fiat_p434_mulx_u64(&mut x8, &mut x9, x7, 0x25a89bcdd12a); let mut x10: u64 = 0; let mut x11: u64 = 0; fiat_p434_mulx_u64(&mut x10, &mut x11, x7, 0x69e16a61c7686d9a); let mut x12: u64 = 0; let mut x13: u64 = 0; fiat_p434_mulx_u64(&mut x12, &mut x13, x7, 0xabcd92bf2dde347e); let mut x14: u64 = 0; let mut x15: u64 = 0; fiat_p434_mulx_u64(&mut x14, &mut x15, x7, 0x175cc6af8d6c7c0b); let mut x16: u64 = 0; let mut x17: u64 = 0; fiat_p434_mulx_u64(&mut x16, &mut x17, x7, 0xab27973f8311688d); let mut x18: u64 = 0; let mut x19: u64 = 0; fiat_p434_mulx_u64(&mut x18, &mut x19, x7, 0xacec7367768798c2); let mut x20: u64 = 0; let mut x21: u64 = 0; fiat_p434_mulx_u64(&mut x20, &mut x21, x7, 0x28e55b65dcd69b30); let mut x22: u64 = 0; let mut x23: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x22, &mut x23, 0x0, x21, x18); let mut x24: u64 = 0; let mut x25: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x24, &mut x25, x23, x19, x16); let mut x26: u64 = 0; let mut x27: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x26, &mut x27, x25, x17, x14); let mut x28: u64 = 0; let mut x29: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x28, &mut x29, x27, x15, x12); let mut x30: u64 = 0; let mut x31: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x30, &mut x31, x29, x13, x10); let mut x32: u64 = 0; let mut x33: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x32, &mut x33, x31, x11, x8); let mut x34: u64 = 0; let mut x35: u64 = 0; fiat_p434_mulx_u64(&mut x34, &mut x35, x20, 0x2341f27177344); let mut x36: u64 = 0; let mut x37: u64 = 0; fiat_p434_mulx_u64(&mut x36, &mut x37, x20, 0x6cfc5fd681c52056); let mut x38: u64 = 0; let mut x39: u64 = 0; fiat_p434_mulx_u64(&mut x38, &mut x39, x20, 0x7bc65c783158aea3); let mut x40: u64 = 0; let mut x41: u64 = 0; fiat_p434_mulx_u64(&mut x40, &mut x41, x20, 0xfdc1767ae2ffffff); let mut x42: u64 = 0; let mut x43: u64 = 0; fiat_p434_mulx_u64(&mut x42, &mut x43, x20, 0xffffffffffffffff); let mut x44: u64 = 0; let mut x45: u64 = 0; fiat_p434_mulx_u64(&mut x44, &mut x45, x20, 0xffffffffffffffff); let mut x46: u64 = 0; let mut x47: u64 = 0; fiat_p434_mulx_u64(&mut x46, &mut x47, x20, 0xffffffffffffffff); let mut x48: u64 = 0; let mut x49: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x48, &mut x49, 0x0, x47, x44); let mut x50: u64 = 0; let mut x51: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x50, &mut x51, x49, x45, x42); let mut x52: u64 = 0; let mut x53: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x52, &mut x53, x51, x43, x40); let mut x54: u64 = 0; let mut x55: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x54, &mut x55, x53, x41, x38); let mut x56: u64 = 0; let mut x57: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x56, &mut x57, x55, x39, x36); let mut x58: u64 = 0; let mut x59: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x58, &mut x59, x57, x37, x34); let mut x60: u64 = 0; let mut x61: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x60, &mut x61, 0x0, x20, x46); let mut x62: u64 = 0; let mut x63: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x62, &mut x63, x61, x22, x48); let mut x64: u64 = 0; let mut x65: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x64, &mut x65, x63, x24, x50); let mut x66: u64 = 0; let mut x67: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x66, &mut x67, x65, x26, x52); let mut x68: u64 = 0; let mut x69: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x68, &mut x69, x67, x28, x54); let mut x70: u64 = 0; let mut x71: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x70, &mut x71, x69, x30, x56); let mut x72: u64 = 0; let mut x73: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x72, &mut x73, x71, x32, x58); let mut x74: u64 = 0; let mut x75: u64 = 0; fiat_p434_mulx_u64(&mut x74, &mut x75, x1, 0x25a89bcdd12a); let mut x76: u64 = 0; let mut x77: u64 = 0; fiat_p434_mulx_u64(&mut x76, &mut x77, x1, 0x69e16a61c7686d9a); let mut x78: u64 = 0; let mut x79: u64 = 0; fiat_p434_mulx_u64(&mut x78, &mut x79, x1, 0xabcd92bf2dde347e); let mut x80: u64 = 0; let mut x81: u64 = 0; fiat_p434_mulx_u64(&mut x80, &mut x81, x1, 0x175cc6af8d6c7c0b); let mut x82: u64 = 0; let mut x83: u64 = 0; fiat_p434_mulx_u64(&mut x82, &mut x83, x1, 0xab27973f8311688d); let mut x84: u64 = 0; let mut x85: u64 = 0; fiat_p434_mulx_u64(&mut x84, &mut x85, x1, 0xacec7367768798c2); let mut x86: u64 = 0; let mut x87: u64 = 0; fiat_p434_mulx_u64(&mut x86, &mut x87, x1, 0x28e55b65dcd69b30); let mut x88: u64 = 0; let mut x89: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x88, &mut x89, 0x0, x87, x84); let mut x90: u64 = 0; let mut x91: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x90, &mut x91, x89, x85, x82); let mut x92: u64 = 0; let mut x93: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x92, &mut x93, x91, x83, x80); let mut x94: u64 = 0; let mut x95: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x94, &mut x95, x93, x81, x78); let mut x96: u64 = 0; let mut x97: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x96, &mut x97, x95, x79, x76); let mut x98: u64 = 0; let mut x99: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x98, &mut x99, x97, x77, x74); let mut x100: u64 = 0; let mut x101: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x100, &mut x101, 0x0, x62, x86); let mut x102: u64 = 0; let mut x103: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x102, &mut x103, x101, x64, x88); let mut x104: u64 = 0; let mut x105: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x104, &mut x105, x103, x66, x90); let mut x106: u64 = 0; let mut x107: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x106, &mut x107, x105, x68, x92); let mut x108: u64 = 0; let mut x109: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x108, &mut x109, x107, x70, x94); let mut x110: u64 = 0; let mut x111: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x110, &mut x111, x109, x72, x96); let mut x112: u64 = 0; let mut x113: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x112, &mut x113, x111, (((x73 as u64) + ((x33 as u64) + x9)) + ((x59 as u64) + x35)), x98); let mut x114: u64 = 0; let mut x115: u64 = 0; fiat_p434_mulx_u64(&mut x114, &mut x115, x100, 0x2341f27177344); let mut x116: u64 = 0; let mut x117: u64 = 0; fiat_p434_mulx_u64(&mut x116, &mut x117, x100, 0x6cfc5fd681c52056); let mut x118: u64 = 0; let mut x119: u64 = 0; fiat_p434_mulx_u64(&mut x118, &mut x119, x100, 0x7bc65c783158aea3); let mut x120: u64 = 0; let mut x121: u64 = 0; fiat_p434_mulx_u64(&mut x120, &mut x121, x100, 0xfdc1767ae2ffffff); let mut x122: u64 = 0; let mut x123: u64 = 0; fiat_p434_mulx_u64(&mut x122, &mut x123, x100, 0xffffffffffffffff); let mut x124: u64 = 0; let mut x125: u64 = 0; fiat_p434_mulx_u64(&mut x124, &mut x125, x100, 0xffffffffffffffff); let mut x126: u64 = 0; let mut x127: u64 = 0; fiat_p434_mulx_u64(&mut x126, &mut x127, x100, 0xffffffffffffffff); let mut x128: u64 = 0; let mut x129: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x128, &mut x129, 0x0, x127, x124); let mut x130: u64 = 0; let mut x131: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x130, &mut x131, x129, x125, x122); let mut x132: u64 = 0; let mut x133: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x132, &mut x133, x131, x123, x120); let mut x134: u64 = 0; let mut x135: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x134, &mut x135, x133, x121, x118); let mut x136: u64 = 0; let mut x137: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x136, &mut x137, x135, x119, x116); let mut x138: u64 = 0; let mut x139: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x138, &mut x139, x137, x117, x114); let mut x140: u64 = 0; let mut x141: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x140, &mut x141, 0x0, x100, x126); let mut x142: u64 = 0; let mut x143: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x142, &mut x143, x141, x102, x128); let mut x144: u64 = 0; let mut x145: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x144, &mut x145, x143, x104, x130); let mut x146: u64 = 0; let mut x147: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x146, &mut x147, x145, x106, x132); let mut x148: u64 = 0; let mut x149: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x148, &mut x149, x147, x108, x134); let mut x150: u64 = 0; let mut x151: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x150, &mut x151, x149, x110, x136); let mut x152: u64 = 0; let mut x153: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x152, &mut x153, x151, x112, x138); let mut x154: u64 = 0; let mut x155: u64 = 0; fiat_p434_mulx_u64(&mut x154, &mut x155, x2, 0x25a89bcdd12a); let mut x156: u64 = 0; let mut x157: u64 = 0; fiat_p434_mulx_u64(&mut x156, &mut x157, x2, 0x69e16a61c7686d9a); let mut x158: u64 = 0; let mut x159: u64 = 0; fiat_p434_mulx_u64(&mut x158, &mut x159, x2, 0xabcd92bf2dde347e); let mut x160: u64 = 0; let mut x161: u64 = 0; fiat_p434_mulx_u64(&mut x160, &mut x161, x2, 0x175cc6af8d6c7c0b); let mut x162: u64 = 0; let mut x163: u64 = 0; fiat_p434_mulx_u64(&mut x162, &mut x163, x2, 0xab27973f8311688d); let mut x164: u64 = 0; let mut x165: u64 = 0; fiat_p434_mulx_u64(&mut x164, &mut x165, x2, 0xacec7367768798c2); let mut x166: u64 = 0; let mut x167: u64 = 0; fiat_p434_mulx_u64(&mut x166, &mut x167, x2, 0x28e55b65dcd69b30); let mut x168: u64 = 0; let mut x169: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x168, &mut x169, 0x0, x167, x164); let mut x170: u64 = 0; let mut x171: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x170, &mut x171, x169, x165, x162); let mut x172: u64 = 0; let mut x173: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x172, &mut x173, x171, x163, x160); let mut x174: u64 = 0; let mut x175: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x174, &mut x175, x173, x161, x158); let mut x176: u64 = 0; let mut x177: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x176, &mut x177, x175, x159, x156); let mut x178: u64 = 0; let mut x179: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x178, &mut x179, x177, x157, x154); let mut x180: u64 = 0; let mut x181: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x180, &mut x181, 0x0, x142, x166); let mut x182: u64 = 0; let mut x183: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x182, &mut x183, x181, x144, x168); let mut x184: u64 = 0; let mut x185: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x184, &mut x185, x183, x146, x170); let mut x186: u64 = 0; let mut x187: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x186, &mut x187, x185, x148, x172); let mut x188: u64 = 0; let mut x189: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x188, &mut x189, x187, x150, x174); let mut x190: u64 = 0; let mut x191: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x190, &mut x191, x189, x152, x176); let mut x192: u64 = 0; let mut x193: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x192, &mut x193, x191, (((x153 as u64) + ((x113 as u64) + ((x99 as u64) + x75))) + ((x139 as u64) + x115)), x178); let mut x194: u64 = 0; let mut x195: u64 = 0; fiat_p434_mulx_u64(&mut x194, &mut x195, x180, 0x2341f27177344); let mut x196: u64 = 0; let mut x197: u64 = 0; fiat_p434_mulx_u64(&mut x196, &mut x197, x180, 0x6cfc5fd681c52056); let mut x198: u64 = 0; let mut x199: u64 = 0; fiat_p434_mulx_u64(&mut x198, &mut x199, x180, 0x7bc65c783158aea3); let mut x200: u64 = 0; let mut x201: u64 = 0; fiat_p434_mulx_u64(&mut x200, &mut x201, x180, 0xfdc1767ae2ffffff); let mut x202: u64 = 0; let mut x203: u64 = 0; fiat_p434_mulx_u64(&mut x202, &mut x203, x180, 0xffffffffffffffff); let mut x204: u64 = 0; let mut x205: u64 = 0; fiat_p434_mulx_u64(&mut x204, &mut x205, x180, 0xffffffffffffffff); let mut x206: u64 = 0; let mut x207: u64 = 0; fiat_p434_mulx_u64(&mut x206, &mut x207, x180, 0xffffffffffffffff); let mut x208: u64 = 0; let mut x209: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x208, &mut x209, 0x0, x207, x204); let mut x210: u64 = 0; let mut x211: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x210, &mut x211, x209, x205, x202); let mut x212: u64 = 0; let mut x213: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x212, &mut x213, x211, x203, x200); let mut x214: u64 = 0; let mut x215: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x214, &mut x215, x213, x201, x198); let mut x216: u64 = 0; let mut x217: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x216, &mut x217, x215, x199, x196); let mut x218: u64 = 0; let mut x219: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x218, &mut x219, x217, x197, x194); let mut x220: u64 = 0; let mut x221: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x220, &mut x221, 0x0, x180, x206); let mut x222: u64 = 0; let mut x223: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x222, &mut x223, x221, x182, x208); let mut x224: u64 = 0; let mut x225: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x224, &mut x225, x223, x184, x210); let mut x226: u64 = 0; let mut x227: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x226, &mut x227, x225, x186, x212); let mut x228: u64 = 0; let mut x229: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x228, &mut x229, x227, x188, x214); let mut x230: u64 = 0; let mut x231: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x230, &mut x231, x229, x190, x216); let mut x232: u64 = 0; let mut x233: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x232, &mut x233, x231, x192, x218); let mut x234: u64 = 0; let mut x235: u64 = 0; fiat_p434_mulx_u64(&mut x234, &mut x235, x3, 0x25a89bcdd12a); let mut x236: u64 = 0; let mut x237: u64 = 0; fiat_p434_mulx_u64(&mut x236, &mut x237, x3, 0x69e16a61c7686d9a); let mut x238: u64 = 0; let mut x239: u64 = 0; fiat_p434_mulx_u64(&mut x238, &mut x239, x3, 0xabcd92bf2dde347e); let mut x240: u64 = 0; let mut x241: u64 = 0; fiat_p434_mulx_u64(&mut x240, &mut x241, x3, 0x175cc6af8d6c7c0b); let mut x242: u64 = 0; let mut x243: u64 = 0; fiat_p434_mulx_u64(&mut x242, &mut x243, x3, 0xab27973f8311688d); let mut x244: u64 = 0; let mut x245: u64 = 0; fiat_p434_mulx_u64(&mut x244, &mut x245, x3, 0xacec7367768798c2); let mut x246: u64 = 0; let mut x247: u64 = 0; fiat_p434_mulx_u64(&mut x246, &mut x247, x3, 0x28e55b65dcd69b30); let mut x248: u64 = 0; let mut x249: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x248, &mut x249, 0x0, x247, x244); let mut x250: u64 = 0; let mut x251: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x250, &mut x251, x249, x245, x242); let mut x252: u64 = 0; let mut x253: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x252, &mut x253, x251, x243, x240); let mut x254: u64 = 0; let mut x255: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x254, &mut x255, x253, x241, x238); let mut x256: u64 = 0; let mut x257: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x256, &mut x257, x255, x239, x236); let mut x258: u64 = 0; let mut x259: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x258, &mut x259, x257, x237, x234); let mut x260: u64 = 0; let mut x261: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x260, &mut x261, 0x0, x222, x246); let mut x262: u64 = 0; let mut x263: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x262, &mut x263, x261, x224, x248); let mut x264: u64 = 0; let mut x265: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x264, &mut x265, x263, x226, x250); let mut x266: u64 = 0; let mut x267: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x266, &mut x267, x265, x228, x252); let mut x268: u64 = 0; let mut x269: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x268, &mut x269, x267, x230, x254); let mut x270: u64 = 0; let mut x271: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x270, &mut x271, x269, x232, x256); let mut x272: u64 = 0; let mut x273: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x272, &mut x273, x271, (((x233 as u64) + ((x193 as u64) + ((x179 as u64) + x155))) + ((x219 as u64) + x195)), x258); let mut x274: u64 = 0; let mut x275: u64 = 0; fiat_p434_mulx_u64(&mut x274, &mut x275, x260, 0x2341f27177344); let mut x276: u64 = 0; let mut x277: u64 = 0; fiat_p434_mulx_u64(&mut x276, &mut x277, x260, 0x6cfc5fd681c52056); let mut x278: u64 = 0; let mut x279: u64 = 0; fiat_p434_mulx_u64(&mut x278, &mut x279, x260, 0x7bc65c783158aea3); let mut x280: u64 = 0; let mut x281: u64 = 0; fiat_p434_mulx_u64(&mut x280, &mut x281, x260, 0xfdc1767ae2ffffff); let mut x282: u64 = 0; let mut x283: u64 = 0; fiat_p434_mulx_u64(&mut x282, &mut x283, x260, 0xffffffffffffffff); let mut x284: u64 = 0; let mut x285: u64 = 0; fiat_p434_mulx_u64(&mut x284, &mut x285, x260, 0xffffffffffffffff); let mut x286: u64 = 0; let mut x287: u64 = 0; fiat_p434_mulx_u64(&mut x286, &mut x287, x260, 0xffffffffffffffff); let mut x288: u64 = 0; let mut x289: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x288, &mut x289, 0x0, x287, x284); let mut x290: u64 = 0; let mut x291: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x290, &mut x291, x289, x285, x282); let mut x292: u64 = 0; let mut x293: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x292, &mut x293, x291, x283, x280); let mut x294: u64 = 0; let mut x295: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x294, &mut x295, x293, x281, x278); let mut x296: u64 = 0; let mut x297: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x296, &mut x297, x295, x279, x276); let mut x298: u64 = 0; let mut x299: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x298, &mut x299, x297, x277, x274); let mut x300: u64 = 0; let mut x301: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x300, &mut x301, 0x0, x260, x286); let mut x302: u64 = 0; let mut x303: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x302, &mut x303, x301, x262, x288); let mut x304: u64 = 0; let mut x305: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x304, &mut x305, x303, x264, x290); let mut x306: u64 = 0; let mut x307: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x306, &mut x307, x305, x266, x292); let mut x308: u64 = 0; let mut x309: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x308, &mut x309, x307, x268, x294); let mut x310: u64 = 0; let mut x311: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x310, &mut x311, x309, x270, x296); let mut x312: u64 = 0; let mut x313: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x312, &mut x313, x311, x272, x298); let mut x314: u64 = 0; let mut x315: u64 = 0; fiat_p434_mulx_u64(&mut x314, &mut x315, x4, 0x25a89bcdd12a); let mut x316: u64 = 0; let mut x317: u64 = 0; fiat_p434_mulx_u64(&mut x316, &mut x317, x4, 0x69e16a61c7686d9a); let mut x318: u64 = 0; let mut x319: u64 = 0; fiat_p434_mulx_u64(&mut x318, &mut x319, x4, 0xabcd92bf2dde347e); let mut x320: u64 = 0; let mut x321: u64 = 0; fiat_p434_mulx_u64(&mut x320, &mut x321, x4, 0x175cc6af8d6c7c0b); let mut x322: u64 = 0; let mut x323: u64 = 0; fiat_p434_mulx_u64(&mut x322, &mut x323, x4, 0xab27973f8311688d); let mut x324: u64 = 0; let mut x325: u64 = 0; fiat_p434_mulx_u64(&mut x324, &mut x325, x4, 0xacec7367768798c2); let mut x326: u64 = 0; let mut x327: u64 = 0; fiat_p434_mulx_u64(&mut x326, &mut x327, x4, 0x28e55b65dcd69b30); let mut x328: u64 = 0; let mut x329: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x328, &mut x329, 0x0, x327, x324); let mut x330: u64 = 0; let mut x331: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x330, &mut x331, x329, x325, x322); let mut x332: u64 = 0; let mut x333: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x332, &mut x333, x331, x323, x320); let mut x334: u64 = 0; let mut x335: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x334, &mut x335, x333, x321, x318); let mut x336: u64 = 0; let mut x337: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x336, &mut x337, x335, x319, x316); let mut x338: u64 = 0; let mut x339: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x338, &mut x339, x337, x317, x314); let mut x340: u64 = 0; let mut x341: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x340, &mut x341, 0x0, x302, x326); let mut x342: u64 = 0; let mut x343: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x342, &mut x343, x341, x304, x328); let mut x344: u64 = 0; let mut x345: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x344, &mut x345, x343, x306, x330); let mut x346: u64 = 0; let mut x347: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x346, &mut x347, x345, x308, x332); let mut x348: u64 = 0; let mut x349: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x348, &mut x349, x347, x310, x334); let mut x350: u64 = 0; let mut x351: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x350, &mut x351, x349, x312, x336); let mut x352: u64 = 0; let mut x353: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x352, &mut x353, x351, (((x313 as u64) + ((x273 as u64) + ((x259 as u64) + x235))) + ((x299 as u64) + x275)), x338); let mut x354: u64 = 0; let mut x355: u64 = 0; fiat_p434_mulx_u64(&mut x354, &mut x355, x340, 0x2341f27177344); let mut x356: u64 = 0; let mut x357: u64 = 0; fiat_p434_mulx_u64(&mut x356, &mut x357, x340, 0x6cfc5fd681c52056); let mut x358: u64 = 0; let mut x359: u64 = 0; fiat_p434_mulx_u64(&mut x358, &mut x359, x340, 0x7bc65c783158aea3); let mut x360: u64 = 0; let mut x361: u64 = 0; fiat_p434_mulx_u64(&mut x360, &mut x361, x340, 0xfdc1767ae2ffffff); let mut x362: u64 = 0; let mut x363: u64 = 0; fiat_p434_mulx_u64(&mut x362, &mut x363, x340, 0xffffffffffffffff); let mut x364: u64 = 0; let mut x365: u64 = 0; fiat_p434_mulx_u64(&mut x364, &mut x365, x340, 0xffffffffffffffff); let mut x366: u64 = 0; let mut x367: u64 = 0; fiat_p434_mulx_u64(&mut x366, &mut x367, x340, 0xffffffffffffffff); let mut x368: u64 = 0; let mut x369: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x368, &mut x369, 0x0, x367, x364); let mut x370: u64 = 0; let mut x371: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x370, &mut x371, x369, x365, x362); let mut x372: u64 = 0; let mut x373: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x372, &mut x373, x371, x363, x360); let mut x374: u64 = 0; let mut x375: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x374, &mut x375, x373, x361, x358); let mut x376: u64 = 0; let mut x377: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x376, &mut x377, x375, x359, x356); let mut x378: u64 = 0; let mut x379: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x378, &mut x379, x377, x357, x354); let mut x380: u64 = 0; let mut x381: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x380, &mut x381, 0x0, x340, x366); let mut x382: u64 = 0; let mut x383: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x382, &mut x383, x381, x342, x368); let mut x384: u64 = 0; let mut x385: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x384, &mut x385, x383, x344, x370); let mut x386: u64 = 0; let mut x387: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x386, &mut x387, x385, x346, x372); let mut x388: u64 = 0; let mut x389: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x388, &mut x389, x387, x348, x374); let mut x390: u64 = 0; let mut x391: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x390, &mut x391, x389, x350, x376); let mut x392: u64 = 0; let mut x393: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x392, &mut x393, x391, x352, x378); let mut x394: u64 = 0; let mut x395: u64 = 0; fiat_p434_mulx_u64(&mut x394, &mut x395, x5, 0x25a89bcdd12a); let mut x396: u64 = 0; let mut x397: u64 = 0; fiat_p434_mulx_u64(&mut x396, &mut x397, x5, 0x69e16a61c7686d9a); let mut x398: u64 = 0; let mut x399: u64 = 0; fiat_p434_mulx_u64(&mut x398, &mut x399, x5, 0xabcd92bf2dde347e); let mut x400: u64 = 0; let mut x401: u64 = 0; fiat_p434_mulx_u64(&mut x400, &mut x401, x5, 0x175cc6af8d6c7c0b); let mut x402: u64 = 0; let mut x403: u64 = 0; fiat_p434_mulx_u64(&mut x402, &mut x403, x5, 0xab27973f8311688d); let mut x404: u64 = 0; let mut x405: u64 = 0; fiat_p434_mulx_u64(&mut x404, &mut x405, x5, 0xacec7367768798c2); let mut x406: u64 = 0; let mut x407: u64 = 0; fiat_p434_mulx_u64(&mut x406, &mut x407, x5, 0x28e55b65dcd69b30); let mut x408: u64 = 0; let mut x409: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x408, &mut x409, 0x0, x407, x404); let mut x410: u64 = 0; let mut x411: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x410, &mut x411, x409, x405, x402); let mut x412: u64 = 0; let mut x413: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x412, &mut x413, x411, x403, x400); let mut x414: u64 = 0; let mut x415: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x414, &mut x415, x413, x401, x398); let mut x416: u64 = 0; let mut x417: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x416, &mut x417, x415, x399, x396); let mut x418: u64 = 0; let mut x419: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x418, &mut x419, x417, x397, x394); let mut x420: u64 = 0; let mut x421: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x420, &mut x421, 0x0, x382, x406); let mut x422: u64 = 0; let mut x423: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x422, &mut x423, x421, x384, x408); let mut x424: u64 = 0; let mut x425: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x424, &mut x425, x423, x386, x410); let mut x426: u64 = 0; let mut x427: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x426, &mut x427, x425, x388, x412); let mut x428: u64 = 0; let mut x429: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x428, &mut x429, x427, x390, x414); let mut x430: u64 = 0; let mut x431: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x430, &mut x431, x429, x392, x416); let mut x432: u64 = 0; let mut x433: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x432, &mut x433, x431, (((x393 as u64) + ((x353 as u64) + ((x339 as u64) + x315))) + ((x379 as u64) + x355)), x418); let mut x434: u64 = 0; let mut x435: u64 = 0; fiat_p434_mulx_u64(&mut x434, &mut x435, x420, 0x2341f27177344); let mut x436: u64 = 0; let mut x437: u64 = 0; fiat_p434_mulx_u64(&mut x436, &mut x437, x420, 0x6cfc5fd681c52056); let mut x438: u64 = 0; let mut x439: u64 = 0; fiat_p434_mulx_u64(&mut x438, &mut x439, x420, 0x7bc65c783158aea3); let mut x440: u64 = 0; let mut x441: u64 = 0; fiat_p434_mulx_u64(&mut x440, &mut x441, x420, 0xfdc1767ae2ffffff); let mut x442: u64 = 0; let mut x443: u64 = 0; fiat_p434_mulx_u64(&mut x442, &mut x443, x420, 0xffffffffffffffff); let mut x444: u64 = 0; let mut x445: u64 = 0; fiat_p434_mulx_u64(&mut x444, &mut x445, x420, 0xffffffffffffffff); let mut x446: u64 = 0; let mut x447: u64 = 0; fiat_p434_mulx_u64(&mut x446, &mut x447, x420, 0xffffffffffffffff); let mut x448: u64 = 0; let mut x449: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x448, &mut x449, 0x0, x447, x444); let mut x450: u64 = 0; let mut x451: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x450, &mut x451, x449, x445, x442); let mut x452: u64 = 0; let mut x453: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x452, &mut x453, x451, x443, x440); let mut x454: u64 = 0; let mut x455: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x454, &mut x455, x453, x441, x438); let mut x456: u64 = 0; let mut x457: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x456, &mut x457, x455, x439, x436); let mut x458: u64 = 0; let mut x459: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x458, &mut x459, x457, x437, x434); let mut x460: u64 = 0; let mut x461: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x460, &mut x461, 0x0, x420, x446); let mut x462: u64 = 0; let mut x463: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x462, &mut x463, x461, x422, x448); let mut x464: u64 = 0; let mut x465: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x464, &mut x465, x463, x424, x450); let mut x466: u64 = 0; let mut x467: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x466, &mut x467, x465, x426, x452); let mut x468: u64 = 0; let mut x469: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x468, &mut x469, x467, x428, x454); let mut x470: u64 = 0; let mut x471: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x470, &mut x471, x469, x430, x456); let mut x472: u64 = 0; let mut x473: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x472, &mut x473, x471, x432, x458); let mut x474: u64 = 0; let mut x475: u64 = 0; fiat_p434_mulx_u64(&mut x474, &mut x475, x6, 0x25a89bcdd12a); let mut x476: u64 = 0; let mut x477: u64 = 0; fiat_p434_mulx_u64(&mut x476, &mut x477, x6, 0x69e16a61c7686d9a); let mut x478: u64 = 0; let mut x479: u64 = 0; fiat_p434_mulx_u64(&mut x478, &mut x479, x6, 0xabcd92bf2dde347e); let mut x480: u64 = 0; let mut x481: u64 = 0; fiat_p434_mulx_u64(&mut x480, &mut x481, x6, 0x175cc6af8d6c7c0b); let mut x482: u64 = 0; let mut x483: u64 = 0; fiat_p434_mulx_u64(&mut x482, &mut x483, x6, 0xab27973f8311688d); let mut x484: u64 = 0; let mut x485: u64 = 0; fiat_p434_mulx_u64(&mut x484, &mut x485, x6, 0xacec7367768798c2); let mut x486: u64 = 0; let mut x487: u64 = 0; fiat_p434_mulx_u64(&mut x486, &mut x487, x6, 0x28e55b65dcd69b30); let mut x488: u64 = 0; let mut x489: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x488, &mut x489, 0x0, x487, x484); let mut x490: u64 = 0; let mut x491: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x490, &mut x491, x489, x485, x482); let mut x492: u64 = 0; let mut x493: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x492, &mut x493, x491, x483, x480); let mut x494: u64 = 0; let mut x495: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x494, &mut x495, x493, x481, x478); let mut x496: u64 = 0; let mut x497: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x496, &mut x497, x495, x479, x476); let mut x498: u64 = 0; let mut x499: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x498, &mut x499, x497, x477, x474); let mut x500: u64 = 0; let mut x501: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x500, &mut x501, 0x0, x462, x486); let mut x502: u64 = 0; let mut x503: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x502, &mut x503, x501, x464, x488); let mut x504: u64 = 0; let mut x505: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x504, &mut x505, x503, x466, x490); let mut x506: u64 = 0; let mut x507: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x506, &mut x507, x505, x468, x492); let mut x508: u64 = 0; let mut x509: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x508, &mut x509, x507, x470, x494); let mut x510: u64 = 0; let mut x511: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x510, &mut x511, x509, x472, x496); let mut x512: u64 = 0; let mut x513: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x512, &mut x513, x511, (((x473 as u64) + ((x433 as u64) + ((x419 as u64) + x395))) + ((x459 as u64) + x435)), x498); let mut x514: u64 = 0; let mut x515: u64 = 0; fiat_p434_mulx_u64(&mut x514, &mut x515, x500, 0x2341f27177344); let mut x516: u64 = 0; let mut x517: u64 = 0; fiat_p434_mulx_u64(&mut x516, &mut x517, x500, 0x6cfc5fd681c52056); let mut x518: u64 = 0; let mut x519: u64 = 0; fiat_p434_mulx_u64(&mut x518, &mut x519, x500, 0x7bc65c783158aea3); let mut x520: u64 = 0; let mut x521: u64 = 0; fiat_p434_mulx_u64(&mut x520, &mut x521, x500, 0xfdc1767ae2ffffff); let mut x522: u64 = 0; let mut x523: u64 = 0; fiat_p434_mulx_u64(&mut x522, &mut x523, x500, 0xffffffffffffffff); let mut x524: u64 = 0; let mut x525: u64 = 0; fiat_p434_mulx_u64(&mut x524, &mut x525, x500, 0xffffffffffffffff); let mut x526: u64 = 0; let mut x527: u64 = 0; fiat_p434_mulx_u64(&mut x526, &mut x527, x500, 0xffffffffffffffff); let mut x528: u64 = 0; let mut x529: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x528, &mut x529, 0x0, x527, x524); let mut x530: u64 = 0; let mut x531: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x530, &mut x531, x529, x525, x522); let mut x532: u64 = 0; let mut x533: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x532, &mut x533, x531, x523, x520); let mut x534: u64 = 0; let mut x535: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x534, &mut x535, x533, x521, x518); let mut x536: u64 = 0; let mut x537: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x536, &mut x537, x535, x519, x516); let mut x538: u64 = 0; let mut x539: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x538, &mut x539, x537, x517, x514); let mut x540: u64 = 0; let mut x541: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x540, &mut x541, 0x0, x500, x526); let mut x542: u64 = 0; let mut x543: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x542, &mut x543, x541, x502, x528); let mut x544: u64 = 0; let mut x545: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x544, &mut x545, x543, x504, x530); let mut x546: u64 = 0; let mut x547: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x546, &mut x547, x545, x506, x532); let mut x548: u64 = 0; let mut x549: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x548, &mut x549, x547, x508, x534); let mut x550: u64 = 0; let mut x551: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x550, &mut x551, x549, x510, x536); let mut x552: u64 = 0; let mut x553: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x552, &mut x553, x551, x512, x538); let x554: u64 = (((x553 as u64) + ((x513 as u64) + ((x499 as u64) + x475))) + ((x539 as u64) + x515)); let mut x555: u64 = 0; let mut x556: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x555, &mut x556, 0x0, x542, 0xffffffffffffffff); let mut x557: u64 = 0; let mut x558: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x557, &mut x558, x556, x544, 0xffffffffffffffff); let mut x559: u64 = 0; let mut x560: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x559, &mut x560, x558, x546, 0xffffffffffffffff); let mut x561: u64 = 0; let mut x562: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x561, &mut x562, x560, x548, 0xfdc1767ae2ffffff); let mut x563: u64 = 0; let mut x564: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x563, &mut x564, x562, x550, 0x7bc65c783158aea3); let mut x565: u64 = 0; let mut x566: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x565, &mut x566, x564, x552, 0x6cfc5fd681c52056); let mut x567: u64 = 0; let mut x568: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x567, &mut x568, x566, x554, 0x2341f27177344); let mut x569: u64 = 0; let mut x570: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x569, &mut x570, x568, (0x0 as u64), (0x0 as u64)); let mut x571: u64 = 0; fiat_p434_cmovznz_u64(&mut x571, x570, x555, x542); let mut x572: u64 = 0; fiat_p434_cmovznz_u64(&mut x572, x570, x557, x544); let mut x573: u64 = 0; fiat_p434_cmovznz_u64(&mut x573, x570, x559, x546); let mut x574: u64 = 0; fiat_p434_cmovznz_u64(&mut x574, x570, x561, x548); let mut x575: u64 = 0; fiat_p434_cmovznz_u64(&mut x575, x570, x563, x550); let mut x576: u64 = 0; fiat_p434_cmovznz_u64(&mut x576, x570, x565, x552); let mut x577: u64 = 0; fiat_p434_cmovznz_u64(&mut x577, x570, x567, x554); out1[0] = x571; out1[1] = x572; out1[2] = x573; out1[3] = x574; out1[4] = x575; out1[5] = x576; out1[6] = x577; } /// The function fiat_p434_nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] #[inline] pub fn fiat_p434_nonzero(out1: &mut u64, arg1: &[u64; 7]) -> () { let x1: u64 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | (arg1[6]))))))); *out1 = x1; } /// The function fiat_p434_selectznz is a multi-limb conditional select. /// Postconditions: /// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_selectznz(out1: &mut [u64; 7], arg1: fiat_p434_u1, arg2: &[u64; 7], arg3: &[u64; 7]) -> () { let mut x1: u64 = 0; fiat_p434_cmovznz_u64(&mut x1, arg1, (arg2[0]), (arg3[0])); let mut x2: u64 = 0; fiat_p434_cmovznz_u64(&mut x2, arg1, (arg2[1]), (arg3[1])); let mut x3: u64 = 0; fiat_p434_cmovznz_u64(&mut x3, arg1, (arg2[2]), (arg3[2])); let mut x4: u64 = 0; fiat_p434_cmovznz_u64(&mut x4, arg1, (arg2[3]), (arg3[3])); let mut x5: u64 = 0; fiat_p434_cmovznz_u64(&mut x5, arg1, (arg2[4]), (arg3[4])); let mut x6: u64 = 0; fiat_p434_cmovznz_u64(&mut x6, arg1, (arg2[5]), (arg3[5])); let mut x7: u64 = 0; fiat_p434_cmovznz_u64(&mut x7, arg1, (arg2[6]), (arg3[6])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; } /// The function fiat_p434_to_bytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..54] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x3ffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x3]] #[inline] pub fn fiat_p434_to_bytes(out1: &mut [u8; 55], arg1: &[u64; 7]) -> () { let x1: u64 = (arg1[6]); let x2: u64 = (arg1[5]); let x3: u64 = (arg1[4]); let x4: u64 = (arg1[3]); let x5: u64 = (arg1[2]); let x6: u64 = (arg1[1]); let x7: u64 = (arg1[0]); let x8: u8 = ((x7 & (0xff as u64)) as u8); let x9: u64 = (x7 >> 8); let x10: u8 = ((x9 & (0xff as u64)) as u8); let x11: u64 = (x9 >> 8); let x12: u8 = ((x11 & (0xff as u64)) as u8); let x13: u64 = (x11 >> 8); let x14: u8 = ((x13 & (0xff as u64)) as u8); let x15: u64 = (x13 >> 8); let x16: u8 = ((x15 & (0xff as u64)) as u8); let x17: u64 = (x15 >> 8); let x18: u8 = ((x17 & (0xff as u64)) as u8); let x19: u64 = (x17 >> 8); let x20: u8 = ((x19 & (0xff as u64)) as u8); let x21: u8 = ((x19 >> 8) as u8); let x22: u8 = ((x6 & (0xff as u64)) as u8); let x23: u64 = (x6 >> 8); let x24: u8 = ((x23 & (0xff as u64)) as u8); let x25: u64 = (x23 >> 8); let x26: u8 = ((x25 & (0xff as u64)) as u8); let x27: u64 = (x25 >> 8); let x28: u8 = ((x27 & (0xff as u64)) as u8); let x29: u64 = (x27 >> 8); let x30: u8 = ((x29 & (0xff as u64)) as u8); let x31: u64 = (x29 >> 8); let x32: u8 = ((x31 & (0xff as u64)) as u8); let x33: u64 = (x31 >> 8); let x34: u8 = ((x33 & (0xff as u64)) as u8); let x35: u8 = ((x33 >> 8) as u8); let x36: u8 = ((x5 & (0xff as u64)) as u8); let x37: u64 = (x5 >> 8); let x38: u8 = ((x37 & (0xff as u64)) as u8); let x39: u64 = (x37 >> 8); let x40: u8 = ((x39 & (0xff as u64)) as u8); let x41: u64 = (x39 >> 8); let x42: u8 = ((x41 & (0xff as u64)) as u8); let x43: u64 = (x41 >> 8); let x44: u8 = ((x43 & (0xff as u64)) as u8); let x45: u64 = (x43 >> 8); let x46: u8 = ((x45 & (0xff as u64)) as u8); let x47: u64 = (x45 >> 8); let x48: u8 = ((x47 & (0xff as u64)) as u8); let x49: u8 = ((x47 >> 8) as u8); let x50: u8 = ((x4 & (0xff as u64)) as u8); let x51: u64 = (x4 >> 8); let x52: u8 = ((x51 & (0xff as u64)) as u8); let x53: u64 = (x51 >> 8); let x54: u8 = ((x53 & (0xff as u64)) as u8); let x55: u64 = (x53 >> 8); let x56: u8 = ((x55 & (0xff as u64)) as u8); let x57: u64 = (x55 >> 8); let x58: u8 = ((x57 & (0xff as u64)) as u8); let x59: u64 = (x57 >> 8); let x60: u8 = ((x59 & (0xff as u64)) as u8); let x61: u64 = (x59 >> 8); let x62: u8 = ((x61 & (0xff as u64)) as u8); let x63: u8 = ((x61 >> 8) as u8); let x64: u8 = ((x3 & (0xff as u64)) as u8); let x65: u64 = (x3 >> 8); let x66: u8 = ((x65 & (0xff as u64)) as u8); let x67: u64 = (x65 >> 8); let x68: u8 = ((x67 & (0xff as u64)) as u8); let x69: u64 = (x67 >> 8); let x70: u8 = ((x69 & (0xff as u64)) as u8); let x71: u64 = (x69 >> 8); let x72: u8 = ((x71 & (0xff as u64)) as u8); let x73: u64 = (x71 >> 8); let x74: u8 = ((x73 & (0xff as u64)) as u8); let x75: u64 = (x73 >> 8); let x76: u8 = ((x75 & (0xff as u64)) as u8); let x77: u8 = ((x75 >> 8) as u8); let x78: u8 = ((x2 & (0xff as u64)) as u8); let x79: u64 = (x2 >> 8); let x80: u8 = ((x79 & (0xff as u64)) as u8); let x81: u64 = (x79 >> 8); let x82: u8 = ((x81 & (0xff as u64)) as u8); let x83: u64 = (x81 >> 8); let x84: u8 = ((x83 & (0xff as u64)) as u8); let x85: u64 = (x83 >> 8); let x86: u8 = ((x85 & (0xff as u64)) as u8); let x87: u64 = (x85 >> 8); let x88: u8 = ((x87 & (0xff as u64)) as u8); let x89: u64 = (x87 >> 8); let x90: u8 = ((x89 & (0xff as u64)) as u8); let x91: u8 = ((x89 >> 8) as u8); let x92: u8 = ((x1 & (0xff as u64)) as u8); let x93: u64 = (x1 >> 8); let x94: u8 = ((x93 & (0xff as u64)) as u8); let x95: u64 = (x93 >> 8); let x96: u8 = ((x95 & (0xff as u64)) as u8); let x97: u64 = (x95 >> 8); let x98: u8 = ((x97 & (0xff as u64)) as u8); let x99: u64 = (x97 >> 8); let x100: u8 = ((x99 & (0xff as u64)) as u8); let x101: u64 = (x99 >> 8); let x102: u8 = ((x101 & (0xff as u64)) as u8); let x103: u8 = ((x101 >> 8) as u8); out1[0] = x8; out1[1] = x10; out1[2] = x12; out1[3] = x14; out1[4] = x16; out1[5] = x18; out1[6] = x20; out1[7] = x21; out1[8] = x22; out1[9] = x24; out1[10] = x26; out1[11] = x28; out1[12] = x30; out1[13] = x32; out1[14] = x34; out1[15] = x35; out1[16] = x36; out1[17] = x38; out1[18] = x40; out1[19] = x42; out1[20] = x44; out1[21] = x46; out1[22] = x48; out1[23] = x49; out1[24] = x50; out1[25] = x52; out1[26] = x54; out1[27] = x56; out1[28] = x58; out1[29] = x60; out1[30] = x62; out1[31] = x63; out1[32] = x64; out1[33] = x66; out1[34] = x68; out1[35] = x70; out1[36] = x72; out1[37] = x74; out1[38] = x76; out1[39] = x77; out1[40] = x78; out1[41] = x80; out1[42] = x82; out1[43] = x84; out1[44] = x86; out1[45] = x88; out1[46] = x90; out1[47] = x91; out1[48] = x92; out1[49] = x94; out1[50] = x96; out1[51] = x98; out1[52] = x100; out1[53] = x102; out1[54] = x103; } /// The function fiat_p434_from_bytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x3]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x3ffffffffffff]] #[inline] pub fn fiat_p434_from_bytes(out1: &mut [u64; 7], arg1: &[u8; 55]) -> () { let x1: u64 = (((arg1[54]) as u64) << 48); let x2: u64 = (((arg1[53]) as u64) << 40); let x3: u64 = (((arg1[52]) as u64) << 32); let x4: u64 = (((arg1[51]) as u64) << 24); let x5: u64 = (((arg1[50]) as u64) << 16); let x6: u64 = (((arg1[49]) as u64) << 8); let x7: u8 = (arg1[48]); let x8: u64 = (((arg1[47]) as u64) << 56); let x9: u64 = (((arg1[46]) as u64) << 48); let x10: u64 = (((arg1[45]) as u64) << 40); let x11: u64 = (((arg1[44]) as u64) << 32); let x12: u64 = (((arg1[43]) as u64) << 24); let x13: u64 = (((arg1[42]) as u64) << 16); let x14: u64 = (((arg1[41]) as u64) << 8); let x15: u8 = (arg1[40]); let x16: u64 = (((arg1[39]) as u64) << 56); let x17: u64 = (((arg1[38]) as u64) << 48); let x18: u64 = (((arg1[37]) as u64) << 40); let x19: u64 = (((arg1[36]) as u64) << 32); let x20: u64 = (((arg1[35]) as u64) << 24); let x21: u64 = (((arg1[34]) as u64) << 16); let x22: u64 = (((arg1[33]) as u64) << 8); let x23: u8 = (arg1[32]); let x24: u64 = (((arg1[31]) as u64) << 56); let x25: u64 = (((arg1[30]) as u64) << 48); let x26: u64 = (((arg1[29]) as u64) << 40); let x27: u64 = (((arg1[28]) as u64) << 32); let x28: u64 = (((arg1[27]) as u64) << 24); let x29: u64 = (((arg1[26]) as u64) << 16); let x30: u64 = (((arg1[25]) as u64) << 8); let x31: u8 = (arg1[24]); let x32: u64 = (((arg1[23]) as u64) << 56); let x33: u64 = (((arg1[22]) as u64) << 48); let x34: u64 = (((arg1[21]) as u64) << 40); let x35: u64 = (((arg1[20]) as u64) << 32); let x36: u64 = (((arg1[19]) as u64) << 24); let x37: u64 = (((arg1[18]) as u64) << 16); let x38: u64 = (((arg1[17]) as u64) << 8); let x39: u8 = (arg1[16]); let x40: u64 = (((arg1[15]) as u64) << 56); let x41: u64 = (((arg1[14]) as u64) << 48); let x42: u64 = (((arg1[13]) as u64) << 40); let x43: u64 = (((arg1[12]) as u64) << 32); let x44: u64 = (((arg1[11]) as u64) << 24); let x45: u64 = (((arg1[10]) as u64) << 16); let x46: u64 = (((arg1[9]) as u64) << 8); let x47: u8 = (arg1[8]); let x48: u64 = (((arg1[7]) as u64) << 56); let x49: u64 = (((arg1[6]) as u64) << 48); let x50: u64 = (((arg1[5]) as u64) << 40); let x51: u64 = (((arg1[4]) as u64) << 32); let x52: u64 = (((arg1[3]) as u64) << 24); let x53: u64 = (((arg1[2]) as u64) << 16); let x54: u64 = (((arg1[1]) as u64) << 8); let x55: u8 = (arg1[0]); let x56: u64 = (x54 + (x55 as u64)); let x57: u64 = (x53 + x56); let x58: u64 = (x52 + x57); let x59: u64 = (x51 + x58); let x60: u64 = (x50 + x59); let x61: u64 = (x49 + x60); let x62: u64 = (x48 + x61); let x63: u64 = (x46 + (x47 as u64)); let x64: u64 = (x45 + x63); let x65: u64 = (x44 + x64); let x66: u64 = (x43 + x65); let x67: u64 = (x42 + x66); let x68: u64 = (x41 + x67); let x69: u64 = (x40 + x68); let x70: u64 = (x38 + (x39 as u64)); let x71: u64 = (x37 + x70); let x72: u64 = (x36 + x71); let x73: u64 = (x35 + x72); let x74: u64 = (x34 + x73); let x75: u64 = (x33 + x74); let x76: u64 = (x32 + x75); let x77: u64 = (x30 + (x31 as u64)); let x78: u64 = (x29 + x77); let x79: u64 = (x28 + x78); let x80: u64 = (x27 + x79); let x81: u64 = (x26 + x80); let x82: u64 = (x25 + x81); let x83: u64 = (x24 + x82); let x84: u64 = (x22 + (x23 as u64)); let x85: u64 = (x21 + x84); let x86: u64 = (x20 + x85); let x87: u64 = (x19 + x86); let x88: u64 = (x18 + x87); let x89: u64 = (x17 + x88); let x90: u64 = (x16 + x89); let x91: u64 = (x14 + (x15 as u64)); let x92: u64 = (x13 + x91); let x93: u64 = (x12 + x92); let x94: u64 = (x11 + x93); let x95: u64 = (x10 + x94); let x96: u64 = (x9 + x95); let x97: u64 = (x8 + x96); let x98: u64 = (x6 + (x7 as u64)); let x99: u64 = (x5 + x98); let x100: u64 = (x4 + x99); let x101: u64 = (x3 + x100); let x102: u64 = (x2 + x101); let x103: u64 = (x1 + x102); out1[0] = x62; out1[1] = x69; out1[2] = x76; out1[3] = x83; out1[4] = x90; out1[5] = x97; out1[6] = x103; } /// The function fiat_p434_set_one returns the field element one in the Montgomery domain. /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_set_one(out1: &mut [u64; 7]) -> () { out1[0] = 0x742c; out1[1] = (0x0 as u64); out1[2] = (0x0 as u64); out1[3] = 0xb90ff404fc000000; out1[4] = 0xd801a4fb559facd4; out1[5] = 0xe93254545f77410c; out1[6] = 0xeceea7bd2eda; } /// The function fiat_p434_msat returns the saturated represtation of the prime modulus. /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_msat(out1: &mut [u64; 8]) -> () { out1[0] = 0xffffffffffffffff; out1[1] = 0xffffffffffffffff; out1[2] = 0xffffffffffffffff; out1[3] = 0xfdc1767ae2ffffff; out1[4] = 0x7bc65c783158aea3; out1[5] = 0x6cfc5fd681c52056; out1[6] = 0x2341f27177344; out1[7] = (0x0 as u64); } /// The function fiat_p434_divstep computes a divstep. /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_divstep(out1: &mut u64, out2: &mut [u64; 8], out3: &mut [u64; 8], out4: &mut [u64; 7], out5: &mut [u64; 7], arg1: u64, arg2: &[u64; 8], arg3: &[u64; 8], arg4: &[u64; 7], arg5: &[u64; 7]) -> () { let mut x1: u64 = 0; let mut x2: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x1, &mut x2, 0x0, (!arg1), (0x1 as u64)); let x3: fiat_p434_u1 = (((x1 >> 63) as fiat_p434_u1) & (((arg3[0]) & (0x1 as u64)) as fiat_p434_u1)); let mut x4: u64 = 0; let mut x5: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x4, &mut x5, 0x0, (!arg1), (0x1 as u64)); let mut x6: u64 = 0; fiat_p434_cmovznz_u64(&mut x6, x3, arg1, x4); let mut x7: u64 = 0; fiat_p434_cmovznz_u64(&mut x7, x3, (arg2[0]), (arg3[0])); let mut x8: u64 = 0; fiat_p434_cmovznz_u64(&mut x8, x3, (arg2[1]), (arg3[1])); let mut x9: u64 = 0; fiat_p434_cmovznz_u64(&mut x9, x3, (arg2[2]), (arg3[2])); let mut x10: u64 = 0; fiat_p434_cmovznz_u64(&mut x10, x3, (arg2[3]), (arg3[3])); let mut x11: u64 = 0; fiat_p434_cmovznz_u64(&mut x11, x3, (arg2[4]), (arg3[4])); let mut x12: u64 = 0; fiat_p434_cmovznz_u64(&mut x12, x3, (arg2[5]), (arg3[5])); let mut x13: u64 = 0; fiat_p434_cmovznz_u64(&mut x13, x3, (arg2[6]), (arg3[6])); let mut x14: u64 = 0; fiat_p434_cmovznz_u64(&mut x14, x3, (arg2[7]), (arg3[7])); let mut x15: u64 = 0; let mut x16: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x15, &mut x16, 0x0, (0x1 as u64), (!(arg2[0]))); let mut x17: u64 = 0; let mut x18: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x17, &mut x18, x16, (0x0 as u64), (!(arg2[1]))); let mut x19: u64 = 0; let mut x20: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x19, &mut x20, x18, (0x0 as u64), (!(arg2[2]))); let mut x21: u64 = 0; let mut x22: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x21, &mut x22, x20, (0x0 as u64), (!(arg2[3]))); let mut x23: u64 = 0; let mut x24: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x23, &mut x24, x22, (0x0 as u64), (!(arg2[4]))); let mut x25: u64 = 0; let mut x26: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x25, &mut x26, x24, (0x0 as u64), (!(arg2[5]))); let mut x27: u64 = 0; let mut x28: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x27, &mut x28, x26, (0x0 as u64), (!(arg2[6]))); let mut x29: u64 = 0; let mut x30: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x29, &mut x30, x28, (0x0 as u64), (!(arg2[7]))); let mut x31: u64 = 0; fiat_p434_cmovznz_u64(&mut x31, x3, (arg3[0]), x15); let mut x32: u64 = 0; fiat_p434_cmovznz_u64(&mut x32, x3, (arg3[1]), x17); let mut x33: u64 = 0; fiat_p434_cmovznz_u64(&mut x33, x3, (arg3[2]), x19); let mut x34: u64 = 0; fiat_p434_cmovznz_u64(&mut x34, x3, (arg3[3]), x21); let mut x35: u64 = 0; fiat_p434_cmovznz_u64(&mut x35, x3, (arg3[4]), x23); let mut x36: u64 = 0; fiat_p434_cmovznz_u64(&mut x36, x3, (arg3[5]), x25); let mut x37: u64 = 0; fiat_p434_cmovznz_u64(&mut x37, x3, (arg3[6]), x27); let mut x38: u64 = 0; fiat_p434_cmovznz_u64(&mut x38, x3, (arg3[7]), x29); let mut x39: u64 = 0; fiat_p434_cmovznz_u64(&mut x39, x3, (arg4[0]), (arg5[0])); let mut x40: u64 = 0; fiat_p434_cmovznz_u64(&mut x40, x3, (arg4[1]), (arg5[1])); let mut x41: u64 = 0; fiat_p434_cmovznz_u64(&mut x41, x3, (arg4[2]), (arg5[2])); let mut x42: u64 = 0; fiat_p434_cmovznz_u64(&mut x42, x3, (arg4[3]), (arg5[3])); let mut x43: u64 = 0; fiat_p434_cmovznz_u64(&mut x43, x3, (arg4[4]), (arg5[4])); let mut x44: u64 = 0; fiat_p434_cmovznz_u64(&mut x44, x3, (arg4[5]), (arg5[5])); let mut x45: u64 = 0; fiat_p434_cmovznz_u64(&mut x45, x3, (arg4[6]), (arg5[6])); let mut x46: u64 = 0; let mut x47: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x46, &mut x47, 0x0, x39, x39); let mut x48: u64 = 0; let mut x49: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x48, &mut x49, x47, x40, x40); let mut x50: u64 = 0; let mut x51: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x50, &mut x51, x49, x41, x41); let mut x52: u64 = 0; let mut x53: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x52, &mut x53, x51, x42, x42); let mut x54: u64 = 0; let mut x55: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x54, &mut x55, x53, x43, x43); let mut x56: u64 = 0; let mut x57: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x56, &mut x57, x55, x44, x44); let mut x58: u64 = 0; let mut x59: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x58, &mut x59, x57, x45, x45); let mut x60: u64 = 0; let mut x61: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x60, &mut x61, 0x0, x46, 0xffffffffffffffff); let mut x62: u64 = 0; let mut x63: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x62, &mut x63, x61, x48, 0xffffffffffffffff); let mut x64: u64 = 0; let mut x65: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x64, &mut x65, x63, x50, 0xffffffffffffffff); let mut x66: u64 = 0; let mut x67: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x66, &mut x67, x65, x52, 0xfdc1767ae2ffffff); let mut x68: u64 = 0; let mut x69: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x68, &mut x69, x67, x54, 0x7bc65c783158aea3); let mut x70: u64 = 0; let mut x71: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x70, &mut x71, x69, x56, 0x6cfc5fd681c52056); let mut x72: u64 = 0; let mut x73: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x72, &mut x73, x71, x58, 0x2341f27177344); let mut x74: u64 = 0; let mut x75: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x74, &mut x75, x73, (x59 as u64), (0x0 as u64)); let x76: u64 = (arg4[6]); let x77: u64 = (arg4[5]); let x78: u64 = (arg4[4]); let x79: u64 = (arg4[3]); let x80: u64 = (arg4[2]); let x81: u64 = (arg4[1]); let x82: u64 = (arg4[0]); let mut x83: u64 = 0; let mut x84: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x83, &mut x84, 0x0, (0x0 as u64), x82); let mut x85: u64 = 0; let mut x86: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x85, &mut x86, x84, (0x0 as u64), x81); let mut x87: u64 = 0; let mut x88: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x87, &mut x88, x86, (0x0 as u64), x80); let mut x89: u64 = 0; let mut x90: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x89, &mut x90, x88, (0x0 as u64), x79); let mut x91: u64 = 0; let mut x92: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x91, &mut x92, x90, (0x0 as u64), x78); let mut x93: u64 = 0; let mut x94: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x93, &mut x94, x92, (0x0 as u64), x77); let mut x95: u64 = 0; let mut x96: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x95, &mut x96, x94, (0x0 as u64), x76); let mut x97: u64 = 0; fiat_p434_cmovznz_u64(&mut x97, x96, (0x0 as u64), 0xffffffffffffffff); let mut x98: u64 = 0; let mut x99: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x98, &mut x99, 0x0, x83, x97); let mut x100: u64 = 0; let mut x101: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x100, &mut x101, x99, x85, x97); let mut x102: u64 = 0; let mut x103: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x102, &mut x103, x101, x87, x97); let mut x104: u64 = 0; let mut x105: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x104, &mut x105, x103, x89, (x97 & 0xfdc1767ae2ffffff)); let mut x106: u64 = 0; let mut x107: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x106, &mut x107, x105, x91, (x97 & 0x7bc65c783158aea3)); let mut x108: u64 = 0; let mut x109: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x108, &mut x109, x107, x93, (x97 & 0x6cfc5fd681c52056)); let mut x110: u64 = 0; let mut x111: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x110, &mut x111, x109, x95, (x97 & 0x2341f27177344)); let mut x112: u64 = 0; fiat_p434_cmovznz_u64(&mut x112, x3, (arg5[0]), x98); let mut x113: u64 = 0; fiat_p434_cmovznz_u64(&mut x113, x3, (arg5[1]), x100); let mut x114: u64 = 0; fiat_p434_cmovznz_u64(&mut x114, x3, (arg5[2]), x102); let mut x115: u64 = 0; fiat_p434_cmovznz_u64(&mut x115, x3, (arg5[3]), x104); let mut x116: u64 = 0; fiat_p434_cmovznz_u64(&mut x116, x3, (arg5[4]), x106); let mut x117: u64 = 0; fiat_p434_cmovznz_u64(&mut x117, x3, (arg5[5]), x108); let mut x118: u64 = 0; fiat_p434_cmovznz_u64(&mut x118, x3, (arg5[6]), x110); let x119: fiat_p434_u1 = ((x31 & (0x1 as u64)) as fiat_p434_u1); let mut x120: u64 = 0; fiat_p434_cmovznz_u64(&mut x120, x119, (0x0 as u64), x7); let mut x121: u64 = 0; fiat_p434_cmovznz_u64(&mut x121, x119, (0x0 as u64), x8); let mut x122: u64 = 0; fiat_p434_cmovznz_u64(&mut x122, x119, (0x0 as u64), x9); let mut x123: u64 = 0; fiat_p434_cmovznz_u64(&mut x123, x119, (0x0 as u64), x10); let mut x124: u64 = 0; fiat_p434_cmovznz_u64(&mut x124, x119, (0x0 as u64), x11); let mut x125: u64 = 0; fiat_p434_cmovznz_u64(&mut x125, x119, (0x0 as u64), x12); let mut x126: u64 = 0; fiat_p434_cmovznz_u64(&mut x126, x119, (0x0 as u64), x13); let mut x127: u64 = 0; fiat_p434_cmovznz_u64(&mut x127, x119, (0x0 as u64), x14); let mut x128: u64 = 0; let mut x129: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x128, &mut x129, 0x0, x31, x120); let mut x130: u64 = 0; let mut x131: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x130, &mut x131, x129, x32, x121); let mut x132: u64 = 0; let mut x133: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x132, &mut x133, x131, x33, x122); let mut x134: u64 = 0; let mut x135: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x134, &mut x135, x133, x34, x123); let mut x136: u64 = 0; let mut x137: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x136, &mut x137, x135, x35, x124); let mut x138: u64 = 0; let mut x139: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x138, &mut x139, x137, x36, x125); let mut x140: u64 = 0; let mut x141: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x140, &mut x141, x139, x37, x126); let mut x142: u64 = 0; let mut x143: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x142, &mut x143, x141, x38, x127); let mut x144: u64 = 0; fiat_p434_cmovznz_u64(&mut x144, x119, (0x0 as u64), x39); let mut x145: u64 = 0; fiat_p434_cmovznz_u64(&mut x145, x119, (0x0 as u64), x40); let mut x146: u64 = 0; fiat_p434_cmovznz_u64(&mut x146, x119, (0x0 as u64), x41); let mut x147: u64 = 0; fiat_p434_cmovznz_u64(&mut x147, x119, (0x0 as u64), x42); let mut x148: u64 = 0; fiat_p434_cmovznz_u64(&mut x148, x119, (0x0 as u64), x43); let mut x149: u64 = 0; fiat_p434_cmovznz_u64(&mut x149, x119, (0x0 as u64), x44); let mut x150: u64 = 0; fiat_p434_cmovznz_u64(&mut x150, x119, (0x0 as u64), x45); let mut x151: u64 = 0; let mut x152: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x151, &mut x152, 0x0, x112, x144); let mut x153: u64 = 0; let mut x154: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x153, &mut x154, x152, x113, x145); let mut x155: u64 = 0; let mut x156: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x155, &mut x156, x154, x114, x146); let mut x157: u64 = 0; let mut x158: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x157, &mut x158, x156, x115, x147); let mut x159: u64 = 0; let mut x160: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x159, &mut x160, x158, x116, x148); let mut x161: u64 = 0; let mut x162: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x161, &mut x162, x160, x117, x149); let mut x163: u64 = 0; let mut x164: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x163, &mut x164, x162, x118, x150); let mut x165: u64 = 0; let mut x166: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x165, &mut x166, 0x0, x151, 0xffffffffffffffff); let mut x167: u64 = 0; let mut x168: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x167, &mut x168, x166, x153, 0xffffffffffffffff); let mut x169: u64 = 0; let mut x170: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x169, &mut x170, x168, x155, 0xffffffffffffffff); let mut x171: u64 = 0; let mut x172: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x171, &mut x172, x170, x157, 0xfdc1767ae2ffffff); let mut x173: u64 = 0; let mut x174: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x173, &mut x174, x172, x159, 0x7bc65c783158aea3); let mut x175: u64 = 0; let mut x176: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x175, &mut x176, x174, x161, 0x6cfc5fd681c52056); let mut x177: u64 = 0; let mut x178: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x177, &mut x178, x176, x163, 0x2341f27177344); let mut x179: u64 = 0; let mut x180: fiat_p434_u1 = 0; fiat_p434_subborrowx_u64(&mut x179, &mut x180, x178, (x164 as u64), (0x0 as u64)); let mut x181: u64 = 0; let mut x182: fiat_p434_u1 = 0; fiat_p434_addcarryx_u64(&mut x181, &mut x182, 0x0, x6, (0x1 as u64)); let x183: u64 = ((x128 >> 1) | ((x130 << 63) & 0xffffffffffffffff)); let x184: u64 = ((x130 >> 1) | ((x132 << 63) & 0xffffffffffffffff)); let x185: u64 = ((x132 >> 1) | ((x134 << 63) & 0xffffffffffffffff)); let x186: u64 = ((x134 >> 1) | ((x136 << 63) & 0xffffffffffffffff)); let x187: u64 = ((x136 >> 1) | ((x138 << 63) & 0xffffffffffffffff)); let x188: u64 = ((x138 >> 1) | ((x140 << 63) & 0xffffffffffffffff)); let x189: u64 = ((x140 >> 1) | ((x142 << 63) & 0xffffffffffffffff)); let x190: u64 = ((x142 & 0x8000000000000000) | (x142 >> 1)); let mut x191: u64 = 0; fiat_p434_cmovznz_u64(&mut x191, x75, x60, x46); let mut x192: u64 = 0; fiat_p434_cmovznz_u64(&mut x192, x75, x62, x48); let mut x193: u64 = 0; fiat_p434_cmovznz_u64(&mut x193, x75, x64, x50); let mut x194: u64 = 0; fiat_p434_cmovznz_u64(&mut x194, x75, x66, x52); let mut x195: u64 = 0; fiat_p434_cmovznz_u64(&mut x195, x75, x68, x54); let mut x196: u64 = 0; fiat_p434_cmovznz_u64(&mut x196, x75, x70, x56); let mut x197: u64 = 0; fiat_p434_cmovznz_u64(&mut x197, x75, x72, x58); let mut x198: u64 = 0; fiat_p434_cmovznz_u64(&mut x198, x180, x165, x151); let mut x199: u64 = 0; fiat_p434_cmovznz_u64(&mut x199, x180, x167, x153); let mut x200: u64 = 0; fiat_p434_cmovznz_u64(&mut x200, x180, x169, x155); let mut x201: u64 = 0; fiat_p434_cmovznz_u64(&mut x201, x180, x171, x157); let mut x202: u64 = 0; fiat_p434_cmovznz_u64(&mut x202, x180, x173, x159); let mut x203: u64 = 0; fiat_p434_cmovznz_u64(&mut x203, x180, x175, x161); let mut x204: u64 = 0; fiat_p434_cmovznz_u64(&mut x204, x180, x177, x163); *out1 = x181; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out2[5] = x12; out2[6] = x13; out2[7] = x14; out3[0] = x183; out3[1] = x184; out3[2] = x185; out3[3] = x186; out3[4] = x187; out3[5] = x188; out3[6] = x189; out3[7] = x190; out4[0] = x191; out4[1] = x192; out4[2] = x193; out4[3] = x194; out4[4] = x195; out4[5] = x196; out4[6] = x197; out5[0] = x198; out5[1] = x199; out5[2] = x200; out5[3] = x201; out5[4] = x202; out5[5] = x203; out5[6] = x204; } /// The function fiat_p434_divstep_precomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if (log2 m) + 1 < 46 then ⌊(49 * ((log2 m) + 1) + 80) / 17⌋ else ⌊(49 * ((log2 m) + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] #[inline] pub fn fiat_p434_divstep_precomp(out1: &mut [u64; 7]) -> () { out1[0] = 0x9f9776e27e1a2b72; out1[1] = 0x28b59f067e2393d0; out1[2] = 0xcf316ce1572add54; out1[3] = 0x312c8965f9032c2f; out1[4] = 0x9d9cab29ad90d34c; out1[5] = 0x6e1ddae1d9609ae1; out1[6] = 0x6df82285eec6; }
41.851637
963
0.65452
231c57390b3019a4f13e2ae0e0c77e879b97eeb3
626
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:panicked at 'Box<Any>' #![allow(unknown_features)] #![feature(box_syntax)] fn main() { panic!(box 413i as Box<::std::any::Any+Send>); }
32.947368
68
0.71885
d6e567bcb3a708948935ca9616e00e934bd52991
12,417
//! Joint is used to restrict motion of two rigid bodies. use crate::utils::log::Log; use crate::{ core::{ algebra::{UnitComplex, Vector2}, inspect::{Inspect, PropertyInfo}, pool::Handle, visitor::prelude::*, }, engine::resource_manager::ResourceManager, impl_directly_inheritable_entity_trait, scene::{ base::{Base, BaseBuilder}, graph::Graph, node::Node, variable::{InheritError, TemplateVariable}, DirectlyInheritableEntity, }, }; use fxhash::FxHashMap; use rapier2d::dynamics::JointHandle; use std::{ cell::Cell, ops::{Deref, DerefMut}, }; /// Ball joint locks any translational moves between two objects on the axis between objects, but /// allows rigid bodies to perform relative rotations. The real world example is a human shoulder, /// pendulum, etc. #[derive(Clone, Debug, Visit, PartialEq, Inspect)] pub struct BallJoint { /// Where the prismatic joint is attached on the first body, expressed in the local space of the /// first attached body. pub local_anchor1: Vector2<f32>, /// Where the prismatic joint is attached on the second body, expressed in the local space of the /// second attached body. pub local_anchor2: Vector2<f32>, /// Are the limits enabled for this joint? pub limits_enabled: bool, /// The axis of the limit cone for this joint, if the local-space of the first body. pub limits_local_axis1: Vector2<f32>, /// The axis of the limit cone for this joint, if the local-space of the first body. pub limits_local_axis2: Vector2<f32>, /// The maximum angle allowed between the two limit axes in world-space. pub limits_angle: f32, } impl Default for BallJoint { fn default() -> Self { Self { local_anchor1: Default::default(), local_anchor2: Default::default(), limits_enabled: false, limits_local_axis1: Default::default(), limits_local_axis2: Default::default(), limits_angle: f32::MAX, } } } /// A fixed joint ensures that two rigid bodies does not move relative to each other. There is no /// straightforward real-world example, but it can be thought as two bodies were "welded" together. #[derive(Clone, Debug, Visit, PartialEq, Inspect)] pub struct FixedJoint { /// Local translation for the first body. pub local_anchor1_translation: Vector2<f32>, /// Local rotation for the first body. pub local_anchor1_rotation: UnitComplex<f32>, /// Local translation for the second body. pub local_anchor2_translation: Vector2<f32>, /// Local rotation for the second body. pub local_anchor2_rotation: UnitComplex<f32>, } impl Default for FixedJoint { fn default() -> Self { Self { local_anchor1_translation: Default::default(), local_anchor1_rotation: UnitComplex::new(0.0), local_anchor2_translation: Default::default(), local_anchor2_rotation: UnitComplex::new(0.0), } } } /// Prismatic joint prevents any relative movement between two rigid-bodies, except for relative /// translations along one axis. The real world example is a sliders that used to support drawers. #[derive(Clone, Debug, Visit, PartialEq, Inspect)] pub struct PrismaticJoint { /// Where the prismatic joint is attached on the first body, expressed in the local space of the /// first attached body. pub local_anchor1: Vector2<f32>, /// The rotation axis of this revolute joint expressed in the local space of the first attached /// body. pub local_axis1: Vector2<f32>, /// Where the prismatic joint is attached on the second body, expressed in the local space of the /// second attached body. pub local_anchor2: Vector2<f32>, /// The rotation axis of this revolute joint expressed in the local space of the second attached /// body. pub local_axis2: Vector2<f32>, /// Whether or not this joint should enforce translational limits along its axis. pub limits_enabled: bool, /// The min an max relative position of the attached bodies along this joint's axis. pub limits: [f32; 2], } impl Default for PrismaticJoint { fn default() -> Self { Self { local_anchor1: Default::default(), local_axis1: Vector2::y(), local_anchor2: Default::default(), local_axis2: Vector2::x(), limits_enabled: false, limits: [f32::MIN, f32::MAX], } } } /// The exact kind of the joint. #[derive(Clone, Debug, PartialEq, Visit)] pub enum JointParams { /// See [`BallJoint`] for more info. BallJoint(BallJoint), /// See [`FixedJoint`] for more info. FixedJoint(FixedJoint), /// See [`PrismaticJoint`] for more info. PrismaticJoint(PrismaticJoint), } impl Inspect for JointParams { fn properties(&self) -> Vec<PropertyInfo<'_>> { match self { JointParams::BallJoint(v) => v.properties(), JointParams::FixedJoint(v) => v.properties(), JointParams::PrismaticJoint(v) => v.properties(), } } } impl Default for JointParams { fn default() -> Self { Self::BallJoint(Default::default()) } } /// Joint is used to restrict motion of two rigid bodies. There are numerous examples of joints in /// real life: door hinge, ball joints in human arms, etc. #[derive(Visit, Inspect, Debug)] pub struct Joint { base: Base, #[inspect(getter = "Deref::deref")] pub(crate) params: TemplateVariable<JointParams>, #[inspect(getter = "Deref::deref")] pub(crate) body1: TemplateVariable<Handle<Node>>, #[inspect(getter = "Deref::deref")] pub(crate) body2: TemplateVariable<Handle<Node>>, #[visit(skip)] #[inspect(skip)] pub(crate) native: Cell<JointHandle>, } impl_directly_inheritable_entity_trait!(Joint; params, body1, body2 ); impl Default for Joint { fn default() -> Self { Self { base: Default::default(), params: Default::default(), body1: Default::default(), body2: Default::default(), native: Cell::new(JointHandle::invalid()), } } } impl Deref for Joint { type Target = Base; fn deref(&self) -> &Self::Target { &self.base } } impl DerefMut for Joint { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.base } } impl Joint { /// Creates a raw copy of the joint node. This is for internal use only! pub fn raw_copy(&self) -> Self { Self { base: self.base.raw_copy(), params: self.params.clone(), body1: self.body1.clone(), body2: self.body2.clone(), native: Cell::new(JointHandle::invalid()), } } /// Returns a shared reference to the current joint parameters. pub fn params(&self) -> &JointParams { &self.params } /// Returns a mutable reference to the current joint parameters. Obtaining the mutable reference /// will force the engine to do additional calculations to reflect changes to the physics engine. pub fn params_mut(&mut self) -> &mut JointParams { self.params.get_mut() } /// Sets the first body of the joint. The handle should point to the RigidBody node, otherwise /// the joint will have no effect! pub fn set_body1(&mut self, handle: Handle<Node>) { self.body1.set(handle); } /// Returns current first body of the joint. pub fn body1(&self) -> Handle<Node> { *self.body1 } /// Sets the second body of the joint. The handle should point to the RigidBody node, otherwise /// the joint will have no effect! pub fn set_body2(&mut self, handle: Handle<Node>) { self.body2.set(handle); } /// Returns current second body of the joint. pub fn body2(&self) -> Handle<Node> { *self.body2 } pub(crate) fn restore_resources(&mut self, _resource_manager: ResourceManager) {} // Prefab inheritance resolving. pub(crate) fn inherit(&mut self, parent: &Node) -> Result<(), InheritError> { self.base.inherit_properties(parent)?; if let Node::Joint2D(parent) = parent { self.try_inherit_self_properties(parent)?; } Ok(()) } pub(crate) fn reset_inheritable_properties(&mut self) { self.base.reset_inheritable_properties(); self.reset_self_inheritable_properties(); } pub(crate) fn remap_handles( &mut self, old_new_mapping: &FxHashMap<Handle<Node>, Handle<Node>>, ) { self.base.remap_handles(old_new_mapping); if let Some(entry) = old_new_mapping.get(&self.body1()) { self.body1.set_silent(*entry); } else { Log::warn(format!( "Unable to remap first body of a joint {}. Handle is {}!", self.name(), self.body1() )) } if let Some(entry) = old_new_mapping.get(&self.body2()) { self.body2.set_silent(*entry); } else { Log::warn(format!( "Unable to remap second body of a joint {}. Handle is {}!", self.name(), self.body2() )) } } } /// Joint builder allows you to build Joint node in a declarative manner. pub struct JointBuilder { base_builder: BaseBuilder, params: JointParams, body1: Handle<Node>, body2: Handle<Node>, } impl JointBuilder { /// Creates a new joint builder instance. pub fn new(base_builder: BaseBuilder) -> Self { Self { base_builder, params: Default::default(), body1: Default::default(), body2: Default::default(), } } /// Sets desired joint parameters which defines exact type of the joint. pub fn with_params(mut self, params: JointParams) -> Self { self.params = params; self } /// Sets desired first body of the joint. This handle should be a handle to rigid body node, /// otherwise joint will have no effect! pub fn with_body1(mut self, body1: Handle<Node>) -> Self { self.body1 = body1; self } /// Sets desired second body of the joint. This handle should be a handle to rigid body node, /// otherwise joint will have no effect! pub fn with_body2(mut self, body2: Handle<Node>) -> Self { self.body2 = body2; self } /// Creates new Joint node, but does not add it to the graph. pub fn build_joint(self) -> Joint { Joint { base: self.base_builder.build_base(), params: self.params.into(), body1: self.body1.into(), body2: self.body2.into(), native: Cell::new(JointHandle::invalid()), } } /// Creates new Joint node, but does not add it to the graph. pub fn build_node(self) -> Node { Node::Joint2D(self.build_joint()) } /// Creates new Joint node and adds it to the graph. pub fn build(self, graph: &mut Graph) -> Handle<Node> { graph.add_node(self.build_node()) } } #[cfg(test)] mod test { use crate::{ core::algebra::Vector2, scene::{ base::{test::check_inheritable_properties_equality, BaseBuilder}, dim2::joint::{BallJoint, JointBuilder, JointParams}, node::Node, }, }; #[test] fn test_joint_2d_inheritance() { let parent = JointBuilder::new(BaseBuilder::new()) .with_params(JointParams::BallJoint(BallJoint { local_anchor1: Vector2::new(1.0, 0.0), local_anchor2: Vector2::new(1.0, 1.0), limits_enabled: true, limits_local_axis1: Vector2::new(1.0, 1.0), limits_local_axis2: Vector2::new(1.0, 1.0), limits_angle: 1.57, })) .build_node(); let mut child = JointBuilder::new(BaseBuilder::new()).build_joint(); child.inherit(&parent).unwrap(); if let Node::Joint2D(parent) = parent { check_inheritable_properties_equality(&child.base, &parent.base); check_inheritable_properties_equality(&child, &parent); } else { unreachable!(); } } }
32.085271
101
0.61746
8a024e580921aaa9701aef2936008f766891fd1b
14,685
// (Lines like the one below ignore selected Clippy rules // - it's useful when you want to check your code with `cargo make verify` // but some rules are too "annoying" or are not applicable for your case.) #![allow(clippy::wildcard_imports)] use seed::{*, prelude::{*}}; // ------ ------ // Init // ------ ------ // `init` describes what should happen when your app started. fn init(_: Url, orders: &mut impl Orders<Msg>) -> Model { let mut wsurl = "ws://127.0.0.1:1234".to_owned(); if let Ok(mut durl) = html_document().url() { let splits : Vec<&str> = durl.split('#').collect(); if splits.len() >= 2 { wsurl = splits[1].to_owned(); // assuming it would be rendered by that time: orders.perform_cmd(cmds::timeout(20, || Msg::AutoConnectAndFocusPassword)); } else { if durl.starts_with("http") { durl = format!("ws{}",&durl[4..]); } if durl.ends_with("/viewer.html") { durl = format!("{}/ws", &durl[..(durl.len()-12)]); wsurl = durl; } } }; let mut password = "".to_owned(); if let Ok(x) = LocalStorage::get("password") { password = x; } initplot(); orders.stream(seed::app::streams::interval(1000, ||Msg::SecondlyUpdate)); Model { wsurl, ws: None, errormsg: "".to_owned(), status: None, password, visible_password: false, conn_status: ConnStatus::Disconnected, ticker_filter: "SPY".to_string(), preroll_size: "100000".to_string(), } } // ------ ------ // Model // ------ ------ // `Model` describes our app state. struct Model { wsurl: String, ws: Option<WebSocket>, errormsg: String, status: Option<SystemStatus>, password: String, visible_password: bool, conn_status: ConnStatus, ticker_filter: String, preroll_size: String, } #[derive(Debug)] enum ConnStatus { Disconnected, Unauthenticated, Connected, } #[derive(serde_derive::Deserialize, Clone, Copy, Debug)] #[serde(rename_all = "snake_case")] pub enum UpstreamStatus { Disabled, Paused, Connecting, Connected, Mirroring, } #[derive(serde_derive::Deserialize, Debug)] pub struct SystemStatus { upstream_status: UpstreamStatus, #[serde(flatten)] #[allow(dead_code)] rest: serde_json::Value, } #[derive(serde_derive::Serialize, Debug)] #[serde(tag = "action", content = "data")] #[serde(rename_all = "snake_case")] #[allow(dead_code)] enum ControlMessage { Preroll(u64), Monitor, Filter(Vec<String>), RemoveRetainingLastN(u64), DatabaseSize, Status, Shutdown, PauseUpstream, ResumeUpstream, CursorToSpecificId(u64), Password(String), WriteConfig(serde_json::Value), ReadConfig, } #[derive(serde_derive::Deserialize, Debug)] #[serde(tag = "T")] #[serde(rename_all = "snake_case")] enum ReplyMessage { Stats(SystemStatus), Error{msg:String}, Hello{status:UpstreamStatus}, Config(serde_json::Value), #[serde(rename="b")] Bar(Bar), PrerollFinished, } #[derive(serde_derive::Serialize, Debug)] struct BarForPlotting { time: i64, open: f32, high: f32, low: f32, close: f32, volume: f32, } #[derive(serde_derive::Deserialize, Debug, Clone)] struct Bar { #[serde(rename="t", deserialize_with="time::serde::rfc3339::deserialize")] datetime: time::OffsetDateTime, #[serde(rename="S")] ticker: String, #[serde(rename="o")] open: f32, #[serde(rename="h")] high: f32, #[serde(rename="l")] low: f32, #[serde(rename="c")] close: f32, #[serde(rename="v")] volume: f32, } // ------ ------ // Update // ------ ------ // (Remove the line below once any of your `Msg` variants doesn't implement `Copy`.) #[derive()] // `Msg` describes the different events you can modify state with. enum Msg { SecondlyUpdate, UpdateWsUrl(String), UpdatePassword(String), ToggleConnectWs, WsClosed, WsError, WsConnected, WsMessage(WebSocketMessage), ToggleVisiblePassword, AutoConnectAndFocusPassword, SendPassword, Plot, UpdateTickerFilter(String), UpdatePrerollSize(String), } fn handle_ws_message(msg: ReplyMessage, model: &mut Model, _orders: &mut impl Orders<Msg>) { if ! matches! (msg, ReplyMessage::Stats{..} | ReplyMessage::Bar{..}) { log(&msg); } model.conn_status = ConnStatus::Connected; match msg { ReplyMessage::Stats(x) => { model.status = Some(x); } ReplyMessage::Error{msg:x} => { if x.contains("Supply a password first") || x.contains("Invalid password") { model.conn_status = ConnStatus::Unauthenticated; } else { model.errormsg = format!("Error from server: {}", x); } } ReplyMessage::Hello{status:upstream_status} => { model.status = Some(SystemStatus{ upstream_status, rest: serde_json::Value::Null, }); if ! model.password.is_empty() { let _ = model.ws.as_ref().unwrap().send_json(&ControlMessage::Password(model.password.clone())); } let _ = model.ws.as_ref().unwrap().send_json(&ControlMessage::Status); } ReplyMessage::Config{0:x} => { drop(x); } ReplyMessage::Bar(x) => { add_bar_to_plot(&x); } ReplyMessage::PrerollFinished => { } } } fn send_ws(cmsg: ControlMessage, model: &mut Model, _orders: &mut impl Orders<Msg>) { if let Some(ws) = model.ws.as_ref() { log(&cmsg); if let Err(e) = ws.send_json(&cmsg) { model.errormsg = format!("WebSocket error: {:?}", e); } } else { model.errormsg = "Error: WebSocket must be connected for this".to_owned(); } } fn closews(model: &mut Model, _orders: &mut impl Orders<Msg>) { if let Some(ws) = model.ws.as_mut() { let _ = ws.close(None, None); model.ws = None; } model.conn_status = ConnStatus::Disconnected; } // `update` describes how to handle each `Msg`. fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) { match msg { Msg::SecondlyUpdate => { if let Some(ws) = model.ws.as_ref() { if ! matches!(model.conn_status, ConnStatus::Unauthenticated) { drop(ws); } } } Msg::UpdateWsUrl(x) => model.wsurl = x, Msg::ToggleConnectWs => { if model.ws.is_some() { closews(model, orders); } else { let ws = seed::browser::web_socket::WebSocket::builder(&model.wsurl, orders) .on_open(||Msg::WsConnected) .on_close(|_|Msg::WsClosed) .on_error(||Msg::WsError) .on_message(|x| Msg::WsMessage(x)) .build_and_open(); match ws { Ok(x) => { // for in-browser debugging using web console: let _ = js_sys::Reflect::set(&window(), &JsValue::from_str("ws"), x.raw_web_socket()); model.ws = Some(x); } Err(e) => { model.errormsg = format!("{:?}", e); log(e); } } } //orders.stream() } Msg::WsClosed => { model.errormsg = "WebSocket closed".to_owned(); closews(model, orders); } Msg::WsError => { model.errormsg = "WebSocket error".to_owned(); closews(model, orders); } Msg::WsConnected => { model.errormsg.clear(); } Msg::WsMessage(x) => { if let Ok(msgs) = x.json().map(|x:Vec<ReplyMessage>|x) { for t in msgs { handle_ws_message(t, model, orders); } } else { log!("Invalid WebSocket message: {}", x.text()); } } Msg::UpdatePassword(x) => model.password = x, Msg::SendPassword => { let _ = LocalStorage::insert("password", &model.password); send_ws(ControlMessage::Password(model.password.clone()), model, orders); model.conn_status=ConnStatus::Connected; }, Msg::ToggleVisiblePassword => model.visible_password ^= true, Msg::AutoConnectAndFocusPassword => { //log("1"); if let Some(pe) = html_document().get_element_by_id("passwordentry") { //log("2"); if let Ok(fm) = js_sys::Reflect::get(pe.as_ref(), &JsValue::from_str("focus")) { //log("3"); if let Some(fm) = wasm_bindgen::JsCast::dyn_ref(&fm) { let _ = js_sys::Function::call0(fm, pe.as_ref()); } } } return update(Msg::ToggleConnectWs, model, orders); } Msg::Plot => { if let Ok(preroll) = model.preroll_size.parse() { clear_plot(); send_ws(ControlMessage::Filter(vec![model.ticker_filter.clone()]), model, orders); send_ws(ControlMessage::Preroll(preroll), model, orders); } else { model.errormsg = "Failed to parse preroll size".to_owned(); } /* let bar = BarForPlotting { time: 1641416197, open: 74.43, high: 120.0, low: 70.0, close: 71.0, volume: 10000.0, }; add_data_to_plot(wasm_bindgen::JsValue::from_serde(&bar).unwrap()); let bar = BarForPlotting { time: 1641416197+3600, open: 74.43, high: 110.0, low: 60.0, close: 84.0, volume: 20000.0,}; add_data_to_plot(wasm_bindgen::JsValue::from_serde(&bar).unwrap()); let bar = BarForPlotting { time: 1641416197+7200, open: 71.43, high: 130.0, low: 65.0, close: 82.0, volume: 15000.0,}; add_data_to_plot(wasm_bindgen::JsValue::from_serde(&bar).unwrap()); */ } Msg::UpdateTickerFilter(x) => { model.ticker_filter = x; } Msg::UpdatePrerollSize(x) => { model.preroll_size = x; } } html_document().set_title(match model.conn_status { ConnStatus::Disconnected => "WsVw: diconnected", ConnStatus::Unauthenticated => "WsVw: passwd", ConnStatus::Connected => match &model.status { Some(us) => match us.upstream_status { UpstreamStatus::Connected => "WsVw", UpstreamStatus::Disabled => "WsVw: off", UpstreamStatus::Paused => "WsVw: paused", UpstreamStatus::Connecting => "WsVw: connecing", UpstreamStatus::Mirroring => "WsVw: mirroring", } None => "WsPrx: ?", } }); } // ------ ------ // View // ------ ------ // `view` describes what to display. fn view(model: &Model) -> Node<Msg> { div![ div![ C!["title"], "AlpacaProxy viewer" ], div![ C!["websocketcontrol"], label![ span!["WebSocket URL:"], input![ C!["websocket-uri"], attrs!{ At::Value => model.wsurl, At::Type => "text" }, input_ev(Ev::Input, Msg::UpdateWsUrl), keyboard_ev(Ev::KeyUp, |e| { if e.key() == "Enter" { Some(Msg::ToggleConnectWs) } else { None } }), ], ], button![ if model.ws.is_none() { "Connect" } else { "Disconnect"} , ev(Ev::Click, |_|Msg::ToggleConnectWs), ], ], div![ C!["passwordcontrol"], label![ span!["Password:"], input![ C!["password"], id!["passwordentry"], attrs! { At::Type => if model.visible_password { "text" } else { "password" }, At::Value => model.password, }, input_ev(Ev::Input, Msg::UpdatePassword), keyboard_ev(Ev::KeyUp, |e| { if e.key() == "Enter" { Some(Msg::SendPassword) } else { None } }), ], ], label![ C!["visiblepwd"], "Visible password", input![ attrs!{At::Type => "checkbox", At::Checked => model.visible_password.as_at_value()}, ev(Ev::Change, |_| Msg::ToggleVisiblePassword), ], ], button![ "Send", ev(Ev::Click, |_|Msg::SendPassword), ], ], div![ C!["errormsg"], &model.errormsg, ], div![ C!["mainactions"], input![ C!["tickerentry"], attrs!{ At::Value => model.ticker_filter, At::Type => "text" }, input_ev(Ev::Input, Msg::UpdateTickerFilter), //keyboard_ev(Ev::KeyUp, |e| { if e.key() == "Enter" { Some(Msg::ToggleConnectWs) } else { None } }), ], input![ C!["prerollentry"], attrs!{ At::Value => model.preroll_size, At::Type => "text" }, input_ev(Ev::Input, Msg::UpdatePrerollSize), //keyboard_ev(Ev::KeyUp, |e| { if e.key() == "Enter" { Some(Msg::ToggleConnectWs) } else { None } }), ], button![ "Preroll", ev(Ev::Click, |_|Msg::Plot), ], ], ] } // ------ ------ // Start // ------ ------ // (This function is invoked by `init` function in `index.html`.) #[wasm_bindgen(start)] pub fn start() { // Mount the `app` to the element with the `id` "app". App::start("app", init, update, view); } /// --- /// Misc /// --- fn add_bar_to_plot(b: &Bar) { let Bar { open, high, low, close, volume , ..} = *b; let time = b.datetime.unix_timestamp(); let bar = BarForPlotting { time, open, high, low, close, volume, }; add_data_to_plot(wasm_bindgen::JsValue::from_serde(&bar).unwrap()); } #[wasm_bindgen] extern "C" { fn initplot(); fn add_data_to_plot(val: wasm_bindgen::JsValue); fn clear_plot(); }
31.378205
130
0.512496
b9c5927646f7183de573cb0350689330fd87f2ac
1,086
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use address::Address; use vm::ActorID; lazy_static! { pub static ref SYSTEM_ACTOR_ADDR: Address = Address::new_id(0); pub static ref INIT_ACTOR_ADDR: Address = Address::new_id(1); pub static ref REWARD_ACTOR_ADDR: Address = Address::new_id(2); pub static ref CRON_ACTOR_ADDR: Address = Address::new_id(3); pub static ref STORAGE_POWER_ACTOR_ADDR: Address = Address::new_id(4); pub static ref STORAGE_MARKET_ACTOR_ADDR: Address = Address::new_id(5); pub static ref VERIFIED_REGISTRY_ACTOR_ADDR: Address = Address::new_id(6); pub static ref CHAOS_ACTOR_ADDR: Address = Address::new_id(97); pub static ref PUPPET_ACTOR_ADDR: Address = Address::new_id(98); /// Distinguished AccountActor that is the destination of all burnt funds. pub static ref BURNT_FUNDS_ACTOR_ADDR: Address = Address::new_id(99); } /// Defines first available ID address after builtin actors pub const FIRST_NON_SINGLETON_ADDR: ActorID = 100;
43.44
78
0.718232
1cbf40068b1d58973d0f16c6dbab5b562cd90474
321
use std::{ hash::{Hash, Hasher}, any::TypeId, collections::hash_map::DefaultHasher, }; pub trait TypeHash: 'static { fn type_hash() -> u64 { let mut hasher = DefaultHasher::new(); TypeId::of::<Self>().hash(&mut hasher); hasher.finish() } } impl<T: 'static> TypeHash for T {}
20.0625
47
0.576324
8af17119dc5155b2855a7ee37700122fc4d97720
1,105
//! The module defines the `Version`. use indexmap::IndexMap; use super::*; /// The `Version` object is utilized to inform the client of the versions of /// different components of the Rosetta implementation. #[derive(Clone, Debug, Default, Deserialize, Serialize)] pub struct Version { /// The `rosetta_version` is the version of the Rosetta interface the /// implementation adheres to. This can be useful for clients looking to /// reliably parse responses. pub rosetta_version: String, /// The `node_version` is the canonical version of the node runtime. This /// can help clients manage deployments. pub node_version: String, /// When a middleware server is used to adhere to the Rosetta interface, it /// should return its version here. This can help clients manage /// deployments. #[serde(skip_serializing_if = "Option::is_none")] pub middleware_version: Option<String>, #[allow(clippy::missing_docs_in_private_items)] #[serde(default)] #[serde(skip_serializing_if = "IndexMap::is_empty")] pub metadata: IndexMap<String, Value>, }
39.464286
79
0.715837
18f21dfe97e478dfaa54899d8dc3a242c1104ecb
36,996
// Copyright 2016 Masaki Hara // Copyright 2019 Fortanix, Inc. // // 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. #![forbid(missing_docs)] use alloc::vec::Vec; #[cfg(feature = "num-bigint")] use num_bigint::{BigUint, BigInt}; #[cfg(feature = "bit-vec")] use bit_vec::BitVec; use super::{PCBit, Tag}; use super::tags::{TAG_BOOLEAN,TAG_INTEGER,TAG_OCTETSTRING}; use super::tags::{TAG_NULL,TAG_OID,TAG_UTF8STRING,TAG_SEQUENCE,TAG_SET,TAG_ENUM,TAG_IA5STRING,TAG_BMPSTRING}; use super::tags::{TAG_NUMERICSTRING,TAG_PRINTABLESTRING,TAG_VISIBLESTRING}; use super::models::{ObjectIdentifier,TaggedDerValue}; #[cfg(feature = "chrono")] use super::models::{UTCTime,GeneralizedTime}; /// Constructs DER-encoded data as `Vec<u8>`. /// /// This function uses the loan pattern: `callback` is called back with /// a [`DERWriter`], to which the ASN.1 value is written. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_sequence(|writer| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// }) /// }); /// assert_eq!(der, vec![48, 6, 2, 1, 10, 1, 1, 255]); /// ``` pub fn construct_der<F>(callback: F) -> Vec<u8> where F: FnOnce(DERWriter) { let mut buf = Vec::new(); { let mut writer = DERWriterSeq { buf: &mut buf, }; callback(writer.next()); } return buf; } /// Tries to construct DER-encoded data as `Vec<u8>`. /// /// Same as [`construct_der`], only that it allows /// returning an error from the passed closure. /// /// This function uses the loan pattern: `callback` is called back with /// a [`DERWriterSeq`], to which the ASN.1 values are written. /// /// # Examples /// /// ``` /// use yasna; /// let res_ok = yasna::try_construct_der::<_, ()>(|writer| { /// writer.write_sequence(|writer| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// }); /// Ok(()) /// }); /// let res_err = yasna::try_construct_der::<_, &str>(|writer| { /// writer.write_sequence(|writer| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// return Err("some error here"); /// })?; /// Ok(()) /// }); /// assert_eq!(res_ok, Ok(vec![48, 6, 2, 1, 10, 1, 1, 255])); /// assert_eq!(res_err, Err("some error here")); /// ``` pub fn try_construct_der<F, E>(callback: F) -> Result<Vec<u8>, E> where F: FnOnce(DERWriter) -> Result<(), E> { let mut buf = Vec::new(); { let mut writer = DERWriterSeq { buf: &mut buf, }; callback(writer.next())?; } return Ok(buf); } /// Constructs DER-encoded sequence of data as `Vec<u8>`. /// /// This is similar to [`construct_der`], but this function /// accepts more than one ASN.1 values. /// /// This function uses the loan pattern: `callback` is called back with /// a [`DERWriterSeq`], to which the ASN.1 values are written. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der_seq(|writer| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// }); /// assert_eq!(der, vec![2, 1, 10, 1, 1, 255]); /// ``` pub fn construct_der_seq<F>(callback: F) -> Vec<u8> where F: FnOnce(&mut DERWriterSeq) { let mut buf = Vec::new(); { let mut writer = DERWriterSeq { buf: &mut buf, }; callback(&mut writer); } return buf; } /// Tries to construct a DER-encoded sequence of data as `Vec<u8>`. /// /// Same as [`construct_der_seq`], only that it allows /// returning an error from the passed closure. /// /// This function uses the loan pattern: `callback` is called back with /// a [`DERWriterSeq`], to which the ASN.1 values are written. /// /// # Examples /// /// ``` /// use yasna; /// let res_ok = yasna::try_construct_der_seq::<_, ()>(|writer| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// Ok(()) /// }); /// let res_err = yasna::try_construct_der_seq::<_, &str>(|writer| { /// return Err("some error here"); /// }); /// assert_eq!(res_ok, Ok(vec![2, 1, 10, 1, 1, 255])); /// assert_eq!(res_err, Err("some error here")); /// ``` pub fn try_construct_der_seq<F, E>(callback: F) -> Result<Vec<u8> , E> where F: FnOnce(&mut DERWriterSeq) -> Result<(), E> { let mut buf = Vec::new(); { let mut writer = DERWriterSeq { buf: &mut buf, }; callback(&mut writer)?; } return Ok(buf); } /// A writer object that accepts an ASN.1 value. /// /// The two main sources of `DERWriterSeq` are: /// /// - The [`construct_der`] function, the starting point of /// DER serialization. /// - The `next` method of [`DERWriterSeq`]. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_i64(10) /// }); /// assert_eq!(der, vec![2, 1, 10]); /// ``` #[derive(Debug)] pub struct DERWriter<'a> { buf: &'a mut Vec<u8>, implicit_tag: Option<Tag>, } impl<'a> DERWriter<'a> { fn from_buf(buf: &'a mut Vec<u8>) -> Self { return DERWriter { buf, implicit_tag: None, } } /// Writes BER identifier (tag + primitive/constructed) octets. fn write_identifier(&mut self, tag: Tag, pc: PCBit) { let tag = if let Some(tag) = self.implicit_tag { tag } else { tag }; self.implicit_tag = None; let classid = tag.tag_class as u8; let pcid = pc as u8; if tag.tag_number < 31 { self.buf.push( (classid << 6) | (pcid << 5) | (tag.tag_number as u8)); return; } self.buf.push((classid << 6) | (pcid << 5) | 31); let mut shiftnum = 63; // ceil(64 / 7) * 7 - 7 while (tag.tag_number >> shiftnum) == 0 { shiftnum -= 7; } while shiftnum > 0 { self.buf.push(128 | (((tag.tag_number >> shiftnum) & 127) as u8)); shiftnum -= 7; } self.buf.push((tag.tag_number & 127) as u8); } /// Writes BER length octets. fn write_length(&mut self, length: usize) { let length = length as u64; if length < 128 { self.buf.push(length as u8); return; } let mut shiftnum = 56; // ceil(64 / 8) * 8 - 8 while (length >> shiftnum) == 0 { shiftnum -= 8; } self.buf.push(128 | ((shiftnum / 8 + 1) as u8)); loop { self.buf.push((length >> shiftnum) as u8); if shiftnum == 0 { break; } shiftnum -= 8; } } /// Deals with unknown length procedures. /// This function first marks the current position and /// allocates 3 bytes. Then it calls back `callback`. /// It then calculates the length and moves the written data /// to the actual position. Finally, it writes the length. fn with_length<T, F>(&mut self, callback: F) -> T where F: FnOnce(&mut Self) -> T { let expected_length_length = 3; for _ in 0..3 { self.buf.push(255); } let start_pos = self.buf.len(); let result = callback(self); let length = (self.buf.len() - start_pos) as u64; let length_length; let mut shiftnum = 56; // ceil(64 / 8) * 8 - 8 if length < 128 { length_length = 1; } else { while (length >> shiftnum) == 0 { shiftnum -= 8; } length_length = shiftnum / 8 + 2; } let new_start_pos; if length_length < expected_length_length { let diff = expected_length_length - length_length; new_start_pos = start_pos - diff; self.buf.drain(new_start_pos .. start_pos); } else if length_length > expected_length_length { let diff = length_length - expected_length_length; new_start_pos = start_pos + diff; for _ in 0..diff { self.buf.insert(start_pos, 0); } } else { new_start_pos = start_pos; } let mut idx = new_start_pos - length_length; if length < 128 { self.buf[idx] = length as u8; } else { self.buf[idx] = 128 | ((shiftnum / 8 + 1) as u8); idx += 1; loop { self.buf[idx] = (length >> shiftnum) as u8; idx += 1; if shiftnum == 0 { break; } shiftnum -= 8; } } return result; } /// Writes `bool` as an ASN.1 BOOLEAN value. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_bool(true) /// }); /// assert_eq!(der, vec![1, 1, 255]); /// ``` pub fn write_bool(mut self, val: bool) { self.write_identifier(TAG_BOOLEAN, PCBit::Primitive); self.write_length(1); self.buf.push(if val { 255 } else { 0 }); } fn write_integer(mut self, tag: Tag, val: i64) { let mut shiftnum = 56; while shiftnum > 0 && (val >> (shiftnum-1) == 0 || val >> (shiftnum-1) == -1) { shiftnum -= 8; } self.write_identifier(tag, PCBit::Primitive); self.write_length(shiftnum / 8 + 1); loop { self.buf.push((val >> shiftnum) as u8); if shiftnum == 0 { break; } shiftnum -= 8; } } /// Writes `i64` as an ASN.1 ENUMERATED value. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_enum(2) /// }); /// assert_eq!(der, vec![10, 1, 2]); /// ``` pub fn write_enum(self, val: i64) { self.write_integer(TAG_ENUM, val); } /// Writes `i64` as an ASN.1 INTEGER value. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_i64(1234567890) /// }); /// assert_eq!(der, vec![2, 4, 73, 150, 2, 210]); /// ``` pub fn write_i64(self, val: i64) { self.write_integer(TAG_INTEGER, val); } /// Writes `u64` as an ASN.1 INTEGER value. pub fn write_u64(mut self, val: u64) { let mut shiftnum = 64; while shiftnum > 0 && val >> (shiftnum-1) == 0 { shiftnum -= 8; } self.write_identifier(TAG_INTEGER, PCBit::Primitive); self.write_length(shiftnum / 8 + 1); if shiftnum == 64 { self.buf.push(0); shiftnum -= 8; } loop { self.buf.push((val >> shiftnum) as u8); if shiftnum == 0 { break; } shiftnum -= 8; } } /// Writes `i32` as an ASN.1 INTEGER value. pub fn write_i32(self, val: i32) { self.write_i64(val as i64) } /// Writes `u32` as an ASN.1 INTEGER value. pub fn write_u32(self, val: u32) { self.write_i64(val as i64) } /// Writes `i16` as an ASN.1 INTEGER value. pub fn write_i16(self, val: i16) { self.write_i64(val as i64) } /// Writes `u16` as an ASN.1 INTEGER value. pub fn write_u16(self, val: u16) { self.write_i64(val as i64) } /// Writes `i8` as an ASN.1 INTEGER value. pub fn write_i8(self, val: i8) { self.write_i64(val as i64) } /// Writes `u8` as an ASN.1 INTEGER value. pub fn write_u8(self, val: u8) { self.write_i64(val as i64) } #[cfg(feature = "num-bigint")] /// Writes `BigInt` as an ASN.1 INTEGER value. /// /// # Examples /// /// ``` /// # fn main() { /// use yasna; /// use num_bigint::BigInt; /// let der = yasna::construct_der(|writer| { /// writer.write_bigint( /// &BigInt::parse_bytes(b"1234567890", 10).unwrap()) /// }); /// assert_eq!(der, vec![2, 4, 73, 150, 2, 210]); /// # } /// ``` /// /// # Features /// /// This method is enabled by `num` feature. /// /// ```toml /// [dependencies] /// yasna = { version = "*", features = ["num-bigint"] } /// ``` pub fn write_bigint(mut self, val: &BigInt) { use num_bigint::Sign; self.write_identifier(TAG_INTEGER, PCBit::Primitive); let (sign, mut bytes) = val.to_bytes_le(); match sign { Sign::NoSign => { self.write_length(1); self.buf.push(0); }, Sign::Plus => { let byteslen = bytes.len(); debug_assert!(bytes[byteslen-1] != 0); if bytes[byteslen-1] >= 128 { self.write_length(byteslen+1); self.buf.push(0); } else { self.write_length(byteslen); } bytes.reverse(); self.buf.extend_from_slice(&bytes); return; }, Sign::Minus => { let byteslen = bytes.len(); debug_assert!(bytes[byteslen-1] != 0); let mut carry : usize = 1; for b in bytes.iter_mut() { let bval = 255 - (*b as usize); *b = (bval + carry) as u8; carry = (bval + carry) >> 8; } if bytes[byteslen-1] < 128 { self.write_length(byteslen+1); self.buf.push(255); } else { self.write_length(byteslen); } bytes.reverse(); self.buf.extend_from_slice(&bytes); return; } }; } #[cfg(feature = "num-bigint")] /// Writes `BigUint` as an ASN.1 INTEGER value. /// /// # Examples /// /// ``` /// # fn main() { /// use yasna; /// use num_bigint::BigUint; /// let der = yasna::construct_der(|writer| { /// writer.write_biguint( /// &BigUint::parse_bytes(b"1234567890", 10).unwrap()) /// }); /// assert_eq!(der, vec![2, 4, 73, 150, 2, 210]); /// # } /// ``` /// /// # Features /// /// This method is enabled by `num` feature. /// /// ```toml /// [dependencies] /// yasna = { version = "*", features = ["num-bigint"] } /// ``` pub fn write_biguint(mut self, val: &BigUint) { self.write_identifier(TAG_INTEGER, PCBit::Primitive); let mut bytes = val.to_bytes_le(); if &bytes == &[0] { self.write_length(1); self.buf.push(0); return; } let byteslen = bytes.len(); debug_assert!(bytes[byteslen-1] != 0); if bytes[byteslen-1] >= 128 { self.write_length(byteslen+1); self.buf.push(0); } else { self.write_length(byteslen); } bytes.reverse(); self.buf.extend_from_slice(&bytes); } #[cfg(feature = "bit-vec")] /// Writes `BitVec` as an ASN.1 BITSTRING value. /// /// # Examples /// /// ``` /// # fn main() { /// use yasna; /// use bit_vec::BitVec; /// let der = yasna::construct_der(|writer| { /// writer.write_bitvec(& /// [1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, /// 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1] /// .iter().map(|&i| i != 0).collect()) /// }); /// assert_eq!(&der, &[3, 5, 3, 206, 213, 116, 24]); /// # } /// ``` /// /// # Features /// /// This method is enabled by `bit-vec` feature. /// /// ```toml /// [dependencies] /// yasna = { version = "*", features = ["bit-vec"] } /// ``` pub fn write_bitvec(self, bitvec: &BitVec) { let len = bitvec.len(); let bytes = bitvec.to_bytes(); self.write_bitvec_bytes(&bytes, len); } /// Writes `&[u8]` and `usize` as an ASN.1 BITSTRING value. /// /// This function is similar to `write_bitvec`, but is available /// even if the `bit-vec` feature is disabled. /// /// # Examples /// /// ``` /// # fn main() { /// use yasna; /// let der_1 = yasna::construct_der(|writer| { /// writer.write_bitvec_bytes(&[117, 13, 64], 18) /// }); /// let der_2 = yasna::construct_der(|writer| { /// writer.write_bitvec_bytes(&[117, 13, 65], 18) /// }); /// assert_eq!(&der_1, &[3, 4, 6, 117, 13, 64]); /// assert_eq!(&der_2, &[3, 4, 6, 117, 13, 64]); /// # } /// ``` pub fn write_bitvec_bytes(mut self, bytes: &[u8], len: usize) { use super::tags::TAG_BITSTRING; self.write_identifier(TAG_BITSTRING, PCBit::Primitive); debug_assert!(len <= 8 * bytes.len()); debug_assert!(8 * bytes.len() < len + 8); self.write_length(1 + bytes.len()); let len_diff = 8 * bytes.len() - len; self.buf.push(len_diff as u8); if bytes.len() > 0 { self.buf.extend_from_slice(&bytes[0 .. bytes.len() - 1]); let mask = !(255u16 >> (8 - len_diff)) as u8; self.buf.push(bytes[bytes.len() - 1] & mask); } } /// Writes `&[u8]` as an ASN.1 OCTETSTRING value. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_bytes(b"Hello!") /// }); /// assert_eq!(der, vec![4, 6, 72, 101, 108, 108, 111, 33]); /// ``` pub fn write_bytes(mut self, bytes: &[u8]) { self.write_identifier(TAG_OCTETSTRING, PCBit::Primitive); self.write_length(bytes.len()); self.buf.extend_from_slice(bytes); } /// Writes `&str` as an ASN.1 UTF8String value. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_utf8_string("Hello!") /// }); /// assert_eq!(der, vec![12, 6, 72, 101, 108, 108, 111, 33]); /// ``` pub fn write_utf8_string(mut self, string: &str) { self.write_identifier(TAG_UTF8STRING, PCBit::Primitive); self.write_length(string.len()); self.buf.extend_from_slice(string.as_bytes()); } /// Writes `&str` as an ASN.1 IA5String value. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_ia5_string("Hello!") /// }); /// assert_eq!(der, vec![22, 6, 72, 101, 108, 108, 111, 33]); /// ``` pub fn write_ia5_string(mut self, string: &str) { assert!(string.is_ascii(), "IA5 string must be ASCII"); self.write_identifier(TAG_IA5STRING, PCBit::Primitive); self.write_length(string.len()); self.buf.extend_from_slice(string.as_bytes()); } /// Writes `&str` as an ASN.1 BMPString value. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_bmp_string("❤πü2?") /// }); /// assert_eq!(der, vec![30, 10, 39, 100, 3, 192, 0, 252, 0, 50, 0, 63]); /// ``` pub fn write_bmp_string(mut self, string: &str) { let utf16 : Vec<u16> = string.encode_utf16().collect(); let mut bytes = Vec::with_capacity(utf16.len() * 2); for c in utf16 { bytes.push((c / 256) as u8); bytes.push((c % 256) as u8); } self.write_identifier(TAG_BMPSTRING, PCBit::Primitive); self.write_length(bytes.len()); self.buf.extend_from_slice(&bytes); } /// Writes the ASN.1 NULL value. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_null() /// }); /// assert_eq!(der, vec![5, 0]); /// ``` pub fn write_null(mut self) { self.write_identifier(TAG_NULL, PCBit::Primitive); self.write_length(0); } /// Writes an ASN.1 object identifier. /// /// # Examples /// /// ``` /// use yasna; /// use yasna::models::ObjectIdentifier; /// let der = yasna::construct_der(|writer| { /// writer.write_oid(&ObjectIdentifier::from_slice( /// &[1, 2, 840, 113549, 1, 1])) /// }); /// assert_eq!(&der, &[6, 8, 42, 134, 72, 134, 247, 13, 1, 1]); /// ``` /// /// # Panics /// /// It panics when the OID cannot be canonically encoded in BER. pub fn write_oid(mut self, oid: &ObjectIdentifier) { assert!(oid.components().len() >= 2, "Invalid OID: too short"); let id0 = oid.components()[0]; let id1 = oid.components()[1]; assert!( (id0 < 3) && (id1 < 18446744073709551535) && (id0 >= 2 || id1 < 40), "Invalid OID {{{} {} ...}}", id0, id1); let subid0 = id0 * 40 + id1; let mut length = 0; for i in 1..oid.components().len() { let mut subid = if i == 1 { subid0 } else { oid.components()[i] } | 1; while subid > 0 { length += 1; subid >>= 7; } } self.write_identifier(TAG_OID, PCBit::Primitive); self.write_length(length); for i in 1..oid.components().len() { let subid = if i == 1 { subid0 } else { oid.components()[i] }; let mut shiftnum = 63; // ceil(64 / 7) * 7 - 7 while ((subid|1) >> shiftnum) == 0 { shiftnum -= 7; } while shiftnum > 0 { self.buf.push(128 | ((((subid|1) >> shiftnum) & 127) as u8)); shiftnum -= 7; } self.buf.push((subid & 127) as u8); } } /// Writes an ASN.1 UTF8String. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_utf8string("gnaw ροκανίζω 𪘂る") /// }); /// assert_eq!(&der, &[ /// 12, 29, 103, 110, 97, 119, 32, 207, 129, 206, 191, 206, /// 186, 206, 177, 206, 189, 206, 175, 206, 182, 207, /// 137, 32, 240, 170, 152, 130, 227, 130, 139]); /// ``` pub fn write_utf8string(self, string: &str) { self.write_tagged_implicit(TAG_UTF8STRING, |writer| { writer.write_bytes(string.as_bytes()) }) } /// Writes ASN.1 SEQUENCE. /// /// This function uses the loan pattern: `callback` is called back with /// a [`DERWriterSeq`], to which the contents of the /// SEQUENCE is written. /// /// This is equivalent to [`write_sequence_of`](Self::write_sequence_of) /// in behavior. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_sequence(|writer| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// }) /// }); /// assert_eq!(der, vec![48, 6, 2, 1, 10, 1, 1, 255]); /// ``` pub fn write_sequence<T, F>(mut self, callback: F) -> T where F: FnOnce(&mut DERWriterSeq) -> T { self.write_identifier(TAG_SEQUENCE, PCBit::Constructed); return self.with_length(|writer| { callback(&mut DERWriterSeq { buf: writer.buf, }) }); } /// Writes ASN.1 SEQUENCE OF. /// /// This function uses the loan pattern: `callback` is called back with /// a [`DERWriterSeq`], to which the contents of the /// SEQUENCE OF are written. /// /// This is equivalent to [`write_sequence`](Self::write_sequence) in /// behavior. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_sequence_of(|writer| { /// for &i in &[10, -129] { /// writer.next().write_i64(i); /// } /// }) /// }); /// assert_eq!(der, vec![48, 7, 2, 1, 10, 2, 2, 255, 127]); /// ``` pub fn write_sequence_of<T, F>(self, callback: F) -> T where F: FnOnce(&mut DERWriterSeq) -> T { self.write_sequence(callback) } /// Writes ASN.1 SET. /// /// This function uses the loan pattern: `callback` is called back with /// a [`DERWriterSet`], to which the contents of the /// SET are written. /// /// For SET OF values, use [`write_set_of`](Self::write_set_of) instead. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_set(|writer| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// }) /// }); /// assert_eq!(der, vec![49, 6, 1, 1, 255, 2, 1, 10]); /// ``` pub fn write_set<T, F>(mut self, callback: F) -> T where F: FnOnce(&mut DERWriterSet) -> T { let mut bufs = Vec::new(); let result = callback(&mut DERWriterSet { bufs: &mut bufs, }); for buf in bufs.iter() { assert!(buf.len() > 0, "Empty output in write_set()"); } bufs.sort_by(|buf0, buf1| { let buf00 = buf0[0] & 223; let buf10 = buf1[0] & 223; if buf00 != buf10 || (buf0[0] & 31) != 31 { return buf00.cmp(&buf10); } let len0 = buf0[1..].iter().position(|x| x & 128 == 0).unwrap(); let len1 = buf1[1..].iter().position(|x| x & 128 == 0).unwrap(); if len0 != len1 { return len0.cmp(&len1); } return buf0[1..].cmp(&buf1[1..]); }); // let bufs_len = bufs.iter().map(|buf| buf.len()).sum(); let bufs_len = bufs.iter().map(|buf| buf.len()).fold(0, |x, y| x + y); self.write_identifier(TAG_SET, PCBit::Constructed); self.write_length(bufs_len); for buf in bufs.iter() { self.buf.extend_from_slice(buf); } return result; } /// Writes ASN.1 SET OF. /// /// This function uses the loan pattern: `callback` is called back with /// a [`DERWriterSet`], to which the contents of the /// SET OF are written. /// /// For SET values, use [`write_set`](Self::write_set) instead. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_set_of(|writer| { /// for &i in &[10, -129] { /// writer.next().write_i64(i); /// } /// }) /// }); /// assert_eq!(der, vec![49, 7, 2, 1, 10, 2, 2, 255, 127]); /// ``` pub fn write_set_of<T, F>(mut self, callback: F) -> T where F: FnOnce(&mut DERWriterSet) -> T { let mut bufs = Vec::new(); let result = callback(&mut DERWriterSet { bufs: &mut bufs, }); for buf in bufs.iter() { assert!(buf.len() > 0, "Empty output in write_set_of()"); } bufs.sort(); // let bufs_len = bufs.iter().map(|buf| buf.len()).sum(); let bufs_len = bufs.iter().map(|buf| buf.len()).fold(0, |x, y| x + y); self.write_identifier(TAG_SET, PCBit::Constructed); self.write_length(bufs_len); for buf in bufs.iter() { self.buf.extend_from_slice(buf); } return result; } /// Writes an ASN.1 NumericString. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_numeric_string("128 256") /// }); /// assert_eq!(&der, &[18, 7, 49, 50, 56, 32, 50, 53, 54]); /// ``` pub fn write_numeric_string(self, string: &str) { let bytes = string.as_bytes(); for &byte in bytes { assert!(byte == b' ' || (b'0' <= byte && byte <= b'9'), "Invalid NumericString: {:?} appeared", byte); } self.write_tagged_implicit(TAG_NUMERICSTRING, |writer| { writer.write_bytes(bytes) }); } /// Writes an ASN.1 PrintableString. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_printable_string("Co., Ltd.") /// }); /// assert_eq!(&der, &[19, 9, 67, 111, 46, 44, 32, 76, 116, 100, 46]); /// ``` pub fn write_printable_string(self, string: &str) { let bytes = string.as_bytes(); for &byte in bytes { assert!( byte == b' ' || (b'\'' <= byte && byte <= b':' && byte != b'*') || byte == b'=' || (b'A' <= byte && byte <= b'Z') || (b'a' <= byte && byte <= b'z'), "Invalid PrintableString: {:?} appeared", byte); } self.write_tagged_implicit(TAG_PRINTABLESTRING, |writer| { writer.write_bytes(bytes) }); } #[cfg(feature = "chrono")] /// Writes an ASN.1 UTCTime. /// /// # Examples /// /// ``` /// # fn main() { /// use yasna; /// use yasna::models::UTCTime; /// use chrono::{Utc,TimeZone}; /// let der = yasna::construct_der(|writer| { /// writer.write_utctime( /// &UTCTime::from_datetime(&Utc.timestamp(378820800, 0))) /// }); /// assert_eq!(&der, &[ /// 23, 13, 56, 50, 48, 49, 48, 50, 49, 50, 48, 48, 48, 48, 90]); /// # } /// ``` /// /// # Features /// /// This method is enabled by `chrono` feature. /// /// ```toml /// [dependencies] /// yasna = { version = "*", features = ["chrono"] } /// ``` pub fn write_utctime(self, datetime: &UTCTime) { use super::tags::TAG_UTCTIME; self.write_tagged_implicit(TAG_UTCTIME, |writer| { writer.write_bytes(&datetime.to_bytes()) }); } #[cfg(feature = "chrono")] /// Writes an ASN.1 GeneralizedTime. /// /// # Examples /// /// ``` /// # fn main() { /// use yasna; /// use yasna::models::GeneralizedTime; /// use chrono::{Utc,TimeZone}; /// let der = yasna::construct_der(|writer| { /// writer.write_generalized_time( /// &GeneralizedTime::from_datetime( /// &Utc.timestamp(500159309, 724_000_000))) /// }); /// assert_eq!(&der, &[ /// 24, 19, 49, 57, 56, 53, 49, 49, 48, 54, 50, /// 49, 48, 56, 50, 57, 46, 55, 50, 52, 90]); /// # } /// ``` /// /// # Features /// /// This method is enabled by `chrono` feature. /// /// ```toml /// [dependencies] /// yasna = { version = "*", features = ["chrono"] } /// ``` pub fn write_generalized_time(self, datetime: &GeneralizedTime) { use super::tags::TAG_GENERALIZEDTIME; self.write_tagged_implicit(TAG_GENERALIZEDTIME, |writer| { writer.write_bytes(&datetime.to_bytes()) }); } /// Writes an ASN.1 VisibleString. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_visible_string("Hi!") /// }); /// assert_eq!(&der, &[26, 3, 72, 105, 33]); /// ``` pub fn write_visible_string(self, string: &str) { let bytes = string.as_bytes(); for &byte in bytes { assert!(b' ' <= byte && byte <= b'~', "Invalid VisibleString: {:?} appeared", byte); } self.write_tagged_implicit(TAG_VISIBLESTRING, |writer| { writer.write_bytes(bytes) }); } /// Writes a (explicitly) tagged value. /// /// # Examples /// /// ``` /// use yasna::{self,Tag}; /// let der = yasna::construct_der(|writer| { /// writer.write_tagged(Tag::context(3), |writer| { /// writer.write_i64(10) /// }) /// }); /// assert_eq!(der, vec![163, 3, 2, 1, 10]); /// ``` /// /// Note: you can achieve the same using `write_tagged_implicit`: /// /// ``` /// use yasna::{self,Tag}; /// let der = yasna::construct_der(|writer| { /// writer.write_tagged_implicit(Tag::context(3), |writer| { /// writer.write_sequence(|writer| { /// let writer = writer.next(); /// writer.write_i64(10) /// }) /// }) /// }); /// assert_eq!(der, vec![163, 3, 2, 1, 10]); /// ``` pub fn write_tagged<T, F>(mut self, tag: Tag, callback: F) -> T where F: FnOnce(DERWriter) -> T { self.write_identifier(tag, PCBit::Constructed); return self.with_length(|writer| { callback(DERWriter::from_buf(writer.buf)) }); } /// Writes an implicitly tagged value. /// /// # Examples /// /// ``` /// use yasna::{self,Tag}; /// let der = yasna::construct_der(|writer| { /// writer.write_tagged_implicit(Tag::context(3), |writer| { /// writer.write_i64(10) /// }) /// }); /// assert_eq!(der, vec![131, 1, 10]); /// ``` pub fn write_tagged_implicit<T, F> (mut self, tag: Tag, callback: F) -> T where F: FnOnce(DERWriter) -> T { let tag = if let Some(tag) = self.implicit_tag { tag } else { tag }; self.implicit_tag = None; let mut writer = DERWriter::from_buf(self.buf); writer.implicit_tag = Some(tag); return callback(writer); } /// Writes the arbitrary tagged DER value in `der`. /// /// # Examples /// /// ``` /// use yasna; /// use yasna::models::TaggedDerValue; /// use yasna::tags::TAG_OCTETSTRING; /// let tagged_der_value = TaggedDerValue::from_tag_and_bytes(TAG_OCTETSTRING, b"Hello!".to_vec()); /// let der1 = yasna::construct_der(|writer| { /// writer.write_tagged_der(&tagged_der_value) /// }); /// let der2 = yasna::construct_der(|writer| { /// writer.write_bytes(b"Hello!") /// }); /// assert_eq!(der1, der2); /// ``` pub fn write_tagged_der(mut self, der: &TaggedDerValue) { self.write_identifier(der.tag(), der.pcbit()); self.write_length(der.value().len()); self.buf.extend_from_slice(der.value()); } /// Writes `&[u8]` into the DER output buffer directly. Properly encoded tag /// and length must be included at the start of the passed buffer. /// /// # Examples /// /// ``` /// use yasna; /// let raw_der = yasna::construct_der(|writer| { /// writer.write_der(b"\x04\x06Hello!") /// }); /// let der = yasna::construct_der(|writer| { /// writer.write_bytes(b"Hello!") /// }); /// assert_eq!(raw_der, der); /// ``` pub fn write_der(self, der: &[u8]) { self.buf.extend_from_slice(der); } } /// A writer object that accepts ASN.1 values. /// /// The main source of this object is the [`write_sequence`][write_sequence] /// method from [`DERWriter`]. /// /// [write_sequence]: DERWriter::write_sequence /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_sequence(|writer : &mut yasna::DERWriterSeq| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// }) /// }); /// assert_eq!(der, vec![48, 6, 2, 1, 10, 1, 1, 255]); /// ``` #[derive(Debug)] pub struct DERWriterSeq<'a> { buf: &'a mut Vec<u8>, } impl<'a> DERWriterSeq<'a> { /// Generates a new [`DERWriter`]. pub fn next<'b>(&'b mut self) -> DERWriter<'b> { return DERWriter::from_buf(self.buf); } } /// A writer object that accepts ASN.1 values. /// /// The main source of this object is the `write_set` method from /// [`DERWriter`]. /// /// # Examples /// /// ``` /// use yasna; /// let der = yasna::construct_der(|writer| { /// writer.write_set(|writer : &mut yasna::DERWriterSet| { /// writer.next().write_i64(10); /// writer.next().write_bool(true); /// }) /// }); /// assert_eq!(der, vec![49, 6, 1, 1, 255, 2, 1, 10]); /// ``` #[derive(Debug)] pub struct DERWriterSet<'a> { bufs: &'a mut Vec<Vec<u8>>, } impl<'a> DERWriterSet<'a> { /// Generates a new [`DERWriter`]. pub fn next<'b>(&'b mut self) -> DERWriter<'b> { self.bufs.push(Vec::new()); return DERWriter::from_buf(self.bufs.last_mut().unwrap()); } } #[cfg(test)] mod tests;
30.424342
109
0.504352
ebf187e5678fc123daa7a69357d8a91c3f94177e
45
pub fn add_two(a: i32) -> i32 { a + 2 }
9
31
0.466667
9ccb62e065b11eff882f2b4cbbf2039af8177647
1,193
use bytes::{Buf, Bytes}; use crate::error::Error; use crate::io::BufExt; pub trait MySqlBufExt: Buf { // Read a length-encoded integer. // NOTE: 0xfb or NULL is only returned for binary value encoding to indicate NULL. // NOTE: 0xff is only returned during a result set to indicate ERR. // <https://dev.mysql.com/doc/internals/en/integer.html#packet-Protocol::LengthEncodedInteger> fn get_uint_lenenc(&mut self) -> u64; // Read a length-encoded string. fn get_str_lenenc(&mut self) -> Result<String, Error>; // Read a length-encoded byte sequence. fn get_bytes_lenenc(&mut self) -> Bytes; } impl MySqlBufExt for Bytes { fn get_uint_lenenc(&mut self) -> u64 { match self.get_u8() { 0xfc => u64::from(self.get_u16_le()), 0xfd => self.get_uint_le(3), 0xfe => self.get_u64_le(), v => u64::from(v), } } fn get_str_lenenc(&mut self) -> Result<String, Error> { let size = self.get_uint_lenenc(); self.get_str(size as usize) } fn get_bytes_lenenc(&mut self) -> Bytes { let size = self.get_uint_lenenc(); self.split_to(size as usize) } }
29.097561
98
0.621961
26b76bc1596d193218128b9de69a5397891a2163
11,867
pub(crate) mod lists; mod sources; use crate::dirs::LOCAL_CRATES_DIR; use crate::prelude::*; use cargo_metadata::PackageId; use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC}; use rustwide::Crate as RustwideCrate; use std::convert::TryFrom; use std::fmt; use std::path::Path; use std::str::FromStr; pub(crate) use crate::crates::sources::github::GitHubRepo; pub(crate) use crate::crates::sources::registry::RegistryCrate; #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Clone)] pub struct GitRepo { pub url: String, pub sha: Option<String>, } #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Clone)] pub enum Crate { Registry(RegistryCrate), GitHub(GitHubRepo), Local(String), Path(String), Git(GitRepo), } impl Crate { pub(crate) fn id(&self) -> String { match *self { Crate::Registry(ref details) => format!("reg/{}/{}", details.name, details.version), Crate::GitHub(ref repo) => { if let Some(ref sha) = repo.sha { format!("gh/{}/{}/{}", repo.org, repo.name, sha) } else { format!("gh/{}/{}", repo.org, repo.name) } } Crate::Local(ref name) => format!("local/{}", name), Crate::Path(ref path) => { format!("path/{}", utf8_percent_encode(path, NON_ALPHANUMERIC)) } Crate::Git(ref repo) => { if let Some(ref sha) = repo.sha { format!( "git/{}/{}", utf8_percent_encode(&repo.url, NON_ALPHANUMERIC), sha ) } else { format!("git/{}", utf8_percent_encode(&repo.url, NON_ALPHANUMERIC),) } } } } pub(crate) fn to_rustwide(&self) -> RustwideCrate { match self { Self::Registry(krate) => RustwideCrate::crates_io(&krate.name, &krate.version), Self::GitHub(repo) => { RustwideCrate::git(&format!("https://github.com/{}/{}", repo.org, repo.name)) } Self::Local(name) => RustwideCrate::local(&LOCAL_CRATES_DIR.join(name)), Self::Path(path) => RustwideCrate::local(Path::new(&path)), Self::Git(repo) => RustwideCrate::git(&repo.url), } } } impl TryFrom<&'_ PackageId> for Crate { type Error = failure::Error; fn try_from(pkgid: &PackageId) -> Fallible<Crate> { let parts = &pkgid .repr .split_ascii_whitespace() .flat_map(|s| { // remove () s.trim_matches(|c: char| c.is_ascii_punctuation()) // split resource and protocol .split('+') }) .collect::<Vec<_>>(); match parts[..] { [name, version, "registry", _] => Ok(Crate::Registry(RegistryCrate { name: name.to_string(), version: version.to_string(), })), [_, _, "path", path] => Ok(Crate::Path(path.to_string())), [_, _, "git", repo] => { if repo.starts_with("https://github.com") { Ok(Crate::GitHub(repo.replace("#", "/").parse()?)) } else { let mut parts = repo.split('#').rev().collect::<Vec<_>>(); let url = parts.pop(); let sha = parts.pop(); match (url, sha) { (Some(url), None) => Ok(Crate::Git(GitRepo { url: url.to_string(), sha: None, })), (Some(url), Some(sha)) => Ok(Crate::Git(GitRepo { // remove additional queries if the sha is present // as the crate version is already uniquely determined url: url.split('?').next().unwrap().to_string(), sha: Some(sha.to_string()), })), _ => bail!("malformed git repo: {}", repo), } } } _ => bail!( "malformed pkgid format: {}\n maybe the representation has changed?", pkgid.repr ), } } } impl fmt::Display for Crate { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match *self { Crate::Registry(ref krate) => format!("{}-{}", krate.name, krate.version), Crate::GitHub(ref repo) => if let Some(ref sha) = repo.sha { format!("{}/{}/{}", repo.org, repo.name, sha) } else { format!("{}/{}", repo.org, repo.name) }, Crate::Local(ref name) => format!("{} (local)", name), Crate::Path(ref path) => format!("{}", utf8_percent_encode(path, NON_ALPHANUMERIC)), Crate::Git(ref repo) => if let Some(ref sha) = repo.sha { format!( "{}/{}", utf8_percent_encode(&repo.url, NON_ALPHANUMERIC), sha ) } else { utf8_percent_encode(&repo.url, NON_ALPHANUMERIC).to_string() }, } ) } } impl FromStr for Crate { type Err = ::failure::Error; // matches with `Crate::id' fn from_str(s: &str) -> Fallible<Self> { match s.split('/').collect::<Vec<_>>()[..] { ["reg", name, version] => Ok(Crate::Registry(RegistryCrate { name: name.to_string(), version: version.to_string(), })), ["gh", org, name, sha] => Ok(Crate::GitHub(GitHubRepo { org: org.to_string(), name: name.to_string(), sha: Some(sha.to_string()), })), ["gh", org, name] => Ok(Crate::GitHub(GitHubRepo { org: org.to_string(), name: name.to_string(), sha: None, })), ["git", repo, sha] => Ok(Crate::Git(GitRepo { url: percent_decode_str(repo).decode_utf8()?.to_string(), sha: Some(sha.to_string()), })), ["git", repo] => Ok(Crate::Git(GitRepo { url: percent_decode_str(repo).decode_utf8()?.to_string(), sha: None, })), ["local", name] => Ok(Crate::Local(name.to_string())), ["path", path] => Ok(Crate::Path( percent_decode_str(path).decode_utf8()?.to_string(), )), _ => bail!("unexpected crate value"), } } } #[cfg(test)] mod tests { use super::{Crate, GitHubRepo, GitRepo, RegistryCrate}; use cargo_metadata::PackageId; use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC}; use std::convert::TryFrom; use std::str::FromStr; macro_rules! test_from_pkgid { ($($str:expr => $rust:expr,)*) => { $( let pkgid = PackageId { repr: $str.to_string(), }; assert_eq!(Crate::try_from(&pkgid).unwrap(), $rust); )* }; } #[test] fn test_parse_from_pkgid() { test_from_pkgid! { "dummy 0.1.0 (path+file:///opt/rustwide/workdir)" => Crate::Path("file:///opt/rustwide/workdir".to_string()), "dummy 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" => Crate::Registry(RegistryCrate { name: "dummy".to_string(), version: "0.1.0".to_string() }), "dummy 0.1.0 (git+https://github.com/dummy_org/dummy#9823f01cf4948a41279f6a3febcf793130cab4f6)" => Crate::GitHub(GitHubRepo { org: "dummy_org".to_string(), name: "dummy".to_string(), sha: Some("9823f01cf4948a41279f6a3febcf793130cab4f6".to_string()) }), "dummy 0.1.0 (git+https://github.com/dummy_org/dummy?rev=dummyrev#9823f01cf4948a41279f6a3febcf793130cab4f6)" => Crate::GitHub(GitHubRepo { org: "dummy_org".to_string(), name: "dummy".to_string(), sha: Some("9823f01cf4948a41279f6a3febcf793130cab4f6".to_string()) }), "dummy 0.1.0 (git+https://github.com/dummy_org/dummy)" => Crate::GitHub(GitHubRepo { org: "dummy_org".to_string(), name: "dummy".to_string(), sha: None }), "dummy 0.1.0 (git+https://gitlab.com/dummy_org/dummy#9823f01cf4948a41279f6a3febcf793130cab4f6)" => Crate::Git(GitRepo { url: "https://gitlab.com/dummy_org/dummy" .to_string(), sha: Some("9823f01cf4948a41279f6a3febcf793130cab4f6".to_string()) }), "dummy 0.1.0 (git+https://gitlab.com/dummy_org/dummy?branch=dummybranch#9823f01cf4948a41279f6a3febcf793130cab4f6)" => Crate::Git(GitRepo { url: "https://gitlab.com/dummy_org/dummy" .to_string(), sha: Some("9823f01cf4948a41279f6a3febcf793130cab4f6".to_string()) }), "dummy 0.1.0 (git+https://gitlab.com/dummy_org/dummy)" => Crate::Git(GitRepo { url: "https://gitlab.com/dummy_org/dummy" .to_string(), sha: None }), "dummy 0.1.0 (git+https://gitlab.com/dummy_org/dummy?branch=dummybranch)" => Crate::Git(GitRepo { url: "https://gitlab.com/dummy_org/dummy?branch=dummybranch" .to_string(), sha: None }), } assert!(Crate::try_from(&PackageId { repr: "invalid".to_string() }) .is_err()); } #[test] fn test_parse() { macro_rules! test_from_str { ($($str:expr => $rust:expr,)*) => { $( // Test parsing from string to rust assert_eq!(Crate::from_str($str).unwrap(), $rust); // Test dumping from rust to string assert_eq!(&$rust.id(), $str); // Test dumping from rust to string to rust assert_eq!(Crate::from_str($rust.id().as_ref()).unwrap(), $rust); )* }; } test_from_str! { "local/build-fail" => Crate::Local("build-fail".to_string()), "path/pathtofile" => Crate::Path("pathtofile".to_string()), &format!("path/{}", utf8_percent_encode("path/with:stange?characters", NON_ALPHANUMERIC)) => Crate::Path("path/with:stange?characters".to_string()), "gh/org/user" => Crate::GitHub(GitHubRepo{org: "org".to_string(), name: "user".to_string(), sha: None}), "gh/org/user/sha" => Crate::GitHub(GitHubRepo{org: "org".to_string(), name: "user".to_string(), sha: Some("sha".to_string())}), "git/url" => Crate::Git(GitRepo{url: "url".to_string(), sha: None}), &format!("git/{}", utf8_percent_encode("url/with:stange?characters", NON_ALPHANUMERIC)) => Crate::Git(GitRepo{url: "url/with:stange?characters".to_string(), sha: None}), "git/url/sha" => Crate::Git(GitRepo{url: "url".to_string(), sha: Some("sha".to_string())}), "reg/name/version" => Crate::Registry(RegistryCrate{name: "name".to_string(), version: "version".to_string()}), } } }
40.363946
181
0.491531
3a02a2805ebf15005cedd11b7b5eaf68c7c09bf0
742
use std::mem::transmute; use getset::Getters; use super::super::prelude::*; #[derive(Debug, Copy, Clone, Getters)] #[get = "pub"] pub struct PanelInterface { inner: Interface, } #[repr(isize)] pub enum PanelVTableIndicies { GetName = 36, } impl PanelInterface { pub const fn new(inner: Interface) -> Self { PanelInterface { inner } } pub fn get_name(&self, vgui_panel: u32) -> Result<*const libc::c_char> { type Func = unsafe extern "thiscall" fn(*const usize, u32) -> *const libc::c_char; Ok(unsafe { transmute::<_, Func>(self.inner.nth(PanelVTableIndicies::GetName as isize)?)( *self.inner.handle(), vgui_panel, ) }) } }
21.823529
90
0.588949
2641bd28c6255d7a9590164cf011b21f4e10e90d
764
//! Optimization //! //! This module provides functions for minimizing objective functions. It //! includes solvers for nonlinear problems, nonlinear least-squares. mod conjugategradient; mod gaussnewton; mod gradient; mod levenbergmarquardt; mod newton; mod nonlinearcg; mod optim; mod optimresult; pub use self::optim::Optim; /// Conjugate Gradient method pub use self::conjugategradient::ConjugateGradient; /// Gauss-Newton method pub use self::gaussnewton::GaussNewton; /// Gradient mehtod pub use self::gradient::Gradient; /// Levenberg Marquardt method pub use self::levenbergmarquardt::LevenbergMarquardt; /// Newton's method pub use self::newton::Newton; //pub use self::nonlinearcg::NonlinearConjugateGradient; pub use self::optimresult::OptimResult;
25.466667
73
0.784031
11684d8663af8ee9c75f3e21081c50b665ed5a16
777
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that using rlibs and rmeta dep crates work together. Specifically, that // there can be both an rmeta and an rlib file and rustc will prefer the rlib. // aux-build:rmeta_rmeta.rs // aux-build:rmeta_rlib.rs extern crate rmeta_aux; use rmeta_aux::Foo; pub fn main() { let _ = Foo { field: 42 }; }
33.782609
79
0.732304
1628fa050e0dd65751f8dce8252dd9b31106de98
227
// clippy2.rs // Make me compile! Execute `rustlings hint clippy2` for hints :) fn main() { let mut res = 42; let option = Some(12); if let Some(x) = option { res += x; } println!("{}", res); }
15.133333
65
0.524229
ed21c5c51337bd1b7a591f8418ad0d7b8ec70a99
7,481
//! This module contains the particle/animation system use crate::game; const TIME_MS_PER_FRAME: f32 = 1000.0 / 60.0; pub struct Particle { pub pos: rltk::PointF, pub col_fg: rltk::RGBA, pub col_bg: rltk::RGBA, pub glyph: char, /// Lifetime of the particle, given in [ms] pub lifetime: f32, /// delay until the particle is displayed, given in [ms] pub start_delay: f32, pub scale: (f32, f32), } impl Particle { pub fn new<NumT, RgbT>( x: NumT, y: NumT, col_fg: RgbT, col_bg: RgbT, glyph: char, lifetime: f32, start_delay: f32, scale: (f32, f32), ) -> Self where NumT: TryInto<f32>, RgbT: Into<rltk::RGBA>, { Particle { // For some reason the y-coordinate needs to be adjusted by 1 for the particle to be // correct, no idea why. pos: rltk::PointF::new( x.try_into().ok().unwrap_or(0.0), y.try_into().ok().unwrap_or(0.0) + 1.0, ), col_fg: col_fg.into(), col_bg: col_bg.into(), glyph, lifetime, start_delay, scale, } } } pub struct ParticleBuilder { pos: rltk::PointF, col_fg: rltk::RGBA, col_bg: rltk::RGBA, glyph: char, lifetime: f32, start_delay: f32, end_pos: Option<rltk::PointF>, end_col: Option<(rltk::RGBA, rltk::RGBA)>, scale: Option<((f32, f32), (f32, f32))>, } impl ParticleBuilder { pub fn new<NumT, RgbT>( x: NumT, y: NumT, col_fg: RgbT, col_bg: RgbT, glyph: char, lifetime: f32, ) -> Self where NumT: TryInto<f32>, RgbT: Into<rltk::RGBA>, { ParticleBuilder { pos: rltk::PointF::new( x.try_into().ok().unwrap_or(0.0), y.try_into().ok().unwrap_or(0.0), ), col_fg: col_fg.into(), col_bg: col_bg.into(), glyph, lifetime, start_delay: 0.0, end_pos: None, end_col: None, scale: None, } } pub fn _with_delay(mut self, start_delay: f32) -> Self { self.start_delay = start_delay; self } pub fn with_moving_to<NumT: TryInto<f32>>(mut self, x: NumT, y: NumT) -> Self { self.end_pos = Some(rltk::PointF::new( x.try_into().ok().unwrap_or(0.0), y.try_into().ok().unwrap_or(0.0), )); self } pub fn with_end_color<T: Into<rltk::RGBA>>(mut self, col_fg: T, col_bg: T) -> Self { self.end_col = Some((col_fg.into(), col_bg.into())); self } pub fn with_scale(mut self, start_scale: (f32, f32), end_scale: (f32, f32)) -> Self { self.scale = Some((start_scale, end_scale)); self } // TODO: Extract each branch into a separate helper function. pub fn build(self) -> Vec<Particle> { let mut particles = Vec::new(); // if we have multiple particles, then render one per frame if self.end_pos.is_some() || self.end_col.is_some() { let pos_start = rltk::PointF::new(self.pos.x as f32, self.pos.y as f32); let mut t = 0.0; while t < self.lifetime { let progress = t / self.lifetime; let pos = self.end_pos.map_or(pos_start, |pos_end| { rltk::PointF::new( pos_start.x + (progress * (pos_end.x as f32 - pos_start.x)), pos_start.y + (progress * (pos_end.y as f32 - pos_start.y)), ) }); let col = self.end_col.map_or((self.col_fg, self.col_bg), |c| { ( rltk::RGBA::from(self.col_fg).lerp(c.0, progress), rltk::RGBA::from(self.col_fg).lerp(c.1, progress), ) }); let scale = self.scale.map_or((1.0, 1.0), |(start_sc, end_sc)| { ( start_sc.0 + (progress * (end_sc.0 - start_sc.0)), start_sc.1 + (progress * (end_sc.1 - start_sc.1)), ) }); let particle = Particle::new( pos.x, pos.y, col.0, col.1, self.glyph, TIME_MS_PER_FRAME, self.start_delay + t, scale, ); particles.push(particle); t += TIME_MS_PER_FRAME; } } particles } } pub struct ParticleSystem { pub particles: Vec<Particle>, vignette: Vec<(game::Position, (u8, u8, u8, u8))>, } impl ParticleSystem { pub fn new() -> Self { ParticleSystem { particles: Vec::new(), vignette: create_vignette(), } } pub fn render(&self, ctx: &mut rltk::BTerm) { ctx.set_active_console(game::consts::PAR_CON); ctx.cls(); let mut draw_batch = rltk::DrawBatch::new(); for particle in &self.particles { if particle.start_delay <= 0.0 { draw_batch.set_fancy( particle.pos, 1, rltk::Degrees::new(0.0), particle.scale.into(), rltk::ColorPair::new(particle.col_fg, particle.col_bg), rltk::to_cp437(particle.glyph), ); } } self.vignette.iter().for_each(|(pos, bg_col)| { let color = rltk::ColorPair::new((0, 0, 0, 0), bg_col.clone()); draw_batch.print_color(rltk::Point::new(pos.x(), pos.y()), " ", color); }); draw_batch.submit(game::consts::PAR_CON_Z).unwrap(); } /// Advance the particle lifetimes and cull all those that have expired. /// Returns `true` if some particles expired in this call. pub fn update(&mut self, ctx: &rltk::BTerm) -> bool { let mut has_changed = false; self.particles.iter_mut().for_each(|p| { if p.start_delay > 0.0 { p.start_delay -= ctx.frame_time_ms; has_changed |= p.start_delay < 0.0; } else { p.lifetime -= ctx.frame_time_ms; has_changed |= p.lifetime < 0.0; } }); self.particles.retain(|p| p.lifetime > 0.0); has_changed } } fn create_vignette() -> Vec<(game::Position, (u8, u8, u8, u8))> { let center_x = (game::consts::WORLD_WIDTH / 2) - 1; let center_y = (game::consts::WORLD_HEIGHT / 2) - 1; let center_pos = game::Position::from_xy(center_x, center_y); let center_point = rltk::Point::new(center_x, center_y); let start_radius = center_x - 2; let end_radius = center_x + 1; let mut vignette = Vec::new(); for radius in start_radius..end_radius { for point in rltk::BresenhamCircleNoDiag::new(center_point, radius) { let pos = game::Position::from_xy(point.x, point.y); let dist = pos.distance(&center_pos); let ratio = (dist - start_radius as f32) / (end_radius as f32 - start_radius as f32); let alpha: u8 = (255.0 * ratio) as u8; vignette.push((pos, (0, 0, 0, alpha))); } } vignette }
31.041494
97
0.501404
f59669f7f24b9e0b2121f73eda5a94e02ffa53a2
989
use std::cmp::{min, Ordering::*}; pub fn arrays_intersection(arr1: Vec<i32>, arr2: Vec<i32>, arr3: Vec<i32>) -> Vec<i32> { two_sorted_arrays_intersection(arr1, two_sorted_arrays_intersection(arr2, arr3)) } fn two_sorted_arrays_intersection(a1: Vec<i32>, a2: Vec<i32>) -> Vec<i32> { let mut res = Vec::with_capacity(min(a1.len(), a2.len())); let mut i = 0; let mut j = 0; while i < a1.len() && j < a2.len() { match a1[i].cmp(&a2[j]) { Equal => { res.push(a1[i]); i += 1; j += 1; } Less => i += 1, Greater => j += 1, } } res } #[test] fn test_arrays_intersection() { let cases = vec![( vec![1, 2, 3, 4, 5], vec![1, 2, 5, 7, 9], vec![1, 3, 4, 5, 8], vec![1, 5], )]; for (a1, a2, a3, expected) in cases { let output = arrays_intersection(a1, a2, a3); assert_eq!(output, expected); } }
25.358974
88
0.484328
5decb81d9f2e26ca461cb3d6f9aa9343341e3adb
6,944
use super::{contains_return, BIND_INSTEAD_OF_MAP}; use crate::utils::{ in_macro, match_qpath, match_type, method_calls, multispan_sugg_with_applicability, paths, remove_blocks, snippet, snippet_with_macro_callsite, span_lint_and_sugg, span_lint_and_then, visitors::find_all_ret_expressions, }; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::Span; pub(crate) struct OptionAndThenSome; impl BindInsteadOfMap for OptionAndThenSome { const TYPE_NAME: &'static str = "Option"; const TYPE_QPATH: &'static [&'static str] = &paths::OPTION; const BAD_METHOD_NAME: &'static str = "and_then"; const BAD_VARIANT_NAME: &'static str = "Some"; const BAD_VARIANT_QPATH: &'static [&'static str] = &paths::OPTION_SOME; const GOOD_METHOD_NAME: &'static str = "map"; } pub(crate) struct ResultAndThenOk; impl BindInsteadOfMap for ResultAndThenOk { const TYPE_NAME: &'static str = "Result"; const TYPE_QPATH: &'static [&'static str] = &paths::RESULT; const BAD_METHOD_NAME: &'static str = "and_then"; const BAD_VARIANT_NAME: &'static str = "Ok"; const BAD_VARIANT_QPATH: &'static [&'static str] = &paths::RESULT_OK; const GOOD_METHOD_NAME: &'static str = "map"; } pub(crate) struct ResultOrElseErrInfo; impl BindInsteadOfMap for ResultOrElseErrInfo { const TYPE_NAME: &'static str = "Result"; const TYPE_QPATH: &'static [&'static str] = &paths::RESULT; const BAD_METHOD_NAME: &'static str = "or_else"; const BAD_VARIANT_NAME: &'static str = "Err"; const BAD_VARIANT_QPATH: &'static [&'static str] = &paths::RESULT_ERR; const GOOD_METHOD_NAME: &'static str = "map_err"; } pub(crate) trait BindInsteadOfMap { const TYPE_NAME: &'static str; const TYPE_QPATH: &'static [&'static str]; const BAD_METHOD_NAME: &'static str; const BAD_VARIANT_NAME: &'static str; const BAD_VARIANT_QPATH: &'static [&'static str]; const GOOD_METHOD_NAME: &'static str; fn no_op_msg() -> String { format!( "using `{}.{}({})`, which is a no-op", Self::TYPE_NAME, Self::BAD_METHOD_NAME, Self::BAD_VARIANT_NAME ) } fn lint_msg() -> String { format!( "using `{}.{}(|x| {}(y))`, which is more succinctly expressed as `{}(|x| y)`", Self::TYPE_NAME, Self::BAD_METHOD_NAME, Self::BAD_VARIANT_NAME, Self::GOOD_METHOD_NAME ) } fn lint_closure_autofixable( cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>], closure_expr: &hir::Expr<'_>, closure_args_span: Span, ) -> bool { if_chain! { if let hir::ExprKind::Call(ref some_expr, ref some_args) = closure_expr.kind; if let hir::ExprKind::Path(ref qpath) = some_expr.kind; if match_qpath(qpath, Self::BAD_VARIANT_QPATH); if some_args.len() == 1; then { let inner_expr = &some_args[0]; if contains_return(inner_expr) { return false; } let some_inner_snip = if inner_expr.span.from_expansion() { snippet_with_macro_callsite(cx, inner_expr.span, "_") } else { snippet(cx, inner_expr.span, "_") }; let closure_args_snip = snippet(cx, closure_args_span, ".."); let option_snip = snippet(cx, args[0].span, ".."); let note = format!("{}.{}({} {})", option_snip, Self::GOOD_METHOD_NAME, closure_args_snip, some_inner_snip); span_lint_and_sugg( cx, BIND_INSTEAD_OF_MAP, expr.span, Self::lint_msg().as_ref(), "try this", note, Applicability::MachineApplicable, ); true } else { false } } } fn lint_closure(cx: &LateContext<'_>, expr: &hir::Expr<'_>, closure_expr: &hir::Expr<'_>) -> bool { let mut suggs = Vec::new(); let can_sugg: bool = find_all_ret_expressions(cx, closure_expr, |ret_expr| { if_chain! { if !in_macro(ret_expr.span); if let hir::ExprKind::Call(ref func_path, ref args) = ret_expr.kind; if let hir::ExprKind::Path(ref qpath) = func_path.kind; if match_qpath(qpath, Self::BAD_VARIANT_QPATH); if args.len() == 1; if !contains_return(&args[0]); then { suggs.push((ret_expr.span, args[0].span.source_callsite())); true } else { false } } }); if can_sugg { span_lint_and_then(cx, BIND_INSTEAD_OF_MAP, expr.span, Self::lint_msg().as_ref(), |diag| { multispan_sugg_with_applicability( diag, "try this", Applicability::MachineApplicable, std::iter::once((*method_calls(expr, 1).2.get(0).unwrap(), Self::GOOD_METHOD_NAME.into())).chain( suggs .into_iter() .map(|(span1, span2)| (span1, snippet(cx, span2, "_").into())), ), ) }); } can_sugg } /// Lint use of `_.and_then(|x| Some(y))` for `Option`s fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) -> bool { if !match_type(cx, cx.typeck_results().expr_ty(&args[0]), Self::TYPE_QPATH) { return false; } match args[1].kind { hir::ExprKind::Closure(_, _, body_id, closure_args_span, _) => { let closure_body = cx.tcx.hir().body(body_id); let closure_expr = remove_blocks(&closure_body.value); if Self::lint_closure_autofixable(cx, expr, args, closure_expr, closure_args_span) { true } else { Self::lint_closure(cx, expr, closure_expr) } }, // `_.and_then(Some)` case, which is no-op. hir::ExprKind::Path(ref qpath) if match_qpath(qpath, Self::BAD_VARIANT_QPATH) => { span_lint_and_sugg( cx, BIND_INSTEAD_OF_MAP, expr.span, Self::no_op_msg().as_ref(), "use the expression directly", snippet(cx, args[0].span, "..").into(), Applicability::MachineApplicable, ); true }, _ => false, } } }
35.793814
124
0.536866
d733f32a99ead1e346de41e10e40c45714427c4d
851
use std::env; use std::fs::File; use std::io::{BufRead, BufReader}; fn calculate_fuel(mass: usize) -> usize { if mass > 6 { let fuel = mass / 3 - 2; fuel + calculate_fuel(fuel) } else { 0 } } fn main() { let args: Vec<String> = env::args().collect(); if args.len() == 2 { let input = File::open(&args[1]).unwrap(); let reader = BufReader::new(input); let mut total = 0; for mass in reader.lines() { total += calculate_fuel(mass.unwrap().parse::<usize>().unwrap()); } println!("Total Fuel Required: {}", total); } else { println!("Usage: {} <Input File>", args[0]); } } #[cfg(test)] mod tests { use super::calculate_fuel; #[test] fn known_values() { assert_eq!(calculate_fuel(12), 2); assert_eq!(calculate_fuel(14), 2); assert_eq!(calculate_fuel(1969), 966); assert_eq!(calculate_fuel(100756), 50346); } }
20.756098
68
0.620447
e262f24534cfcad7187514ee0e8ebd5ce42323e1
19,133
use imgui::{CollapsingHeader, Condition, ImStr, ImString, Slider, Window}; use itertools::Itertools; use crate::framework::context::Context; use crate::framework::error::GameResult; use crate::scene::game_scene::GameScene; use crate::scripting::tsc::text_script::TextScriptExecutionState; use crate::shared_game_state::SharedGameState; #[derive(Debug, PartialEq, Eq, Copy, Clone)] #[repr(u8)] pub enum ScriptType { Scene, Global, Inventory, StageSelect, } pub struct LiveDebugger { map_selector_visible: bool, events_visible: bool, flags_visible: bool, npc_inspector_visible: bool, last_stage_id: usize, stages: Vec<ImString>, selected_stage: i32, events: Vec<ImString>, event_ids: Vec<(ScriptType, u16)>, selected_event: i32, text_windows: Vec<(u32, ImString, ImString)>, error: Option<ImString>, } impl LiveDebugger { pub fn new() -> Self { Self { map_selector_visible: false, events_visible: false, flags_visible: false, npc_inspector_visible: false, last_stage_id: usize::MAX, stages: Vec::new(), selected_stage: -1, events: Vec::new(), event_ids: Vec::new(), selected_event: -1, text_windows: Vec::new(), error: None, } } pub fn run_ingame( &mut self, game_scene: &mut GameScene, state: &mut SharedGameState, ctx: &mut Context, ui: &mut imgui::Ui, ) -> GameResult { if self.last_stage_id != game_scene.stage_id { self.last_stage_id = game_scene.stage_id; self.events.clear(); self.selected_event = -1; } if !state.debugger { return Ok(()); } Window::new("Debugger") .resizable(false) .collapsed(true, Condition::FirstUseEver) .position([5.0, 5.0], Condition::FirstUseEver) .size([400.0, 190.0], Condition::FirstUseEver) .build(ui, || { ui.text(format!( "Player position: ({:.1},{:.1}), velocity: ({:.1},{:.1})", game_scene.player1.x as f32 / 512.0, game_scene.player1.y as f32 / 512.0, game_scene.player1.vel_x as f32 / 512.0, game_scene.player1.vel_y as f32 / 512.0, )); ui.text(format!( "frame: ({:.1},{:.1} -> {:.1},{:.1} / {})", game_scene.frame.x as f32 / 512.0, game_scene.frame.y as f32 / 512.0, game_scene.frame.target_x as f32 / 512.0, game_scene.frame.target_y as f32 / 512.0, game_scene.frame.wait )); ui.text(format!( "NPC Count: {}/{}/{} Booster fuel: {}", game_scene.npc_list.iter_alive().count(), game_scene.npc_list.current_capacity(), game_scene.npc_list.max_capacity(), game_scene.player1.booster_fuel )); ui.text(format!("Game speed ({:.1} TPS):", state.current_tps())); let mut speed = state.settings.speed; Slider::new("", 0.1, 3.0).build(ui, &mut speed); ui.same_line(); if ui.button("Reset") { speed = 1.0 } #[allow(clippy::float_cmp)] if state.settings.speed != speed { state.set_speed(speed); } if ui.button("Maps") { self.map_selector_visible = !self.map_selector_visible; } ui.same_line(); if ui.button("TSC Scripts") { self.events_visible = !self.events_visible; } ui.same_line(); if ui.button("Flags") { self.flags_visible = !self.flags_visible; } #[cfg(feature = "scripting-lua")] { ui.same_line(); if ui.button("Reload Lua Scripts") { if let Err(err) = state.lua.reload_scripts(ctx) { log::error!("Error reloading scripts: {:?}", err); self.error = Some(ImString::new(err.to_string())); } } } if game_scene.player2.cond.alive() { if ui.button("Drop Player 2") { game_scene.drop_player2(); } } else if ui.button("Add Player 2") { game_scene.add_player2(); } ui.same_line(); if ui.button("NPC Inspector") { self.npc_inspector_visible = !self.npc_inspector_visible; } }); if self.map_selector_visible { Window::new("Map selector") .resizable(false) .position([80.0, 80.0], Condition::Appearing) .size([240.0, 280.0], Condition::Appearing) .build(ui, || { if self.stages.is_empty() { for s in &state.stages { self.stages.push(ImString::new(s.name.to_owned())); } self.selected_stage = match state.stages.iter().find_position(|s| s.name == game_scene.stage.data.name) { Some((pos, _)) => pos as i32, _ => -1, }; } let stages: Vec<&ImStr> = self.stages.iter().map(|e| e.as_ref()).collect(); ui.push_item_width(-1.0); ui.list_box("", &mut self.selected_stage, &stages, 10); if ui.button("Load") { match GameScene::new(state, ctx, self.selected_stage as usize) { Ok(mut scene) => { let tile_size = scene.stage.map.tile_size.as_int() * 0x200; scene.inventory_player1 = game_scene.inventory_player1.clone(); scene.inventory_player2 = game_scene.inventory_player2.clone(); scene.player1 = game_scene.player1.clone(); scene.player1.x = scene.stage.map.width as i32 / 2 * tile_size; scene.player1.y = scene.stage.map.height as i32 / 2 * tile_size; if scene.player1.life == 0 { scene.player1.life = scene.player1.max_life; } scene.player2 = game_scene.player2.clone(); scene.player2.x = scene.stage.map.width as i32 / 2 * tile_size; scene.player2.y = scene.stage.map.height as i32 / 2 * tile_size; if scene.player2.life == 0 { scene.player2.life = scene.player1.max_life; } state.textscript_vm.suspend = true; state.textscript_vm.state = TextScriptExecutionState::Running(94, 0); state.next_scene = Some(Box::new(scene)); } Err(e) => { log::error!("Error loading map: {:?}", e); self.error = Some(ImString::new(e.to_string())); } } } }); } if self.events_visible { Window::new("TSC Scripts") .resizable(false) .position([80.0, 80.0], Condition::Appearing) .size([300.0, 320.0], Condition::Appearing) .build(ui, || { if self.events.is_empty() { self.event_ids.clear(); let scripts = state.textscript_vm.scripts.borrow(); for event in scripts.scene_script.get_event_ids() { self.events.push(ImString::new(format!("Scene: #{:04}", event))); self.event_ids.push((ScriptType::Scene, event)); } for event in scripts.global_script.get_event_ids() { self.events.push(ImString::new(format!("Global: #{:04}", event))); self.event_ids.push((ScriptType::Global, event)); } for event in scripts.inventory_script.get_event_ids() { self.events.push(ImString::new(format!("Inventory: #{:04}", event))); self.event_ids.push((ScriptType::Inventory, event)); } for event in scripts.stage_select_script.get_event_ids() { self.events.push(ImString::new(format!("Stage Select: #{:04}", event))); self.event_ids.push((ScriptType::StageSelect, event)); } } let events: Vec<&ImStr> = self.events.iter().map(|e| e.as_ref()).collect(); ui.text_wrapped(&ImString::new(format!( "TextScript execution state: {:?}", state.textscript_vm.state ))); ui.text_wrapped(&ImString::new(format!( "CreditScript execution state: {:?}", state.creditscript_vm.state ))); ui.push_item_width(-1.0); ui.list_box("", &mut self.selected_event, &events, 10); if ui.button("Execute") { assert_eq!(self.event_ids.len(), self.events.len()); if let Some((_, event_num)) = self.event_ids.get(self.selected_event as usize) { state.control_flags.set_tick_world(true); state.control_flags.set_interactions_disabled(true); state.textscript_vm.start_script(*event_num); } } ui.same_line(); if ui.button("Decompile") { if let Some((stype, event_num)) = self.event_ids.get(self.selected_event as usize) { let id = ((*stype as u32) << 16) | (*event_num as u32); if !self.text_windows.iter().any(|(e, _, _)| *e == id) { let scripts = state.textscript_vm.scripts.borrow(); let script = match stype { ScriptType::Scene => &scripts.scene_script, ScriptType::Global => &scripts.global_script, ScriptType::Inventory => &scripts.inventory_script, ScriptType::StageSelect => &scripts.stage_select_script, }; match script.decompile_event(*event_num) { Ok(code) => { self.text_windows.push(( id, ImString::new(format!("Decompiled event: #{:04}", *event_num)), ImString::new(code), )); } Err(e) => { self.error = Some(ImString::new(format!( "Error decompiling TextScript #{:04}: {}", *event_num, e ))); } } } } } }); } if self.flags_visible { Window::new("Flags") .position([80.0, 80.0], Condition::FirstUseEver) .size([280.0, 300.0], Condition::FirstUseEver) .build(ui, || { if CollapsingHeader::new("Control flags").default_open(false).build(ui) { ui.checkbox_flags("Tick world", &mut state.control_flags.0, 1); ui.checkbox_flags("Control enabled", &mut state.control_flags.0, 2); ui.checkbox_flags("Interactions disabled", &mut state.control_flags.0, 4); ui.checkbox_flags("Credits running", &mut state.control_flags.0, 8); ui.separator(); ui.checkbox_flags("[Internal] Windy level", &mut state.control_flags.0, 15); } if CollapsingHeader::new("Player condition flags").default_open(false).build(ui) { cond_flags(ui, &mut game_scene.player1.cond); } if CollapsingHeader::new("Player equipment").default_open(false).build(ui) { ui.checkbox_flags("Booster 0.8", &mut game_scene.player1.equip.0, 1); ui.checkbox_flags("Map System", &mut game_scene.player1.equip.0, 2); ui.checkbox_flags("Arms Barrier", &mut game_scene.player1.equip.0, 4); ui.checkbox_flags("Turbocharge", &mut game_scene.player1.equip.0, 8); ui.checkbox_flags("Air Tank", &mut game_scene.player1.equip.0, 16); ui.checkbox_flags("Booster 2.0", &mut game_scene.player1.equip.0, 32); ui.checkbox_flags("Mimiga Mask", &mut game_scene.player1.equip.0, 64); ui.checkbox_flags("Whimsical Star", &mut game_scene.player1.equip.0, 128); ui.checkbox_flags("Nikumaru Counter", &mut game_scene.player1.equip.0, 256); } }); } if self.npc_inspector_visible { Window::new("NPC Inspector") .position([80.0, 80.0], Condition::FirstUseEver) .size([280.0, 300.0], Condition::FirstUseEver) .scrollable(true) .always_vertical_scrollbar(true) .build(ui, || { for npc in game_scene.npc_list.iter_alive() { if CollapsingHeader::new(&ImString::from(format!("id={} type={}", npc.id, npc.npc_type))) .default_open(false) .build(ui) { let mut position = [npc.x as f32 / 512.0, npc.y as f32 / 512.0]; ui.input_float2("Position:", &mut position).build(); npc.x = (position[0] * 512.0) as i32; npc.y = (position[1] * 512.0) as i32; let content = &ImString::from(format!( "\ Velocity: ({:.1},{:.1})\n\ Vel2/State2: ({:.1},{:.1} / {} {})\n\ Animation: frame={}, counter={}\n\ Action: num={}, counter={}, counter2={}\n\ Health: {}, Experience drop: {}\n\ Event ID: {}, Flag ID: {}\n\ Parent: {}, Shock: {}, Size: {}", npc.vel_x as f32 / 512.0, npc.vel_y as f32 / 512.0, npc.vel_x2 as f32 / 512.0, npc.vel_y2 as f32 / 512.0, npc.vel_x2, npc.vel_y2, npc.anim_num, npc.anim_counter, npc.action_num, npc.action_counter, npc.action_counter2, npc.life, npc.exp, npc.event_num, npc.flag_num, npc.parent_id, npc.shock, npc.size )); ui.text_wrapped(content); cond_flags(ui, &mut npc.cond); } } }); } let mut remove = -1; for (idx, (_, title, contents)) in self.text_windows.iter().enumerate() { let mut opened = true; Window::new(title) .position([100.0, 100.0], Condition::FirstUseEver) .size([400.0, 300.0], Condition::FirstUseEver) .opened(&mut opened) .build(ui, || { ui.text_wrapped(contents); }); if !opened { remove = idx as i32; } } if remove >= 0 { self.text_windows.remove(remove as usize); } if self.error.is_some() { Window::new("Error!") .resizable(false) .collapsible(false) .position( [((state.screen_size.0 - 300.0) / 2.0).floor(), ((state.screen_size.1 - 100.0) / 2.0).floor()], Condition::Appearing, ) .size([300.0, 100.0], Condition::Appearing) .build(ui, || { ui.push_item_width(-1.0); ui.text_wrapped(self.error.as_ref().unwrap()); if ui.button("OK") { self.error = None; } }); } Ok(()) } } fn cond_flags(ui: &imgui::Ui, cond: &mut crate::common::Condition) { ui.checkbox_flags("Interacted", &mut cond.0, 1); ui.checkbox_flags("Hidden", &mut cond.0, 2); ui.checkbox_flags("Fallen", &mut cond.0, 4); ui.checkbox_flags("Built-in NPC destroy handler", &mut cond.0, 8); ui.checkbox_flags("Damage first boss NPC", &mut cond.0, 16); ui.checkbox_flags("Increased acceleration", &mut cond.0, 32); ui.checkbox_flags("Unknown (0x40)", &mut cond.0, 64); ui.checkbox_flags("Alive", &mut cond.0, 128); }
43.583144
115
0.429886
e9b887b4505f15385d2f0e45547662bf8ea913af
5,483
//! A library for inspecting Rust code #![warn( missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications )] use std::env; use std::fs; use std::fs::File; use std::io::Write; use std::path::PathBuf; use std::process::Command; /// Available configuration settings when using cargo-inspect as a library pub mod config; /// Contains all types defined for error handling pub mod errors; mod comment; mod diff; mod format; mod hir; mod tmpfile; use prettyprint::PrettyPrinter; pub use crate::config::{Config, Opt}; pub use crate::errors::InspectError; use crate::comment::comment_file; pub use crate::diff::diff; use crate::format::format; use crate::hir::HIR; pub use crate::tmpfile::tmpfile; /// inspect takes a Rust file or crate as an input and returns the desugared /// output. pub fn inspect(config: &Config) -> Result<(), InspectError> { let output = match &config.files { Some(files) => { let hir0 = inspect_file( PathBuf::from(files.0.clone()), config.verbose, config.unpretty.clone(), )?; let hir1 = inspect_file( PathBuf::from(files.1.clone()), config.verbose, config.unpretty.clone(), )?; diff(try_format(hir0.output)?, try_format(hir1.output)?)? } None => inspect_single(config)?, }; if config.plain { println!("{}", output); } else if config.unpretty.starts_with("flowgraph") { if let Some(path) = &config.input { let input_path = PathBuf::from(path); // Extract the file name from our input path. let file_name = input_path .file_name() .ok_or(InspectError::Flowgraph(String::from( "Invalid path found. The input path should be a file.", )))?; let mut output_path = PathBuf::from(file_name); let ext = &config.format; output_path.set_extension(&ext); // Create a temporary file to dump out the plain output let tmp_file_path = tmpfile()?; let mut file = File::create(&tmp_file_path)?; file.write_all(output.as_bytes())?; // For now setup the correct `dot` arguments to write to a png let output_str = output_path .to_str() .ok_or(InspectError::Flowgraph(String::from( "Failed to convert output path to string.", )))?; let input_str = tmp_file_path .to_str() .ok_or(InspectError::Flowgraph(String::from( "Failed to convert temporary path to string.", )))?; log::info!("Writing \"{}\"...", output_str); let args = [&format!("-T{}", ext), "-o", output_str, input_str]; Command::new("dot") .args(&args) .spawn() .map_err(|e| InspectError::DotExec(e))?; } } else { let mut builder = PrettyPrinter::default(); builder.language("rust"); if let Some(theme) = &config.theme { builder.theme(theme.clone()); } let printer = builder.build()?; let header = config.input.to_owned().unwrap_or(env::current_dir()?); printer.string_with_header(output, header.to_string_lossy().to_string())?; } Ok(()) } /// Run inspection on a single file or crate. Return the compiler output /// (preferably formatted with rustfmt) pub fn inspect_single(config: &Config) -> Result<String, InspectError> { let hir = match config.input.clone() { Some(input) => inspect_file(input, config.verbose, config.unpretty.clone()), None => inspect_crate(config), }?; Ok(try_format(hir.output)?) } /// Run cargo-inspect on a file fn inspect_file(input: PathBuf, verbose: bool, unpretty: String) -> Result<HIR, InspectError> { let input = match verbose { true => { // Create a temporary copy of the input file, // which contains comments for each input line // to avoid modifying the original input file. // This will be used as the input of rustc. let tmp = tmpfile()?; fs::copy(&input, &tmp)?; comment_file(&tmp)?; tmp } false => input.into(), }; hir::from_file(&input, &unpretty) } /// Run cargo-inspect on a crate fn inspect_crate(config: &Config) -> Result<HIR, InspectError> { if config.verbose { unimplemented!( "Verbose option doesn't work for crates yet. \ See https://github.com/mre/cargo-inspect/issues/5" ) // comment_crate()?; } hir::from_crate(&config.unpretty) } // TODO: This should really be more idiomatic; // maybe by having a `Formatted` type and a `let fmt = Formatted::try_from(string);` fn try_format(input: String) -> Result<String, InspectError> { let mut formatted = format(&input)?; if formatted.is_empty() { // In case of an error, rustfmt returns an empty string // and we continue with the unformatted output. // Not ideal, but better than panicking. formatted = input; } Ok(formatted) }
31.693642
95
0.584716
f449e3ec7424a5d206d7e1ca76dcaa9f26237e0c
820
use clap::Parser; use console::style; use proctor::tracing::{get_subscriber, init_subscriber}; use springline::settings::CliOptions; use springline_explorer::AppMenu; fn main() { let app_name = std::env::args().next().unwrap(); let subscriber = get_subscriber(app_name.as_str(), "warn", std::io::stdout); init_subscriber(subscriber); let main_span = tracing::info_span!("main"); let _main_span_guard = main_span.enter(); let options: CliOptions = CliOptions::parse(); let mut app = AppMenu::new(options).expect("failed to create application menu"); eprintln!( "\n{} {}!", style("Welcome to the").bold(), style("Springline Policy Explorer").green().bold() ); if let Err(err) = app.interact() { eprintln!("{} failed: {}", app_name, err); } }
30.37037
84
0.643902
ef1f11f435b61f859559995bbfd3d204dedaf7de
4,278
// SPDX-License-Identifier: Apache-2.0 use super::*; use core::marker::PhantomData; use core::mem::size_of; use core::ops::*; /// An offset of a number of items of type `T` from a base /// /// Note well that this is NOT stored in memory as the number of bytes, /// but rather the number of items. /// /// One important additional feature is that offsets can be converted between /// underlying types so long as the conversion is lossless for the target CPU /// architecture. For example, `Offset<u64>` can be converted to /// `Offset<usize>` on 64-bit systems. #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] #[repr(transparent)] pub struct Offset<T, U>(T, PhantomData<U>); impl<T, U> Offset<T, U> { /// Create an offset value from the number of items #[inline] pub const fn from_items(items: T) -> Self { Self(items, PhantomData) } /// Get the number of items #[inline] pub fn items(self) -> T { self.0 } } impl<T, U> Offset<T, U> where Offset<usize, ()>: Into<Offset<T, ()>>, T: Mul<T, Output = T>, { /// Get the number of bytes #[inline] pub fn bytes(self) -> T { self.0 * Offset(size_of::<U>(), PhantomData).into().items() } } impl<T: Zero, U: Copy> Zero for Offset<T, U> { const ZERO: Offset<T, U> = Offset::from_items(T::ZERO); } impl<T: One, U: Copy> One for Offset<T, U> { const ONE: Offset<T, U> = Offset::from_items(T::ONE); } impl<T, U> From<Register<T>> for Offset<T, U> { #[inline] fn from(value: Register<T>) -> Self { Self::from_items(value.raw()) } } impl<T, U> From<Offset<T, U>> for Register<T> { #[inline] fn from(value: Offset<T, U>) -> Self { Self::from_raw(value.0) } } #[cfg(target_pointer_width = "64")] impl<U> From<Offset<u64, U>> for Offset<usize, U> { #[inline] fn from(value: Offset<u64, U>) -> Self { Self(value.0 as _, PhantomData) } } #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] impl<U> From<Offset<usize, U>> for Offset<u64, U> { #[inline] fn from(value: Offset<usize, U>) -> Self { Self(value.0 as _, PhantomData) } } #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] impl<U> From<Offset<u32, U>> for Offset<usize, U> { #[inline] fn from(value: Offset<u32, U>) -> Self { Self(value.0 as _, PhantomData) } } #[cfg(target_pointer_width = "32")] impl<U> From<Offset<usize, U>> for Offset<u32, U> { #[inline] fn from(value: Offset<usize, U>) -> Self { Self(value.0 as _, PhantomData) } } impl<T: Add<T, Output = T>, U> Add for Offset<T, U> { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self::Output { Self(self.0 + rhs.0, PhantomData) } } impl<T: AddAssign<T>, U> AddAssign for Offset<T, U> { #[inline] fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; } } impl<T: Div<T, Output = T>, U> Div for Offset<T, U> { type Output = Self; #[inline] fn div(self, rhs: Self) -> Self::Output { Self(self.0 / rhs.0, PhantomData) } } impl<T: DivAssign<T>, U> DivAssign for Offset<T, U> { #[inline] fn div_assign(&mut self, rhs: Self) { self.0 /= rhs.0; } } impl<T: Mul<T, Output = T>, U> Mul for Offset<T, U> { type Output = Self; #[inline] fn mul(self, rhs: Self) -> Self::Output { Self(self.0 * rhs.0, PhantomData) } } impl<T: MulAssign<T>, U> MulAssign for Offset<T, U> { #[inline] fn mul_assign(&mut self, rhs: Self) { self.0 *= rhs.0; } } impl<T: Rem<T, Output = T>, U> Rem for Offset<T, U> { type Output = Self; #[inline] fn rem(self, rhs: Self) -> Self::Output { Self(self.0 % rhs.0, PhantomData) } } impl<T: RemAssign<T>, U> RemAssign for Offset<T, U> { #[inline] fn rem_assign(&mut self, rhs: Self) { self.0 %= rhs.0; } } impl<T: Sub<T, Output = T>, U> Sub for Offset<T, U> { type Output = Self; #[inline] fn sub(self, rhs: Self) -> Self::Output { Self(self.0 - rhs.0, PhantomData) } } impl<T: SubAssign<T>, U> SubAssign for Offset<T, U> { #[inline] fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; } }
23.766667
77
0.578074
e81caa72512729785184643a75e126237dd0d92b
2,419
use skulpin_renderer::ash; use ash::vk; use ash::prelude::VkResult; use ash::version::DeviceV1_0; use skulpin_renderer::util; pub struct VkImage { pub device: ash::Device, // This struct is not responsible for releasing this pub image: vk::Image, pub image_memory: vk::DeviceMemory, pub extent: vk::Extent3D, } impl VkImage { pub fn new( logical_device: &ash::Device, device_memory_properties: &vk::PhysicalDeviceMemoryProperties, extent: vk::Extent3D, format: vk::Format, tiling: vk::ImageTiling, usage: vk::ImageUsageFlags, required_property_flags: vk::MemoryPropertyFlags, ) -> VkResult<Self> { let image_create_info = vk::ImageCreateInfo::builder() .image_type(vk::ImageType::TYPE_2D) .extent(extent) .mip_levels(1) .array_layers(1) .format(format) .tiling(tiling) .initial_layout(vk::ImageLayout::UNDEFINED) .usage(usage) .sharing_mode(vk::SharingMode::EXCLUSIVE) .samples(vk::SampleCountFlags::TYPE_1); let image = unsafe { logical_device.create_image(&image_create_info, None)? }; let image_memory_req = unsafe { logical_device.get_image_memory_requirements(image) }; //TODO: Better error handling here let image_memory_index = util::find_memorytype_index( &image_memory_req, device_memory_properties, required_property_flags, ) .expect("Unable to find suitable memorytype for the vertex buffer."); let image_allocate_info = vk::MemoryAllocateInfo::builder() .allocation_size(image_memory_req.size) .memory_type_index(image_memory_index); let image_memory = unsafe { logical_device.allocate_memory(&image_allocate_info, None)? }; unsafe { logical_device.bind_image_memory(image, image_memory, 0)?; } Ok(VkImage { device: logical_device.clone(), image, image_memory, extent, }) } } impl Drop for VkImage { fn drop(&mut self) { log::debug!("destroying VkImage"); unsafe { self.device.destroy_image(self.image, None); self.device.free_memory(self.image_memory, None); } log::debug!("destroyed VkImage"); } }
29.5
98
0.618024
0a2a756c6b1c24739813d3dfdfb3d087617b6547
2,831
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(missing_doc)] #![experimental] //! Contains struct definitions for the layout of compiler built-in types. //! //! They can be used as targets of transmutes in unsafe code for manipulating //! the raw representations directly. //! //! Their definition should always match the ABI defined in `rustc::back::abi`. use mem; /// The representation of a Rust managed box pub struct Box<T> { pub ref_count: uint, pub drop_glue: fn(ptr: *mut u8), pub prev: *mut Box<T>, pub next: *mut Box<T>, pub data: T, } /// The representation of a Rust slice pub struct Slice<T> { pub data: *T, pub len: uint, } /// The representation of a Rust closure pub struct Closure { pub code: *(), pub env: *(), } /// The representation of a Rust procedure (`proc()`) pub struct Procedure { pub code: *(), pub env: *(), } /// The representation of a Rust trait object. /// /// This struct does not have a `Repr` implementation /// because there is no way to refer to all trait objects generically. pub struct TraitObject { pub vtable: *(), pub data: *(), } /// This trait is meant to map equivalences between raw structs and their /// corresponding rust values. pub trait Repr<T> { /// This function "unwraps" a rust value (without consuming it) into its raw /// struct representation. This can be used to read/write different values /// for the struct. This is a safe method because by default it does not /// enable write-access to the fields of the return value in safe code. #[inline] fn repr(&self) -> T { unsafe { mem::transmute_copy(self) } } } impl<'a, T> Repr<Slice<T>> for &'a [T] {} impl<'a> Repr<Slice<u8>> for &'a str {} #[cfg(test)] mod tests { use super::*; use mem; #[test] fn synthesize_closure() { unsafe { let x = 10; let f: |int| -> int = |y| x + y; assert_eq!(f(20), 30); let original_closure: Closure = mem::transmute(f); let actual_function_pointer = original_closure.code; let environment = original_closure.env; let new_closure = Closure { code: actual_function_pointer, env: environment }; let new_f: |int| -> int = mem::transmute(new_closure); assert_eq!(new_f(20), 30); } } }
27.754902
80
0.635465
8933234fb9e5c0205b111614b49e32a91e3f2649
403
use yarnspinner::{DialogRunner, Error}; const SALLY_SRC: &str = include_str!("sally.yarn"); fn run() -> Result<(), Error<'static>>{ let mut runner = DialogRunner::new(); runner.load_yarn_file(SALLY_SRC)?; while let Some(e) = runner.next_event() { println!("dialog event: {:?}", e); } Ok(()) } fn main() { if let Err(e) = run() { eprintln!("{}", e); } }
18.318182
51
0.55335
efdfe5b7952e1c7ee86f16e2eb970b6c6438561b
2,365
use std::convert::TryFrom; use std::fmt; use ibc_proto::ibc::core::commitment::v1::MerkleProof as RawMerkleProof; use crate::ics23_commitment::error::{Error, Kind}; use super::merkle::MerkleProof; #[derive(Clone, Debug, PartialEq, Eq)] pub struct CommitmentRoot(pub Vec<u8>); // Todo: write constructor impl CommitmentRoot { pub fn from_bytes(bytes: &[u8]) -> Self { Self { 0: Vec::from(bytes), } } } impl From<Vec<u8>> for CommitmentRoot { fn from(v: Vec<u8>) -> Self { Self { 0: v } } } #[derive(Clone, Debug, PartialEq)] pub struct CommitmentPath; #[derive(Clone, Debug, PartialEq, Eq)] pub struct CommitmentProof(Vec<u8>); impl CommitmentProof { pub fn is_empty(&self) -> bool { self.0.len() == 0 } } impl From<Vec<u8>> for CommitmentProof { fn from(v: Vec<u8>) -> Self { Self { 0: v } } } impl From<CommitmentProof> for Vec<u8> { fn from(p: CommitmentProof) -> Vec<u8> { p.0 } } impl From<MerkleProof> for CommitmentProof { fn from(proof: MerkleProof) -> Self { let raw_proof: RawMerkleProof = proof.into(); raw_proof.into() } } impl From<RawMerkleProof> for CommitmentProof { fn from(proof: RawMerkleProof) -> Self { let mut buf = Vec::new(); prost::Message::encode(&proof, &mut buf).unwrap(); buf.into() } } impl TryFrom<CommitmentProof> for RawMerkleProof { type Error = Error; fn try_from(value: CommitmentProof) -> Result<Self, Self::Error> { let value: Vec<u8> = value.into(); let res: RawMerkleProof = prost::Message::decode(value.as_ref()) .map_err(|e| Kind::InvalidRawMerkleProof.context(e))?; Ok(res) } } // TODO: decent getter or Protobuf trait implementation #[derive(Clone, PartialEq, Eq)] pub struct CommitmentPrefix(pub Vec<u8>); impl CommitmentPrefix { pub fn is_empty(&self) -> bool { self.0.len() == 0 } } impl From<Vec<u8>> for CommitmentPrefix { fn from(v: Vec<u8>) -> Self { Self { 0: v } } } impl fmt::Debug for CommitmentPrefix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let converted = std::str::from_utf8(&self.0); match converted { Ok(s) => write!(f, "{}", s), Err(_e) => write!(f, "{:?}", &self.0), } } }
23.415842
72
0.595772
61e7a0e077a6bc0f6c781c574a59588786c17f5b
10,781
use std::{cell::RefCell, sync::Arc}; use ray_tracing::{ bvh::BvhNode, hittable::{HittableList, RotateY, Translate}, material::{Dielectric, DiffuseLight, Lambertian, Mat, Metal}, medium, objects::{rect, Cube, MovingSphere, Sphere}, rand_range, ray::{Point, Vec3}, render::Color, texture::{CheckerTexture, ImageTexture, NoiseTexture}, }; #[derive(Debug, Clone, Copy, clap::ArgEnum)] pub enum Worlds { RandomScene, TwoPerlinSpheres, TwoSpheres, Earth, SimpleLight, CornellBox, CornellBoxSmoke, FinalScene, } pub fn final_scene() -> anyhow::Result<HittableList> { let mut objects = HittableList::new(); const CUBE_PER_SIDE: usize = 20; let mut cubes = HittableList::with_capacity(CUBE_PER_SIDE * CUBE_PER_SIDE); let ground = Lambertian::new([0.48, 0.83, 0.53].into()); for i in 0..CUBE_PER_SIDE { for j in 0..CUBE_PER_SIDE { let w = 100.0; let x0 = -1000.0 + (i as f64) * w; let y0 = 0.0; let z0 = -1000.0 + (j as f64) * w; let x1 = x0 + w; let y1 = rand_range(1.0..101.0); let z1 = z0 + w; let cube = Cube::new(&[x0, y0, z0].into(), &[x1, y1, z1].into(), ground.clone()); cubes.add(cube); } } objects.add(BvhNode::from_hittable_list(&cubes, 0.0, 1.0)); let light = DiffuseLight::new([7.0, 7.0, 7.0].into()); objects.add(rect::XZ::new(light, (123.0, 423.0), (147.0, 412.0), 554.0)); let center1 = [400.0, 400.0, 200.0].into(); let center2 = center1 + [30.0, 0.0, 0.0].into(); let mam = Lambertian::new([0.7, 0.3, 0.1].into()); objects.add(MovingSphere::new( (center1, center2), (0.0, 1.0), 50.0, Arc::new(mam), )); for (c, m) in [ ([260.0, 150.0, 45.0], Arc::new(Dielectric::new(1.5)) as Mat), ( [0.0, 150.0, 145.0], Arc::new(Metal::new([0.8, 0.8, 0.9].into(), 1.0)), ), ] { objects.add(Sphere::new(c.into(), 50.0, m)); } let glass = Arc::new(Dielectric::new(1.5)); let boundary = Sphere::new([360.0, 150.0, 145.0].into(), 70.0, glass.clone()); objects.add(boundary.clone()); objects.add(medium::Constant::new( boundary, 0.2, &[0.2, 0.4, 0.9].into(), )); let boundary = Sphere::new(Point::zeros(), 5000.0, glass); objects.add(medium::Constant::new( boundary, 0.0001, &[1.0, 1.0, 1.0].into(), )); let emat = Lambertian::with_texture(ImageTexture::new("assets/earthmap.jpg")?); objects.add(Sphere::new( [400.0, 200.0, 400.0].into(), 100.0, Arc::new(emat), )); let pertext = NoiseTexture::with_scale(0.1); objects.add(Sphere::new( [200.0, 280.0, 300.0].into(), 80.0, Arc::new(Lambertian::with_texture(pertext)), )); let mut cubes = HittableList::new(); let white = Arc::new(Lambertian::new([0.73, 0.73, 0.73].into())); const NS: usize = 1000; for _ in 0..NS { let sphere = Sphere::new(Point::random_range(0.0..165.0), 10.0, white.clone()); cubes.add(sphere); } objects.add(Translate::new( RotateY::new(BvhNode::from_hittable_list(&cubes, 0.0, 1.0), 15.0), [-100.0, 270.0, 395.0].into(), )); Ok(objects) } pub fn cornell_box() -> HittableList { let mut world = HittableList::new(); // Setup colors let red = Lambertian::new([0.65, 0.05, 0.05].into()); let white = Lambertian::new([0.73, 0.73, 0.73].into()); let green = Lambertian::new([0.12, 0.45, 0.15].into()); let light = DiffuseLight::new([15.0, 15.0, 15.0].into()); // Walls for (k, mp) in [(555.0, green), (0.0, red)] { let yz = rect::YZ::new(mp, (0.0, 555.0), (0.0, 555.0), k); world.add(yz); } world.add(rect::XZ::new(light, (213.0, 343.0), (227.0, 332.0), 554.0)); for k in [555.0, 0.0] { let xz = rect::XZ::new(white.clone(), (0.0, 555.0), (0.0, 555.0), k); world.add(xz); } world.add(rect::XY::new( white.clone(), (0.0, 555.0), (0.0, 555.0), 555.0, )); // Cubes in the middle let cubes = [ ([165.0, 333.0, 165.0], 15.0, [265.0, 0.0, 295.0]), ([165.0, 165.0, 165.0], -18.0, [130.0, 0.0, 65.0]), ]; for (pos, ang, tra) in cubes { let cube = Cube::new(&Point::zeros(), &pos.into(), white.clone()); let cube = RotateY::new(cube, ang); let cube = Translate::new(cube, tra.into()); world.add(cube); } world } pub fn cornell_box_smoke() -> HittableList { let mut world = HittableList::new(); // Setup colors let red = Lambertian::new([0.65, 0.05, 0.05].into()); let white = Lambertian::new([0.73, 0.73, 0.73].into()); let green = Lambertian::new([0.12, 0.45, 0.15].into()); let light = DiffuseLight::new([15.0, 15.0, 15.0].into()); // Walls for (k, mp) in [(555.0, green), (0.0, red)] { let yz = rect::YZ::new(mp, (0.0, 555.0), (0.0, 555.0), k); world.add(yz); } world.add(rect::XZ::new(light, (213.0, 343.0), (227.0, 332.0), 554.0)); for k in [555.0, 0.0] { let xz = rect::XZ::new(white.clone(), (0.0, 555.0), (0.0, 555.0), k); world.add(xz); } world.add(rect::XY::new( white.clone(), (0.0, 555.0), (0.0, 555.0), 555.0, )); // Cubes in the middle let cubes = [ ( [165.0, 333.0, 165.0], 15.0, [265.0, 0.0, 295.0], Color::zeros(), ), ( [165.0, 165.0, 165.0], -18.0, [130.0, 0.0, 65.0], Color::ones(), ), ]; for (pos, ang, tra, col) in cubes { let cube = Cube::new(&Point::zeros(), &pos.into(), white.clone()); let cube = RotateY::new(cube, ang); let cube = Translate::new(cube, tra.into()); let cube = medium::Constant::new(cube, 0.01, &col); world.add(cube); } world } pub fn simple_light() -> HittableList { let mut world = HittableList::new(); let pertext = NoiseTexture::with_scale(4.0); let lam = Lambertian::with_texture(pertext); let lam = Arc::new(lam); let objs = [ ([0.0, -1000.0, 0.0].into(), 1000.0), ([0.0, 2.0, 0.0].into(), 2.0), ]; for s in objs { world.add(Sphere::new(s.0, s.1, lam.clone())); } let difflight = DiffuseLight::new([4.0, 4.0, 4.0].into()); let rect = rect::XY::new(difflight, (3.0, 5.0), (1.0, 3.0), -2.0); world.add(rect); world } pub fn earth() -> anyhow::Result<HittableList> { let mut world = HittableList::new(); let earth_texture = ImageTexture::new("assets/earthmap.jpg")?; let earth_surface = Lambertian::with_texture(earth_texture); let globe = Sphere::new([0.0, 0.0, 0.0].into(), 2.0, Arc::new(earth_surface)); world.add(globe); Ok(world) } pub fn two_perlin_spheres() -> HittableList { let mut world = HittableList::with_capacity(2); let pertext = NoiseTexture::with_scale(4.0); let lam = Lambertian::with_texture(pertext); let lam = Arc::new(lam); let spheres = [((0.0, -1000.0, 0.0), 1000.0), ((0.0, 2.0, 0.0), 2.0)]; for ((x, y, z), v) in spheres { let sphere = Sphere::new(Point::new(x, y, z), v, lam.clone()); world.add(sphere); } world } pub fn two_spheres() -> HittableList { let mut world = HittableList::with_capacity(2); let checker = CheckerTexture::with_color(Color::new(0.2, 0.3, 0.1), Color::new(0.9, 0.9, 0.9)); let checker = Lambertian::with_texture(checker); let checker = Arc::new(checker); let spheres = &[(0.0, -10.0, 0.0), (0.0, 10.0, 0.0)]; for (x, y, z) in spheres.iter() { let sphere = Sphere::new(Point::new(*x, *y, *z), 10.0, checker.clone()); world.add(sphere); } world } pub fn random_scene() -> HittableList { let world = HittableList::with_capacity(11 * 2 * 2); // RefCell is needed here as the world // is mutably borrowed by two functions // and the borrow checker cannot prove // that they will not be run at the same // time let world = RefCell::new(Some(world)); let adder_point = |p, r, m| { (world) .borrow_mut() .as_mut() .unwrap() .add(Sphere::new(p, r, m)); }; let adder_m_point = |c1, c2, t1, t2, r, m| { (world) .borrow_mut() .as_mut() .unwrap() .add(MovingSphere::new((c1, c2), (t1, t2), r, m)); }; let make_lam = |p: Color| Arc::new(Lambertian::new(p)); let make_met = |p: Color, f| Arc::new(Metal::new(p, f)); let make_diel = |x| Arc::new(Dielectric::new(x)); let make_lam_o = |(x, y, z)| make_lam(Color::new(x, y, z)); let make_met_o = |(x, y, z), f| make_met(Color::new(x, y, z), f); // Add ground let checker = CheckerTexture::with_color(Color::new(0.2, 0.3, 0.1), Color::new(0.9, 0.9, 0.9)); let checker = Lambertian::with_texture(checker); adder_point(Point::new(0.0, -1000.0, 0.0), 1000.0, Arc::new(checker)); let calc = |v| (v as f64) + 0.9 * rand_range(0.0..1.0); for a in -11..11 { for b in -11..11 { let choose_mat = rand_range(0.0..1.0); let center = Point::new(calc(a), 0.2, calc(b)); if (center - Point::new(4.0, 0.2, 0.0)).length() <= 0.9 { continue; } if choose_mat < 0.5 { let albedo = Color::random_range(0.05..0.95) * Color::random_range(0.05..0.95); let center2 = center + Vec3::new(0.0, rand_range(0.0..0.5), 0.0); adder_m_point(center, center2, 0.0, 1.0, 0.2, make_lam(albedo)); } else if choose_mat < 0.85 { let albedo = Color::random_range(0.5..1.0); let fuzz = rand_range(0.0..0.5); adder_point(center, 0.2, make_met(albedo, fuzz)); } else { adder_point(center, 0.2, make_diel(1.5)); } } } let a: &[(_, Mat)] = &[ ((0.0, 1.0, 0.0), make_diel(1.5)), ( (-4.0, 1.0, 0.0), make_lam_o((130.0 / 256.0, 22.0 / 256.0, 22.0 / 256.0)), ), ((4.0, 1.0, 0.0), make_met_o((0.7, 0.6, 0.5), 0.0)), ]; for m in a { let p = Point::new(m.0 .0, m.0 .1, m.0 .2); adder_point(p, 1.0, m.1.clone()); } // unwrap is safe to work here // as the Option above is soley // used to be able to take the // resulting world let res = world.borrow_mut().take().unwrap(); res }
29.137838
99
0.518227
50f08aec4982270f64f09c970ac3cf615bbd9715
1,688
// [See license/rust-lang/libm] Copyright (c) 2018 Jorge Aparicio pub fn trunc(x: f32) -> f32 { let mut i: u32 = x.to_bits(); let mut e: i32 = (i >> 23 & 0xff) as i32 - 0x7f + 9; let m: u32; if e >= 23 + 9 { return x; } if e < 9 { e = 1; } m = -1i32 as u32 >> e; if (i & m) == 0 { return x; } i &= !m; f32::from_bits(i) } #[inline(always)] pub fn as_i32(value: f32) -> i32 { value as i32 } #[inline(always)] pub fn fract(value: f32) -> f32 { value - trunc(value) } // [See license/rust-lang/libm] Copyright (c) 2018 Jorge Aparicio pub fn ceil(x: f32) -> f32 { let mut ui = x.to_bits(); let e = (((ui >> 23) & 0xff).wrapping_sub(0x7f)) as i32; if e >= 23 { return x; } if e >= 0 { let m = 0x007fffff >> e; if (ui & m) == 0 { return x; } if ui >> 31 == 0 { ui += m; } ui &= !m; } else { if ui >> 31 != 0 { return -0.0; } else if ui << 1 != 0 { return 1.0; } } f32::from_bits(ui) } // [See license/rust-lang/libm] Copyright (c) 2018 Jorge Aparicio pub fn floor(x: f32) -> f32 { let mut ui = x.to_bits(); let e = (((ui >> 23) as i32) & 0xff) - 0x7f; if e >= 23 { return x; } if e >= 0 { let m: u32 = 0x007fffff >> e; if (ui & m) == 0 { return x; } if ui >> 31 != 0 { ui += m; } ui &= !m; } else { if ui >> 31 == 0 { ui = 0; } else if ui << 1 != 0 { return -1.0; } } f32::from_bits(ui) }
20.585366
65
0.413507
3a2c2097948f6a7a73602053f77d806d8de54462
5,121
#[macro_export] macro_rules! ScriptRepeatRange { () => { $crate::Program!("RepeatRange"; $crate::Discard!($crate::Equals!("{")), $crate::ScriptWS0!(?), $crate::Matches!("Minimum"; r"\d+"), $crate::ScriptWS0!(?), $crate::Optional!($crate::Equals!("Seperator"; ",")), $crate::ScriptWS0!(?), $crate::Optional!($crate::Matches!("Maximum"; r"\d+")), $crate::ScriptWS0!(?), $crate::Discard!($crate::Equals!("}")), ) }; } #[cfg(test)] mod tests { use crate::{ matcher::{MatcherFailure}, parser::Parser, parser_context::ParserContext, source_range::SourceRange, }; #[test] fn it_works1() { let parser = Parser::new(r"{10}"); let parser_context = ParserContext::new(&parser, "Test"); let matcher = ScriptRepeatRange!(); let result = ParserContext::tokenize(parser_context, matcher); if let Ok(token) = result { let token = token.borrow(); assert_eq!(token.get_name(), "RepeatRange"); assert_eq!(*token.get_captured_range(), SourceRange::new(1, 3)); assert_eq!(*token.get_matched_range(), SourceRange::new(0, 4)); assert_eq!(token.get_value(), r"10"); assert_eq!(token.get_matched_value(), r"{10}"); assert_eq!(token.get_children().len(), 1); let first = token.get_children()[0].borrow(); assert_eq!(first.get_name(), "Minimum"); assert_eq!(*first.get_captured_range(), SourceRange::new(1, 3)); assert_eq!(*first.get_matched_range(), SourceRange::new(1, 3)); assert_eq!(first.get_value(), "10"); assert_eq!(first.get_matched_value(), "10"); } else { unreachable!("Test failed!"); }; } #[test] fn it_works2() { let parser = Parser::new(r"{ 9, 11 }"); let parser_context = ParserContext::new(&parser, "Test"); let matcher = ScriptRepeatRange!(); let result = ParserContext::tokenize(parser_context, matcher); if let Ok(token) = result { let token = token.borrow(); assert_eq!(token.get_name(), "RepeatRange"); assert_eq!(*token.get_captured_range(), SourceRange::new(2, 7)); assert_eq!(*token.get_matched_range(), SourceRange::new(0, 9)); assert_eq!(token.get_value(), r"9, 11"); assert_eq!(token.get_matched_value(), r"{ 9, 11 }"); assert_eq!(token.get_children().len(), 3); let first = token.get_children()[0].borrow(); assert_eq!(first.get_name(), "Minimum"); assert_eq!(*first.get_captured_range(), SourceRange::new(2, 3)); assert_eq!(*first.get_matched_range(), SourceRange::new(2, 3)); assert_eq!(first.get_value(), "9"); assert_eq!(first.get_matched_value(), "9"); let second = token.get_children()[1].borrow(); assert_eq!(second.get_name(), "Seperator"); assert_eq!(*second.get_captured_range(), SourceRange::new(3, 4)); assert_eq!(*second.get_matched_range(), SourceRange::new(3, 4)); assert_eq!(second.get_value(), ","); assert_eq!(second.get_matched_value(), ","); let third = token.get_children()[2].borrow(); assert_eq!(third.get_name(), "Maximum"); assert_eq!(*third.get_captured_range(), SourceRange::new(5, 7)); assert_eq!(*third.get_matched_range(), SourceRange::new(5, 7)); assert_eq!(third.get_value(), "11"); assert_eq!(third.get_matched_value(), "11"); } else { unreachable!("Test failed!"); }; } #[test] fn it_works3() { let parser = Parser::new(r"{19,}"); let parser_context = ParserContext::new(&parser, "Test"); let matcher = ScriptRepeatRange!(); let result = ParserContext::tokenize(parser_context, matcher); if let Ok(token) = result { let token = token.borrow(); assert_eq!(token.get_name(), "RepeatRange"); assert_eq!(*token.get_captured_range(), SourceRange::new(1, 4)); assert_eq!(*token.get_matched_range(), SourceRange::new(0, 5)); assert_eq!(token.get_value(), r"19,"); assert_eq!(token.get_matched_value(), r"{19,}"); assert_eq!(token.get_children().len(), 2); let first = token.get_children()[0].borrow(); assert_eq!(first.get_name(), "Minimum"); assert_eq!(*first.get_captured_range(), SourceRange::new(1, 3)); assert_eq!(*first.get_matched_range(), SourceRange::new(1, 3)); assert_eq!(first.get_value(), "19"); assert_eq!(first.get_matched_value(), "19"); let second = token.get_children()[1].borrow(); assert_eq!(second.get_name(), "Seperator"); assert_eq!(*second.get_captured_range(), SourceRange::new(3, 4)); assert_eq!(*second.get_matched_range(), SourceRange::new(3, 4)); assert_eq!(second.get_value(), ","); assert_eq!(second.get_matched_value(), ","); } else { unreachable!("Test failed!"); }; } #[test] fn it_fails1() { let parser = Parser::new("Testing"); let parser_context = ParserContext::new(&parser, "Test"); let matcher = ScriptRepeatRange!(); if let Err(MatcherFailure::Fail) = ParserContext::tokenize(parser_context, matcher) { } else { unreachable!("Test failed!"); }; } }
35.5625
89
0.618239
def452a93eca6b4cdeb3f060ab7bb536d1010ee9
930
mod lib; use lib::configuration::Conf; use lib::image::ImageInfo; use lib::image::SVG; use lib::template::process; use lib::constant::conf::CONF_FILE; fn main() { let config = Conf::load(CONF_FILE); let front_img = ImageInfo::by_path(&config.front_path); let back_img = match config.back_path.is_empty() { true => ImageInfo::random(&config.back_folder), _ => ImageInfo::by_folder_path(&config.back_folder, &config.back_path), }; let images: Vec<&ImageInfo> = match (&back_img, &front_img) { (Some(back), Some(front)) => vec![back, front], (Some(back), None) => vec![back], _ => Vec::new(), }; match process(&config, &images) { Ok(res) => { let svg = SVG::from(&res); if let Err(err) = svg.save_png(&config.output_path) { panic!("{}", err); } } Err(err) => panic!("{}", err), } }
29.0625
79
0.56129
5d4ba89de6e901e14606e17c36be8405c24792c0
577
#[cfg(not(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd")))] #[inline(always)] pub fn fract(value: f32) -> f32 { value - super::trunc(value) } #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd"))] #[inline(always)] pub fn fract(value: f32) -> f32 { #[cfg(target_arch = "x86")] use core::arch::x86::*; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::*; unsafe { let packed = _mm_set_ss(value); _mm_cvtss_f32(_mm_sub_ps(packed, _mm_cvtepi32_ps(_mm_cvttps_epi32(packed)))) } }
28.85
84
0.615251
d7cc82a89b8ee7516e3c5a9ab87d583b7a13da0e
62
#[cfg(any(feature = "google-devtools-build-v1"))] pub mod v1;
20.666667
49
0.677419
f9339e390885e511ea87de6bdd4afcebf976a431
24,532
/* * MIT License * * Copyright (c) 2020 Reto Achermann * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * SPDX-License-Identifier: MIT */ /*********************************************************************************************** * *** * * !!!! WARNING: THIS FILE IS AUTO GENERATED. ANY CHANGES MAY BE OVERWRITTEN !!!! * * Generated on: 2020-10-05T16:49:32.070942 * Version: Armv8.7-A-2020-09 * Source: https://developer.arm.com/-/media/developer/products/architecture/armv8-a-architecture/2020-09/SysReg_xml_v87A-2020-09.tar.gz * * !!!! WARNING: THIS FILE IS AUTO GENERATED. ANY CHANGES MAY BE OVERWRITTEN !!!! * ********************************************************************************************** * * */ /* * ================================================================================================ * Register Information * ================================================================================================ * * Register: Secure Configuration Register (scr_el3) * Group: Security registers * Type: 64-bit Register * Description: Defines the configuration of the current Security state. It specifies: * File: AArch64-scr_el3.xml */ /* * ================================================================================================ * Register Read/Write Functions * ================================================================================================ */ /// reading the Secure Configuration Register (scr_el3) register pub fn reg_rawrd() -> u64 { let mut regval: u64; unsafe { // MRS <Xt>, SCR_EL3 llvm_asm!("mrs $0, scr_el3" : "=r"(regval)); } return regval; } /// writing the Secure Configuration Register (scr_el3) register pub fn reg_rawwr(val: u64) { unsafe { // MSR SCR_EL3, <Xt> llvm_asm!("msr scr_el3, $0" : : "r"(val)); } } /* * ================================================================================================ * Register Fields Read/Write Functions * ================================================================================================ */ /// reads field val from register pub fn hxen_1_read() -> u64 { // bits 38..38 let val = reg_rawrd(); (val >> 38) & 0x1 } /// inserts field val into register pub fn hxen_1_write(newval: u64) { // bits 38..38 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 38) | ((newval & 0x1) << 38)); } /// reads field val from register pub fn aden_1_read() -> u64 { // bits 37..37 let val = reg_rawrd(); (val >> 37) & 0x1 } /// inserts field val into register pub fn aden_1_write(newval: u64) { // bits 37..37 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 37) | ((newval & 0x1) << 37)); } /// reads field val from register pub fn enas0_1_read() -> u64 { // bits 36..36 let val = reg_rawrd(); (val >> 36) & 0x1 } /// inserts field val into register pub fn enas0_1_write(newval: u64) { // bits 36..36 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 36) | ((newval & 0x1) << 36)); } /// reads field val from register pub fn amvoffen_1_read() -> u64 { // bits 35..35 let val = reg_rawrd(); (val >> 35) & 0x1 } /// inserts field val into register pub fn amvoffen_1_write(newval: u64) { // bits 35..35 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 35) | ((newval & 0x1) << 35)); } /// reads field val from register pub fn twedel_1_read() -> u64 { // bits 30..33 let val = reg_rawrd(); (val >> 30) & 0xf } /// inserts field val into register pub fn twedel_1_write(newval: u64) { // bits 30..33 let val = reg_rawrd(); reg_rawwr(val & !(0xf << 30) | ((newval & 0xf) << 30)); } /// reads field val from register pub fn tweden_1_read() -> u64 { // bits 29..29 let val = reg_rawrd(); (val >> 29) & 0x1 } /// inserts field val into register pub fn tweden_1_write(newval: u64) { // bits 29..29 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 29) | ((newval & 0x1) << 29)); } /// reads field val from register pub fn ecven_1_read() -> u64 { // bits 28..28 let val = reg_rawrd(); (val >> 28) & 0x1 } /// inserts field val into register pub fn ecven_1_write(newval: u64) { // bits 28..28 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 28) | ((newval & 0x1) << 28)); } /// reads field val from register pub fn fgten_1_read() -> u64 { // bits 27..27 let val = reg_rawrd(); (val >> 27) & 0x1 } /// inserts field val into register pub fn fgten_1_write(newval: u64) { // bits 27..27 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 27) | ((newval & 0x1) << 27)); } /// reads field val from register pub fn ata_1_read() -> u64 { // bits 26..26 let val = reg_rawrd(); (val >> 26) & 0x1 } /// inserts field val into register pub fn ata_1_write(newval: u64) { // bits 26..26 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 26) | ((newval & 0x1) << 26)); } /// reads field val from register pub fn enscxt_1_read() -> u64 { // bits 25..25 let val = reg_rawrd(); (val >> 25) & 0x1 } /// inserts field val into register pub fn enscxt_1_write(newval: u64) { // bits 25..25 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 25) | ((newval & 0x1) << 25)); } /// reads field val from register pub fn fien_1_read() -> u64 { // bits 21..21 let val = reg_rawrd(); (val >> 21) & 0x1 } /// inserts field val into register pub fn fien_1_write(newval: u64) { // bits 21..21 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 21) | ((newval & 0x1) << 21)); } /// reads field val from register pub fn nmea_1_read() -> u64 { // bits 20..20 let val = reg_rawrd(); (val >> 20) & 0x1 } /// inserts field val into register pub fn nmea_1_write(newval: u64) { // bits 20..20 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 20) | ((newval & 0x1) << 20)); } /// reads field val from register pub fn ease_1_read() -> u64 { // bits 19..19 let val = reg_rawrd(); (val >> 19) & 0x1 } /// inserts field val into register pub fn ease_1_write(newval: u64) { // bits 19..19 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 19) | ((newval & 0x1) << 19)); } /// reads field val from register pub fn eel2_1_read() -> u64 { // bits 18..18 let val = reg_rawrd(); (val >> 18) & 0x1 } /// inserts field val into register pub fn eel2_1_write(newval: u64) { // bits 18..18 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 18) | ((newval & 0x1) << 18)); } /// reads field val from register pub fn api_1_read() -> u64 { // bits 17..17 let val = reg_rawrd(); (val >> 17) & 0x1 } /// inserts field val into register pub fn api_1_write(newval: u64) { // bits 17..17 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 17) | ((newval & 0x1) << 17)); } /// reads field val from register pub fn api_2_read() -> u64 { // bits 17..17 let val = reg_rawrd(); (val >> 17) & 0x1 } /// inserts field val into register pub fn api_2_write(newval: u64) { // bits 17..17 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 17) | ((newval & 0x1) << 17)); } /// reads field val from register pub fn apk_1_read() -> u64 { // bits 16..16 let val = reg_rawrd(); (val >> 16) & 0x1 } /// inserts field val into register pub fn apk_1_write(newval: u64) { // bits 16..16 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 16) | ((newval & 0x1) << 16)); } /// reads field val from register pub fn terr_1_read() -> u64 { // bits 15..15 let val = reg_rawrd(); (val >> 15) & 0x1 } /// inserts field val into register pub fn terr_1_write(newval: u64) { // bits 15..15 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 15) | ((newval & 0x1) << 15)); } /// reads field val from register pub fn tlor_1_read() -> u64 { // bits 14..14 let val = reg_rawrd(); (val >> 14) & 0x1 } /// inserts field val into register pub fn tlor_1_write(newval: u64) { // bits 14..14 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 14) | ((newval & 0x1) << 14)); } /// reads field val from register pub fn twe_read() -> u64 { // bits 13..13 let val = reg_rawrd(); (val >> 13) & 0x1 } /// inserts field val into register pub fn twe_write(newval: u64) { // bits 13..13 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 13) | ((newval & 0x1) << 13)); } /// reads field val from register pub fn twi_read() -> u64 { // bits 12..12 let val = reg_rawrd(); (val >> 12) & 0x1 } /// inserts field val into register pub fn twi_write(newval: u64) { // bits 12..12 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 12) | ((newval & 0x1) << 12)); } /// reads field val from register pub fn st_read() -> u64 { // bits 11..11 let val = reg_rawrd(); (val >> 11) & 0x1 } /// inserts field val into register pub fn st_write(newval: u64) { // bits 11..11 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 11) | ((newval & 0x1) << 11)); } /// reads field val from register pub fn rw_1_read() -> u64 { // bits 10..10 let val = reg_rawrd(); (val >> 10) & 0x1 } /// inserts field val into register pub fn rw_1_write(newval: u64) { // bits 10..10 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 10) | ((newval & 0x1) << 10)); } /// reads field val from register pub fn sif_1_read() -> u64 { // bits 9..9 let val = reg_rawrd(); (val >> 9) & 0x1 } /// inserts field val into register pub fn sif_1_write(newval: u64) { // bits 9..9 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 9) | ((newval & 0x1) << 9)); } /// reads field val from register pub fn sif_2_read() -> u64 { // bits 9..9 let val = reg_rawrd(); (val >> 9) & 0x1 } /// inserts field val into register pub fn sif_2_write(newval: u64) { // bits 9..9 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 9) | ((newval & 0x1) << 9)); } /// reads field val from register pub fn hce_read() -> u64 { // bits 8..8 let val = reg_rawrd(); (val >> 8) & 0x1 } /// inserts field val into register pub fn hce_write(newval: u64) { // bits 8..8 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 8) | ((newval & 0x1) << 8)); } /// reads field val from register pub fn smd_read() -> u64 { // bits 7..7 let val = reg_rawrd(); (val >> 7) & 0x1 } /// inserts field val into register pub fn smd_write(newval: u64) { // bits 7..7 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 7) | ((newval & 0x1) << 7)); } /// reads field val from register pub fn ea_read() -> u64 { // bits 3..3 let val = reg_rawrd(); (val >> 3) & 0x1 } /// inserts field val into register pub fn ea_write(newval: u64) { // bits 3..3 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 3) | ((newval & 0x1) << 3)); } /// reads field val from register pub fn fiq_read() -> u64 { // bits 2..2 let val = reg_rawrd(); (val >> 2) & 0x1 } /// inserts field val into register pub fn fiq_write(newval: u64) { // bits 2..2 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 2) | ((newval & 0x1) << 2)); } /// reads field val from register pub fn irq_read() -> u64 { // bits 1..1 let val = reg_rawrd(); (val >> 1) & 0x1 } /// inserts field val into register pub fn irq_write(newval: u64) { // bits 1..1 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 1) | ((newval & 0x1) << 1)); } /// reads field val from register pub fn ns_read() -> u64 { // bits 0..0 let val = reg_rawrd(); (val >> 0) & 0x1 } /// inserts field val into register pub fn ns_write(newval: u64) { // bits 0..0 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 0) | ((newval & 0x1) << 0)); } /* * ================================================================================================ * Data Structure Definitions * ================================================================================================ */ /// struct holding a copy of the Secure Configuration Register value in memory pub struct RegVal { val: u64, } /// struct implementation for accessing the fields of register scr_el3 impl RegVal { // creates a new default value pub fn default() -> RegVal { RegVal { val: 0 } } /// inserts field val into current value pub fn current(&mut self) -> RegVal { let curval = reg_rawrd() & 0x7bfe3fff8f; RegVal { val: curval } } /// extracts field val from current value pub fn read(&mut self) { self.val = reg_rawrd() & 0x7bfe3fff8f } /// inserts field val into current value pub fn write(&self) { reg_rawwr(self.val & 0x7bfe3fff8f) } // sets the value of the struct pub fn set(&mut self, newval: u64) { self.val = newval & 532546584463; } // gets the value of the struct pub fn get(&self) -> u64 { self.val } /// extracts field val from current value pub fn hxen_1_extract(&mut self) -> u64 { // bits 38..38 (self.val >> 38) & 0x1 } /// inserts field val into current value pub fn hxen_1_insert(&mut self, val: u64) { // bits 38..38 self.val = self.val & !(0x1 << 38) | ((val & 0x1) << 38); } /// extracts field val from current value pub fn aden_1_extract(&mut self) -> u64 { // bits 37..37 (self.val >> 37) & 0x1 } /// inserts field val into current value pub fn aden_1_insert(&mut self, val: u64) { // bits 37..37 self.val = self.val & !(0x1 << 37) | ((val & 0x1) << 37); } /// extracts field val from current value pub fn enas0_1_extract(&mut self) -> u64 { // bits 36..36 (self.val >> 36) & 0x1 } /// inserts field val into current value pub fn enas0_1_insert(&mut self, val: u64) { // bits 36..36 self.val = self.val & !(0x1 << 36) | ((val & 0x1) << 36); } /// extracts field val from current value pub fn amvoffen_1_extract(&mut self) -> u64 { // bits 35..35 (self.val >> 35) & 0x1 } /// inserts field val into current value pub fn amvoffen_1_insert(&mut self, val: u64) { // bits 35..35 self.val = self.val & !(0x1 << 35) | ((val & 0x1) << 35); } /// extracts field val from current value pub fn twedel_1_extract(&mut self) -> u64 { // bits 30..33 (self.val >> 30) & 0xf } /// inserts field val into current value pub fn twedel_1_insert(&mut self, val: u64) { // bits 30..33 self.val = self.val & !(0xf << 30) | ((val & 0xf) << 30); } /// extracts field val from current value pub fn tweden_1_extract(&mut self) -> u64 { // bits 29..29 (self.val >> 29) & 0x1 } /// inserts field val into current value pub fn tweden_1_insert(&mut self, val: u64) { // bits 29..29 self.val = self.val & !(0x1 << 29) | ((val & 0x1) << 29); } /// extracts field val from current value pub fn ecven_1_extract(&mut self) -> u64 { // bits 28..28 (self.val >> 28) & 0x1 } /// inserts field val into current value pub fn ecven_1_insert(&mut self, val: u64) { // bits 28..28 self.val = self.val & !(0x1 << 28) | ((val & 0x1) << 28); } /// extracts field val from current value pub fn fgten_1_extract(&mut self) -> u64 { // bits 27..27 (self.val >> 27) & 0x1 } /// inserts field val into current value pub fn fgten_1_insert(&mut self, val: u64) { // bits 27..27 self.val = self.val & !(0x1 << 27) | ((val & 0x1) << 27); } /// extracts field val from current value pub fn ata_1_extract(&mut self) -> u64 { // bits 26..26 (self.val >> 26) & 0x1 } /// inserts field val into current value pub fn ata_1_insert(&mut self, val: u64) { // bits 26..26 self.val = self.val & !(0x1 << 26) | ((val & 0x1) << 26); } /// extracts field val from current value pub fn enscxt_1_extract(&mut self) -> u64 { // bits 25..25 (self.val >> 25) & 0x1 } /// inserts field val into current value pub fn enscxt_1_insert(&mut self, val: u64) { // bits 25..25 self.val = self.val & !(0x1 << 25) | ((val & 0x1) << 25); } /// extracts field val from current value pub fn fien_1_extract(&mut self) -> u64 { // bits 21..21 (self.val >> 21) & 0x1 } /// inserts field val into current value pub fn fien_1_insert(&mut self, val: u64) { // bits 21..21 self.val = self.val & !(0x1 << 21) | ((val & 0x1) << 21); } /// extracts field val from current value pub fn nmea_1_extract(&mut self) -> u64 { // bits 20..20 (self.val >> 20) & 0x1 } /// inserts field val into current value pub fn nmea_1_insert(&mut self, val: u64) { // bits 20..20 self.val = self.val & !(0x1 << 20) | ((val & 0x1) << 20); } /// extracts field val from current value pub fn ease_1_extract(&mut self) -> u64 { // bits 19..19 (self.val >> 19) & 0x1 } /// inserts field val into current value pub fn ease_1_insert(&mut self, val: u64) { // bits 19..19 self.val = self.val & !(0x1 << 19) | ((val & 0x1) << 19); } /// extracts field val from current value pub fn eel2_1_extract(&mut self) -> u64 { // bits 18..18 (self.val >> 18) & 0x1 } /// inserts field val into current value pub fn eel2_1_insert(&mut self, val: u64) { // bits 18..18 self.val = self.val & !(0x1 << 18) | ((val & 0x1) << 18); } /// extracts field val from current value pub fn api_1_extract(&mut self) -> u64 { // bits 17..17 (self.val >> 17) & 0x1 } /// inserts field val into current value pub fn api_1_insert(&mut self, val: u64) { // bits 17..17 self.val = self.val & !(0x1 << 17) | ((val & 0x1) << 17); } /// extracts field val from current value pub fn api_2_extract(&mut self) -> u64 { // bits 17..17 (self.val >> 17) & 0x1 } /// inserts field val into current value pub fn api_2_insert(&mut self, val: u64) { // bits 17..17 self.val = self.val & !(0x1 << 17) | ((val & 0x1) << 17); } /// extracts field val from current value pub fn apk_1_extract(&mut self) -> u64 { // bits 16..16 (self.val >> 16) & 0x1 } /// inserts field val into current value pub fn apk_1_insert(&mut self, val: u64) { // bits 16..16 self.val = self.val & !(0x1 << 16) | ((val & 0x1) << 16); } /// extracts field val from current value pub fn terr_1_extract(&mut self) -> u64 { // bits 15..15 (self.val >> 15) & 0x1 } /// inserts field val into current value pub fn terr_1_insert(&mut self, val: u64) { // bits 15..15 self.val = self.val & !(0x1 << 15) | ((val & 0x1) << 15); } /// extracts field val from current value pub fn tlor_1_extract(&mut self) -> u64 { // bits 14..14 (self.val >> 14) & 0x1 } /// inserts field val into current value pub fn tlor_1_insert(&mut self, val: u64) { // bits 14..14 self.val = self.val & !(0x1 << 14) | ((val & 0x1) << 14); } /// extracts field val from current value pub fn twe_extract(&mut self) -> u64 { // bits 13..13 (self.val >> 13) & 0x1 } /// inserts field val into current value pub fn twe_insert(&mut self, val: u64) { // bits 13..13 self.val = self.val & !(0x1 << 13) | ((val & 0x1) << 13); } /// extracts field val from current value pub fn twi_extract(&mut self) -> u64 { // bits 12..12 (self.val >> 12) & 0x1 } /// inserts field val into current value pub fn twi_insert(&mut self, val: u64) { // bits 12..12 self.val = self.val & !(0x1 << 12) | ((val & 0x1) << 12); } /// extracts field val from current value pub fn st_extract(&mut self) -> u64 { // bits 11..11 (self.val >> 11) & 0x1 } /// inserts field val into current value pub fn st_insert(&mut self, val: u64) { // bits 11..11 self.val = self.val & !(0x1 << 11) | ((val & 0x1) << 11); } /// extracts field val from current value pub fn rw_1_extract(&mut self) -> u64 { // bits 10..10 (self.val >> 10) & 0x1 } /// inserts field val into current value pub fn rw_1_insert(&mut self, val: u64) { // bits 10..10 self.val = self.val & !(0x1 << 10) | ((val & 0x1) << 10); } /// extracts field val from current value pub fn sif_1_extract(&mut self) -> u64 { // bits 9..9 (self.val >> 9) & 0x1 } /// inserts field val into current value pub fn sif_1_insert(&mut self, val: u64) { // bits 9..9 self.val = self.val & !(0x1 << 9) | ((val & 0x1) << 9); } /// extracts field val from current value pub fn sif_2_extract(&mut self) -> u64 { // bits 9..9 (self.val >> 9) & 0x1 } /// inserts field val into current value pub fn sif_2_insert(&mut self, val: u64) { // bits 9..9 self.val = self.val & !(0x1 << 9) | ((val & 0x1) << 9); } /// extracts field val from current value pub fn hce_extract(&mut self) -> u64 { // bits 8..8 (self.val >> 8) & 0x1 } /// inserts field val into current value pub fn hce_insert(&mut self, val: u64) { // bits 8..8 self.val = self.val & !(0x1 << 8) | ((val & 0x1) << 8); } /// extracts field val from current value pub fn smd_extract(&mut self) -> u64 { // bits 7..7 (self.val >> 7) & 0x1 } /// inserts field val into current value pub fn smd_insert(&mut self, val: u64) { // bits 7..7 self.val = self.val & !(0x1 << 7) | ((val & 0x1) << 7); } /// extracts field val from current value pub fn ea_extract(&mut self) -> u64 { // bits 3..3 (self.val >> 3) & 0x1 } /// inserts field val into current value pub fn ea_insert(&mut self, val: u64) { // bits 3..3 self.val = self.val & !(0x1 << 3) | ((val & 0x1) << 3); } /// extracts field val from current value pub fn fiq_extract(&mut self) -> u64 { // bits 2..2 (self.val >> 2) & 0x1 } /// inserts field val into current value pub fn fiq_insert(&mut self, val: u64) { // bits 2..2 self.val = self.val & !(0x1 << 2) | ((val & 0x1) << 2); } /// extracts field val from current value pub fn irq_extract(&mut self) -> u64 { // bits 1..1 (self.val >> 1) & 0x1 } /// inserts field val into current value pub fn irq_insert(&mut self, val: u64) { // bits 1..1 self.val = self.val & !(0x1 << 1) | ((val & 0x1) << 1); } /// extracts field val from current value pub fn ns_extract(&mut self) -> u64 { // bits 0..0 (self.val >> 0) & 0x1 } /// inserts field val into current value pub fn ns_insert(&mut self, val: u64) { // bits 0..0 self.val = self.val & !(0x1 << 0) | ((val & 0x1) << 0); } }
25.741868
136
0.534486
cc5dd80f9dbbceffb82910e829d3672e37bcc4e3
10,038
//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm. #![cfg_attr(not(feature = "std"), no_std)] // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. #![recursion_limit="256"] #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; use parity_codec::{Encode, Decode}; use rstd::prelude::*; #[cfg(feature = "std")] use primitives::bytes; use primitives::{ed25519, sr25519, OpaqueMetadata}; use runtime_primitives::{ ApplyResult, transaction_validity::TransactionValidity, generic, create_runtime_str, traits::{self, NumberFor, BlakeTwo256, Block as BlockT, StaticLookup, Verify} }; use client::{ block_builder::api::{CheckInherentsResult, InherentData, self as block_builder_api}, runtime_api, impl_runtime_apis }; use version::RuntimeVersion; #[cfg(feature = "std")] use version::NativeVersion; // A few exports that help ease life for downstream crates. #[cfg(any(feature = "std", test))] pub use runtime_primitives::BuildStorage; pub use consensus::Call as ConsensusCall; pub use timestamp::Call as TimestampCall; pub use balances::Call as BalancesCall; pub use runtime_primitives::{Permill, Perbill}; pub use timestamp::BlockPeriod; pub use support::{StorageValue, construct_runtime}; /// The type that is used for identifying authorities. pub type AuthorityId = <AuthoritySignature as Verify>::Signer; /// The type used by authorities to prove their ID. pub type AuthoritySignature = ed25519::Signature; /// Alias to pubkey that identifies an account on the chain. pub type AccountId = <AccountSignature as Verify>::Signer; /// The type used by authorities to prove their ID. pub type AccountSignature = sr25519::Signature; /// A hash of some data used by the chain. pub type Hash = primitives::H256; /// Index of a block number in the chain. pub type BlockNumber = u64; /// Index of an account's extrinsic in the chain. pub type Nonce = u64; /// Used for the module template in `./template.rs` mod template; mod substratekitties; /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know /// the specifics of the runtime. They can then be made to be agnostic over specific formats /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core datastructures. pub mod opaque { use super::*; /// Opaque, encoded, unchecked extrinsic. #[derive(PartialEq, Eq, Clone, Default, Encode, Decode)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct UncheckedExtrinsic(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>); #[cfg(feature = "std")] impl std::fmt::Debug for UncheckedExtrinsic { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { write!(fmt, "{}", primitives::hexdisplay::HexDisplay::from(&self.0)) } } impl traits::Extrinsic for UncheckedExtrinsic { fn is_signed(&self) -> Option<bool> { None } } /// Opaque block header type. pub type Header = generic::Header<BlockNumber, BlakeTwo256, generic::DigestItem<Hash, AuthorityId, AuthoritySignature>>; /// Opaque block type. pub type Block = generic::Block<Header, UncheckedExtrinsic>; /// Opaque block identifier type. pub type BlockId = generic::BlockId<Block>; /// Opaque session key type. pub type SessionKey = AuthorityId; } /// This runtime version. pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("substratekitties"), impl_name: create_runtime_str!("substratekitties"), authoring_version: 3, spec_version: 4, impl_version: 4, apis: RUNTIME_API_VERSIONS, }; /// The version infromation used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } } impl system::Trait for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = Indices; /// The index type for storing how many extrinsics an account has signed. type Index = Nonce; /// The index type for blocks. type BlockNumber = BlockNumber; /// The type for hashing blocks and tries. type Hash = Hash; /// The hashing algorithm used. type Hashing = BlakeTwo256; /// The header digest type. type Digest = generic::Digest<Log>; /// The header type. type Header = generic::Header<BlockNumber, BlakeTwo256, Log>; /// The ubiquitous event type. type Event = Event; /// The ubiquitous log type. type Log = Log; /// The ubiquitous origin type. type Origin = Origin; } impl aura::Trait for Runtime { type HandleReport = (); } impl consensus::Trait for Runtime { /// The identifier we use to refer to authorities. type SessionKey = AuthorityId; // The aura module handles offline-reports internally // rather than using an explicit report system. type InherentOfflineReport = (); /// The ubiquitous log type. type Log = Log; } impl indices::Trait for Runtime { /// The type for recording indexing into the account enumeration. If this ever overflows, there /// will be problems! type AccountIndex = u32; /// Use the standard means of resolving an index hint from an id. type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>; /// Determine whether an account is dead. type IsDeadAccount = Balances; /// The uniquitous event type. type Event = Event; } impl timestamp::Trait for Runtime { /// A timestamp: seconds since the unix epoch. type Moment = u64; type OnTimestampSet = Aura; } impl balances::Trait for Runtime { /// The type for recording an account's balance. type Balance = u128; /// What to do if an account's free balance gets zeroed. type OnFreeBalanceZero = (); /// What to do if a new account is created. type OnNewAccount = Indices; /// The uniquitous event type. type Event = Event; type TransactionPayment = (); type DustRemoval = (); type TransferPayment = (); } impl sudo::Trait for Runtime { /// The uniquitous event type. type Event = Event; type Proposal = Call; } impl substratekitties::Trait for Runtime{ type Event = Event; } /// Used for the module template in `./template.rs` impl template::Trait for Runtime { type Event = Event; } /// Used for the module template in `./template.rs` impl substrate_module_template::Trait for Runtime { type Event = Event; } construct_runtime!( pub enum Runtime with Log(InternalLog: DigestItem<Hash, AuthorityId, AuthoritySignature>) where Block = Block, NodeBlock = opaque::Block, UncheckedExtrinsic = UncheckedExtrinsic { System: system::{default, Log(ChangesTrieRoot)}, Timestamp: timestamp::{Module, Call, Storage, Config<T>, Inherent}, Consensus: consensus::{Module, Call, Storage, Config<T>, Log(AuthoritiesChange), Inherent}, Aura: aura::{Module}, Indices: indices, Balances: balances, Sudo: sudo, // Used for the module template in `./template.rs` TemplateModule: template::{Module, Call, Storage, Event<T>}, ExampleModule: substrate_module_template::{Module, Call, Storage, Event<T>}, Substratekitties:substratekitties::{Module, Call, Storage, Event<T>}, } ); /// The type used as a helper for interpreting the sender of transactions. type Context = system::ChainContext<Runtime>; /// The address format for describing accounts. type Address = <Indices as StaticLookup>::Source; /// Block header type as expected by this runtime. pub type Header = generic::Header<BlockNumber, BlakeTwo256, Log>; /// Block type as expected by this runtime. pub type Block = generic::Block<Header, UncheckedExtrinsic>; /// BlockId type as expected by this runtime. pub type BlockId = generic::BlockId<Block>; /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedMortalCompactExtrinsic<Address, Nonce, Call, AccountSignature>; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Nonce, Call>; /// Executive: handles dispatch to the various modules. pub type Executive = executive::Executive<Runtime, Block, Context, Balances, AllModules>; // Implement our runtime API endpoints. This is just a bunch of proxying. impl_runtime_apis! { impl runtime_api::Core<Block> for Runtime { fn version() -> RuntimeVersion { VERSION } fn execute_block(block: Block) { Executive::execute_block(block) } fn initialize_block(header: &<Block as BlockT>::Header) { Executive::initialize_block(header) } fn authorities() -> Vec<AuthorityId> { panic!("Deprecated, please use `AuthoritiesApi`.") } } impl runtime_api::Metadata<Block> for Runtime { fn metadata() -> OpaqueMetadata { Runtime::metadata().into() } } impl block_builder_api::BlockBuilder<Block> for Runtime { fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult { Executive::apply_extrinsic(extrinsic) } fn finalize_block() -> <Block as BlockT>::Header { Executive::finalize_block() } fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> { data.create_extrinsics() } fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult { data.check_extrinsics(&block) } fn random_seed() -> <Block as BlockT>::Hash { System::random_seed() } } impl runtime_api::TaggedTransactionQueue<Block> for Runtime { fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity { Executive::validate_transaction(tx) } } impl consensus_aura::AuraApi<Block> for Runtime { fn slot_duration() -> u64 { Aura::slot_duration() } } impl offchain_primitives::OffchainWorkerApi<Block> for Runtime { fn offchain_worker(n: NumberFor<Block>) { Executive::offchain_worker(n) } } impl consensus_authorities::AuthoritiesApi<Block> for Runtime { fn authorities() -> Vec<AuthorityId> { Consensus::authorities() } } }
31.866667
121
0.731221
3994949e5668f59f2c1339181fcfefc37ef5d803
20,973
use std::collections::HashMap; use std::os::unix::io::RawFd; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{channel, Sender}; use std::sync::{Arc, Mutex, RwLock}; use super::super::super::legacy::Gic; use super::super::Queue as VirtQueue; use super::super::VIRTIO_MMIO_INT_VRING; use super::defs; use super::defs::uapi; use super::muxer_rxq::{rx_to_pkt, MuxerRxQ}; use super::muxer_thread::MuxerThread; use super::packet::{TsiGetnameRsp, VsockPacket}; use super::proxy::{Proxy, ProxyRemoval, ProxyUpdate}; use super::reaper::ReaperThread; use super::tcp::TcpProxy; use super::udp::UdpProxy; use super::VsockError; use utils::epoll::{ControlOperation, Epoll, EpollEvent, EventSet}; use utils::eventfd::EventFd; use vm_memory::GuestMemoryMmap; pub type ProxyMap = Arc<RwLock<HashMap<u64, Mutex<Box<dyn Proxy>>>>>; /// A muxer RX queue item. #[derive(Debug)] pub enum MuxerRx { Reset { local_port: u32, peer_port: u32, }, GetnameResponse { local_port: u32, peer_port: u32, data: TsiGetnameRsp, }, ConnResponse { local_port: u32, peer_port: u32, result: i32, }, OpRequest { local_port: u32, peer_port: u32, }, OpResponse { local_port: u32, peer_port: u32, }, CreditRequest { local_port: u32, peer_port: u32, fwd_cnt: u32, }, CreditUpdate { local_port: u32, peer_port: u32, fwd_cnt: u32, }, ListenResponse { local_port: u32, peer_port: u32, result: i32, }, AcceptResponse { local_port: u32, peer_port: u32, result: i32, }, } pub fn push_packet( cid: u64, rx: MuxerRx, rxq_mutex: &Arc<Mutex<MuxerRxQ>>, queue_mutex: &Arc<Mutex<VirtQueue>>, mem: &GuestMemoryMmap, ) { let mut queue = queue_mutex.lock().unwrap(); if let Some(head) = queue.pop(mem) { if let Ok(mut pkt) = VsockPacket::from_rx_virtq_head(&head) { rx_to_pkt(cid, rx, &mut pkt); queue.add_used(mem, head.index, pkt.hdr().len() as u32 + pkt.len()); } } else { error!("couldn't push pkt to queue, adding it to rxq"); drop(queue); rxq_mutex.lock().unwrap().push(rx); } } pub struct VsockMuxer { cid: u64, host_port_map: Option<HashMap<u16, u16>>, queue_stream: Option<Arc<Mutex<VirtQueue>>>, queue_dgram: Option<Arc<Mutex<VirtQueue>>>, mem: Option<GuestMemoryMmap>, rxq_stream: Arc<Mutex<MuxerRxQ>>, rxq_dgram: Arc<Mutex<MuxerRxQ>>, epoll: Epoll, interrupt_evt: EventFd, interrupt_status: Arc<AtomicUsize>, intc: Option<Arc<Mutex<Gic>>>, irq_line: Option<u32>, proxy_map: ProxyMap, reaper_sender: Option<Sender<u64>>, } impl VsockMuxer { pub(crate) fn new( cid: u64, host_port_map: Option<HashMap<u16, u16>>, interrupt_evt: EventFd, interrupt_status: Arc<AtomicUsize>, ) -> Self { VsockMuxer { cid, host_port_map, queue_stream: None, queue_dgram: None, mem: None, rxq_stream: Arc::new(Mutex::new(MuxerRxQ::new())), rxq_dgram: Arc::new(Mutex::new(MuxerRxQ::new())), epoll: Epoll::new().unwrap(), interrupt_evt, interrupt_status, intc: None, irq_line: None, proxy_map: Arc::new(RwLock::new(HashMap::new())), reaper_sender: None, } } pub(crate) fn activate( &mut self, mem: GuestMemoryMmap, queue_stream: Arc<Mutex<VirtQueue>>, queue_dgram: Arc<Mutex<VirtQueue>>, intc: Option<Arc<Mutex<Gic>>>, irq_line: Option<u32>, ) { self.queue_stream = Some(queue_stream.clone()); self.queue_dgram = Some(queue_dgram.clone()); self.mem = Some(mem.clone()); self.intc = intc.clone(); self.irq_line = irq_line; let (sender, receiver) = channel(); let thread = MuxerThread::new( self.cid, self.epoll.clone(), self.rxq_stream.clone(), self.rxq_dgram.clone(), self.proxy_map.clone(), mem, queue_stream, queue_dgram, self.interrupt_evt.try_clone().unwrap(), self.interrupt_status.clone(), intc, irq_line, sender.clone(), ); thread.run(); self.reaper_sender = Some(sender); let reaper = ReaperThread::new(receiver, self.proxy_map.clone()); reaper.run(); } pub(crate) fn has_pending_stream_rx(&self) -> bool { !self.rxq_stream.lock().unwrap().is_empty() } pub(crate) fn has_pending_dgram_rx(&self) -> bool { !self.rxq_dgram.lock().unwrap().is_empty() } pub(crate) fn recv_stream_pkt(&mut self, pkt: &mut VsockPacket) -> super::Result<()> { debug!("vsock: recv_stream_pkt"); if self.rxq_stream.lock().unwrap().is_empty() { return Err(VsockError::NoData); } if let Some(rx) = self.rxq_stream.lock().unwrap().pop() { rx_to_pkt(self.cid, rx, pkt); } Ok(()) } pub(crate) fn recv_dgram_pkt(&mut self, pkt: &mut VsockPacket) -> super::Result<()> { debug!("vsock: recv_dgram_pkt"); if self.rxq_dgram.lock().unwrap().is_empty() { return Err(VsockError::NoData); } if let Some(rx) = self.rxq_dgram.lock().unwrap().pop() { rx_to_pkt(self.cid, rx, pkt); } Ok(()) } pub fn update_polling(&self, id: u64, fd: RawFd, evset: EventSet) { debug!("update_polling id={} fd={:?} evset={:?}", id, fd, evset); let _ = self .epoll .ctl(ControlOperation::Delete, fd, &EpollEvent::default()); if !evset.is_empty() { let _ = self.epoll.ctl( ControlOperation::Add, fd, &EpollEvent::new(evset, id as u64), ); } } fn process_proxy_update(&self, id: u64, update: ProxyUpdate) { if let Some(polling) = update.polling { self.update_polling(polling.0, polling.1, polling.2); } match update.remove_proxy { ProxyRemoval::Keep => {} ProxyRemoval::Immediate => { warn!("immediately removing proxy: {}", id); self.proxy_map.write().unwrap().remove(&id); } ProxyRemoval::Deferred => { warn!("deferring proxy removal: {}", id); if let Some(reaper_sender) = &self.reaper_sender { if reaper_sender.send(id).is_err() { self.proxy_map.write().unwrap().remove(&id); } } } } if update.signal_queue { self.interrupt_status .fetch_or(VIRTIO_MMIO_INT_VRING as usize, Ordering::SeqCst); if let Err(e) = self.interrupt_evt.write(1) { warn!("failed to signal used queue: {:?}", e); } } } fn process_proxy_create(&self, pkt: &VsockPacket) { debug!("vsock: proxy create request"); if let Some(req) = pkt.read_proxy_create() { debug!( "vsock: proxy create request: peer_port={}, type={}", req.peer_port, req._type ); let mem = match self.mem.as_ref() { Some(m) => m, None => { error!("proxy creation without mem"); return; } }; let queue_stream = match self.queue_stream.as_ref() { Some(q) => q, None => { error!("stream proxy creation without stream queue"); return; } }; let queue_dgram = match self.queue_dgram.as_ref() { Some(q) => q, None => { error!("dgram proxy creation without dgram queue"); return; } }; match req._type { defs::SOCK_STREAM => { debug!("vsock: proxy create stream"); let id = (req.peer_port as u64) << 32 | defs::TSI_PROXY_PORT as u64; match TcpProxy::new( id, self.cid, defs::TSI_PROXY_PORT, req.peer_port, pkt.src_port(), mem.clone(), queue_stream.clone(), queue_dgram.clone(), self.rxq_stream.clone(), self.rxq_dgram.clone(), ) { Ok(proxy) => { self.proxy_map .write() .unwrap() .insert(id, Mutex::new(Box::new(proxy))); } Err(e) => debug!("error creating tcp proxy: {}", e), } } defs::SOCK_DGRAM => { debug!("vsock: proxy create dgram"); let id = (req.peer_port as u64) << 32 | defs::TSI_PROXY_PORT as u64; match UdpProxy::new( id, self.cid, req.peer_port, mem.clone(), queue_dgram.clone(), self.rxq_dgram.clone(), ) { Ok(proxy) => { self.proxy_map .write() .unwrap() .insert(id, Mutex::new(Box::new(proxy))); } Err(e) => debug!("error creating udp proxy: {}", e), } } _ => debug!("vsock: unknown type on connection request"), }; } } fn process_connect(&self, pkt: &VsockPacket) { debug!("vsock: proxy connect request"); if let Some(req) = pkt.read_connect_req() { let id = (req.peer_port as u64) << 32 | defs::TSI_PROXY_PORT as u64; debug!("vsock: proxy connect request: id={}", id); let update = self .proxy_map .read() .unwrap() .get(&id) .map(|proxy| proxy.lock().unwrap().connect(pkt, req)); if let Some(update) = update { self.process_proxy_update(id, update); } } } fn process_getname(&self, pkt: &VsockPacket) { debug!("vsock: new getname request"); if let Some(req) = pkt.read_getname_req() { let id = (req.peer_port as u64) << 32 | (req.local_port as u64); debug!( "vsock: new getname request: id={}, peer_port={}, local_port={}", id, req.peer_port, req.local_port ); if let Some(proxy) = self.proxy_map.read().unwrap().get(&id) { proxy.lock().unwrap().getpeername(pkt); } } } fn process_sendto_addr(&self, pkt: &VsockPacket) { debug!("vsock: new DGRAM sendto addr: src={}", pkt.src_port()); if let Some(req) = pkt.read_sendto_addr() { let id = (req.peer_port as u64) << 32 | defs::TSI_PROXY_PORT as u64; debug!("vsock: new DGRAM sendto addr: id={}", id); let update = self .proxy_map .read() .unwrap() .get(&id) .map(|proxy| proxy.lock().unwrap().sendto_addr(req)); if let Some(update) = update { self.process_proxy_update(id, update); } } } fn process_sendto_data(&self, pkt: &VsockPacket) { let id = (pkt.src_port() as u64) << 32 | defs::TSI_PROXY_PORT as u64; debug!("vsock: DGRAM sendto data: id={} src={}", id, pkt.src_port()); if let Some(proxy) = self.proxy_map.read().unwrap().get(&id) { proxy.lock().unwrap().sendto_data(pkt); } } fn process_listen_request(&self, pkt: &VsockPacket) { debug!("vsock: DGRAM listen request: src={}", pkt.src_port()); if let Some(req) = pkt.read_listen_req() { let id = (req.peer_port as u64) << 32 | defs::TSI_PROXY_PORT as u64; debug!("vsock: DGRAM listen request: id={}", id); let update = self .proxy_map .read() .unwrap() .get(&id) .map(|proxy| proxy.lock().unwrap().listen(pkt, req, &self.host_port_map)); if let Some(update) = update { self.process_proxy_update(id, update); } } } fn process_accept_request(&self, pkt: &VsockPacket) { debug!("vsock: DGRAM accept request: src={}", pkt.src_port()); if let Some(req) = pkt.read_accept_req() { let id = (req.peer_port as u64) << 32 | defs::TSI_PROXY_PORT as u64; debug!("vsock: DGRAM accept request: id={}", id); let update = self .proxy_map .read() .unwrap() .get(&id) .map(|proxy| proxy.lock().unwrap().accept(req)); if let Some(update) = update { self.process_proxy_update(id, update); } } } fn process_proxy_release(&self, pkt: &VsockPacket) { debug!("vsock: DGRAM release request: src={}", pkt.src_port()); if let Some(req) = pkt.read_release_req() { let id = (req.peer_port as u64) << 32 | req.local_port as u64; debug!( "vsock: DGRAM release request: id={} local_port={} peer_port={}", id, req.local_port, req.peer_port ); let update = if let Some(proxy) = self.proxy_map.read().unwrap().get(&id) { Some(proxy.lock().unwrap().release()) } else { debug!( "release without proxy: id={}, proxies={}", id, self.proxy_map.read().unwrap().len() ); None }; if let Some(update) = update { self.process_proxy_update(id, update); } } debug!( "vsock: DGRAM release request: proxies={}", self.proxy_map.read().unwrap().len() ); } fn process_dgram_rw(&self, pkt: &VsockPacket) { debug!("vsock: DGRAM OP_RW"); let id = (pkt.src_port() as u64) << 32 | defs::TSI_PROXY_PORT as u64; if let Some(proxy_lock) = self.proxy_map.read().unwrap().get(&id) { debug!("vsock: DGRAM allowing OP_RW for {}", pkt.src_port()); let mut proxy = proxy_lock.lock().unwrap(); let update = proxy.sendmsg(pkt); self.process_proxy_update(id, update); } else { debug!("vsock: DGRAM ignoring OP_RW for {}", pkt.src_port()); } } pub(crate) fn send_dgram_pkt(&mut self, pkt: &VsockPacket) -> super::Result<()> { debug!( "vsock: send_dgram_pkt: src_port={} dst_port={}", pkt.src_port(), pkt.dst_port() ); if pkt.dst_cid() != uapi::VSOCK_HOST_CID { debug!( "vsock: dropping guest packet for unknown CID: {:?}", pkt.hdr() ); return Ok(()); } match pkt.dst_port() { defs::TSI_PROXY_CREATE => self.process_proxy_create(pkt), defs::TSI_CONNECT => self.process_connect(pkt), defs::TSI_GETNAME => self.process_getname(pkt), defs::TSI_SENDTO_ADDR => self.process_sendto_addr(pkt), defs::TSI_SENDTO_DATA => self.process_sendto_data(pkt), defs::TSI_LISTEN => self.process_listen_request(pkt), defs::TSI_ACCEPT => self.process_accept_request(pkt), defs::TSI_PROXY_RELEASE => self.process_proxy_release(pkt), _ => { if pkt.op() == uapi::VSOCK_OP_RW { self.process_dgram_rw(pkt); } else { error!("unexpected dgram pkt: {}", pkt.op()); } } } Ok(()) } fn process_op_request(&self, pkt: &VsockPacket) { debug!("vsock: OP_REQUEST"); let id: u64 = (pkt.src_port() as u64) << 32 | pkt.dst_port() as u64; if let Some(proxy) = self.proxy_map.read().unwrap().get(&id) { proxy.lock().unwrap().confirm_connect(pkt) } } fn process_op_response(&self, pkt: &VsockPacket) { debug!("vsock: OP_RESPONSE"); let id: u64 = (pkt.src_port() as u64) << 32 | pkt.dst_port() as u64; let update = self .proxy_map .read() .unwrap() .get(&id) .map(|proxy| proxy.lock().unwrap().process_op_response(pkt)); update .as_ref() .and_then(|u| u.push_accept) .and_then(|(_id, parent_id)| { self.proxy_map .read() .unwrap() .get(&parent_id) .map(|proxy| proxy.lock().unwrap().enqueue_accept()) }); if let Some(update) = update { self.process_proxy_update(id, update); } } fn process_op_shutdown(&self, pkt: &VsockPacket) { debug!("vsock: OP_SHUTDOWN"); let id: u64 = (pkt.src_port() as u64) << 32 | pkt.dst_port() as u64; if let Some(proxy) = self.proxy_map.read().unwrap().get(&id) { proxy.lock().unwrap().shutdown(pkt); } } fn process_op_credit_update(&self, pkt: &VsockPacket) { debug!("vsock: OP_CREDIT_UPDATE"); let id: u64 = (pkt.src_port() as u64) << 32 | pkt.dst_port() as u64; let update = self .proxy_map .read() .unwrap() .get(&id) .map(|proxy| proxy.lock().unwrap().update_peer_credit(pkt)); if let Some(update) = update { self.process_proxy_update(id, update); } } fn process_stream_rw(&self, pkt: &VsockPacket) { debug!("vsock: OP_RW"); let id: u64 = (pkt.src_port() as u64) << 32 | pkt.dst_port() as u64; if let Some(proxy_lock) = self.proxy_map.read().unwrap().get(&id) { debug!( "vsock: allowing OP_RW: src={} dst={}", pkt.src_port(), pkt.dst_port() ); let mut proxy = proxy_lock.lock().unwrap(); let update = proxy.sendmsg(pkt); self.process_proxy_update(id, update); } else { debug!("vsock: invalid OP_RW for {}, sending reset", pkt.src_port()); let mem = match self.mem.as_ref() { Some(m) => m, None => { warn!("OP_RW without mem"); return; } }; let queue = match self.queue_stream.as_ref() { Some(q) => q, None => { warn!("OP_RW without queue"); return; } }; // This response goes to the connection. let rx = MuxerRx::Reset { local_port: pkt.dst_port(), peer_port: pkt.src_port(), }; push_packet(self.cid, rx, &self.rxq_stream, queue, mem); } } pub(crate) fn send_stream_pkt(&mut self, pkt: &VsockPacket) -> super::Result<()> { debug!( "vsock: send_pkt: src_port={} dst_port={}, op={}", pkt.src_port(), pkt.dst_port(), pkt.op() ); if pkt.dst_cid() != uapi::VSOCK_HOST_CID { debug!( "vsock: dropping guest packet for unknown CID: {:?}", pkt.hdr() ); return Ok(()); } match pkt.op() { uapi::VSOCK_OP_REQUEST => self.process_op_request(pkt), uapi::VSOCK_OP_RESPONSE => self.process_op_response(pkt), uapi::VSOCK_OP_SHUTDOWN => self.process_op_shutdown(pkt), uapi::VSOCK_OP_CREDIT_UPDATE => self.process_op_credit_update(pkt), uapi::VSOCK_OP_RW => self.process_stream_rw(pkt), _ => warn!("stream: unhandled op={}", pkt.op()), } Ok(()) } }
33.664526
90
0.491441
16e0a334440ff0f3570e2bde57c64eb69aebbe4b
47,696
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub use self::Constructor::*; use self::Usefulness::*; use self::WitnessPreference::*; use dep_graph::DepNode; use middle::const_eval::{compare_const_vals, ConstVal}; use middle::const_eval::{eval_const_expr, eval_const_expr_partial}; use middle::const_eval::{const_expr_to_pat, lookup_const_by_id}; use middle::const_eval::EvalHint::ExprTypeChecked; use middle::def::*; use middle::def_id::{DefId}; use middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor}; use middle::expr_use_visitor::{LoanCause, MutateMode}; use middle::expr_use_visitor as euv; use middle::infer; use middle::mem_categorization::{cmt}; use middle::pat_util::*; use middle::traits::ProjectionMode; use middle::ty::*; use middle::ty; use std::cmp::Ordering; use std::fmt; use std::iter::{FromIterator, IntoIterator, repeat}; use rustc_front::hir; use rustc_front::hir::{Pat, PatKind}; use rustc_front::intravisit::{self, Visitor, FnKind}; use rustc_front::util as front_util; use rustc_back::slice; use syntax::ast::{self, DUMMY_NODE_ID, NodeId}; use syntax::ast_util; use syntax::codemap::{Span, Spanned, DUMMY_SP}; use rustc_front::fold::{Folder, noop_fold_pat}; use rustc_front::print::pprust::pat_to_string; use syntax::ptr::P; use util::nodemap::FnvHashMap; pub const DUMMY_WILD_PAT: &'static Pat = &Pat { id: DUMMY_NODE_ID, node: PatKind::Wild, span: DUMMY_SP }; struct Matrix<'a>(Vec<Vec<&'a Pat>>); /// Pretty-printer for matrices of patterns, example: /// ++++++++++++++++++++++++++ /// + _ + [] + /// ++++++++++++++++++++++++++ /// + true + [First] + /// ++++++++++++++++++++++++++ /// + true + [Second(true)] + /// ++++++++++++++++++++++++++ /// + false + [_] + /// ++++++++++++++++++++++++++ /// + _ + [_, _, ..tail] + /// ++++++++++++++++++++++++++ impl<'a> fmt::Debug for Matrix<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "\n")); let &Matrix(ref m) = self; let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| { row.iter() .map(|&pat| pat_to_string(&pat)) .collect::<Vec<String>>() }).collect(); let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0); assert!(m.iter().all(|row| row.len() == column_count)); let column_widths: Vec<usize> = (0..column_count).map(|col| { pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0) }).collect(); let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1; let br = repeat('+').take(total_width).collect::<String>(); try!(write!(f, "{}\n", br)); for row in pretty_printed_matrix { try!(write!(f, "+")); for (column, pat_str) in row.into_iter().enumerate() { try!(write!(f, " ")); try!(write!(f, "{:1$}", pat_str, column_widths[column])); try!(write!(f, " +")); } try!(write!(f, "\n")); try!(write!(f, "{}\n", br)); } Ok(()) } } impl<'a> FromIterator<Vec<&'a Pat>> for Matrix<'a> { fn from_iter<T: IntoIterator<Item=Vec<&'a Pat>>>(iter: T) -> Matrix<'a> { Matrix(iter.into_iter().collect()) } } //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv pub struct MatchCheckCtxt<'a, 'tcx: 'a> { pub tcx: &'a TyCtxt<'tcx>, pub param_env: ParameterEnvironment<'a, 'tcx>, } #[derive(Clone, PartialEq)] pub enum Constructor { /// The constructor of all patterns that don't vary by constructor, /// e.g. struct patterns and fixed-length arrays. Single, /// Enum variants. Variant(DefId), /// Literal values. ConstantValue(ConstVal), /// Ranges of literal values (2..5). ConstantRange(ConstVal, ConstVal), /// Array patterns of length n. Slice(usize), /// Array patterns with a subslice. SliceWithSubslice(usize, usize) } #[derive(Clone, PartialEq)] enum Usefulness { Useful, UsefulWithWitness(Vec<P<Pat>>), NotUseful } #[derive(Copy, Clone)] enum WitnessPreference { ConstructWitness, LeaveOutWitness } impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> { fn visit_expr(&mut self, ex: &hir::Expr) { check_expr(self, ex); } fn visit_local(&mut self, l: &hir::Local) { check_local(self, l); } fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl, b: &'v hir::Block, s: Span, n: NodeId) { check_fn(self, fk, fd, b, s, n); } } pub fn check_crate(tcx: &TyCtxt) { tcx.visit_all_items_in_krate(DepNode::MatchCheck, &mut MatchCheckCtxt { tcx: tcx, param_env: tcx.empty_parameter_environment(), }); tcx.sess.abort_if_errors(); } fn check_expr(cx: &mut MatchCheckCtxt, ex: &hir::Expr) { intravisit::walk_expr(cx, ex); match ex.node { hir::ExprMatch(ref scrut, ref arms, source) => { for arm in arms { // First, check legality of move bindings. check_legality_of_move_bindings(cx, arm.guard.is_some(), &arm.pats); // Second, if there is a guard on each arm, make sure it isn't // assigning or borrowing anything mutably. match arm.guard { Some(ref guard) => check_for_mutation_in_guard(cx, &guard), None => {} } } let mut static_inliner = StaticInliner::new(cx.tcx, None); let inlined_arms = arms.iter().map(|arm| { (arm.pats.iter().map(|pat| { static_inliner.fold_pat((*pat).clone()) }).collect(), arm.guard.as_ref().map(|e| &**e)) }).collect::<Vec<(Vec<P<Pat>>, Option<&hir::Expr>)>>(); // Bail out early if inlining failed. if static_inliner.failed { return; } for pat in inlined_arms .iter() .flat_map(|&(ref pats, _)| pats) { // Third, check legality of move bindings. check_legality_of_bindings_in_at_patterns(cx, &pat); // Fourth, check if there are any references to NaN that we should warn about. check_for_static_nan(cx, &pat); // Fifth, check if for any of the patterns that match an enumerated type // are bindings with the same name as one of the variants of said type. check_for_bindings_named_the_same_as_variants(cx, &pat); } // Fourth, check for unreachable arms. check_arms(cx, &inlined_arms[..], source); // Finally, check if the whole match expression is exhaustive. // Check for empty enum, because is_useful only works on inhabited types. let pat_ty = cx.tcx.node_id_to_type(scrut.id); if inlined_arms.is_empty() { if !pat_ty.is_empty(cx.tcx) { // We know the type is inhabited, so this must be wrong let mut err = struct_span_err!(cx.tcx.sess, ex.span, E0002, "non-exhaustive patterns: type {} is non-empty", pat_ty); span_help!(&mut err, ex.span, "Please ensure that all possible cases are being handled; \ possibly adding wildcards or more match arms."); err.emit(); } // If the type *is* empty, it's vacuously exhaustive return; } let matrix: Matrix = inlined_arms .iter() .filter(|&&(_, guard)| guard.is_none()) .flat_map(|arm| &arm.0) .map(|pat| vec![&**pat]) .collect(); check_exhaustive(cx, ex.span, &matrix, source); }, _ => () } } fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) { front_util::walk_pat(pat, |p| { match p.node { PatKind::Ident(hir::BindByValue(hir::MutImmutable), ident, None) => { let pat_ty = cx.tcx.pat_ty(p); if let ty::TyEnum(edef, _) = pat_ty.sty { let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def()); if let Some(Def::Local(..)) = def { if edef.variants.iter().any(|variant| variant.name == ident.node.unhygienic_name && variant.kind() == VariantKind::Unit ) { let ty_path = cx.tcx.item_path_str(edef.did); let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170, "pattern binding `{}` is named the same as one \ of the variants of the type `{}`", ident.node, ty_path); fileline_help!(err, p.span, "if you meant to match on a variant, \ consider making the path in the pattern qualified: `{}::{}`", ty_path, ident.node); err.emit(); } } } } _ => () } true }); } // Check that we do not match against a static NaN (#6804) fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) { front_util::walk_pat(pat, |p| { if let PatKind::Lit(ref expr) = p.node { match eval_const_expr_partial(cx.tcx, &expr, ExprTypeChecked, None) { Ok(ConstVal::Float(f)) if f.is_nan() => { span_warn!(cx.tcx.sess, p.span, E0003, "unmatchable NaN in pattern, \ use the is_nan method in a guard instead"); } Ok(_) => {} Err(err) => { let mut diag = struct_span_err!(cx.tcx.sess, err.span, E0471, "constant evaluation error: {}", err.description()); if !p.span.contains(err.span) { diag.span_note(p.span, "in pattern here"); } diag.emit(); } } } true }); } // Check for unreachable patterns fn check_arms(cx: &MatchCheckCtxt, arms: &[(Vec<P<Pat>>, Option<&hir::Expr>)], source: hir::MatchSource) { let mut seen = Matrix(vec![]); let mut printed_if_let_err = false; for &(ref pats, guard) in arms { for pat in pats { let v = vec![&**pat]; match is_useful(cx, &seen, &v[..], LeaveOutWitness) { NotUseful => { match source { hir::MatchSource::IfLetDesugar { .. } => { if printed_if_let_err { // we already printed an irrefutable if-let pattern error. // We don't want two, that's just confusing. } else { // find the first arm pattern so we can use its span let &(ref first_arm_pats, _) = &arms[0]; let first_pat = &first_arm_pats[0]; let span = first_pat.span; span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern"); printed_if_let_err = true; } }, hir::MatchSource::WhileLetDesugar => { // find the first arm pattern so we can use its span let &(ref first_arm_pats, _) = &arms[0]; let first_pat = &first_arm_pats[0]; let span = first_pat.span; span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern"); }, hir::MatchSource::ForLoopDesugar => { // this is a bug, because on `match iter.next()` we cover // `Some(<head>)` and `None`. It's impossible to have an unreachable // pattern // (see libsyntax/ext/expand.rs for the full expansion of a for loop) cx.tcx.sess.span_bug(pat.span, "unreachable for-loop pattern") }, hir::MatchSource::Normal => { span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern") }, hir::MatchSource::TryDesugar => { cx.tcx.sess.span_bug(pat.span, "unreachable try pattern") }, } } Useful => (), UsefulWithWitness(_) => unreachable!() } if guard.is_none() { let Matrix(mut rows) = seen; rows.push(v); seen = Matrix(rows); } } } } fn raw_pat<'a>(p: &'a Pat) -> &'a Pat { match p.node { PatKind::Ident(_, _, Some(ref s)) => raw_pat(&s), _ => p } } fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix, source: hir::MatchSource) { match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) { UsefulWithWitness(pats) => { let witnesses = if pats.is_empty() { vec![DUMMY_WILD_PAT] } else { pats.iter().map(|w| &**w ).collect() }; match source { hir::MatchSource::ForLoopDesugar => { // `witnesses[0]` has the form `Some(<head>)`, peel off the `Some` let witness = match witnesses[0].node { PatKind::TupleStruct(_, Some(ref pats)) => match &pats[..] { [ref pat] => &**pat, _ => unreachable!(), }, _ => unreachable!(), }; span_err!(cx.tcx.sess, sp, E0297, "refutable pattern in `for` loop binding: \ `{}` not covered", pat_to_string(witness)); }, _ => { let pattern_strings: Vec<_> = witnesses.iter().map(|w| { pat_to_string(w) }).collect(); const LIMIT: usize = 3; let joined_patterns = match pattern_strings.len() { 0 => unreachable!(), 1 => format!("`{}`", pattern_strings[0]), 2...LIMIT => { let (tail, head) = pattern_strings.split_last().unwrap(); format!("`{}`", head.join("`, `") + "` and `" + tail) }, _ => { let (head, tail) = pattern_strings.split_at(LIMIT); format!("`{}` and {} more", head.join("`, `"), tail.len()) } }; span_err!(cx.tcx.sess, sp, E0004, "non-exhaustive patterns: {} not covered", joined_patterns ); }, } } NotUseful => { // This is good, wildcard pattern isn't reachable }, _ => unreachable!() } } fn const_val_to_expr(value: &ConstVal) -> P<hir::Expr> { let node = match value { &ConstVal::Bool(b) => ast::LitKind::Bool(b), _ => unreachable!() }; P(hir::Expr { id: 0, node: hir::ExprLit(P(Spanned { node: node, span: DUMMY_SP })), span: DUMMY_SP, attrs: None, }) } pub struct StaticInliner<'a, 'tcx: 'a> { pub tcx: &'a TyCtxt<'tcx>, pub failed: bool, pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>, } impl<'a, 'tcx> StaticInliner<'a, 'tcx> { pub fn new<'b>(tcx: &'b TyCtxt<'tcx>, renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>) -> StaticInliner<'b, 'tcx> { StaticInliner { tcx: tcx, failed: false, renaming_map: renaming_map } } } struct RenamingRecorder<'map> { substituted_node_id: NodeId, origin_span: Span, renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId> } impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> { fn visit_id(&mut self, node_id: NodeId) { let key = (node_id, self.origin_span); self.renaming_map.insert(key, self.substituted_node_id); } } impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> { fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> { return match pat.node { PatKind::Ident(..) | PatKind::Path(..) | PatKind::QPath(..) => { let def = self.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()); match def { Some(Def::AssociatedConst(did)) | Some(Def::Const(did)) => { let substs = Some(self.tcx.node_id_item_substs(pat.id).substs); if let Some((const_expr, _)) = lookup_const_by_id(self.tcx, did, substs) { const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| { if let Some(ref mut renaming_map) = self.renaming_map { // Record any renamings we do here record_renamings(const_expr, &pat, renaming_map); } new_pat }) } else { self.failed = true; span_err!(self.tcx.sess, pat.span, E0158, "statics cannot be referenced in patterns"); pat } } _ => noop_fold_pat(pat, self) } } _ => noop_fold_pat(pat, self) }; fn record_renamings(const_expr: &hir::Expr, substituted_pat: &hir::Pat, renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) { let mut renaming_recorder = RenamingRecorder { substituted_node_id: substituted_pat.id, origin_span: substituted_pat.span, renaming_map: renaming_map, }; let mut id_visitor = front_util::IdVisitor::new(&mut renaming_recorder); id_visitor.visit_expr(const_expr); } } } /// Constructs a partial witness for a pattern given a list of /// patterns expanded by the specialization step. /// /// When a pattern P is discovered to be useful, this function is used bottom-up /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset /// of values, V, where each value in that set is not covered by any previously /// used patterns and is covered by the pattern P'. Examples: /// /// left_ty: tuple of 3 elements /// pats: [10, 20, _] => (10, 20, _) /// /// left_ty: struct X { a: (bool, &'static str), b: usize} /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 } fn construct_witness<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor, pats: Vec<&Pat>, left_ty: Ty<'tcx>) -> P<Pat> { let pats_len = pats.len(); let mut pats = pats.into_iter().map(|p| P((*p).clone())); let pat = match left_ty.sty { ty::TyTuple(_) => PatKind::Tup(pats.collect()), ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => { let v = adt.variant_of_ctor(ctor); match v.kind() { VariantKind::Struct => { let field_pats: hir::HirVec<_> = v.fields.iter() .zip(pats) .filter(|&(_, ref pat)| pat.node != PatKind::Wild) .map(|(field, pat)| Spanned { span: DUMMY_SP, node: hir::FieldPat { name: field.name, pat: pat, is_shorthand: false, } }).collect(); let has_more_fields = field_pats.len() < pats_len; PatKind::Struct(def_to_path(cx.tcx, v.did), field_pats, has_more_fields) } VariantKind::Tuple => { PatKind::TupleStruct(def_to_path(cx.tcx, v.did), Some(pats.collect())) } VariantKind::Unit => { PatKind::Path(def_to_path(cx.tcx, v.did)) } } } ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => { match ty.sty { ty::TyArray(_, n) => match ctor { &Single => { assert_eq!(pats_len, n); PatKind::Vec(pats.collect(), None, hir::HirVec::new()) }, _ => unreachable!() }, ty::TySlice(_) => match ctor { &Slice(n) => { assert_eq!(pats_len, n); PatKind::Vec(pats.collect(), None, hir::HirVec::new()) }, _ => unreachable!() }, ty::TyStr => PatKind::Wild, _ => { assert_eq!(pats_len, 1); PatKind::Ref(pats.nth(0).unwrap(), mutbl) } } } ty::TyArray(_, len) => { assert_eq!(pats_len, len); PatKind::Vec(pats.collect(), None, hir::HirVec::new()) } _ => { match *ctor { ConstantValue(ref v) => PatKind::Lit(const_val_to_expr(v)), _ => PatKind::Wild, } } }; P(hir::Pat { id: 0, node: pat, span: DUMMY_SP }) } impl<'tcx, 'container> ty::AdtDefData<'tcx, 'container> { fn variant_of_ctor(&self, ctor: &Constructor) -> &VariantDefData<'tcx, 'container> { match ctor { &Variant(vid) => self.variant_with_id(vid), _ => self.struct_variant() } } } fn missing_constructors(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix, left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> { let used_constructors: Vec<Constructor> = rows.iter() .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length)) .collect(); all_constructors(cx, left_ty, max_slice_length) .into_iter() .filter(|c| !used_constructors.contains(c)) .collect() } /// This determines the set of all possible constructors of a pattern matching /// values of type `left_ty`. For vectors, this would normally be an infinite set /// but is instead bounded by the maximum fixed length of slice patterns in /// the column of patterns being analyzed. fn all_constructors(_cx: &MatchCheckCtxt, left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> { match left_ty.sty { ty::TyBool => [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(), ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty { ty::TySlice(_) => (0..max_slice_length+1).map(|length| Slice(length)).collect(), _ => vec![Single] }, ty::TyEnum(def, _) => def.variants.iter().map(|v| Variant(v.did)).collect(), _ => vec![Single] } } // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html // // Whether a vector `v` of patterns is 'useful' in relation to a set of such // vectors `m` is defined as there being a set of inputs that will match `v` // but not any of the sets in `m`. // // This is used both for reachability checking (if a pattern isn't useful in // relation to preceding patterns, it is not reachable) and exhaustiveness // checking (if a wildcard pattern is useful in relation to a matrix, the // matrix isn't exhaustive). // Note: is_useful doesn't work on empty types, as the paper notes. // So it assumes that v is non-empty. fn is_useful(cx: &MatchCheckCtxt, matrix: &Matrix, v: &[&Pat], witness: WitnessPreference) -> Usefulness { let &Matrix(ref rows) = matrix; debug!("{:?}", matrix); if rows.is_empty() { return match witness { ConstructWitness => UsefulWithWitness(vec!()), LeaveOutWitness => Useful }; } if rows[0].is_empty() { return NotUseful; } assert!(rows.iter().all(|r| r.len() == v.len())); let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) { Some(r) => raw_pat(r[0]), None if v.is_empty() => return NotUseful, None => v[0] }; let left_ty = if real_pat.id == DUMMY_NODE_ID { cx.tcx.mk_nil() } else { let left_ty = cx.tcx.pat_ty(&real_pat); match real_pat.node { PatKind::Ident(hir::BindByRef(..), _, _) => { left_ty.builtin_deref(false, NoPreference).unwrap().ty } _ => left_ty, } }; let max_slice_length = rows.iter().filter_map(|row| match row[0].node { PatKind::Vec(ref before, _, ref after) => Some(before.len() + after.len()), _ => None }).max().map_or(0, |v| v + 1); let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length); if constructors.is_empty() { let constructors = missing_constructors(cx, matrix, left_ty, max_slice_length); if constructors.is_empty() { all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| { match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) { UsefulWithWitness(pats) => UsefulWithWitness({ let arity = constructor_arity(cx, &c, left_ty); let mut result = { let pat_slice = &pats[..]; let subpats: Vec<_> = (0..arity).map(|i| { pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p) }).collect(); vec![construct_witness(cx, &c, subpats, left_ty)] }; result.extend(pats.into_iter().skip(arity)); result }), result => result } }).find(|result| result != &NotUseful).unwrap_or(NotUseful) } else { let matrix = rows.iter().filter_map(|r| { if pat_is_binding_or_wild(&cx.tcx.def_map.borrow(), raw_pat(r[0])) { Some(r[1..].to_vec()) } else { None } }).collect(); match is_useful(cx, &matrix, &v[1..], witness) { UsefulWithWitness(pats) => { let mut new_pats: Vec<_> = constructors.into_iter().map(|constructor| { let arity = constructor_arity(cx, &constructor, left_ty); let wild_pats = vec![DUMMY_WILD_PAT; arity]; construct_witness(cx, &constructor, wild_pats, left_ty) }).collect(); new_pats.extend(pats); UsefulWithWitness(new_pats) }, result => result } } } else { constructors.into_iter().map(|c| is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) ).find(|result| result != &NotUseful).unwrap_or(NotUseful) } } fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix, v: &[&Pat], ctor: Constructor, lty: Ty, witness: WitnessPreference) -> Usefulness { let arity = constructor_arity(cx, &ctor, lty); let matrix = Matrix(m.iter().filter_map(|r| { specialize(cx, &r[..], &ctor, 0, arity) }).collect()); match specialize(cx, v, &ctor, 0, arity) { Some(v) => is_useful(cx, &matrix, &v[..], witness), None => NotUseful } } /// Determines the constructors that the given pattern can be specialized to. /// /// In most cases, there's only one constructor that a specific pattern /// represents, such as a specific enum variant or a specific literal value. /// Slice patterns, however, can match slices of different lengths. For instance, /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on. /// /// On the other hand, a wild pattern and an identifier pattern cannot be /// specialized in any way. fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat, left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> { let pat = raw_pat(p); match pat.node { PatKind::Struct(..) | PatKind::TupleStruct(..) | PatKind::Path(..) | PatKind::Ident(..) => match cx.tcx.def_map.borrow().get(&pat.id).unwrap().full_def() { Def::Const(..) | Def::AssociatedConst(..) => cx.tcx.sess.span_bug(pat.span, "const pattern should've \ been rewritten"), Def::Struct(..) | Def::TyAlias(..) => vec![Single], Def::Variant(_, id) => vec![Variant(id)], Def::Local(..) => vec![], def => cx.tcx.sess.span_bug(pat.span, &format!("pat_constructors: unexpected \ definition {:?}", def)), }, PatKind::QPath(..) => cx.tcx.sess.span_bug(pat.span, "const pattern should've \ been rewritten"), PatKind::Lit(ref expr) => vec!(ConstantValue(eval_const_expr(cx.tcx, &expr))), PatKind::Range(ref lo, ref hi) => vec!(ConstantRange(eval_const_expr(cx.tcx, &lo), eval_const_expr(cx.tcx, &hi))), PatKind::Vec(ref before, ref slice, ref after) => match left_ty.sty { ty::TyArray(_, _) => vec!(Single), _ => if slice.is_some() { (before.len() + after.len()..max_slice_length+1) .map(|length| Slice(length)) .collect() } else { vec!(Slice(before.len() + after.len())) } }, PatKind::Box(_) | PatKind::Tup(_) | PatKind::Ref(..) => vec!(Single), PatKind::Wild => vec!(), } } /// This computes the arity of a constructor. The arity of a constructor /// is how many subpattern patterns of that constructor should be expanded to. /// /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3. /// A struct pattern's arity is the number of fields it contains, etc. pub fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize { match ty.sty { ty::TyTuple(ref fs) => fs.len(), ty::TyBox(_) => 1, ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty { ty::TySlice(_) => match *ctor { Slice(length) => length, ConstantValue(_) => 0, _ => unreachable!() }, ty::TyStr => 0, _ => 1 }, ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => { adt.variant_of_ctor(ctor).fields.len() } ty::TyArray(_, n) => n, _ => 0 } } fn range_covered_by_constructor(ctor: &Constructor, from: &ConstVal, to: &ConstVal) -> Option<bool> { let (c_from, c_to) = match *ctor { ConstantValue(ref value) => (value, value), ConstantRange(ref from, ref to) => (from, to), Single => return Some(true), _ => unreachable!() }; let cmp_from = compare_const_vals(c_from, from); let cmp_to = compare_const_vals(c_to, to); match (cmp_from, cmp_to) { (Some(cmp_from), Some(cmp_to)) => { Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater) } _ => None } } /// This is the main specialization step. It expands the first pattern in the given row /// into `arity` patterns based on the constructor. For most patterns, the step is trivial, /// for instance tuple patterns are flattened and box patterns expand into their inner pattern. /// /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple /// different patterns. /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing /// fields filled with wild patterns. pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], constructor: &Constructor, col: usize, arity: usize) -> Option<Vec<&'a Pat>> { let &Pat { id: pat_id, ref node, span: pat_span } = raw_pat(r[col]); let head: Option<Vec<&Pat>> = match *node { PatKind::Wild => Some(vec![DUMMY_WILD_PAT; arity]), PatKind::Path(..) | PatKind::Ident(..) => { let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def(); match def { Def::Const(..) | Def::AssociatedConst(..) => cx.tcx.sess.span_bug(pat_span, "const pattern should've \ been rewritten"), Def::Variant(_, id) if *constructor != Variant(id) => None, Def::Variant(..) | Def::Struct(..) => Some(Vec::new()), Def::Local(..) => Some(vec![DUMMY_WILD_PAT; arity]), _ => cx.tcx.sess.span_bug(pat_span, &format!("specialize: unexpected \ definition {:?}", def)), } } PatKind::TupleStruct(_, ref args) => { let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def(); match def { Def::Const(..) | Def::AssociatedConst(..) => cx.tcx.sess.span_bug(pat_span, "const pattern should've \ been rewritten"), Def::Variant(_, id) if *constructor != Variant(id) => None, Def::Variant(..) | Def::Struct(..) => { Some(match args { &Some(ref args) => args.iter().map(|p| &**p).collect(), &None => vec![DUMMY_WILD_PAT; arity], }) } _ => None } } PatKind::QPath(_, _) => { cx.tcx.sess.span_bug(pat_span, "const pattern should've \ been rewritten") } PatKind::Struct(_, ref pattern_fields, _) => { let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def(); let adt = cx.tcx.node_id_to_type(pat_id).ty_adt_def().unwrap(); let variant = adt.variant_of_ctor(constructor); let def_variant = adt.variant_of_def(def); if variant.did == def_variant.did { Some(variant.fields.iter().map(|sf| { match pattern_fields.iter().find(|f| f.node.name == sf.name) { Some(ref f) => &*f.node.pat, _ => DUMMY_WILD_PAT } }).collect()) } else { None } } PatKind::Tup(ref args) => Some(args.iter().map(|p| &**p).collect()), PatKind::Box(ref inner) | PatKind::Ref(ref inner, _) => Some(vec![&**inner]), PatKind::Lit(ref expr) => { let expr_value = eval_const_expr(cx.tcx, &expr); match range_covered_by_constructor(constructor, &expr_value, &expr_value) { Some(true) => Some(vec![]), Some(false) => None, None => { span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms"); None } } } PatKind::Range(ref from, ref to) => { let from_value = eval_const_expr(cx.tcx, &from); let to_value = eval_const_expr(cx.tcx, &to); match range_covered_by_constructor(constructor, &from_value, &to_value) { Some(true) => Some(vec![]), Some(false) => None, None => { span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms"); None } } } PatKind::Vec(ref before, ref slice, ref after) => { match *constructor { // Fixed-length vectors. Single => { let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect(); pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len())); pats.extend(after.iter().map(|p| &**p)); Some(pats) }, Slice(length) if before.len() + after.len() <= length && slice.is_some() => { let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect(); pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len())); pats.extend(after.iter().map(|p| &**p)); Some(pats) }, Slice(length) if before.len() + after.len() == length => { let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect(); pats.extend(after.iter().map(|p| &**p)); Some(pats) }, SliceWithSubslice(prefix, suffix) if before.len() == prefix && after.len() == suffix && slice.is_some() => { let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect(); pats.extend(after.iter().map(|p| &**p)); Some(pats) } _ => None } } }; head.map(|mut head| { head.extend_from_slice(&r[..col]); head.extend_from_slice(&r[col + 1..]); head }) } fn check_local(cx: &mut MatchCheckCtxt, loc: &hir::Local) { intravisit::walk_local(cx, loc); let pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone()); check_irrefutable(cx, &pat, false); // Check legality of move bindings and `@` patterns. check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat)); check_legality_of_bindings_in_at_patterns(cx, &loc.pat); } fn check_fn(cx: &mut MatchCheckCtxt, kind: FnKind, decl: &hir::FnDecl, body: &hir::Block, sp: Span, fn_id: NodeId) { match kind { FnKind::Closure => {} _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id), } intravisit::walk_fn(cx, kind, decl, body, sp); for input in &decl.inputs { check_irrefutable(cx, &input.pat, true); check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat)); check_legality_of_bindings_in_at_patterns(cx, &input.pat); } } fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) { let origin = if is_fn_arg { "function argument" } else { "local binding" }; is_refutable(cx, pat, |uncovered_pat| { span_err!(cx.tcx.sess, pat.span, E0005, "refutable pattern in {}: `{}` not covered", origin, pat_to_string(uncovered_pat), ); }); } fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where F: FnOnce(&Pat) -> A, { let pats = Matrix(vec!(vec!(pat))); match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) { UsefulWithWitness(pats) => Some(refutable(&pats[0])), NotUseful => None, Useful => unreachable!() } } // Legality of move bindings checking fn check_legality_of_move_bindings(cx: &MatchCheckCtxt, has_guard: bool, pats: &[P<Pat>]) { let tcx = cx.tcx; let def_map = &tcx.def_map; let mut by_ref_span = None; for pat in pats { pat_bindings(def_map, &pat, |bm, _, span, _path| { match bm { hir::BindByRef(_) => { by_ref_span = Some(span); } hir::BindByValue(_) => { } } }) } let check_move = |p: &Pat, sub: Option<&Pat>| { // check legality of moving out of the enum // x @ Foo(..) is legal, but x @ Foo(y) isn't. if sub.map_or(false, |p| pat_contains_bindings(&def_map.borrow(), &p)) { span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings"); } else if has_guard { span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard"); } else if by_ref_span.is_some() { let mut err = struct_span_err!(cx.tcx.sess, p.span, E0009, "cannot bind by-move and by-ref in the same pattern"); span_note!(&mut err, by_ref_span.unwrap(), "by-ref binding occurs here"); err.emit(); } }; for pat in pats { front_util::walk_pat(&pat, |p| { if pat_is_binding(&def_map.borrow(), &p) { match p.node { PatKind::Ident(hir::BindByValue(_), _, ref sub) => { let pat_ty = tcx.node_id_to_type(p.id); //FIXME: (@jroesch) this code should be floated up as well let infcx = infer::new_infer_ctxt(cx.tcx, &cx.tcx.tables, Some(cx.param_env.clone()), ProjectionMode::AnyFinal); if infcx.type_moves_by_default(pat_ty, pat.span) { check_move(p, sub.as_ref().map(|p| &**p)); } } PatKind::Ident(hir::BindByRef(_), _, _) => { } _ => { cx.tcx.sess.span_bug( p.span, &format!("binding pattern {} is not an \ identifier: {:?}", p.id, p.node)); } } } true }); } } /// Ensures that a pattern guard doesn't borrow by mutable reference or /// assign. fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>, guard: &hir::Expr) { let mut checker = MutationChecker { cx: cx, }; let infcx = infer::new_infer_ctxt(cx.tcx, &cx.tcx.tables, Some(checker.cx.param_env.clone()), ProjectionMode::AnyFinal); let mut visitor = ExprUseVisitor::new(&mut checker, &infcx); visitor.walk_expr(guard); } struct MutationChecker<'a, 'tcx: 'a> { cx: &'a MatchCheckCtxt<'a, 'tcx>, } impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> { fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {} fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {} fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {} fn borrow(&mut self, _: NodeId, span: Span, _: cmt, _: Region, kind: BorrowKind, _: LoanCause) { match kind { MutBorrow => { span_err!(self.cx.tcx.sess, span, E0301, "cannot mutably borrow in a pattern guard") } ImmBorrow | UniqueImmBorrow => {} } } fn decl_without_init(&mut self, _: NodeId, _: Span) {} fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) { match mode { MutateMode::JustWrite | MutateMode::WriteAndRead => { span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard") } MutateMode::Init => {} } } } /// Forbids bindings in `@` patterns. This is necessary for memory safety, /// because of the way rvalues are handled in the borrow check. (See issue /// #14587.) fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) { AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat); } struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> { cx: &'a MatchCheckCtxt<'b, 'tcx>, bindings_allowed: bool } impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> { fn visit_pat(&mut self, pat: &Pat) { if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map.borrow(), pat) { span_err!(self.cx.tcx.sess, pat.span, E0303, "pattern bindings are not allowed \ after an `@`"); } match pat.node { PatKind::Ident(_, _, Some(_)) => { let bindings_were_allowed = self.bindings_allowed; self.bindings_allowed = false; intravisit::walk_pat(self, pat); self.bindings_allowed = bindings_were_allowed; } _ => intravisit::walk_pat(self, pat), } } }
39.450786
100
0.490251
61d6a8b18c6fafc8669fff8b3cc86420fac603e6
2,520
use bytes::Bytes; use crate::{block, consensus, prelude::*, Time}; use super::super::types::ValidatorUpdate; /// Called on genesis to initialize chain state. /// /// [ABCI documentation](https://docs.tendermint.com/master/spec/abci/abci.html#initchain) #[derive(Clone, PartialEq, Eq, Debug)] pub struct InitChain { /// The genesis time. pub time: Time, /// The ID of the blockchain. pub chain_id: String, /// Initial consensus-critical parameters. pub consensus_params: consensus::Params, /// Initial genesis validators, sorted by voting power. pub validators: Vec<ValidatorUpdate>, /// Serialized JSON bytes containing the initial application state. pub app_state_bytes: Bytes, /// Height of the initial block (typically `1`). pub initial_height: block::Height, } // ============================================================================= // Protobuf conversions // ============================================================================= use crate::Error; use core::convert::{TryFrom, TryInto}; use tendermint_proto::abci as pb; use tendermint_proto::Protobuf; impl From<InitChain> for pb::RequestInitChain { fn from(init_chain: InitChain) -> Self { Self { time: Some(init_chain.time.into()), chain_id: init_chain.chain_id, consensus_params: Some(init_chain.consensus_params.into()), validators: init_chain.validators.into_iter().map(Into::into).collect(), app_state_bytes: init_chain.app_state_bytes, initial_height: init_chain.initial_height.into(), } } } impl TryFrom<pb::RequestInitChain> for InitChain { type Error = Error; fn try_from(init_chain: pb::RequestInitChain) -> Result<Self, Self::Error> { Ok(Self { time: init_chain .time .ok_or_else(Error::missing_genesis_time)? .try_into()?, chain_id: init_chain.chain_id, consensus_params: init_chain .consensus_params .ok_or_else(Error::missing_consensus_params)? .try_into()?, validators: init_chain .validators .into_iter() .map(TryInto::try_into) .collect::<Result<_, _>>()?, app_state_bytes: init_chain.app_state_bytes, initial_height: init_chain.initial_height.try_into()?, }) } } impl Protobuf<pb::RequestInitChain> for InitChain {}
34.054054
90
0.592857
e473fbb67b117bd54fbe16b841dd8ad575a117c4
9,609
use crate::buffer::Buffer; const MACHINE_TRANS_KEYS: &[u8] = &[ 5, 26, 5, 21, 5, 26, 5, 21, 1, 16, 5, 21, 5, 26, 5, 21, 5, 26, 5, 21, 5, 21, 5, 26, 5, 21, 1, 16, 5, 21, 5, 26, 5, 21, 5, 26, 5, 21, 5, 26, 1, 29, 5, 29, 5, 29, 5, 29, 22, 22, 5, 22, 5, 29, 5, 29, 5, 29, 1, 16, 5, 26, 5, 29, 5, 29, 22, 22, 5, 22, 5, 29, 5, 29, 1, 16, 5, 29, 5, 29, 0 ]; const MACHINE_KEY_SPANS: &[u8] = &[ 22, 17, 22, 17, 16, 17, 22, 17, 22, 17, 17, 22, 17, 16, 17, 22, 17, 22, 17, 22, 29, 25, 25, 25, 1, 18, 25, 25, 25, 16, 22, 25, 25, 1, 18, 25, 25, 16, 25, 25 ]; const MACHINE_INDEX_OFFSETS: &[u16] = &[ 0, 23, 41, 64, 82, 99, 117, 140, 158, 181, 199, 217, 240, 258, 275, 293, 316, 334, 357, 375, 398, 428, 454, 480, 506, 508, 527, 553, 579, 605, 622, 645, 671, 697, 699, 718, 744, 770, 787, 813 ]; const MACHINE_INDICIES: &[u8] = &[ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 4, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 4, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 11, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 4, 0, 11, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 14, 14, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 15, 13, 14, 14, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 15, 16, 16, 16, 16, 17, 16, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 19, 19, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 19, 16, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 21, 16, 22, 22, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 23, 16, 16, 16, 16, 17, 16, 22, 22, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 23, 16, 24, 24, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 25, 16, 16, 16, 16, 17, 16, 24, 24, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 25, 16, 14, 14, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 26, 15, 16, 16, 16, 16, 17, 16, 28, 28, 27, 27, 29, 29, 27, 27, 27, 27, 2, 2, 27, 30, 27, 28, 27, 27, 27, 27, 15, 19, 27, 27, 27, 17, 23, 25, 21, 27, 32, 32, 31, 31, 31, 31, 31, 31, 31, 33, 31, 31, 31, 31, 31, 2, 3, 6, 31, 31, 31, 4, 10, 12, 8, 31, 34, 34, 31, 31, 31, 31, 31, 31, 31, 35, 31, 31, 31, 31, 31, 31, 3, 6, 31, 31, 31, 4, 10, 12, 8, 31, 5, 5, 31, 31, 31, 31, 31, 31, 31, 35, 31, 31, 31, 31, 31, 31, 4, 6, 31, 31, 31, 31, 31, 31, 8, 31, 6, 31, 7, 7, 31, 31, 31, 31, 31, 31, 31, 35, 31, 31, 31, 31, 31, 31, 8, 6, 31, 36, 36, 31, 31, 31, 31, 31, 31, 31, 35, 31, 31, 31, 31, 31, 31, 10, 6, 31, 31, 31, 4, 31, 31, 8, 31, 37, 37, 31, 31, 31, 31, 31, 31, 31, 35, 31, 31, 31, 31, 31, 31, 12, 6, 31, 31, 31, 4, 10, 31, 8, 31, 34, 34, 31, 31, 31, 31, 31, 31, 31, 33, 31, 31, 31, 31, 31, 31, 3, 6, 31, 31, 31, 4, 10, 12, 8, 31, 28, 28, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 28, 31, 14, 14, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 15, 38, 38, 38, 38, 17, 38, 40, 40, 39, 39, 39, 39, 39, 39, 39, 41, 39, 39, 39, 39, 39, 39, 15, 19, 39, 39, 39, 17, 23, 25, 21, 39, 18, 18, 39, 39, 39, 39, 39, 39, 39, 41, 39, 39, 39, 39, 39, 39, 17, 19, 39, 39, 39, 39, 39, 39, 21, 39, 19, 39, 20, 20, 39, 39, 39, 39, 39, 39, 39, 41, 39, 39, 39, 39, 39, 39, 21, 19, 39, 42, 42, 39, 39, 39, 39, 39, 39, 39, 41, 39, 39, 39, 39, 39, 39, 23, 19, 39, 39, 39, 17, 39, 39, 21, 39, 43, 43, 39, 39, 39, 39, 39, 39, 39, 41, 39, 39, 39, 39, 39, 39, 25, 19, 39, 39, 39, 17, 23, 39, 21, 39, 44, 44, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 44, 39, 45, 45, 39, 39, 39, 39, 39, 39, 39, 30, 39, 39, 39, 39, 39, 26, 15, 19, 39, 39, 39, 17, 23, 25, 21, 39, 40, 40, 39, 39, 39, 39, 39, 39, 39, 30, 39, 39, 39, 39, 39, 39, 15, 19, 39, 39, 39, 17, 23, 25, 21, 39, 0 ]; const MACHINE_TRANS_TARGS: &[u8] = &[ 20, 1, 28, 22, 23, 3, 24, 5, 25, 7, 26, 9, 27, 20, 10, 31, 20, 32, 12, 33, 14, 34, 16, 35, 18, 36, 39, 20, 21, 30, 37, 20, 0, 29, 2, 4, 6, 8, 20, 20, 11, 13, 15, 17, 38, 19 ]; const MACHINE_TRANS_ACTIONS: &[u8] = &[ 1, 0, 2, 2, 2, 0, 0, 0, 2, 0, 2, 0, 2, 3, 0, 4, 5, 2, 0, 0, 0, 2, 0, 2, 0, 2, 4, 8, 2, 9, 0, 10, 0, 0, 0, 0, 0, 0, 11, 12, 0, 0, 0, 0, 4, 0 ]; const MACHINE_TO_STATE_ACTIONS: &[u8] = &[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const MACHINE_FROM_STATE_ACTIONS: &[u8] = &[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const MACHINE_EOF_TRANS: &[u8] = &[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 14, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 32, 32, 32, 32, 32, 32, 32, 32, 32, 39, 40, 40, 40, 40, 40, 40, 40, 40, 40 ]; #[derive(Clone, Copy)] pub enum SyllableType { ConsonantSyllable = 0, BrokenCluster, NonKhmerCluster, } pub fn find_syllables_khmer(buffer: &mut Buffer) { let mut cs = 20usize; let mut ts = 0; let mut te = 0; let mut act = 0; let mut p = 0; let pe = buffer.len; let eof = buffer.len; let mut syllable_serial = 1u8; let mut reset = true; let mut slen; let mut trans = 0; if p == pe { if MACHINE_EOF_TRANS[cs] > 0 { trans = (MACHINE_EOF_TRANS[cs] - 1) as usize; } } loop { if reset { if MACHINE_FROM_STATE_ACTIONS[cs] == 7 { ts = p; } slen = MACHINE_KEY_SPANS[cs] as usize; let cs_idx = ((cs as i32) << 1) as usize; let i = if slen > 0 && MACHINE_TRANS_KEYS[cs_idx] <= buffer.info[p].indic_category() as u8 && buffer.info[p].indic_category() as u8 <= MACHINE_TRANS_KEYS[cs_idx + 1] { (buffer.info[p].indic_category() as u8 - MACHINE_TRANS_KEYS[cs_idx]) as usize } else { slen }; trans = MACHINE_INDICIES[MACHINE_INDEX_OFFSETS[cs] as usize + i] as usize; } reset = true; cs = MACHINE_TRANS_TARGS[trans] as usize; if MACHINE_TRANS_ACTIONS[trans] != 0 { match MACHINE_TRANS_ACTIONS[trans] { 2 => te = p + 1, 8 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonKhmerCluster, buffer); } 10 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::ConsonantSyllable, buffer); } 12 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::BrokenCluster, buffer); } 11 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonKhmerCluster, buffer); } 1 => { p = te - 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::ConsonantSyllable, buffer); } 5 => { p = te - 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::BrokenCluster, buffer); } 3 => { match act { 2 => { p = te - 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::BrokenCluster, buffer); } 3 => { p = te - 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonKhmerCluster, buffer); } _ => {} } } 4 => { te = p + 1; act = 2; } 9 => { te = p + 1; act = 3; } _ => {} } } if MACHINE_TO_STATE_ACTIONS[cs] == 6 { ts = 0; } p += 1; if p != pe { continue; } if p == eof { if MACHINE_EOF_TRANS[cs] > 0 { trans = (MACHINE_EOF_TRANS[cs] - 1) as usize; reset = false; continue; } } break; } } #[inline] fn found_syllable( start: usize, end: usize, syllable_serial: &mut u8, kind: SyllableType, buffer: &mut Buffer, ) { for i in start..end { buffer.info[i].set_syllable((*syllable_serial << 4) | kind as u8); } *syllable_serial += 1; if *syllable_serial == 16 { *syllable_serial = 1; } }
30.122257
112
0.420751
f7b456dd835e5adc3e8941473a6eb383140a83fc
32,392
use std::sync::Arc; use hdk::prelude::*; use holo_hash::DhtOpHash; use holochain::conductor::config::ConductorConfig; use holochain::sweettest::{SweetConductor, SweetConductorBatch, SweetDnaFile}; use holochain::test_utils::consistency_10s; use holochain::test_utils::network_simulation::{data_zome, generate_test_data}; use holochain::{ conductor::ConductorBuilder, test_utils::consistency::local_machine_session_with_hashes, }; use kitsune_p2p::agent_store::AgentInfoSigned; use kitsune_p2p::gossip::sharded_gossip::test_utils::create_ops_bloom; use kitsune_p2p::gossip::sharded_gossip::test_utils::{check_ops_boom, create_agent_bloom}; use kitsune_p2p::KitsuneP2pConfig; #[derive(serde::Serialize, serde::Deserialize, Debug, SerializedBytes, derive_more::From)] #[serde(transparent)] #[repr(transparent)] struct AppString(String); #[cfg(feature = "test_utils")] #[tokio::test(flavor = "multi_thread")] async fn fullsync_sharded_gossip() -> anyhow::Result<()> { use holochain::{ conductor::handle::DevSettingsDelta, test_utils::inline_zomes::simple_create_read_zome, }; let _g = observability::test_run().ok(); const NUM_CONDUCTORS: usize = 2; let mut tuning = kitsune_p2p_types::config::tuning_params_struct::KitsuneP2pTuningParams::default(); tuning.gossip_strategy = "sharded-gossip".to_string(); let mut network = KitsuneP2pConfig::default(); network.transport_pool = vec![kitsune_p2p::TransportConfig::Quic { bind_to: None, override_host: None, override_port: None, }]; network.tuning_params = Arc::new(tuning); let mut config = ConductorConfig::default(); config.network = Some(network); let mut conductors = SweetConductorBatch::from_config(NUM_CONDUCTORS, config).await; for c in conductors.iter() { c.update_dev_settings(DevSettingsDelta { publish: Some(false), ..Default::default() }); } let (dna_file, _) = SweetDnaFile::unique_from_inline_zome("zome1", simple_create_read_zome()) .await .unwrap(); let apps = conductors.setup_app("app", &[dna_file]).await.unwrap(); conductors.exchange_peer_info().await; let ((alice,), (bobbo,)) = apps.into_tuples(); // Call the "create" zome fn on Alice's app let hash: HeaderHash = conductors[0].call(&alice.zome("zome1"), "create", ()).await; let all_cells = vec![&alice, &bobbo]; // Wait long enough for Bob to receive gossip consistency_10s(&all_cells).await; // let p2p = conductors[0].envs().p2p().lock().values().next().cloned().unwrap(); // holochain_state::prelude::dump_tmp(&p2p); // holochain_state::prelude::dump_tmp(&alice.env()); // Verify that bobbo can run "read" on his cell and get alice's Header let element: Option<Element> = conductors[1].call(&bobbo.zome("zome1"), "read", hash).await; let element = element.expect("Element was None: bobbo couldn't `get` it"); // Assert that the Element bobbo sees matches what alice committed assert_eq!(element.header().author(), alice.agent_pubkey()); assert_eq!( *element.entry(), ElementEntry::Present(Entry::app(().try_into().unwrap()).unwrap()) ); Ok(()) } #[cfg(feature = "test_utils")] #[tokio::test(flavor = "multi_thread")] async fn fullsync_sharded_local_gossip() -> anyhow::Result<()> { use holochain::{ conductor::handle::DevSettingsDelta, sweettest::SweetConductor, test_utils::inline_zomes::simple_create_read_zome, }; let _g = observability::test_run().ok(); let mut tuning = kitsune_p2p_types::config::tuning_params_struct::KitsuneP2pTuningParams::default(); tuning.gossip_strategy = "sharded-gossip".to_string(); let mut network = KitsuneP2pConfig::default(); network.transport_pool = vec![kitsune_p2p::TransportConfig::Quic { bind_to: None, override_host: None, override_port: None, }]; network.tuning_params = Arc::new(tuning); let mut config = ConductorConfig::default(); config.network = Some(network); let mut conductor = SweetConductor::from_config(config).await; conductor.update_dev_settings(DevSettingsDelta { publish: Some(false), ..Default::default() }); let (dna_file, _) = SweetDnaFile::unique_from_inline_zome("zome1", simple_create_read_zome()) .await .unwrap(); let alice = conductor .setup_app("app", &[dna_file.clone()]) .await .unwrap(); let (alice,) = alice.into_tuple(); let bobbo = conductor.setup_app("app2 ", &[dna_file]).await.unwrap(); let (bobbo,) = bobbo.into_tuple(); // Call the "create" zome fn on Alice's app let hash: HeaderHash = conductor.call(&alice.zome("zome1"), "create", ()).await; let all_cells = vec![&alice, &bobbo]; // Wait long enough for Bob to receive gossip consistency_10s(&all_cells).await; // Verify that bobbo can run "read" on his cell and get alice's Header let element: Option<Element> = conductor.call(&bobbo.zome("zome1"), "read", hash).await; let element = element.expect("Element was None: bobbo couldn't `get` it"); // Assert that the Element bobbo sees matches what alice committed assert_eq!(element.header().author(), alice.agent_pubkey()); assert_eq!( *element.entry(), ElementEntry::Present(Entry::app(().try_into().unwrap()).unwrap()) ); Ok(()) } #[cfg(feature = "test_utils")] #[tokio::test(flavor = "multi_thread")] #[ignore = "Prototype test that is not suitable for CI"] /// This is a prototype test to demonstrate how to create a /// simulated network. /// It tests one real agent talking to a number of simulated agents. /// The simulated agents respond to initiated gossip rounds but do /// not initiate there own. /// The simulated agents respond to gets correctly. /// The test checks that the real agent: /// - Can reach consistency. /// - Initiates with all the simulated agents that it should. /// - Does not route gets or publishes to the wrong agents. async fn mock_network_sharded_gossip() { use std::sync::atomic::AtomicUsize; use holochain_p2p::mock_network::{GossipProtocol, MockScenario}; use holochain_p2p::{ dht_arc::DhtArcSet, mock_network::{ AddressedHolochainP2pMockMsg, HolochainP2pMockChannel, HolochainP2pMockMsg, }, }; use holochain_p2p::{dht_arc::DhtLocation, AgentPubKeyExt, DnaHashExt}; use holochain_sqlite::db::AsP2pAgentStoreConExt; use kitsune_p2p::TransportConfig; use kitsune_p2p_types::tx2::tx2_adapter::AdapterFactory; // Get the env var settings for number of simulated agents and // the minimum number of ops that should be held by each agent // if there are some or use defaults. let (num_agents, min_ops) = std::env::var_os("NUM_AGENTS") .and_then(|s| s.to_string_lossy().parse::<usize>().ok()) .and_then(|na| { std::env::var_os("MIN_OPS") .and_then(|s| s.to_string_lossy().parse::<usize>().ok()) .map(|mo| (na, mo)) }) .unwrap_or((100, 10)); // Check if we should for new data to be generated even if it already exists. let force_new_data = std::env::var_os("FORCE_NEW_DATA").is_some(); let _g = observability::test_run().ok(); // Generate or use cached test data. let (data, mut conn) = generate_test_data(num_agents, min_ops, false, force_new_data).await; let data = Arc::new(data); // We have to use the same dna that was used to generate the test data. // This is a short coming I hope to overcome in future versions. let dna_file = data_zome(data.uuid.clone()).await; // We are pretending that all simulated agents have all other agents (except the real agent) // for this test. // Create the one agent bloom. let agent_bloom = create_agent_bloom(data.agent_info(), None); // Create the simulated network. let (from_kitsune_tx, to_kitsune_rx, mut channel) = HolochainP2pMockChannel::channel( // Pass in the generated simulated peer data. data.agent_info().cloned().collect(), // We want to buffer up to 1000 network messages. 1000, MockScenario { // Don't drop any individual messages. percent_drop_msg: 0.0, // A random 10% of simulated agents will never be online. percent_offline: 0.1, // Simulated agents will receive messages from within 50 to 100 ms. inbound_delay_range: std::time::Duration::from_millis(50) ..std::time::Duration::from_millis(150), // Simulated agents will send messages from within 50 to 100 ms. outbound_delay_range: std::time::Duration::from_millis(50) ..std::time::Duration::from_millis(150), }, ); // Share alice's peer data as it changes. let alice_info = Arc::new(parking_lot::Mutex::new(None)); // Share the number of hashes alice should be holding. let num_hashes_alice_should_hold = Arc::new(AtomicUsize::new(0)); // Create some oneshot to notify of any publishes to the wrong node. let (bad_publish_tx, mut bad_publish_rx) = tokio::sync::oneshot::channel(); // Create some oneshot to notify of any gets to the wrong node. let (bad_get_tx, mut bad_get_rx) = tokio::sync::oneshot::channel(); // Track the agents that have been gossiped with. let (agents_gossiped_with_tx, mut agents_gossiped_with_rx) = tokio::sync::watch::channel(HashSet::new()); // Spawn the task that will simulate the network. tokio::task::spawn({ let data = data.clone(); let alice_info = alice_info.clone(); let num_hashes_alice_should_hold = num_hashes_alice_should_hold.clone(); async move { let mut gossiped_ops = HashSet::new(); let start_time = std::time::Instant::now(); let mut agents_gossiped_with = HashSet::new(); let mut num_missed_gossips = 0; let mut last_intervals = None; let mut bad_publish = Some(bad_publish_tx); let mut bad_get = Some(bad_get_tx); // Get the next network message. while let Some((msg, respond)) = channel.next().await { let alice: Option<AgentInfoSigned> = alice_info.lock().clone(); let num_hashes_alice_should_hold = num_hashes_alice_should_hold.load(std::sync::atomic::Ordering::Relaxed); let AddressedHolochainP2pMockMsg { agent, msg } = msg; let agent = Arc::new(agent); // Match on the message and create a response (if a response is needed). match msg { HolochainP2pMockMsg::Wire { msg, .. } => match msg { holochain_p2p::WireMessage::CallRemote { .. } => debug!("CallRemote"), holochain_p2p::WireMessage::Publish { ops, .. } => { if bad_publish.is_some() { let arc = data.agent_to_arc[&agent]; if ops .into_iter() .any(|(_, op)| !arc.contains(op.dht_basis().get_loc())) { bad_publish.take().unwrap().send(()).unwrap(); } } } holochain_p2p::WireMessage::ValidationReceipt { receipt: _ } => { debug!("Validation Receipt") } holochain_p2p::WireMessage::Get { dht_hash, options } => { let txn = conn .transaction_with_behavior(rusqlite::TransactionBehavior::Exclusive) .unwrap(); let ops = holochain_cascade::test_utils::handle_get_txn( &txn, dht_hash.clone(), options, ); if bad_get.is_some() { let arc = data.agent_to_arc[&agent]; if !arc.contains(dht_hash.get_loc()) { bad_get.take().unwrap().send(()).unwrap(); } } let ops: Vec<u8> = UnsafeBytes::from(SerializedBytes::try_from(ops).unwrap()).into(); let msg = HolochainP2pMockMsg::CallResp(ops.into()); respond.unwrap().respond(msg); } holochain_p2p::WireMessage::GetMeta { .. } => debug!("get_meta"), holochain_p2p::WireMessage::GetLinks { .. } => debug!("get_links"), holochain_p2p::WireMessage::GetAgentActivity { .. } => { debug!("get_agent_activity") } holochain_p2p::WireMessage::GetValidationPackage { .. } => { debug!("get_validation_package") } holochain_p2p::WireMessage::CountersigningAuthorityResponse { .. } => { debug!("countersigning_authority_response") } }, HolochainP2pMockMsg::CallResp(_) => debug!("CallResp"), HolochainP2pMockMsg::PeerGet(_) => debug!("PeerGet"), HolochainP2pMockMsg::PeerGetResp(_) => debug!("PeerGetResp"), HolochainP2pMockMsg::PeerQuery(_) => debug!("PeerQuery"), HolochainP2pMockMsg::PeerQueryResp(_) => debug!("PeerQueryResp"), HolochainP2pMockMsg::Gossip { dna, module, gossip, } => { if let kitsune_p2p::GossipModuleType::ShardedRecent = module { if let GossipProtocol::Sharded(gossip) = gossip { use kitsune_p2p::gossip::sharded_gossip::*; match gossip { ShardedGossipWire::Initiate(Initiate { intervals, .. }) => { // Capture the intervals from alice. // This works because alice will only initiate with one simulated // agent at a time. last_intervals = Some(intervals); let arc = data.agent_to_arc[&agent]; let interval = arc.interval(); // If we have info for alice check the overlap. if let Some(alice) = &alice { let a = alice.storage_arc.interval(); let b = interval.clone(); debug!("{}\n{}", a.to_ascii(10), b.to_ascii(10)); let a: DhtArcSet = a.into(); let b: DhtArcSet = b.into(); if !a.overlap(&b) { num_missed_gossips += 1; } } // Record that this simulated agent was initiated with. agents_gossiped_with.insert(agent.clone()); agents_gossiped_with_tx .send(agents_gossiped_with.clone()) .unwrap(); // Accept the initiate. let msg = HolochainP2pMockMsg::Gossip { dna: dna.clone(), module: module.clone(), gossip: GossipProtocol::Sharded( ShardedGossipWire::accept(vec![interval]), ), }; channel.send(msg.addressed((*agent).clone())).await; // Create an ops bloom and send it back. let window = (Timestamp::now() - std::time::Duration::from_secs(60 * 60)) .unwrap() ..Timestamp::now(); let this_agent_hashes: Vec<_> = data .hashes_authority_for(&agent) .into_iter() .filter(|h| { window.contains(&data.ops[h].header().timestamp()) }) .map(|k| data.op_hash_to_kit[&k].clone()) .collect(); let filter = if this_agent_hashes.is_empty() { EncodedTimedBloomFilter::MissingAllHashes { time_window: window, } } else { let filter = create_ops_bloom(this_agent_hashes); EncodedTimedBloomFilter::HaveHashes { time_window: window, filter, } }; let msg = HolochainP2pMockMsg::Gossip { dna: dna.clone(), module: module.clone(), gossip: GossipProtocol::Sharded( ShardedGossipWire::ops(filter, true), ), }; channel.send(msg.addressed((*agent).clone())).await; // Create an agent bloom and send it. if let Some(ref agent_bloom) = agent_bloom { let msg = HolochainP2pMockMsg::Gossip { dna: dna.clone(), module: module.clone(), gossip: GossipProtocol::Sharded( ShardedGossipWire::agents(agent_bloom.clone()), ), }; channel.send(msg.addressed((*agent).clone())).await; } } ShardedGossipWire::Ops(Ops { missing_hashes, .. }) => { // We have received an ops bloom so we can respond with any missing // hashes if there are nay. let this_agent_hashes = data.hashes_authority_for(&agent); let num_this_agent_hashes = this_agent_hashes.len(); let hashes = this_agent_hashes.iter().map(|h| { ( data.ops[h].header().timestamp(), &data.op_hash_to_kit[h], ) }); let missing_hashes = check_ops_boom(hashes, missing_hashes); let missing_hashes = match &last_intervals { Some(intervals) => missing_hashes .into_iter() .filter(|hash| { intervals[0].contains( data.op_to_loc[&data.op_kit_to_hash[*hash]], ) }) .collect(), None => vec![], }; gossiped_ops.extend(missing_hashes.iter().cloned()); let missing_ops: Vec<_> = missing_hashes .into_iter() .map(|h| { ( h.clone(), data.ops[&data.op_kit_to_hash[h]].clone(), ) }) .map(|(hash, op)| { ( hash, holochain_p2p::WireDhtOpData { op_data: op.into_content(), } .encode() .unwrap(), ) }) .collect(); let num_gossiped = gossiped_ops.len(); let p_done = num_gossiped as f64 / num_hashes_alice_should_hold as f64 * 100.0; let avg_gossip_freq = start_time .elapsed() .checked_div(agents_gossiped_with.len() as u32) .unwrap_or_default(); let avg_gossip_size = num_gossiped / agents_gossiped_with.len(); let time_to_completion = num_hashes_alice_should_hold .checked_sub(num_gossiped) .and_then(|n| n.checked_div(avg_gossip_size)) .unwrap_or_default() as u32 * avg_gossip_freq; let (overlap, max_could_get) = alice .as_ref() .map(|alice| { let arc = data.agent_to_arc[&agent]; let a = alice.storage_arc.interval(); let b = arc.interval(); let num_should_hold = this_agent_hashes .iter() .filter(|hash| { let loc = data.op_to_loc[*hash]; alice.storage_arc.contains(loc) }) .count(); (a.overlap_coverage(&b) * 100.0, num_should_hold) }) .unwrap_or((0.0, 0)); // Print out some stats. debug!( "Gossiped with {}, got {} of {} ops, overlap: {:.2}%, max could get {}, {:.2}% done, avg freq of gossip {:?}, est finish in {:?}", agent, missing_ops.len(), num_this_agent_hashes, overlap, max_could_get, p_done, avg_gossip_freq, time_to_completion ); let msg = HolochainP2pMockMsg::Gossip { dna, module, gossip: GossipProtocol::Sharded( ShardedGossipWire::missing_ops(missing_ops, true), ), }; channel.send(msg.addressed((*agent).clone())).await; } ShardedGossipWire::MissingOps(MissingOps { ops, .. }) => { debug!( "Gossiped with {} {} out of {}, who sent {} ops and gossiped with {} nodes outside of arc", agent, agents_gossiped_with.len(), data.num_agents(), ops.len(), num_missed_gossips ); } ShardedGossipWire::MissingAgents(MissingAgents { .. }) => {} _ => (), } } } } HolochainP2pMockMsg::Failure(reason) => panic!("Failure: {}", reason), } } } }); // Create the mock network. let mock_network = kitsune_p2p::test_util::mock_network::mock_network(from_kitsune_tx, to_kitsune_rx); let mock_network: AdapterFactory = Arc::new(mock_network); // Setup the network. let mut tuning = kitsune_p2p_types::config::tuning_params_struct::KitsuneP2pTuningParams::default(); tuning.gossip_strategy = "sharded-gossip".to_string(); tuning.gossip_dynamic_arcs = true; let mut network = KitsuneP2pConfig::default(); network.transport_pool = vec![TransportConfig::Mock { mock_network: mock_network.into(), }]; network.tuning_params = Arc::new(tuning); let mut config = ConductorConfig::default(); config.network = Some(network); // Add it to the conductor builder. let builder = ConductorBuilder::new().config(config); let mut conductor = SweetConductor::from_builder(builder).await; // Add in all the agent info. conductor .add_agent_infos(data.agent_to_info.values().cloned().collect()) .await .unwrap(); // Install the real agent alice. let apps = conductor .setup_app("app", &[dna_file.clone()]) .await .unwrap(); let (alice,) = apps.into_tuple(); let alice_p2p_env = conductor.get_p2p_env(alice.cell_id().dna_hash().to_kitsune()); let alice_kit = alice.agent_pubkey().to_kitsune(); // Spawn a task to update alice's agent info. tokio::spawn({ let alice_info = alice_info.clone(); async move { loop { let info = alice_p2p_env .conn() .unwrap() .p2p_get_agent(&alice_kit) .unwrap(); { *alice_info.lock() = info; } tokio::time::sleep(std::time::Duration::from_secs(5)).await; } } }); // Get the expected hashes and agents alice should gossip. let ( // The expected hashes that should be held by alice. hashes_to_be_held, // The agents that alice should initiate with. agents_that_should_be_initiated_with, ): ( Vec<(DhtLocation, Arc<DhtOpHash>)>, HashSet<Arc<AgentPubKey>>, ) = loop { if let Some(alice) = alice_info.lock().clone() { if (alice.storage_arc.coverage() - data.coverage()).abs() < 0.01 { let hashes_to_be_held = data .ops .iter() .filter_map(|(hash, op)| { let loc = op.dht_basis().get_loc(); alice.storage_arc.contains(loc).then(|| (loc, hash.clone())) }) .collect::<Vec<_>>(); let agents_that_should_be_initiated_with = data .agents() .filter(|h| alice.storage_arc.contains(h.get_loc())) .cloned() .collect::<HashSet<_>>(); num_hashes_alice_should_hold.store( hashes_to_be_held.len(), std::sync::atomic::Ordering::Relaxed, ); debug!("Alice covers {} and the target coverage is {}. She should hold {} out of {} ops. She should gossip with {} agents", alice.storage_arc.coverage(), data.coverage(), hashes_to_be_held.len(), data.ops.len(), agents_that_should_be_initiated_with.len()); break (hashes_to_be_held, agents_that_should_be_initiated_with); } } tokio::time::sleep(std::time::Duration::from_secs(5)).await; }; // Wait for consistency to be reached. local_machine_session_with_hashes( vec![&conductor.handle()], hashes_to_be_held.iter().map(|(l, h)| (*l, (**h).clone())), dna_file.dna_hash(), std::time::Duration::from_secs(60 * 60), ) .await; // Check alice initiates with all the expected agents. // Note this won't pass if some agents are offline. while agents_gossiped_with_rx.changed().await.is_ok() { let new = agents_gossiped_with_rx.borrow(); let diff: Vec<_> = agents_that_should_be_initiated_with .difference(&new) .collect(); if diff.is_empty() { break; } else { debug!("Waiting for {} to initiated agents", diff.len()); } } // Check if we got any publishes to the wrong agent. match bad_publish_rx.try_recv() { Ok(_) | Err(tokio::sync::oneshot::error::TryRecvError::Closed) => { panic!("Got a bad publish") } Err(_) => (), } // Check if we got any gets to the wrong agent. match bad_get_rx.try_recv() { Ok(_) | Err(tokio::sync::oneshot::error::TryRecvError::Closed) => { panic!("Got a bad get") } Err(_) => (), } }
48.636637
272
0.457675
870b589d1e701daf7a9afc0cb5cf2f170ab9dfd9
16,308
use super::{AssemblyError, Operation, Token}; use vm_core::utils::PushMany; // STACK MANIPULATION // ================================================================================================ /// Translates drop assembly instruction to VM operation DROP. pub fn parse_drop(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => span_ops.push(Operation::Drop), _ => return Err(AssemblyError::extra_param(op)), } Ok(()) } /// Translates dropw assembly instruction to VM operations DROP DROP DROP DROP. pub fn parse_dropw(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => span_ops.push_many(Operation::Drop, 4), _ => return Err(AssemblyError::extra_param(op)), } Ok(()) } /// Translates padw assembly instruction to VM operations PAD PAD PAD PAD. pub fn parse_padw(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => span_ops.push_many(Operation::Pad, 4), _ => return Err(AssemblyError::extra_param(op)), } Ok(()) } /// Translates dup.n assembly instruction to VM operations DUPN. pub fn parse_dup(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => span_ops.push(Operation::Dup0), 2 => match op.parts()[1] { "0" => span_ops.push(Operation::Dup0), "1" => span_ops.push(Operation::Dup1), "2" => span_ops.push(Operation::Dup2), "3" => span_ops.push(Operation::Dup3), "4" => span_ops.push(Operation::Dup4), "5" => span_ops.push(Operation::Dup5), "6" => span_ops.push(Operation::Dup6), "7" => span_ops.push(Operation::Dup7), "8" => { span_ops.push(Operation::Pad); span_ops.push(Operation::Dup9); span_ops.push(Operation::Add); } "9" => span_ops.push(Operation::Dup9), "10" => { span_ops.push(Operation::Pad); span_ops.push(Operation::Dup11); span_ops.push(Operation::Add); } "11" => span_ops.push(Operation::Dup11), "12" => { span_ops.push(Operation::Pad); span_ops.push(Operation::Dup13); span_ops.push(Operation::Add); } "13" => span_ops.push(Operation::Dup13), "14" => { span_ops.push(Operation::Pad); span_ops.push(Operation::Dup15); span_ops.push(Operation::Add); } "15" => span_ops.push(Operation::Dup15), _ => return Err(AssemblyError::invalid_param(op, 1)), }, _ => return Err(AssemblyError::extra_param(op)), } Ok(()) } /// Translates dupw.n assembly instruction to four VM operations DUP depending on /// the index of the word. pub fn parse_dupw(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => { span_ops.push(Operation::Dup3); span_ops.push(Operation::Dup3); span_ops.push(Operation::Dup3); span_ops.push(Operation::Dup3); } 2 => match op.parts()[1] { "0" => { span_ops.push(Operation::Dup3); span_ops.push(Operation::Dup3); span_ops.push(Operation::Dup3); span_ops.push(Operation::Dup3); } "1" => { span_ops.push(Operation::Dup7); span_ops.push(Operation::Dup7); span_ops.push(Operation::Dup7); span_ops.push(Operation::Dup7); } "2" => { span_ops.push(Operation::Dup11); span_ops.push(Operation::Dup11); span_ops.push(Operation::Dup11); span_ops.push(Operation::Dup11); } "3" => { span_ops.push(Operation::Dup15); span_ops.push(Operation::Dup15); span_ops.push(Operation::Dup15); span_ops.push(Operation::Dup15); } _ => return Err(AssemblyError::invalid_param(op, 1)), }, _ => return Err(AssemblyError::extra_param(op)), } Ok(()) } /// Translates swap.x assembly instruction to VM operations MOVUPX MOVDN(X-1) pub fn parse_swap(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => span_ops.push(Operation::Swap), 2 => match op.parts()[1] { "1" => span_ops.push(Operation::Swap), "2" => { span_ops.push(Operation::Swap); span_ops.push(Operation::MovUp2); } "3" => { span_ops.push(Operation::MovDn2); span_ops.push(Operation::MovUp3); } "4" => { span_ops.push(Operation::MovDn3); span_ops.push(Operation::MovUp4); } "5" => { span_ops.push(Operation::MovDn4); span_ops.push(Operation::MovUp5); } "6" => { span_ops.push(Operation::MovDn5); span_ops.push(Operation::MovUp6); } "7" => { span_ops.push(Operation::MovDn6); span_ops.push(Operation::MovUp7); } "8" => { span_ops.push(Operation::MovDn7); // MovUp8 span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp9); span_ops.push(Operation::Add); } "9" => { span_ops.push(Operation::MovDn9); span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp9); span_ops.push(Operation::Add); } "10" => { span_ops.push(Operation::MovDn9); // MovUp10 span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp11); span_ops.push(Operation::Add); } "11" => { span_ops.push(Operation::MovDn11); span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp11); span_ops.push(Operation::Add); } "12" => { span_ops.push(Operation::MovDn11); // MovUp12 span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp13); span_ops.push(Operation::Add); } "13" => { span_ops.push(Operation::MovDn13); span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp13); span_ops.push(Operation::Add); } "14" => { span_ops.push(Operation::MovDn13); // MovUp14 span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp15); span_ops.push(Operation::Add); } "15" => { span_ops.push(Operation::MovDn15); span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp15); span_ops.push(Operation::Add); } _ => return Err(AssemblyError::invalid_param(op, 1)), }, _ => return Err(AssemblyError::extra_param(op)), } Ok(()) } /// Translates swapw.n assembly instruction to four VM operation SWAPWN pub fn parse_swapw(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => span_ops.push(Operation::SwapW), 2 => match op.parts()[1] { "1" => span_ops.push(Operation::SwapW), "2" => span_ops.push(Operation::SwapW2), "3" => span_ops.push(Operation::SwapW3), _ => return Err(AssemblyError::invalid_param(op, 1)), }, _ => return Err(AssemblyError::extra_param(op)), } Ok(()) } /// Translates movup.x assembly instruction to VM operations. /// We specifically utilize the MovUpX VM operations for indexes that match /// exactly with the assembly instruction. /// The reamaining ones we implement them PAD MOVUPX ADD. pub fn parse_movup(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0..=1 => return Err(AssemblyError::missing_param(op)), 2 => match op.parts()[1] { "2" => span_ops.push(Operation::MovUp2), "3" => span_ops.push(Operation::MovUp3), "4" => span_ops.push(Operation::MovUp4), "5" => span_ops.push(Operation::MovUp5), "6" => span_ops.push(Operation::MovUp6), "7" => span_ops.push(Operation::MovUp7), "8" => { span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp9); span_ops.push(Operation::Add); } "9" => span_ops.push(Operation::MovUp9), "10" => { span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp11); span_ops.push(Operation::Add); } "11" => span_ops.push(Operation::MovUp11), "12" => { span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp13); span_ops.push(Operation::Add); } "13" => span_ops.push(Operation::MovUp13), "14" => { span_ops.push(Operation::Pad); span_ops.push(Operation::MovUp15); span_ops.push(Operation::Add); } "15" => span_ops.push(Operation::MovUp15), _ => return Err(AssemblyError::invalid_param(op, 1)), }, _ => return Err(AssemblyError::extra_param(op)), }; Ok(()) } /// Translates movupw.x assembly instruction to VM operations. /// /// Specifically: /// * movupw.2 is translated into SWAPW SWAPW2 /// * movupw.3 is translated into SWAPW SWAPW2 SWAPW3 pub fn parse_movupw(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0..=1 => return Err(AssemblyError::missing_param(op)), 2 => match op.parts()[1] { "2" => { span_ops.push(Operation::SwapW); span_ops.push(Operation::SwapW2); } "3" => { span_ops.push(Operation::SwapW); span_ops.push(Operation::SwapW2); span_ops.push(Operation::SwapW3); } _ => return Err(AssemblyError::invalid_param(op, 1)), }, _ => return Err(AssemblyError::extra_param(op)), }; Ok(()) } /// Translates movdn.x assembly instruction to VM operations. /// We specifically utilize the MovDnX VM operations for indexes that match /// exactly with the assembly instruction. /// The reamaining ones we implement them PAD SWAP MOVDNX DROP. pub fn parse_movdn(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0..=1 => return Err(AssemblyError::missing_param(op)), 2 => match op.parts()[1] { "2" => span_ops.push(Operation::MovDn2), "3" => span_ops.push(Operation::MovDn3), "4" => span_ops.push(Operation::MovDn4), "5" => span_ops.push(Operation::MovDn5), "6" => span_ops.push(Operation::MovDn6), "7" => span_ops.push(Operation::MovDn7), "8" => { span_ops.push(Operation::Pad); span_ops.push(Operation::Swap); span_ops.push(Operation::MovDn9); span_ops.push(Operation::Drop); } "9" => span_ops.push(Operation::MovDn9), "10" => { span_ops.push(Operation::Pad); span_ops.push(Operation::Swap); span_ops.push(Operation::MovDn11); span_ops.push(Operation::Drop); } "11" => span_ops.push(Operation::MovDn11), "12" => { span_ops.push(Operation::Pad); span_ops.push(Operation::Swap); span_ops.push(Operation::MovDn13); span_ops.push(Operation::Drop); } "13" => span_ops.push(Operation::MovDn13), "14" => { span_ops.push(Operation::Pad); span_ops.push(Operation::Swap); span_ops.push(Operation::MovDn15); span_ops.push(Operation::Drop); } "15" => span_ops.push(Operation::MovDn15), _ => return Err(AssemblyError::invalid_param(op, 1)), }, _ => return Err(AssemblyError::extra_param(op)), }; Ok(()) } /// Translates movdnw.x assembly instruction to VM operations. /// /// Specifically: /// * movdnw.2 is translated into SWAPW2 SWAPW /// * movdnw.3 is translated into SWAPW3 SWAPW2 SWAPW pub fn parse_movdnw(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0..=1 => return Err(AssemblyError::missing_param(op)), 2 => match op.parts()[1] { "2" => { span_ops.push(Operation::SwapW2); span_ops.push(Operation::SwapW); } "3" => { span_ops.push(Operation::SwapW3); span_ops.push(Operation::SwapW2); span_ops.push(Operation::SwapW); } _ => return Err(AssemblyError::invalid_param(op, 1)), }, _ => return Err(AssemblyError::extra_param(op)), }; Ok(()) } // CONDITIONAL MANIPULATION // ================================================================================================ /// Translates cswap assembly instruction that translates to CSWAP. pub fn parse_cswap(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => span_ops.push(Operation::CSwap), _ => return Err(AssemblyError::extra_param(op)), }; Ok(()) } /// Translates cswapw assembly instruction that translates to CSWAPW. pub fn parse_cswapw(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => span_ops.push(Operation::CSwapW), _ => return Err(AssemblyError::extra_param(op)), }; Ok(()) } /// Translates cdrop assembly instruction that translates to CSWAP DROP pub fn parse_cdrop(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => { span_ops.push(Operation::CSwap); span_ops.push(Operation::Drop); } _ => return Err(AssemblyError::extra_param(op)), }; Ok(()) } /// Translates cdropw assembly instruction that translates to CSWAPW DROP DROP DROP DROP pub fn parse_cdropw(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { match op.num_parts() { 0 => return Err(AssemblyError::missing_param(op)), 1 => { span_ops.push(Operation::CSwapW); span_ops.push(Operation::Drop); span_ops.push(Operation::Drop); span_ops.push(Operation::Drop); span_ops.push(Operation::Drop); } _ => return Err(AssemblyError::extra_param(op)), }; Ok(()) }
36.979592
99
0.527778